← Back to SQL, page 12

sql-0226 · Medium mid

Name the read anomalies that isolation levels are defined by, and which levels prevent each.

Dirty read: seeing another transaction's uncommitted change. Non-repeatable read: reading the same row twice and getting different committed values. Phantom read: rerunning a range query and finding new rows. READ UNCOMMITTED allows all three, READ COMMITTED prevents dirty reads, REPEATABLE READ also prevents non-repeatable reads, and SERIALIZABLE prevents all three plus other anomalies such as write skew.

Full answer

The SQL standard defines four levels by which anomalies they forbid:

text
Level              Dirty read  Non-repeatable  Phantom
READ UNCOMMITTED   possible    possible        possible
READ COMMITTED     no          possible        possible
REPEATABLE READ    no          no              possible
SERIALIZABLE       no          no              no

Real engines are often stricter than the table requires:

  • PostgreSQL treats READ UNCOMMITTED as READ COMMITTED, and its REPEATABLE READ (snapshot isolation) also prevents phantoms. Its default is READ COMMITTED.
  • MySQL InnoDB defaults to REPEATABLE READ.
  • SQLite transactions are serializable, because only one writer runs at a time and readers see a consistent snapshot.

PostgreSQL's default can be read directly:

sql
SHOW default_transaction_isolation;
default_transaction_isolation
read committed

The table leaves out lost updates and write skew, which matter just as much in practice and are covered separately.

Key points

  • Dirty, non-repeatable and phantom reads define the standard levels
  • Each stronger level forbids one more anomaly
  • PostgreSQL defaults to READ COMMITTED; InnoDB to REPEATABLE READ
  • SQLite transactions are serializable

Common mistakes

  • Assuming every engine's REPEATABLE READ behaves the same
  • Forgetting lost updates and write skew

Follow-ups

  • What is write skew?
  • Why might you not run everything at SERIALIZABLE?

Tips

  • Draw the table from memory