Isolation Levels

Concurrency Anomalies

AnomalyWhat happens
Dirty readT1 reads a row T2 changed but has not committed; T2 rolls back, so T1 used data that never existed
Non-repeatable readT1 reads a row twice and gets different values because T2 committed an update in between
Phantom readT1 runs the same query twice and new rows appear because T2 inserted them
Lost updateT1 and T2 read the same value, both update it, and one change overwrites the other

The Four SQL Standard Levels

Isolation levelDirty readNon-repeatable readPhantom read
READ UNCOMMITTEDpossiblepossiblepossible
READ COMMITTEDpreventedpossiblepossible
REPEATABLE READpreventedpreventedpossible*
SERIALIZABLEpreventedpreventedprevented

* 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.