Sub topic 5
Phantom reads
This chapter assumes you know the dirty read and the non-repeatable read from the previous chapters. It also assumes you can run two psql sessions side by side, or two MySQL clients. A phantom read is the third read anomaly in the SQL standard. It is the one that row-level protection cannot stop, and it explains most of the differences between the standard levels and real engines.
What a phantom read is
A phantom read happens when a transaction runs the same query twice, using a search condition, and the second run returns a different set of rows. The difference comes from rows that another transaction inserted or deleted, or from rows that another transaction changed so that they now match or no longer match the condition. The rows that appear or vanish are called phantoms.
The query must select by a predicate, such as WHERE status = 'open' or WHERE total > 100. A predicate describes a set of rows, and that set includes rows that do not exist yet.
Here is the standard example. The schedule uses PostgreSQL at its default level, READ COMMITTED.
-- Setup
CREATE TABLE orders (id serial PRIMARY KEY, customer text NOT NULL, total int NOT NULL);
INSERT INTO orders (customer, total) VALUES ('ann', 120), ('bob', 150);
-- Session A
BEGIN;
SELECT count(*), sum(total) FROM orders WHERE total > 100; -- 2, 270
-- Session B
BEGIN;
INSERT INTO orders (customer, total) VALUES ('cy', 200);
COMMIT;
-- Session A
SELECT count(*), sum(total) FROM orders WHERE total > 100; -- 3, 470: a phantom
COMMIT;Session A never saw row cy the first time. The second query finds it, so the result set changed inside one transaction.
How it differs from a non-repeatable read
A non-repeatable read means a row you already read has changed. A phantom read means the set of rows matching your condition has changed.
| Anomaly | What changes between the two reads | What it needs |
|---|---|---|
| Non-repeatable read | The value in a row you already read | An `UPDATE` or `DELETE` on that row, committed by another transaction |
| Phantom read | Which rows match the predicate | An `INSERT`, `DELETE`, or an `UPDATE` that moves a row into or out of the predicate |
The difference matters because of how each is prevented. If a transaction locks every row it reads, nobody can change those rows, which stops non-repeatable reads. That does nothing for a row that is not in the table yet, because there is nothing to lock. Stopping phantoms requires protecting the predicate itself, not only the rows found by it.
Why row locks are not enough
Consider a locking database. Session A runs SELECT ... WHERE total > 100 and takes shared locks on the two rows it finds. Session B inserts a third row. The insert touches a new row, which A holds no lock on, so it succeeds. A's locks gave it a stable view of two rows and no protection against a third.
To prevent this, a locking engine must lock something wider than the rows found. There are three common forms:
- Predicate locks lock the condition itself, so any insert that would match is blocked. This is conceptually clean but expensive to check, and few engines use it in pure form.
- Index-range locks lock the range of an index that the query scanned, including the gaps between index entries. Inserts that fall into a locked range wait. SQL Server's key-range locks and InnoDB's next-key locks work this way.
- Table locks block all inserts. They are simple but remove nearly all concurrency.
Index-range locks only protect what the query actually scanned through an index. If the predicate has no useful index, the engine may scan, and therefore lock, far more than you intended, up to the entire table.
Phantoms in the standard
The SQL standard defines phantom reads as one of three phenomena and uses them to define the levels. SERIALIZABLE is the only level that must forbid them. REPEATABLE READ is allowed to permit them.
| Level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| `READ UNCOMMITTED` | Allowed | Allowed | Allowed |
| `READ COMMITTED` | Prevented | Allowed | Allowed |
| `REPEATABLE READ` | Prevented | Prevented | Allowed |
| `SERIALIZABLE` | Prevented | Prevented | Prevented |
This table describes what the standard permits, not what every engine does. Several engines prevent more than the standard requires.
What real engines do
PostgreSQL
At READ COMMITTED, every statement takes a fresh snapshot, so the example above produces a phantom. At REPEATABLE READ, the transaction uses one snapshot taken at its first statement, so rows inserted afterwards are invisible. PostgreSQL's REPEATABLE READ therefore prevents phantoms for reads, which is stronger than the standard demands.
-- Session A
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM orders WHERE total > 100; -- 3
-- Session B
INSERT INTO orders (customer, total) VALUES ('di', 300); -- autocommits
-- Session A
SELECT count(*) FROM orders WHERE total > 100; -- still 3
COMMIT;MySQL InnoDB
InnoDB's default is REPEATABLE READ. A plain SELECT there reads from a snapshot, so it does not see phantoms. Statements that read the latest data behave differently. These are SELECT ... FOR UPDATE, SELECT ... FOR SHARE, UPDATE and DELETE. Under InnoDB's default REPEATABLE READ, locking reads and writes use next-key locks, which lock index records and the gaps before them, so concurrent inserts into the scanned range wait. A locking read or write that finds rows will see the committed data, not the snapshot.
This combination produces a documented surprise. Suppose a tasks table has two rows with status = 'open'.
-- Session A (MySQL, REPEATABLE READ)
START TRANSACTION;
SELECT count(*) FROM tasks WHERE status = 'open'; -- 2
-- Session B
INSERT INTO tasks (title, status) VALUES ('new', 'open'); -- autocommits
-- Session A
SELECT count(*) FROM tasks WHERE status = 'open'; -- still 2 (snapshot)
UPDATE tasks SET status = 'closed' WHERE status = 'open'; -- affects 3 rows
SELECT count(*) FROM tasks WHERE status = 'closed'; -- 3, includes B's row
COMMIT;Once A modifies B's row, that row becomes part of A's own work and A sees it. The plain SELECT showed no phantom, but the transaction as a whole did observe one. Mixing snapshot reads with locking reads or writes in one transaction is where InnoDB's REPEATABLE READ can surprise you.
SQL Server and Oracle
In SQL Server, REPEATABLE READ holds shared locks on the rows it has read, so those rows cannot change, but other transactions can still insert matching rows. Phantoms are possible there. SERIALIZABLE adds key-range locks, which block inserts into the scanned range. The optional SNAPSHOT level avoids phantoms with row versions instead of locks.
Oracle has no REPEATABLE READ level. Its default is READ COMMITTED, where phantoms occur. Its SERIALIZABLE level is snapshot-based, so it prevents phantoms in reads, but, as the next section shows, it does not give true serializability.
| Engine | Phantom possible at | Phantom prevented at |
|---|---|---|
| PostgreSQL | `READ COMMITTED` | `REPEATABLE READ`, `SERIALIZABLE` |
| MySQL InnoDB | `READ COMMITTED`; locking reads and writes mixed with snapshot reads at `REPEATABLE READ` | `SERIALIZABLE`, and plain reads at `REPEATABLE READ` |
| SQL Server | `READ COMMITTED`, `REPEATABLE READ` | `SERIALIZABLE`, `SNAPSHOT` |
| Oracle | `READ COMMITTED` | `SERIALIZABLE` (snapshot-based) |
Phantoms that break writes
A snapshot hides phantoms from your reads, but it does not stop another transaction from inserting a row that makes your decision wrong. The usual shape is check-then-insert: look for a conflicting row, find none, and insert.
-- Setup
CREATE TABLE bookings (
id serial PRIMARY KEY,
room int NOT NULL,
slot int NOT NULL
);
-- Both sessions run at REPEATABLE READ and check the same slot
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM bookings WHERE room = 7 AND slot = 9; -- 0 in both sessions
INSERT INTO bookings (room, slot) VALUES (7, 9);
COMMIT; -- both commits succeedEach transaction inserts a different row, so snapshot isolation finds no write conflict. Both commits succeed and the room is double-booked. This is a phantom, since the row you were looking for appeared after your check. It is also a form of write skew, which a later chapter covers.
You have three ways to fix it:
- Add a constraint so the database enforces the rule itself. For this example,
ALTER TABLE bookings ADD CONSTRAINT one_booking UNIQUE (room, slot);makes the second insert fail with a unique violation. This is the best option when the rule can be expressed as a constraint. - Run both transactions at
SERIALIZABLE. PostgreSQL then aborts one with SQLSTATE40001, and the application retries it. - Lock something that both transactions share, such as a parent row for the room, using
SELECT ... FOR UPDATEbefore the check. Locking the rows the check found does not work, because no rows were found.
Common mistakes
- Assuming
REPEATABLE READmeans the same thing everywhere. It forbids phantom reads in PostgreSQL, allows them in SQL Server, and in InnoDB depends on whether a statement is a plain read or a locking one. - Relying on a row count taken earlier in the transaction to guard a later insert, without a constraint or a serializable level.
- Locking with a predicate that has no index on InnoDB or SQL Server. The engine may lock a large range or the whole table, which causes waits and deadlocks.
- Running
SERIALIZABLEwithout retry logic. Aborts are part of the contract and must be handled.
Exercise
In PostgreSQL, Session A starts a transaction at REPEATABLE READ and runs SELECT count(*) FROM orders WHERE total > 100, which returns 3. Session B inserts a matching order and commits. Session A runs the same count again. What does it return, and does this violate the SQL standard's definition of REPEATABLE READ?
Show answer
It returns 3. The standard allows phantoms at REPEATABLE READ but does not require them, and PostgreSQL's snapshot is fixed at the first statement. Preventing them is stronger than the standard requires, so nothing is violated.
Exercise
Two sessions each check that no booking exists for room 7, slot 9, then insert one. Both run at REPEATABLE READ in PostgreSQL and both commit. Name the cheapest fix that does not require retry logic, and say why SELECT ... FOR UPDATE on the check query does not work.
Show answer
Add a UNIQUE (room, slot) constraint, so the second insert fails immediately. FOR UPDATE does not work because the check query returns no rows, so there is nothing to lock in PostgreSQL, and the other session's insert is not blocked.