Coding

What Is T-SQL? Transact-SQL Explained With Examples

T-SQL, short for Transact-SQL, is Microsoft's dialect of SQL, used to talk to SQL Server, Azure SQL and related Microsoft data services. It covers the usual statements for reading and changing data, and adds programming features such as variables, error handling and transactions that you use inside scripts and stored procedures.

What T-SQL is and where it runs

Microsoft's reference describes it plainly: "T-SQL is central to using Microsoft SQL products and services. All tools and applications that communicate with a SQL Server database do so by sending T-SQL commands." In other words, whatever graphical tool or application you use, what reaches the database engine is T-SQL text.

The reference articles cover more than one product. They span SQL Server starting with version 2008 (10.0.x), plus Azure SQL Database, Azure SQL Managed Instance and Azure Synapse Analytics. Each article starts with an "Applies to" label, and Microsoft states that "if a product is omitted, then the feature described by the article isn't available in that product." Always check that label before copying a snippet to a different product, because a feature that works on SQL Server may not exist in Azure Synapse Analytics. The TOP clause, for example, has slightly different syntax for Azure Synapse Analytics than for SQL Server, since the PERCENT option is not listed there.

Microsoft keeps a separate document on how the standards are implemented, linked from the reference under "T-SQL compliance with the SQL standard". The practical reading is that the common core is shared with other SQL databases and the extras are Microsoft-specific. For the general idea of what SQL is, see SQL for beginners.

T-SQL vs SQL: what is different

SQL on its own is a declarative language: you describe the rows you want and the database decides how to fetch them. Is SQL a programming language? covers that in detail. T-SQL keeps that core and adds the procedural layer you need for scripts, stored procedures and triggers.

TaskCore SQL statementT-SQL addition
Read rowsSELECT ... FROM ... WHERETOP (n) to limit rows
Hold a value in a scriptNot part of a single statementDECLARE @name type
Handle failuresNot part of a single statementBEGIN TRY ... BEGIN CATCH
Group changes so they succeed or fail togetherNot part of a single statementBEGIN TRANSACTION, COMMIT, ROLLBACK

The third column is not a complete list of what T-SQL adds. It is the set of features this article opens in Microsoft's documentation, and they are the ones you meet first.

T-SQL syntax basics

Keywords are written in uppercase by convention. Microsoft's syntax conventions page lists UPPERCASE for Transact-SQL keywords, and says data types in code blocks are rendered in uppercase too, such as INT and VARCHAR(255). Object names can be qualified with up to four parts: server_name.database_name.schema_name.object_name. Most of the time you only need schema_name.object_name, for example dbo.Cars. The documentation recommends specifying the schema name whenever you reference a schema-scoped object, to avoid name resolution errors.

The semicolon is the statement terminator. The docs say it "isn't required for most statements in this version of SQL Server, it will be required in a future version", so it is a good habit to end every statement with one.

Unicode string constants are prefixed with N, as in N'Deleting a Job Candidate'. Without the prefix, Microsoft notes, the string is converted to the default code page of the database, "which might not recognize certain characters".

Variables in T-SQL

Local variable names start with @. Per the DECLARE documentation, variables "are declared in the body of a batch or procedure with the DECLARE statement and are assigned values by using either a SET or SELECT statement", and they start as NULL unless you give a value in the declaration. Example:

DECLARE @min_price MONEY = 9000;

SELECT Model, Price
FROM dbo.Cars
WHERE Price >= @min_price
ORDER BY Price;

Two limits are worth knowing. The scope of a local variable is the batch in which it is declared, so a variable from one batch is gone after a GO separator. And variables can be used only in expressions, "not in place of object names or keywords", so you cannot put a table name in a variable and select from it directly. For that, the documentation points to EXECUTE for building dynamic SQL statements. Dynamic SQL built from user input is where injection bugs come from, so read SQL injection explained before you use it.

Limiting rows with TOP

T-SQL has its own way to cap a result. Microsoft describes TOP as limiting "the rows returned in a query result set to a specified number of rows or percentage of rows".

SELECT TOP (3) Model, Price
FROM dbo.Cars
ORDER BY Price DESC;

Always pair TOP with ORDER BY. Without it, the documentation says TOP returns "the first n number of rows in an undefined order", and its best-practices section calls ORDER BY "the only way to predictably indicate which rows are affected by TOP". Two options change the behaviour. TOP (5) PERCENT returns a percentage of rows and rounds a fractional row count up to the next whole number. WITH TIES requires ORDER BY and can return more rows than you asked for: if you ask for 5 and two more rows match the sort values of row 5, you get 7 rows.

