Sub topic 4
Non-repeatable reads
This chapter assumes you can write basic SQL, use BEGIN, COMMIT and ROLLBACK, and know that a database serves many clients at once. It also assumes you have read the chapter on dirty reads. A non-repeatable read is the next anomaly up from that one, and it appears once dirty reads are already prevented.
What a non-repeatable read is
A non-repeatable read happens when a transaction reads the same row twice and gets different values, because another transaction changed that row and committed in between.
The word "committed" matters. In a dirty read, you see data that was never committed. Here, every value you see was committed at some point. The problem is that the committed state changed during your transaction.
A precise definition: transaction A reads a row, transaction B modifies or deletes that row and commits, and transaction A reads the row again and sees the modified value or finds the row gone.
Reproducing it
You need two sessions, for example two psql windows connected to PostgreSQL. First create the data:
CREATE TABLE accounts (id int PRIMARY KEY, balance int);
INSERT INTO accounts VALUES (1, 100);Then run these steps in order. PostgreSQL's default level is READ COMMITTED.
-- Session A
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- returns 100
-- Session B
BEGIN;
UPDATE accounts SET balance = 50 WHERE id = 1;
COMMIT;
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- returns 50: a non-repeatable read
COMMIT;Now reset the balance to 100 and repeat, but start Session A with BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ;. The second SELECT in Session A still returns 100, even though Session B has committed 50. Session A is reading from a snapshot, a frozen view of the data, and the snapshot does not change until the transaction ends.
Why `READ COMMITTED` allows it
READ COMMITTED promises one thing: you never see uncommitted data. It does not promise that two statements see the same data. In most engines, each statement sees the database as of the moment that statement started. A later statement starts later, so it can see more commits.
Some consequences:
- A single statement is still consistent in PostgreSQL and Oracle. A single
SELECTnever sees half of another transaction's changes, because it uses one snapshot for its whole run. - Two statements in the same transaction are not consistent with each other.
- A statement that contains a subquery sees one snapshot for the whole statement in PostgreSQL. In engines that use shared locks for reads, the guarantee can differ (see the engine table below).
Where it hurts in practice
Non-repeatable reads are harmless when each statement stands alone. They cause bugs when a transaction makes a decision from one read and acts on a second read, or when it reads several values that must agree.
Reports that must add up
Suppose a report runs two queries in one transaction: the total of all balances, and the list of individual balances. A transfer committed between the two queries makes the list disagree with the total. Each query is correct on its own, but the report is not.
Check-then-act
BEGIN;
SELECT balance FROM accounts WHERE id = 1; -- application sees 100
-- application decides a withdrawal of 80 is allowed
-- meanwhile another session withdraws 70 and commits
SELECT balance FROM accounts WHERE id = 1; -- now 30
UPDATE accounts SET balance = balance - 80 WHERE id = 1;
COMMIT;The first read supports a decision that the second read contradicts. Without a constraint, the balance ends at -50. Raising the isolation level is one fix. A better first step is often to let the database check the rule itself.
ALTER TABLE accounts ADD CONSTRAINT balance_not_negative CHECK (balance >= 0);With the constraint in place, the UPDATE fails instead of corrupting the data, whatever the isolation level.
Read-then-write
If your application reads a value, computes a new one, and writes it back, a concurrent change between the read and the write can be overwritten. That problem is the lost update, covered in its own chapter. It is related to non-repeatable reads, because the same gap between two looks at a row causes both.
How to prevent it
You have three main options. Choose the cheapest one that covers the risk.
- Collapse the logic into one statement.
UPDATE accounts SET balance = balance - 80 WHERE id = 1 AND balance >= 80;reads and writes in one atomic step. Check the number of affected rows to see whether it succeeded. - Lock the row you read.
SELECT ... FOR UPDATEblocks other writers on that row until you finish, so the value cannot change under you. - Use a stricter isolation level. At
REPEATABLE READorSERIALIZABLE, repeated reads of the same row return the same result.
BEGIN;
SELECT balance FROM accounts WHERE id = 1 FOR UPDATE;
-- no other transaction can change this row until COMMIT or ROLLBACK
UPDATE accounts SET balance = balance - 80 WHERE id = 1;
COMMIT;What each level allows
The SQL standard defines the isolation levels by which anomalies they permit.
| Isolation level | Dirty read | Non-repeatable read | Phantom read |
|---|---|---|---|
| READ UNCOMMITTED | Possible | Possible | Possible |
| READ COMMITTED | Prevented | Possible | Possible |
| REPEATABLE READ | Prevented | Prevented | Possible |
| SERIALIZABLE | Prevented | Prevented | Prevented |
The name REPEATABLE READ comes from this anomaly. The level exists to make reads of the same row repeatable. A non-repeatable read concerns rows you already read. If new rows appear in a repeated range query, that is a phantom read, which is a separate anomaly with its own chapter.
How engines differ
The standard describes outcomes. Engines reach those outcomes in different ways, and the details matter when you debug real behavior.
| Engine | Default level | Behavior around non-repeatable reads |
|---|---|---|
| PostgreSQL | READ COMMITTED | New snapshot for each statement. `REPEATABLE READ` takes one snapshot per transaction. |
| MySQL InnoDB | REPEATABLE READ | Plain `SELECT` reads from a snapshot taken at the first read. Under `READ COMMITTED`, each plain `SELECT` gets a fresh snapshot. |
| SQL Server | READ COMMITTED | By default uses shared locks released right after each read, so other transactions can change the row afterward. With `READ_COMMITTED_SNAPSHOT` enabled, it uses a statement-level snapshot. |
| Oracle | READ COMMITTED | Statement-level read consistency. It has no `REPEATABLE READ`; use `SERIALIZABLE` or read-only transactions for a stable view. |
In SQL Server you set the level before starting the transaction:
SET TRANSACTION ISOLATION LEVEL REPEATABLE READ;
BEGIN TRANSACTION;
SELECT balance FROM accounts WHERE id = 1;
-- shared lock on the row is held until the transaction ends
COMMIT;SQL Server's REPEATABLE READ uses locks, so it prevents the anomaly by blocking writers. PostgreSQL's uses a snapshot, so it prevents the anomaly without blocking anyone. Both give the same guarantee, but the cost differs: lock-based reads cause waiting, and snapshot-based reads can cause aborted transactions.
Edge cases to know
- The snapshot starts late. In PostgreSQL and MySQL, a
REPEATABLE READsnapshot is taken at the first query in the transaction, not atBEGIN. Work done before that first query is not covered. - Writes see the latest data. In PostgreSQL at
REPEATABLE READ, if your transaction tries to update a row that another transaction changed and committed after your snapshot, you get an error:could not serialize access due to concurrent update(SQLSTATE40001). Your application must roll back and retry. - InnoDB is different here. In MySQL at
REPEATABLE READ, a plainSELECTuses the snapshot, butUPDATE,DELETEandSELECT ... FOR UPDATEoperate on the latest committed rows. A transaction can therefore read 100 from its snapshot and then update a row that is now 50, and a later plainSELECTin that transaction shows the row with your own change applied. Do not assume the snapshot covers writes. - Deleted rows count. If a row you read is deleted by another committed transaction, a repeated read at
READ COMMITTEDfinds nothing. That is still a non-repeatable read.
Cost of preventing it
A stricter level is not free.
- With snapshots, the database must keep old row versions until the oldest snapshot ends. A long-running
REPEATABLE READtransaction can bloat tables and delay cleanup. - With locks, readers hold locks longer, so writers wait and deadlocks become more likely.
- At
REPEATABLE READin PostgreSQL, conflicting writes fail rather than wait, so you need retry logic.
For many workloads the right answer is to stay at READ COMMITTED and fix the few risky spots with a single atomic statement, a constraint, or FOR UPDATE. Reserve the stricter levels for transactions that need a consistent view across several reads, such as reports.
Exercise
In PostgreSQL at the default level, Session A runs SELECT balance FROM accounts WHERE id = 1 (result 100) inside a transaction. Session B then runs UPDATE accounts SET balance = 50 WHERE id = 1 and commits. Session A runs the same SELECT again. What does it return, what is this anomaly called, and what is the smallest change to Session A that makes the second SELECT return 100?
Show answer
The second SELECT returns 50. This is a non-repeatable read, allowed because the default level is READ COMMITTED and each statement gets a fresh snapshot. Starting Session A with BEGIN TRANSACTION ISOLATION LEVEL REPEATABLE READ makes both reads use one snapshot, so the second SELECT returns 100.
Exercise
A withdrawal routine reads the balance, checks in application code that it is at least 80, then runs UPDATE accounts SET balance = balance - 80 WHERE id = 1. Name two ways other than raising the isolation level to stop the balance going negative.
Show answer
Make the check part of the statement: UPDATE accounts SET balance = balance - 80 WHERE id = 1 AND balance >= 80, then check that one row was affected. Alternatively, lock the row first with SELECT balance FROM accounts WHERE id = 1 FOR UPDATE. A CHECK (balance >= 0) constraint also makes the bad write fail.