Phantom Reads

Difficulty: Advanced

Question

What is a phantom read, and which transaction isolation levels prevent it?

Answer

A phantom read happens when a transaction runs the same range query twice and the second run returns a different set of rows, because another transaction inserted or deleted rows matching the condition and committed in between. The rows themselves were not changed; new ones "appeared" like phantoms. The SQL standard allows phantoms under READ UNCOMMITTED, READ COMMITTED and REPEATABLE READ, and forbids them only under SERIALIZABLE, but real databases often do better than the standard minimum.

A concrete example

Transaction A checks seat availability for a bus on a booking site:

  1. A: SELECT count(*) FROM bookings WHERE bus_id = 12 AND seat_class = 'sleeper' returns 29.
  2. B: inserts a new sleeper booking for bus 12 and commits.
  3. A: runs the same query again and gets 30.

Nothing A read was modified. A new matching row appeared, so A's earlier decision ("one seat left, allow the booking") is based on a result that no longer holds.

Phantom vs non-repeatable read vs dirty read

AnomalyWhat changes between readsExample
Dirty readYou see another transaction's uncommitted changeReading a balance that is later rolled back
Non-repeatable readAn existing row's values changeSame row's price goes from 100 to 120
Phantom readThe set of rows matching a condition changesA new row appears in a WHERE range

The key difference: non-repeatable reads are about existing rows being updated; phantoms are about rows entering or leaving the result set.

What real databases do

  • PostgreSQL REPEATABLE READ uses snapshot isolation: the transaction sees one snapshot taken at its first statement, so plain re-reads never see phantoms. It is stronger than the standard requires. It still allows write skew, where two transactions each read a range, decide based on it, and insert rows that together break a rule.
  • PostgreSQL SERIALIZABLE uses Serializable Snapshot Isolation (SSI) with predicate (SIRead) locks. It detects dangerous patterns and aborts one transaction with a serialization failure (SQLSTATE 40001), which the app must retry.
  • MySQL InnoDB REPEATABLE READ (the default) uses a consistent snapshot for plain SELECTs, so they do not see phantoms. Locking reads (SELECT ... FOR UPDATE, UPDATE, DELETE) read the latest data and take next-key locks (row plus gap locks) that block other transactions from inserting into the scanned range.
  • SQL Server prevents phantoms under SERIALIZABLE with key-range locks; its SNAPSHOT level behaves like snapshot isolation.

How to protect against phantom-driven bugs

  • Use SERIALIZABLE for invariants over ranges and handle retries.
  • Lock the parent row first (SELECT ... FROM buses WHERE id = 12 FOR UPDATE) so concurrent bookings for the same bus serialize.
  • Enforce the rule with a constraint where possible: a UNIQUE (bus_id, seat_no) index, or a PostgreSQL exclusion constraint for overlapping time ranges.
  • In MySQL, use locking reads so gap locks protect the range.
A phantom row appearing mid-transaction. Transaction A repeats its range query and sees a row that B inserted and committed.
  1. Transaction A → Database: SELECT count(*) WHERE bus_id = 12
  2. Database → Transaction A: Returns 29 rows
  3. Transaction B → Database: INSERT booking for bus 12
  4. Transaction B → Database: COMMIT
  5. Transaction A → Database: Same SELECT again
  6. Database → Transaction A: Returns 30 rows (phantom)

Code examples

Preventing phantom-driven overbooking in PostgreSQL

-- Option 1: SERIALIZABLE, retry on SQLSTATE 40001
BEGIN ISOLATION LEVEL SERIALIZABLE;
SELECT count(*) FROM bookings WHERE bus_id = 12 AND seat_class = 'sleeper';
-- app checks count < capacity, then:
INSERT INTO bookings (bus_id, seat_class, seat_no, user_id)
VALUES (12, 'sleeper', 'L7', 501);
COMMIT;  -- may fail with a serialization error; retry the whole transaction

-- Option 2: serialize on the parent row
BEGIN;
SELECT id FROM buses WHERE id = 12 FOR UPDATE;   -- concurrent bookers wait here
SELECT count(*) FROM bookings WHERE bus_id = 12 AND seat_class = 'sleeper';
INSERT INTO bookings (bus_id, seat_class, seat_no, user_id)
VALUES (12, 'sleeper', 'L7', 501);
COMMIT;

SERIALIZABLE detects the conflict and aborts one transaction, while locking the parent row forces bookings for the same bus to run one at a time.

Key points

  • Phantom read: a repeated range query returns a different set of rows due to committed inserts or deletes.
  • Non-repeatable read is about changed values in existing rows; phantom is about new or removed rows.
  • SQL standard: only SERIALIZABLE forbids phantoms.
  • PostgreSQL REPEATABLE READ prevents phantoms via snapshots but allows write skew.
  • MySQL InnoDB uses next-key (gap) locks on locking reads to block phantom inserts.

Common follow-up questions

  • What is write skew and why does snapshot isolation allow it?
  • How do gap locks and next-key locks work in InnoDB?
  • How should an application handle serialization failures?
  • What is the default isolation level in PostgreSQL and MySQL?

Interview tips

  • Clearly separate phantom reads from non-repeatable reads; interviewers test exactly this distinction.
  • Mention that real databases differ from the SQL standard table, citing PostgreSQL or InnoDB behaviour.
  • Use a business example like seat booking to show why phantoms cause real bugs.

Concepts covered

Phantom Read, Isolation Levels, Gap Locks, Snapshot Isolation, Serializable

More Database Design questions