SQL Server Interview Question #141
What is a transaction in SQL Server?
Transactions, Locking, Blocking & Deadlocks Senior Advanced
Detailed Explanation
A transaction is a logical unit of work containing one or more database operations that should be treated as a single consistent operation.
If all required statements succeed, the transaction can be committed. If a failure occurs, the transaction can be rolled back. Transactions are essential for operations such as transferring money, creating an order together with its order items, or updating multiple related tables.
Code Example
BEGIN TRANSACTION;
UPDATE dbo.Accounts
SET Balance = Balance - 1000
WHERE Id = 1;
UPDATE dbo.Accounts
SET Balance = Balance + 1000
WHERE Id = 2;
COMMIT TRANSACTION;