getbetterat.work
TOPIC: DATABASE LOGIC

What is T-SQL?

T-SQL makes normal SQL smarter. It gives your database a brain.

Normal SQL is like a simple calculator. It can ask a database to add things or show a list. But T-SQL (Transact-SQL) is like a mini-computer program living inside Microsoft SQL Server. It can make choices, remember things in boxes, and fix its own mistakes.

Normal SQL vs. T-SQL

Normal SQL

  • Only reads and writes data.
  • Reads one instruction at a time.
  • Cannot make decisions (No IF/ELSE).

T-SQL

  • Has step-by-step logic.
  • Runs many steps as one big job.
  • Can decide what to do based on data.

1. Variables (Sticky Notes)

A variable is like a sticky note. You can write a piece of information on it, stick it in the computer's memory, and look at it later. In T-SQL, variables always start with the @ symbol.

DECLARE @MyAge INT;
SET @MyAge = 25;

SELECT @MyAge AS AgeResult;

We made a box named @MyAge. We put 25 inside it. Then we looked inside the box.

2. IF and ELSE (Making Choices)

Normal SQL just gets data. T-SQL can look at the data and make a choice, like a traffic light. IF the light is green, go. ELSE, stop.

DECLARE @MoneyInBank INT = 50;

IF @MoneyInBank > 100
    PRINT 'You can buy the toy.';
ELSE
    PRINT 'You do not have enough money.';

T-SQL checks the money. Since 50 is not bigger than 100, it prints the second message.

3. WHILE Loops (Doing it again)

A loop is like a washing machine. It keeps spinning over and over until the timer runs out. In T-SQL, a WHILE loop runs code over and over until a rule tells it to stop.

DECLARE @Count INT = 1;

WHILE @Count <= 3
BEGIN
    PRINT 'Counting: ' + CAST(@Count AS VARCHAR);
    SET @Count = @Count + 1;
END
Output Screen: Counting: 1 Counting: 2 Counting: 3

4. Error Handling (Safety Net)

If a normal program breaks, the whole system crashes and stops working. T-SQL uses a safety net called TRY...CATCH. It says, "TRY to do this job. If it fails, CATCH the mistake smoothly so the system stays alive."

BEGIN TRY
  -- Trying to divide by zero!
  SELECT 10 / 0;
END TRY
BEGIN CATCH
  PRINT 'Oops! You cannot divide by zero.';
END CATCH

5. Built-in Tools

T-SQL comes with a toolbox of ready-to-use functions. Instead of doing hard math or changing text yourself, you just ask the tool to do it for you.

  • GETDATE()
    Finds today's exact date and time.
  • UPPER()
    Makes text ALL CAPITAL LETTERS.
  • LEN()
    Counts how many letters are in a word.

6. Stored Procedures (Saving Recipes)

If you have a very long piece of code that you use every day, you do not want to write it out every time. A Stored Procedure lets you save that code like a food recipe. Next time, you just say, "Make the recipe!"

CREATE PROCEDURE GetStudentNames
AS
BEGIN
    SELECT FirstName, LastName FROM Students;
END

Now, anyone can just type EXEC GetStudentNames to run the whole thing instantly!

7. Triggers (The Automatic Alarm)

A Trigger is a piece of code that wakes up automatically when something happens in the database.

Example: Every time someone deletes a file, a Trigger wakes up and automatically saves a backup copy of the file before it is gone forever.

Real World Example: The Bank

How does a bank move money safely without losing it? They use T-SQL.

01

Check the Balance (IF/ELSE)

T-SQL checks your account. IF you have $100, the process continues. ELSE, it stops and says "Not enough money."

02

Move the Money (Variables & Math)

It takes $100 out of your account, saves the number in a variable, and adds $100 to your friend's account.

03

Protect the Process (TRY/CATCH)

If the computer power turns off right in the middle, the TRY/CATCH blocks the mistake, cancels the whole move, and gives your $100 back so it doesn't get lost in the wires.

