Careeroza
Isolation Levels
Concurrency Anomalies
| Anomaly | What happens |
|---|---|
| Dirty read | T1 reads a row T2 changed but has not committed; T2 rolls back, so T1 used data that never existed |
| Non-repeatable read | T1 reads a row twice and gets different values because T2 committed an update in between |
| Phantom read | T1 runs the same query twice and new rows appear because T2 inserted them |
| Lost update | T1 and T2 read the same value, both update it, and one change overwrites the other |
The Four SQL Standard Levels
| Isolation level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| READ UNCOMMITTED | possible | possible | possible |
| READ COMMITTED | prevented | possible | possible |
| REPEATABLE READ | prevented | prevented | possible* |
| SERIALIZABLE | prevented | prevented | prevented |
* MySQL InnoDB and PostgreSQL also prevent phantoms at REPEATABLE READ.
Defaults: READ COMMITTED in PostgreSQL, SQL Server and Oracle; REPEATABLE READ in MySQL InnoDB.
Setting the Level
-- SQL Server / MySQL (next transaction)
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
BEGIN TRANSACTION;
...
COMMIT;
-- PostgreSQL
BEGIN ISOLATION LEVEL REPEATABLE READ;
...
COMMIT;Tip: Higher isolation means fewer anomalies but more blocking or more transactions failing with serialization errors that must be retried.