Sub topic 5
Phantom Reads
Prerequisites and the problem
This chapter assumes you know basic SQL, primary keys, and the use of BEGIN, COMMIT, and ROLLBACK. You should also understand that two database clients can run transactions at the same time.
A phantom read occurs when a transaction repeats a query and finds new or missing rows that match the same search condition. The rows are called “phantoms” because they appear between two reads.
A phantom is different from a non-repeatable read:
- A non-repeatable read sees a changed value in an existing row.
- A phantom read sees a changed set of rows because another transaction inserted, deleted, or changed rows so that they now match the condition.
A phantom read schedule
Suppose an application checks whether an order total is below a spending limit. Session A reads all pending orders for a customer. Session B inserts another matching order and commits. When Session A repeats its query, it sees an extra row.
-- Setup
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer NOT NULL,
status varchar(20) NOT NULL,
total numeric(10, 2) NOT NULL
);
INSERT INTO orders VALUES (1, 7, 'pending', 40.00);
-- Session A, using READ COMMITTED
BEGIN;
SELECT id, total
FROM orders
WHERE customer_id = 7 AND status = 'pending';
-- Returns one row: order 1
-- Session B runs while Session A is still open:
BEGIN;
INSERT INTO orders VALUES (2, 7, 'pending', 30.00);
COMMIT;
-- Session A repeats the same query:
SELECT id, total
FROM orders
WHERE customer_id = 7 AND status = 'pending';
-- Returns two rows: orders 1 and 2
COMMIT;Session A did not reread a changed version of order 1. It read a different result set because a new row appeared in its search range.
Why row locks are not always enough
A lock on the rows returned by the first query does not necessarily protect the gaps where new rows could be inserted. The database must protect the predicate, meaning the condition that defines the matching set.
For the query above, the predicate is:
customer_id = 7 AND status = 'pending'A database can protect this predicate with range locks, index-gap locks, or a transaction snapshot. The exact mechanism depends on the database engine and the query plan.
Isolation levels and phantoms
The SQL standard describes phantom behavior this way:
| Isolation level | Phantom reads permitted? | Typical meaning |
|---|---|---|
| READ UNCOMMITTED | Yes | Uncommitted and changing data may be visible |
| READ COMMITTED | Yes | Each statement can see a newer committed result set |
| REPEATABLE READ | Yes in the standard | Existing row values remain stable, but matching rows may change |
| SERIALIZABLE | No | Concurrent execution must preserve serial transaction behavior |
The standard describes minimum guarantees. Database engines often provide stronger behavior. For example, PostgreSQL's REPEATABLE READ uses one transaction snapshot, so repeated ordinary queries see the same committed row set. MySQL InnoDB also uses consistent snapshots for ordinary reads at REPEATABLE READ, while locking reads use different locking rules.
Preventing phantom reads
Use SERIALIZABLE when the correctness rule depends on the complete result set. The database may block a concurrent transaction or abort one transaction with a serialization error. Applications must retry that transaction.
For narrower operations, an explicit locking query may be simpler. In engines that support it, SELECT ... FOR UPDATE can lock existing rows, but it may not protect an empty range unless the engine uses suitable range or predicate locks.
Exercise
Session A repeats SELECT COUNT(*) FROM orders WHERE status = 'pending' and sees the count increase after Session B commits an insert. What anomaly occurred, and which SQL standard isolation level forbids it?
Show answer
This is a phantom read. The SERIALIZABLE isolation level forbids it.