Sub topic 2
Where PostgreSQL records commit and abort
This chapter assumes you know basic SQL, what BEGIN, COMMIT and ROLLBACK do, and how to run two psql sessions against one database. It builds on the row versions described earlier in this tutorial.
Where commit status lives
Each transaction gets a transaction ID (XID). PostgreSQL records each transaction's outcome in the commit log, stored in the pg_xact directory (called pg_clog before version 10). The log holds a small status for each XID: in progress, committed, or aborted.
A row version stores only its creating XID in xmin and its deleting XID in xmax. When a backend first checks a row's status, it sets hint bits in the row header to cache the answer. Later readers can skip the lookup in pg_xact.
Snapshots: what a query can see
A snapshot is the set of transactions a query treats as finished when it runs. You can inspect one:
SELECT pg_current_snapshot();
-- example result: 748:752:748,750The result reads as xmin:xmax:xip_list. Transactions below xmin are finished. Transactions at or above xmax started too late to be seen. Transactions in xip_list were still running when the snapshot was taken, so their work is hidden even if they commit a moment later.
How a row version is judged visible
Isolation levels as snapshot timing
The isolation level decides when the snapshot is taken.
| Isolation level | Snapshot taken | Effect |
|---|---|---|
| Read Committed | Start of each statement | Each query sees commits made before it started |
| Repeatable Read | First query of the transaction | Every query sees the same data |
| Serializable | First query, plus conflict tracking | Same snapshot as Repeatable Read, and may fail on dangerous patterns |
Under Read Committed, two SELECTs in one transaction can return different values if another session commits between them. Repeatable Read prevents that:
-- Session A
BEGIN ISOLATION LEVEL REPEATABLE READ;
SELECT balance FROM accounts WHERE id = 1;
-- Session B (autocommits)
UPDATE accounts SET balance = balance + 10 WHERE id = 1;
-- Session A
SELECT balance FROM accounts WHERE id = 1; -- same value as the first query
COMMIT;Exercise
At Read Committed, session A runs two SELECTs inside one transaction. Session B commits an UPDATE to the same row between them. What does A's second SELECT return?
Show answer
The updated value. Read Committed takes a new snapshot for each statement, and B's commit was finished before the second statement started.