Transaction (SQL)
A transaction groups several SQL statements into a single all-or-nothing unit of work. Either every statement succeeds and is saved (COMMIT), or none are (ROLLBACK).
SQL
Transactions protect data when several changes must happen together — for example, transferring money: subtracting from one account and adding to another must both succeed or both fail.
Databases guarantee transactions follow the ACID properties (Atomicity, Consistency, Isolation, Durability). You start one with BEGIN, finalize it with COMMIT, or undo it with ROLLBACK.
Syntax
BEGIN;
-- statements
COMMIT; -- or ROLLBACK;Examples
SQL
BEGIN;
UPDATE accounts SET balance = balance - 100 WHERE id = 1;
UPDATE accounts SET balance = balance + 100 WHERE id = 2;
COMMIT;Output:
Both updates saved together, or neither.