T-SQL Transactions in SQL Server

Transactions are fundamental to ensuring data integrity and consistency in SQL Server. A transaction is a sequence of operations performed as a single logical unit of work. SQL Server guarantees the ACID properties (Atomicity, Consistency, Isolation, Durability) for transactions.

ACID Properties

Transaction Control Language (TCL)

T-SQL provides commands to manage transactions:

BEGIN TRANSACTION

Initiates a new transaction. You can optionally provide a transaction name for easier reference.

BEGIN TRANSACTION MyTransaction;
-- SQL statements here
GO

COMMIT TRANSACTION

Marks the end of a transaction and makes all its changes permanent in the database. This operation commits the transaction.

COMMIT TRANSACTION MyTransaction;
GO

ROLLBACK TRANSACTION

Undoes all changes made during the current transaction since the last BEGIN TRANSACTION. The database is returned to its state before the transaction began.

ROLLBACK TRANSACTION MyTransaction;
GO

SAVE TRANSACTION

Creates a savepoint within a transaction. This allows you to roll back to a specific point within a larger transaction without undoing the entire transaction.

BEGIN TRANSACTION OuterTransaction;
    -- Some operations
    SAVE TRANSACTION SavePoint1;
    -- More operations
    -- If something goes wrong here, we can roll back to SavePoint1
    ROLLBACK TRANSACTION SavePoint1;
    -- Continue with other operations or rollback the entire transaction
    COMMIT TRANSACTION OuterTransaction;
GO

Transaction Isolation Levels

Isolation levels control how one transaction's modifications are visible to other concurrent transactions. Choosing the appropriate isolation level is crucial for balancing data consistency and concurrency performance.

Default Isolation Level

The default isolation level in SQL Server is READ COMMITTED.

Common Isolation Levels

Setting Isolation Levels

You can set the isolation level for the current session using the SET TRANSACTION ISOLATION LEVEL statement.

SET TRANSACTION ISOLATION LEVEL READ COMMITTED;
GO

BEGIN TRANSACTION;
    -- Transaction logic
COMMIT TRANSACTION;
GO

Important: Incorrectly configured transaction isolation levels can lead to data corruption or deadlocks. Always understand the implications before changing the default settings.

Implicit vs. Explicit Transactions

Note: The AUTOCOMMIT mode, where each statement is its own transaction, is the default behavior when IMPLICIT_TRANSACTIONS is OFF.

Best Practices