Full answer
Sample schema and data:
sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);sql
BEGIN; SELECT balance FROM accounts WHERE id = 1;PostgreSQL returns:
text
balance
---------
500
(1 row)In a second session:
sql
UPDATE accounts SET balance = 450 WHERE id = 1;Result on PostgreSQL 17:
text
UPDATE 1sql
SELECT balance FROM accounts WHERE id = 1;Result:
text
balance
---------
450
(1 row)sql
COMMIT; BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 1;Output:
text
balance
---------
450
(1 row)In a second session:
sql
UPDATE accounts SET balance = 400 WHERE id = 1;PostgreSQL returns:
text
UPDATE 1sql
SELECT balance FROM accounts WHERE id = 1;Result on PostgreSQL 17:
text
balance
---------
450
(1 row)sql
COMMIT; SELECT balance FROM accounts WHERE id = 1;Result:
text
balance
---------
400
(1 row)In the first transaction, A reads 500, B commits 450 in autocommit mode, and A's next statement reads 450 although A never ended its transaction. Under REPEATABLE READ, A's snapshot is fixed at its first query: after B commits 400, A still reads 450 until it commits, and only a new statement after COMMIT sees 400. Reports that compute several totals in one transaction should use REPEATABLE READ so the numbers agree with each other.
sql
CREATE TABLE accounts (id int PRIMARY KEY, owner text, balance int);
INSERT INTO accounts VALUES (1, 'Asha', 500), (2, 'Ben', 300);
BEGIN; SELECT balance FROM accounts WHERE id = 1;
-- session B
UPDATE accounts SET balance = 450 WHERE id = 1;
SELECT balance FROM accounts WHERE id = 1;
COMMIT; BEGIN ISOLATION LEVEL REPEATABLE READ; SELECT balance FROM accounts WHERE id = 1;
-- session B
UPDATE accounts SET balance = 400 WHERE id = 1;
SELECT balance FROM accounts WHERE id = 1;
COMMIT; SELECT balance FROM accounts WHERE id = 1;Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.
Key points
- READ COMMITTED snapshots per statement
- Committed changes appear mid-transaction
- REPEATABLE READ fixes the snapshot
- The snapshot starts at the first query
- Use REPEATABLE READ for consistent multi-query reports
Common mistakes
- Assuming BEGIN alone gives a consistent view
- Running multi-query reports in READ COMMITTED
Follow-ups
- What happens if A tries to update the row under REPEATABLE READ?
- Does PostgreSQL implement READ UNCOMMITTED?
Tips
- Narrate the timeline