Difficulty: Advanced
What is a phantom read, and which transaction isolation levels prevent it?
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.
Transaction A checks seat availability for a bus on a booking site:
SELECT count(*) FROM bookings WHERE bus_id = 12 AND seat_class = 'sleeper' returns 29.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.
| Anomaly | What changes between reads | Example |
|---|---|---|
| Dirty read | You see another transaction's uncommitted change | Reading a balance that is later rolled back |
| Non-repeatable read | An existing row's values change | Same row's price goes from 100 to 120 |
| Phantom read | The set of rows matching a condition changes | A 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.
40001), which the app must retry.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.SELECT ... FROM buses WHERE id = 12 FOR UPDATE) so concurrent bookings for the same bus serialize.UNIQUE (bus_id, seat_no) index, or a PostgreSQL exclusion constraint for overlapping time ranges.-- 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.
Phantom Read, Isolation Levels, Gap Locks, Snapshot Isolation, Serializable