MSDN Documentation

Microsoft Developer Network

SQL Transactions

SQL transactions are a fundamental concept in relational database management systems. They allow a sequence of operations to be treated as a single, atomic unit of work. This ensures data integrity and consistency, especially in scenarios involving multiple, interdependent data modifications.

What is a Transaction?

A transaction is a logical unit of work that comprises one or more SQL statements. These statements are executed sequentially. The core principle of a transaction is that either all the operations within it are successfully completed, or none of them are. This is often referred to as the "all or nothing" principle.

ACID Properties

Transactions are governed by the ACID properties to guarantee reliability:

Transaction Control Language (TCL)

SQL provides specific commands to manage transactions:

Example: Transferring Funds

Consider a common scenario: transferring money between two bank accounts. This operation involves two steps: debiting one account and crediting another. Both must succeed or fail together.


-- Assume two accounts: AccountA and AccountB
-- Transfer $100 from AccountA to AccountB

BEGIN TRANSACTION;

UPDATE Accounts
SET Balance = Balance - 100
WHERE AccountID = 'AccountA';

UPDATE Accounts
SET Balance = Balance + 100
WHERE AccountID = 'AccountB';

-- If both updates are successful, commit the transaction
COMMIT;

-- If an error occurs during either update, rollback:
-- ROLLBACK;
            

Isolation Levels

Databases offer different isolation levels to manage the trade-off between data consistency and concurrency. Common levels include:

The default isolation level often varies between database systems.

Best Practices