For paging, Microsoft recommends OFFSET and FETCH in the ORDER BY clause instead of TOP, and says you cannot combine the two in the same query scope.

Error handling with TRY...CATCH

T-SQL has structured error handling that Microsoft describes as "similar to the exception handling in the C# and Visual C++ languages". Statements go in a TRY block, and if an error occurs, "control passes to the first statement in the associated CATCH block".

BEGIN TRY
    SELECT 1 / 0;
END TRY
BEGIN CATCH
    SELECT ERROR_NUMBER() AS ErrorNumber,
           ERROR_MESSAGE() AS ErrorMessage;
END CATCH;

Inside the CATCH block you can call ERROR_NUMBER(), ERROR_SEVERITY(), ERROR_STATE(), ERROR_PROCEDURE(), ERROR_LINE() and ERROR_MESSAGE(). Outside a CATCH block they return NULL. Three limits from the documentation catch people out:

  • It catches errors with a severity higher than 10 that do not close the database connection. Warnings and informational messages of severity 10 or lower are not caught.
  • Compile errors such as syntax errors, and object name resolution errors at the same level of execution, are not caught. They are returned to the level that ran the batch. A SELECT from a table that does not exist is the documented example.
  • A TRY...CATCH construct cannot span multiple batches, and it cannot be used in a user-defined function.

Errors caught by CATCH are not sent to the calling application automatically. In Microsoft's words, "if any part of the error information must be returned to the application, the code in the CATCH block must do so", for example with a SELECT result set or RAISERROR.

Transactions: all changes succeed or none do

BEGIN TRANSACTION "marks the starting point of an explicit, local transaction", which ends with COMMIT or ROLLBACK. A commit makes the changes a permanent part of the database, and a rollback erases them.

BEGIN TRANSACTION;

UPDATE dbo.Accounts SET Balance = Balance - 100 WHERE AccountID = 1;
UPDATE dbo.Accounts SET Balance = Balance + 100 WHERE AccountID = 2;

COMMIT TRANSACTION;

The table names here are made up for illustration. Combined with TRY...CATCH, the usual pattern is to roll back in the CATCH block. The documentation's own example checks @@TRANCOUNT first, so you never roll back when no transaction is open:

BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRANSACTION;
END CATCH;

Do not leave a transaction open. Microsoft warns that transactions left outstanding for long periods can keep other sessions from reaching locked resources and can prevent transaction log truncation. The docs also note that nested transactions are not independent: a rollback of an inner transaction always rolls back the outer one, unless a savepoint exists and is named in the ROLLBACK.

Where to run T-SQL

Microsoft lists these tools that send T-SQL to the database: SQL Server Management Studio (SSMS), the MSSQL extension for Visual Studio Code, SQL Server Data Tools (SSDT) and the sqlcmd utility. Pressing F1 on a keyword in the SSMS query editor opens the matching reference article.

To try the examples above you need a database you are allowed to change. Create a scratch database and a small dbo.Cars table first, and do not run UPDATE or DELETE statements against a production database without a WHERE clause and a transaction you can roll back.

When T-SQL is the wrong thing to learn first

If your database is PostgreSQL, MySQL or SQLite, T-SQL is not what you need. Start with standard SELECT queries and the dialect your product documents. The core skills carry over, but the procedural parts differ by vendor, so a script full of DECLARE @x and TOP will not run unchanged elsewhere. If your database is SQL Server or any of the Azure SQL services, T-SQL is the language it expects.

Frequently asked questions

Is T-SQL the same as SQL?
No. SQL is the general language for relational databases, and T-SQL is Microsoft's version of it. Basic statements such as SELECT, INSERT, UPDATE and DELETE look the same, but T-SQL adds its own features, such as local variables, TRY...CATCH and the TOP clause, that other database products do not necessarily support in the same form.
Which databases use T-SQL?
Microsoft's documentation lists SQL Server, Azure SQL Database, Azure SQL Managed Instance, Azure Synapse Analytics and Microsoft Fabric as products covered by the Transact-SQL reference. Each article has an 'Applies to' label, and a feature is not available in a product that the label omits.
Is T-SQL hard to learn if I already know SQL?
Not usually. If you can write SELECT queries with joins and filters, you already know the core. The new parts are the procedural pieces: declaring variables, controlling flow, handling errors and wrapping work in transactions. You can add them one at a time.
What tools can run T-SQL?
Microsoft names SQL Server Management Studio, the MSSQL extension for Visual Studio Code, SQL Server Data Tools and the sqlcmd utility as tools that send T-SQL commands to the database.

Sources