SQL Server › Transactions & ACID
What is a transaction in SQL Server, and why is grouping multiple statements into one important?
BeginnerAnswer
A transaction groups one or more SQL statements together so they are treated as a single unit of work, meaning either all of the statements succeed together and their changes are saved, or if something goes wrong, all of the changes are undone together, protecting your data from being left in an inconsistent, partially updated state.
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 100 WHERE AccountId = 1;
UPDATE Accounts SET Balance = Balance + 100 WHERE AccountId = 2;
COMMIT TRANSACTION;Real-world example A bank transfer uses a transaction to ensure that money is either successfully moved from one account to another completely, or not moved at all if something fails, preventing money from disappearing or being duplicated.