Sub topic 2
Phantom Reads
This chapter assumes you know basic SQL, BEGIN, COMMIT and ROLLBACK, and that several clients use one database at the same time.
Phantom reads
A phantom read happens when a query runs twice in one transaction and the second run returns extra rows. Another transaction inserted rows that match the filter and committed between the two reads. The rows that were already there are unchanged. Only the set of matching rows grows.
The four SQL standard isolation levels
The SQL standard defines four isolation levels. Each one forbids some anomalies and allows others:
- READ UNCOMMITTED allows dirty reads, non-repeatable reads and phantom reads.
- READ COMMITTED forbids dirty reads. It allows non-repeatable reads and phantom reads.
- REPEATABLE READ forbids dirty and non-repeatable reads. It allows phantom reads.
- SERIALIZABLE forbids all three.
Engines often go further than the standard. PostgreSQL's REPEATABLE READ also blocks phantoms, as covered later in this chapter.
Setting the isolation level in practice
The level applies per transaction. The syntax differs by engine.
-- PostgreSQL: set the level when the transaction starts
BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;
SELECT count(*) FROM orders WHERE status = 'open';
COMMIT;
-- MySQL: set the level for the next transaction in this session
SET TRANSACTION ISOLATION LEVEL SERIALIZABLE;
START TRANSACTION;
SELECT count(*) FROM orders WHERE status = 'open';
COMMIT;SQL Server uses SET TRANSACTION ISOLATION LEVEL with the same standard level names, plus SNAPSHOT.
Lost updates and how to prevent them
A lost update happens when two transactions read a balance, each compute a new value, and write it back. The second write overwrites the first. Under READ COMMITTED, both transactions can read 100, and the final balance reflects only one deposit.
Avoid the read-modify-write pattern. Let the database do the arithmetic in one statement:
UPDATE accounts SET balance = balance + 10 WHERE id = 1;If you must read first, lock the row with SELECT ... FOR UPDATE (PostgreSQL and MySQL).
How databases implement isolation: locks and MVCC
Engines use two main mechanisms. Locking makes a transaction wait for another transaction that holds a conflicting lock. Multiversion concurrency control (MVCC) keeps several versions of each row, so a reader sees a consistent snapshot without waiting for writers. Most engines combine both.
:::exercise Q: A transaction under READ COMMITTED runs the same SELECT twice and gets a new row the second time. Which anomaly is this, and which level forbids it under the standard? A: A phantom read. The standard forbids it only at SERIALIZABLE. :::