Video in progress
What are dirty read, non-repeatable read and phantom read? Which ones does PostgreSQL protect against by default?
A dirty read is seeing another transaction's uncommitted change; a non-repeatable read is getting different values when you read the same row twice; a phantom is new rows appearing when you re-run the same condition. PostgreSQL's default Read Committed level protects only against dirty reads.
📖 Answer
Under Read Committed, each query sees the committed state as of the moment it started. If others commit between two queries inside your transaction, the second query sees the new state:
-- Transaction A -- Transaction B
BEGIN;
SELECT balance FROM acc WHERE id=1; -- 100
UPDATE acc SET balance=50 WHERE id=1; COMMIT;
SELECT balance FROM acc WHERE id=1; -- 50 (non-repeatable read)
COMMIT;
| Level | Dirty | Non-repeatable | Phantom |
|---|---|---|---|
| Read Committed (default) | no | possible | possible |
| Repeatable Read | no | no | not in PostgreSQL |
| Serializable | no | no | no |
PostgreSQL has two quirks. If you ask for READ UNCOMMITTED, it behaves like Read Committed, so dirty reads never happen at all. And Repeatable Read works on a snapshot, so it doesn't show phantoms either (even though the standard allows them there).
The higher levels have a price: under Repeatable Read and Serializable, if concurrent writes collide, the transaction fails with could not serialize access and the application has to run it again. In Spring: @Transactional(isolation = Isolation.REPEATABLE_READ).
Sign up to mark studied questions and save your progress.