A transaction groups several statements into one unit of work that either fully happens or not at all. It is what makes a money transfer safe.
ACID
| Property | Guarantee | Mechanism |
|---|---|---|
| Atomicity | All statements succeed, or none take effect | Undo/rollback log |
| Consistency | Each transaction moves the DB from one valid state to another (constraints hold) | Constraints, triggers, your logic |
| Isolation | Concurrent transactions don't see each other's partial work (to a chosen degree) | Locks and/or MVCC snapshots |
| Durability | Once committed, changes survive crashes and power loss | Write-ahead log (WAL) flushed to disk |
BEGIN, COMMIT, ROLLBACK
BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
UPDATE accounts SET balance = balance + 200 WHERE id = 2;
COMMIT;
SELECT * FROM accounts ORDER BY id;id | owner | balance
---+-------+--------
1 | Asha | 800
2 | Ravi | 700BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
-- …the app detects a problem before crediting Ravi
ROLLBACK;
SELECT * FROM accounts ORDER BY id;id | owner | balance
---+-------+--------
1 | Asha | 1000
2 | Ravi | 500When a statement fails
A transfer of 1500 breaks the CHECK (balance >= 0) constraint on the debit:
BEGIN;
UPDATE accounts SET balance = balance + 1500 WHERE id = 2; -- credit first
UPDATE accounts SET balance = balance - 1500 WHERE id = 1; -- fails
COMMIT;CHECK constraint failed: balance >= 0Savepoints: partial rollback
BEGIN;
INSERT INTO accounts VALUES (3, 'Meera', 300);
SAVEPOINT before_bonus;
UPDATE accounts SET balance = balance + 10000 WHERE id = 3; -- mistake
ROLLBACK TO before_bonus; -- undo only the bonus
COMMIT;
SELECT * FROM accounts ORDER BY id;id | owner | balance
---+-------+--------
1 | Asha | 1000
2 | Ravi | 500
3 | Meera | 300Autocommit
Outside an explicit BEGIN, most engines run in autocommit mode: every statement is its own transaction. Oracle is the exception — a transaction starts implicitly and you must COMMIT. Python's DB-API and many drivers open transactions for you and require conn.commit().
Explain ACID with a bank transfer.
What is the difference between COMMIT and ROLLBACK?