Sub topic 2
Isolation: concurrent transactions without interference
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), tables with primary keys and constraints, and that several sessions can use one database at the same time.
Isolation: concurrent transactions without interference
Isolation means each transaction should behave as if no other transaction runs at the same time. The database achieves this with locks, snapshots, or both. How strict it is depends on the isolation level you choose, covered below.
Durability: committed data survives failure
Durability means that once COMMIT returns, the change survives a crash. The database writes each change to a write-ahead log (WAL), an append-only file on disk, before it commits. After a crash, the database replays the log to restore committed work and discards uncommitted work.
Concurrency anomalies: what goes wrong without isolation
| Anomaly | What happens |
|---|---|
| Dirty read | You read data another transaction has not committed, and that transaction may roll back. |
| Non-repeatable read | Reading the same row twice returns different values because another transaction committed a change between reads. |
| Phantom read | Re-running a query returns new rows that another transaction inserted. |
| Lost update | Two transactions read the same value and write back their own results, so one update overwrites the other. |
| Write skew | Two transactions each check a condition over different rows, then update, and together break a rule. |
Isolation levels and what each one prevents
In PostgreSQL, Read Uncommitted behaves like Read Committed. Repeatable Read uses a snapshot taken at the first query, so it also prevents phantom reads. Serializable detects anomalies such as write skew and aborts one transaction. Stronger levels cost more, because they block more often or abort more transactions.
Savepoints and partial rollback
A savepoint marks a point inside a transaction. ROLLBACK TO SAVEPOINT undoes only the work after that mark, and the rest of the transaction can still commit.
CREATE TABLE accounts (
id integer PRIMARY KEY,
balance numeric(12,2) NOT NULL CHECK (balance >= 0)
);
INSERT INTO accounts (id, balance) VALUES (1, 100.00), (2, 50.00);
BEGIN;
UPDATE accounts SET balance = balance - 10 WHERE id = 1;
SAVEPOINT before_bonus;
UPDATE accounts SET balance = balance + 1000 WHERE id = 2;
ROLLBACK TO SAVEPOINT before_bonus;
COMMIT;
SELECT id, balance FROM accounts ORDER BY id;
-- id 1 = 90.00, id 2 = 50.00Exercise
Exercise
Which isolation level in PostgreSQL prevents write skew, and what must the application do when it occurs?
Show answer
Serializable prevents write skew. The database aborts one of the conflicting transactions with SQLSTATE 40001 (serialization_failure), so the application must retry that transaction.