8. Transactions

The "All or Nothing" Rule

If you move money between accounts, you cannot let the computer crash halfway. T-SQL uses Transactions to guarantee safety. It tells the database: "Do all these steps perfectly, or undo everything."

BEGIN TRAN;
  -- Step 1: Take money from John
  -- Step 2: Give money to Jane
COMMIT TRAN; -- Save it permanently!

-- If there is an error, we run:
ROLLBACK TRAN; -- Undo everything!

9. Temp Tables (The Scratchpad)

Sometimes you need to do a lot of messy math before you save the final answer. T-SQL lets you create a temporary table that automatically deletes itself when you close the program.

-- The '#' symbol means it is temporary
CREATE TABLE #MyScratchpad (
    TempID INT,
    TempName VARCHAR(50)
);

-- Once you disconnect, #MyScratchpad vanishes into thin air.

10. Views (The Safe Window)

Imagine a giant table containing names, emails, and secret passwords. You want the marketing team to see the names and emails, but not the passwords. A View is a fake table. It acts like a window that only shows the safe columns.

Real Table
(Name, Email, Password)
The View
(Only Name, Email)

11. Custom Tools (UDFs)

We already learned about built-in tools like UPPER(). But what if you need a tool that calculates the specific tax for your city? T-SQL lets you build User-Defined Functions (UDFs). You build the tool once, and your whole team can use it forever.

SELECT
  Price,
  dbo.CalculateCityTax(Price) AS Tax
FROM Products;

12. CASE (The Data Shapeshifter)

Sometimes the raw data is ugly (like saving "1" for Active and "2" for Fired). A CASE statement translates ugly data into human words right as it prints on the screen. It says: "In case you see this, show that instead."

SELECT EmployeeName,
  CASE StatusID
    WHEN 1 THEN 'Active'
    WHEN 2 THEN 'On Vacation'
    ELSE 'Fired'
  END AS StatusWord
FROM Employees;

13. CTEs (Step-by-Step Logic)

If you have a giant, confusing question to ask the database, a CTE (Common Table Expression) helps you break it into small, readable steps. It starts with the magic word WITH.

  1. Step 1: Find all sales from today.
  2. Step 2: Take only the sales from New York.
  3. Step 3: Show me the final list.

Instead of writing one giant messy paragraph, CTEs stack the logic block by block so a human can easily read it.

14. Indexes (The Fast Lane)

Imagine looking for the word "Zebra" in a 1,000-page book without a table of contents. You would have to read every single page. That is how a database searches without an Index.

An Index is exactly like the back pages of a book. It tells the computer exactly which row has the data, turning a 10-minute search into a 1-second search.

15. Cursors (The Slow Reader)

Normally, T-SQL wants to look at millions of rows at the exact same time. This makes it super fast. A Cursor forces the database to put on reading glasses and look at data one single row at a time.

Rule of thumb: Cursors are very slow. Only use them if you absolutely have to process things one-by-one.

16. Batches (The 'GO' Button)

If you write 500 lines of code, you might not want to send all of it to the server at exactly the same time. The word GO breaks your code into batches. It tells the server, "Okay, stop reading here, execute what I just wrote, and then continue."

CREATE TABLE NewBox (ID INT); GO SELECT * FROM NewBox; GO

17. Permissions (The Vault)

A database is completely useless if just anyone can walk in and delete all the financial records. T-SQL has built-in security guards using two main words: GRANT (give a key) and REVOKE (take the key away).

GRANT

"Give the intern permission to READ the data, but nothing else."

REVOKE

"Take away the intern's ability to DELETE the data."

Why Big Companies Use T-SQL

  • It is Fast

    Since T-SQL runs directly inside the database, it doesn't have to send data across the internet to do math. It does it right where the data lives.

  • It is Safe

    With its built-in error catchers, large businesses trust it not to lose important files or money.

  • Microsoft Power

    It works perfectly with every other Microsoft tool, making it the standard choice for major corporations around the world.