Skip to content
  • Transactions & ACID · SQL

Transactions & ACID

LearnViaNotes @learnvianotes· 3 min read

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

PropertyGuaranteeMechanism
AtomicityAll statements succeed, or none take effectUndo/rollback log
ConsistencyEach transaction moves the DB from one valid state to another (constraints hold)Constraints, triggers, your logic
IsolationConcurrent transactions don't see each other's partial work (to a chosen degree)Locks and/or MVCC snapshots
DurabilityOnce committed, changes survive crashes and power lossWrite-ahead log (WAL) flushed to disk

BEGIN, COMMIT, ROLLBACK

SQL
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;
Output
id | owner | balance
---+-------+--------
1  | Asha  | 800
2  | Ravi  | 700
SQL
BEGIN;
UPDATE accounts SET balance = balance - 200 WHERE id = 1;
-- …the app detects a problem before crediting Ravi
ROLLBACK;

SELECT * FROM accounts ORDER BY id;
Output
id | owner | balance
---+-------+--------
1  | Asha  | 1000
2  | Ravi  | 500

When a statement fails

A transfer of 1500 breaks the CHECK (balance >= 0) constraint on the debit:

SQL
BEGIN;
UPDATE accounts SET balance = balance + 1500 WHERE id = 2;   -- credit first
UPDATE accounts SET balance = balance - 1500 WHERE id = 1;   -- fails
COMMIT;
Error
CHECK constraint failed: balance >= 0

Savepoints: partial rollback

SQL
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;
Output
id | owner | balance
---+-------+--------
1  | Asha  | 1000
2  | Ravi  | 500
3  | Meera | 300

Autocommit

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?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report