Sub topic 1
Why PostgreSQL keeps multiple versions of a row
Prerequisites
This chapter assumes you know basic SQL (SELECT, INSERT, UPDATE, DELETE), what a transaction is (BEGIN, COMMIT, ROLLBACK), and how to run psql against a database.
Why multiple versions exist
PostgreSQL uses multiversion concurrency control (MVCC). An UPDATE does not overwrite a row in place. It writes a new version of the row and leaves the old one in the table. Readers keep seeing the version that matches their snapshot, so readers and writers do not block each other.
Row versions in the heap
A table's rows are stored in the heap, a set of fixed-size pages. Each stored copy of a row is a tuple, also called a row version. Several versions of the same logical row can sit on the same page at once.
Transaction IDs
Every transaction that writes gets a transaction ID (XID), a number that increases over time. PostgreSQL records the XID in each row version that the transaction creates or removes.
Reading xmin, xmax and ctid
Every row has hidden system columns:
xmin: the XID of the transaction that created this version.xmax: the XID that deleted or locked this version, or 0 if none has.ctid: the physical location of the version as (page, item).
CREATE TABLE accounts (id int PRIMARY KEY, balance int NOT NULL);
INSERT INTO accounts VALUES (1, 100);
SELECT xmin, xmax, ctid, * FROM accounts;What INSERT, UPDATE and DELETE do to row versions
- INSERT writes a version with
xminset to the inserting transaction andxmaxset to 0. - UPDATE sets
xmaxon the old version and writes a new version at a newctid, withxminset to the updating transaction. - DELETE sets
xmaxon the current version. The row data stays in place.
BEGIN;
UPDATE accounts SET balance = 90 WHERE id = 1;
SELECT xmin, xmax, ctid, * FROM accounts;
COMMIT;The visible row now has xmin equal to the current transaction ID and a different ctid than before.
Exercise
After the UPDATE above commits, what is the xmax of the new row version, and why?
Show answer
It is 0. The new version has not been deleted or locked by any transaction, so its xmax stays at its initial value.