Dualo
SQL Essentials

Transactions & isolation levels

ACID, what it guarantees, and how isolation levels (Read Committed, Repeatable Read, Serializable) trade consistency for concurrency.

1 min read

A transaction is a group of statements that either ALL succeed or NONE apply. Classic example: transferring 100€ from account A to account B is TWO writes; if the second fails, the first must undo. That grouping is the transaction.

**** describes what a transaction guarantees: **Atomicity** (all-or-nothing), **Consistency** (DB remains valid — all constraints hold before and after), **Isolation** (concurrent transactions don't interfere with each other's intermediate state), **Durability** (once committed, the change survives crashes).

**BEGIN / COMMIT / ROLLBACK**: `BEGIN;` starts a transaction. `COMMIT;` makes changes visible to everyone. `ROLLBACK;` undoes them. In most drivers, one statement without BEGIN = an implicit single-statement transaction (auto-commit).

Isolation levels define HOW STRICT the isolation is. Stricter = safer from data anomalies but less concurrency. Standard levels: Read Uncommitted (lowest — you can see other transactions' uncommitted changes; rare), Read Committed (default in Postgres/Oracle — you see only committed data, but each statement sees a fresh snapshot), Repeatable Read (default in MySQL — within a transaction, re-reading the same row gives the same answer), Serializable (strictest — behaves as if transactions ran one after another).

Classic anomalies each level prevents: Dirty read (seeing uncommitted changes — Read Uncommitted allows, higher levels block). Non-repeatable read (row changes between two reads — Read Committed allows, Repeatable Read blocks). Phantom read (new rows matching your filter appear — Repeatable Read allows in some engines, Serializable blocks).

Grounded on https://www.postgresql.org/docs/current/transaction-iso.html

Next up

Window functions — ranking, running totals, LAG/LEAD

Aggregate without collapsing rows. Ranks, running totals, period-over-period comparisons — the superpower of modern SQL.