Leerpad
T- SQL (Transact-SQL) is Microsoft’s extension of standard SQL, designed specifically for use with Microsoft SQL Server. While it includes all the core capabilities of SQL for querying and managing data, T-SQL adds procedural programming features that let you write more powerful and dynamic database logic.
In this guide, I will show you how T-SQL works and how to use it effectively in real-world scenarios. I will also cover common use cases such as querying databases, writing stored procedures, and automating routine workflows, with practical examples.
If you are new to SQL, start with our Introduction to SQL course, or the Intermediate SQL course if you have some experience. Also, I find the SQL Basics Cheat Sheet, which you can download, is a helpful reference because it has all the most common SQL functions.
What Is T-SQL and How It Differ from SQL
To understand T-SQL better, think of SQL as a universal language and T-SQL as a specialized professional dialect.
SQL (Structured Query Language) is the standard language used to interact with relational databases. It is declarative, meaning you specify what result you want, such as selecting or filtering data, and the database engine decides how to execute the query.
T-SQL, on the other hand, is Microsoft’s extension of SQL used in Microsoft SQL Server. It builds on standard SQL by adding procedural programming capabilities, allowing you to control how operations are carried out step by step.
From this definition, T-SQL introduces several powerful features that go beyond basic querying, including:
-
Variables: You can use
DECLAREandSETkeywords to store data in memory and reuse it within scripts -
Control flow: You can use logic like
IF,WHILE, andBEGIN...ENDto control execution and decide which code runs. -
Error handling: T-SQL introduces
TRY...CATCHblocks, which allow the database to catch an error and handle it gracefully without crashing the entire operation. -
Stored procedures: You can create reusable blocks of logic that run inside the database.
If you find yourself working with SQL Server, know that DataCamp has a lot of great resources to help. To start, I recommend taking DataCamp’s Introduction to SQL Server course to master the basics of SQL Server for data analysis.
Basic T-SQL Syntax and Structure
T-SQL uses the same core syntax as standard SQL, so if you’re already familiar with SQL, you will easily understand it. In this section, I will walk you through the most common statements of T-SQL with simple, practical examples.
SELECT, INSERT, UPDATE, DELETE
These commands are standard across most SQL dialects, including Microsoft SQL Server, for which T-SQL is built.
SELECT
The command used to retrieve data from specific tables. For example, the query below retrieves FirstName and LastName from the Customers table.
-- Retrieve data from the Customers table
SELECT FirstName, LastName
FROM Customers
WHERE Country = ‘USA’; -- Filters rows to only customers in the USA
INSERT
This command is used to insert new data into the table. The query below inserts a new row into the customers table.
-- Insert a new row into a table
INSERT INTO customers (FirstName, city)
VALUES (‘Alice’, ‘Nairobi’);
UPDATE
This command is used to modify existing data in the database. For example, the query below changes the city name to “Mombasa” for the user “Alice.”
-- Update existing data
UPDATE customers
SET city = ‘Mombasa’
WHERE FirstName= ‘Alice’; -- Always use WHERE to avoid updating all rows
DELETE
This command removes data from the database. For example, the query below removes the row where FirstName is “Alice.”
-- Delete data from a table
DELETE FROM customers
WHERE FirstName= ‘Alice’; -- Filters which rows to remove
I recommend trying our SQL Server Fundamentals skill track to learn more about summarizing and analyzing data using SQL Server functions
Batch execution
One unique feature of T-SQL is how it executes code in batches. A batch is a group of one or more SQL statements sent to SQL Server as a single unit.
The GO keyword is used to separate batches:
-- First batch
SELECT * FROM Customers;
GO
-- Second batch (executed separately)
SELECT * FROM Orders;
GO
It is important to note that:
-
GOis not a T-SQL command, but it’s recognized by tools like SQL Server Management Studio. -
It signals the end of one batch and the start of another.
-
The variables do not persist across batches. Temporary objects actually do persist across batches in the same session.
Comments and formatting
You can use comments in T-SQL to help make your SQL code easier to read and maintain. You can use either single-line or multi-line comments as shown below:
-- This query retrieves all customers
SELECT * FROM Customers;
/* This query retrieves customers
from the USA and Canada */
SELECT *
FROM Customers
WHERE Country IN ('USA', 'Canada');
Variables and Data Types in T-SQL
T-SQL allows you to store values in variables and use them in queries, making your scripts more flexible and dynamic. Let’s look at how to create these variables.
Declaring variables
To create a variable, you use the DECLARE keyword. By convention, all T-SQL variable names must start with the @ symbol.
-- Declares a variable to store text
DECLARE @CustomerName VARCHAR(50);
Assigning values
You can assign values using either SET (recommended for single values) or SELECT (useful when retrieving from a table).
-- Assign using SET
SET @CustomerName = 'Alice';
-- Assign using SELECT
SELECT @Age = 30;
For example, the query below returns a list of customers who live in London, using a variable instead of hardcoding the value.
-- Assign the variable city
DECLARE @City VARCHAR(50);
SET @City = 'London';
-- Use the variable in a query
SELECT name, city
FROM customers
WHERE city = @City; -- Filters results based on variable value
Common data types
The following are some commonly used T-SQL data types that are standard across SQL data types:
-
INT: Whole numbers, for example, 1, 100. -
VARCHAR(n): Variable-length text like names and emails. -
DATETIME: Date and time values -
DECIMAL(p, s): Fixed precision numbers like currency.
Control Flow in T-SQL (IF, WHILE, BEGIN...END)
One of the advantages of T-SQL is that it lets you add programming logic to your queries. Instead of just retrieving data, you can control how and when code executes. Below are examples of control flow logic.
IF...ELSE (Conditional execution)
The IF statement allows you to execute a block of code only if a specific condition is met. If the condition is false, you can use ELSE to provide an alternative action.
For example, the query below counts the total number of orders, then prints “High order volume” if it’s above 100 orders or prints “Low order volume” when it’s below 100.
DECLARE @TotalOrders INT;
SELECT @TotalOrders = COUNT(*)
FROM Orders; -- Count total number of orders
IF @TotalOrders > 100
BEGIN
PRINT 'High order volume'; -- Runs if condition is true
END
ELSE
BEGIN
PRINT 'Low order volume'; -- Runs if condition is false
END
WHILE loops (Iterative logic)
The WHILE loop repeats a block of code as long as a condition remains true. This is useful for tasks that need to happen in “chunks” or for generating test data.
The query below initializes a counter at 1 and uses a loop to print the current number and increase it by 1 until it reaches 5.
DECLARE @Counter INT = 1;
WHILE @Counter <= 5
BEGIN
PRINT @Counter; -- Prints numbers from 1 to 5
SET @Counter = @Counter + 1; -- Increment counter
END
BEGIN...END (Grouping statements)
The BEGIN...END flow is used to group multiple statements into a single block to ensure all grouped code executes together atomically.
For example, the query below will print both “Customers found in USA” and “Proceeding with operation.” Without BEGIN...END, only the first statement after IF would be executed.
IF EXISTS (SELECT 1 FROM Customers WHERE Country = 'USA')
BEGIN
PRINT 'Customers found in USA';
PRINT 'Proceeding with operation'; -- Both statements run together
END
When is control flow useful?
Control flow in T-SQL is commonly used for:
- Automation: Running scheduled scripts or maintenance tasks
- Data validation: Checking conditions before inserting or updating data
- Batch processing: Handling data in steps or loops
- Business logic: Applying rules directly inside the database
Stored Procedures in T-SQL
A stored procedure is a saved collection of T-SQL statements that you can reuse over and over. Instead of sending a massive block of code from your application to the server every time, you save the code on the server and just call its name.
Stored procedures are useful because you can reuse them many times. The precompiled execution plans improve efficiency and hide complex logic behind a simple interface.
For example, this stored procedure retrieves the first and last name of a customer based on the ID you provide.
-- Create a stored procedure named GetCustomerByID
CREATE PROCEDURE GetCustomerByID
@CustomerID INT -- Input parameter to pass a customer ID
AS
BEGIN
-- Select the first and last name of a customer
SELECT FirstName, LastName
FROM Customers
WHERE CustomerID = @CustomerID; -- Filter to match the given ID
END;
You can then execute the stored procedure using the query below:
-- Calls the procedure
EXEC GetCustomerByID @CustomerID = 1; Earn a Top SQL Certification
Functions in T-SQL
T-SQL includes both built-in functions and user-defined functions (UDFs) used to transform data.
Built-in functions
These functions are already available in SQL Server and can be used directly in queries.
String function
This is a function that transforms string data types. For example, the query below retrieves all first names from the Customers table and converts them to uppercase.
-- Converts text to uppercase
SELECT UPPER(FirstName)
FROM Customers;
Date function
This function transforms date functions. The query below returns the current system date and time.
-- Returns current date and time
SELECT GETDATE();
Aggregate function
These are functions used to aggregate values in a table. For example, the query below counts the total number of rows (customers) in the Customers table.
-- Counts rows
SELECT COUNT(*) AS TotalCustomers
FROM Customers;
User-defined functions (UDFs)
You can also create your own functions to reuse logic in multiple queries.
Scalar function
A scalar function returns a single value and is useful when you need a single computed value, such as formatting or calculations. In the query below, the function takes a first name and last name as input and returns them as a single full name.
-- Create a function that combines the first and last name
CREATE FUNCTION GetFullName
(@FirstName VARCHAR(50), @LastName VARCHAR(50))
RETURNS VARCHAR(100)
AS
BEGIN
RETURN @FirstName + ' ' + @LastName; -- Concatenates the two values
END;
Table-valued functions
Table-valued functions return a table. For example, the function below returns a table of all customers who belong to the specified country.
-- Create a table-valued function named GetCustomersByCountry
CREATE FUNCTION GetCustomersByCountry (@Country VARCHAR(50))
RETURNS TABLE -- Specifies that the function returns a table
AS
RETURN
(
-- Select all columns from the Customers table
SELECT *
FROM Customers
WHERE Country = @Country -- Filter rows by the given country
);
I recommend trying our full SQL Server Developer career track, which will not only equip you with the skills to create, update, and execute stored procedures, but will also help you with aggregate functions, joining, inserting, and deleting tables, and much more.
Error Handling in T-SQL
T-SQL uses TRY...CATCH blocks to handle errors without stopping the entire script. This is important as it prevents scripts from crashing unexpectedly and allows you to return meaningful messages for debugging or logging.
For example, the query below tries to run a calculation that causes an error, catches it, and prints a readable error message instead of crashing.
BEGIN TRY
-- Attempt to run this code
SELECT 1 / 0; -- This causes a divide-by-zero error
END TRY
BEGIN CATCH
-- Runs if an error occurs in the TRY block
PRINT 'An error occurred: ' + ERROR_MESSAGE(); -- Displays the error message
END CATCH;
Transactions in T-SQL
A Transaction ensures that a group of operations either all succeed or all fail. This follows the ACID principle, which guarantees that your database stays consistent even if the power goes out mid-update.
In the example below, the transaction transfers money from one account to another and saves both changes together.
BEGIN TRANSACTION; -- Start the transaction
-- Deduct money from Account 1
UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 1;
-- Add money to Account 2
UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 2;
COMMIT; -- Save all changes permanently
If something goes wrong, you can use the ROLLBACK function to cancel the transaction and restore the data to its previous state.
-- Undo all changes made in the current transaction
ROLLBACK;
Transactions in T-SQL are important as they ensure data integrity, especially in critical systems like financial applications, where partial updates could lead to inconsistencies.
You can try our Transactions and Error Handling in SQL Server career track, which covers transactions and error handling in SQL Server.
Common T-SQL Features for Data Analysis
T-SQL includes some tools that are especially useful for data professionals. Let’s look at some examples and how to apply them in data analysis.
Window functions
Window functions perform calculations across rows without grouping them into a single result. They are mostly used in ranking, running totals, and advanced analytics.
In the example below, the query assigns a unique row number to each customer based on their CustomerID.
-- Assigns row numbers to customers
SELECT
FirstName,
ROW_NUMBER() OVER (ORDER BY CustomerID) AS RowNum -- Assigns row numbers
FROM Customers;
In the query;
-
ROW_NUMBER(): Assigns unique row numbers
-
RANK(): Assigns rank with gaps for ties -
OVER(): Defines the window (ordering/partitioning)
I recommend checking out our SQL Window Functions Cheat Sheet, which you can download, where you will have a handy reference guide to the various types of window functions in SQL. Also, check out our Intermediate SQL Server course to learn more about using T-SQL in data analysis, including window functions to summarize data.
Common table expressions (CTEs)
CTEs (Common Table Expressions) create a temporary result set that you can reuse within a query. The query below creates a temporary list of USA customers and then retrieves data from it.
-- Define a CTE
WITH CustomerCTE AS (
SELECT FirstName, Country
FROM Customers
WHERE Country = 'USA' -- Filter only USA customers
)
-- Query the CTE
SELECT *
FROM CustomerCTE;
On the other hand, recursive CTEs are a special type of CTE that reference themselves within their definition, allowing the query to perform repeated operations. This makes them ideal for working with hierarchical data like organizational charts.
I recommend taking our Hierarchical and Recursive Queries in SQL Server course to learn how to write advanced queries in SQL Server, including involving CTEs and recursive CTEs, with practical examples.
Temporary tables
Temporary tables store data for short-term use during a session. They are useful for staging data, simplifying multi-step transformations, or improving performance in complex queries.
To demonstrate how temporary tables work in t-SQL, consider the following three query blocks. The first one creates a temporary table, then fills it with customer data, and then queries it within the same session.
-- Create a temporary table
CREATE TABLE #TempCustomers (
FirstName VARCHAR(50),
Country VARCHAR(50)
);
-- Insert data into the temporary table
INSERT INTO #TempCustomers
SELECT FirstName, Country
FROM Customers;
-- Retrieve data from the temporary table
SELECT * FROM #TempCustomers;
It is important to note that temporary tables are prefixed with # and they are automatically dropped when the session ends.
T-SQL vs. Other SQL Dialects
All SQL dialects share the same foundation, but each database system adds its own syntax and features. T-SQL is designed specifically for Microsoft SQL Server, which influences how it works and where it’s best used.
T-SQL vs. PostgreSQL (PL/pgSQL)
PostgreSQL uses PL/pgSQL for procedural logic, similar to T-SQL but with different syntax and strengths. The table below summarizes these differences:
|
Category |
T-SQL (SQL Server) |
PostgreSQL (PL/pgSQL) |
|
Procedural language |
Built into T-SQL |
Uses PL/pgSQL |
|
Variable syntax |
|
|
|
Variable naming |
Uses |
No prefix (For example, |
|
Block structure |
Simpler, often implicit or |
Explicit: |
|
Example block |
Standard T-SQL batch |
Wrapped in |
|
Advanced data types |
Limited |
Advanced native support (JSONB, Arrays, Geometric) |
|
Tooling & integration |
Tight integration with SQL Server tools |
Flexible across platforms |
|
Ecosystem |
Optimized for Windows, Azure, SSMS, and Power BI |
Open-source, cross-platform |
Check out our SQL for Database Administrators skill track to learn how to design relational databases and structure your queries to improve performance.
T-SQL vs. MySQL
MySQL also supports procedural SQL, but with a simpler and more limited approach. The table below compares the syntax and feature differences of these two dialects.
|
Category |
T-SQL (Microsoft) |
MySQL |
|
Row Limitation |
|
|
|
Error Handling |
Robust |
More limited DECLARE HANDLER syntax |
|
Procedural Logic |
Rich, structured, and highly programmable |
Simpler and more limited procedural features |
|
Analytics |
Window functions and CTEs |
Basic analytical features (improving in newer versions) |
|
Ecosystem |
Tied to SQL Server and Enterprise tooling |
Lightweight; heart of the LAMP stack (Linux, Apache, etc.) |
|
Best for |
Complex business logic and data warehousing |
Web applications and high-speed read operations |
Real-World Use Cases of T-SQL
T-SQL is widely used beyond simple data querying. The following are examples where I found it useful as a data professional.
Reporting queries
T-SQL is commonly used to generate reports directly from the database. For example, you can aggregate sales by region or rank top-performing products using window functions.
ETL processes (Extract, Transform, Load)
T-SQL is used in data pipelines by data engineers to prepare and move data. For example, you can extract data from staging tables, transform formats, clean inconsistencies, and load into final reporting tables.
Data cleaning scripts
If your database has millions of rows with inconsistent address formats, you can use a T-SQL script using WHILE loops or CTEs to identify duplicates, fill missing values, or standardize formats.
Backend logic in applications
Many applications rely on T-SQL to handle business logic inside the database. You can use stored procedures for CRUD operations, perform validations before inserting data, or use transaction handling for critical operations.
Common Mistakes and Best Practices
Although T-SQL is useful for advanced database querying, you are likely to run into a few common issues. The following are some common mistakes I have encountered when using T- SQL:
-
Overusing loops instead of set-based logic: Using loops, like
WHILE, for row-by-row operations can slow down performance. SQL is designed to work with sets of data at once. -
Poor indexing awareness: Not using indexes properly can make queries slow, especially on large tables.
-
Not using transactions properly: Running multiple related operations without wrapping them in a transaction can leave your data in an inconsistent state if something fails midway.
-
Ignoring error handling: If you skip the
TRY...CATCHblocks, it makes debugging harder and can cause scripts to fail silently or unpredictably in production.
Below are the best practices I recommend to help you write more efficient and reliable queries:
-
Prefer set-based queries: Use
JOIN,GROUP BY, and window functions instead of loops whenever possible. This aligns with how SQL Server is designed to process data efficiently. -
Write readable, maintainable code: Use clear naming conventions, format queries consistently, and add comments where necessary. This makes your code readable, easier to debug, and collaborate on.
-
Test procedures: Always test stored procedures and queries with different inputs to ensure they work correctly and handle edge cases.
Conclusion
T-SQL extends standard SQL by adding programming capabilities, making it a flexible and powerful tool for automation, data processing, and analysis. With features like variables, stored procedures, and error handling, it allows you to build more dynamic and efficient database solutions.
As a next step, I recommend trying out our Associate Data Analyst in SQL career track to become a proficient data analyst. Our Reporting in SQL course will also help you become proficient in building complex reports. Finally, you should obtain our SQL Associate Certification to showcase your mastery in using SQL to solve business problems and stand out among other professionals.
T-SQL FAQs
How is T-SQL different from standard SQL?
SQL is mainly declarative, while T-SQL combines declarative querying with procedural programming, allowing you to control how operations are executed.
Do I need to learn SQL before learning T-SQL?
Yes, a basic understanding of SQL is important since T-SQL builds directly on core SQL concepts like SELECT, INSERT, UPDATE, and DELETE.
Is T-SQL available in all SQL dialects?
No, T-SQL is specific to Microsoft’s ecosystem and is primarily used with Microsoft SQL Server and related tools like Azure SQL.
What are stored procedures, and why are they useful?
Stored procedures are reusable blocks of T-SQL code that run inside the database. They help improve performance, enforce consistency, and simplify application logic.
What are window functions in T-SQL used for?
Window functions are used for advanced analysis tasks like ranking, running totals, and comparing values across rows without grouping the data.



