← Back to PostgreSQL, page 3

postgresql-0056 · Medium mid

Show how an UPDATE creates a new row version, using ctid and xmin.

PostgreSQL never updates a row in place: an UPDATE writes a new row version with a new physical location (ctid) and creating transaction (xmin), and marks the old version as deleted by setting its xmax. Old versions become dead rows that VACUUM later reclaims. This is why heavy updates cause bloat.

Full answer

Setup for the example:

sql
CREATE TABLE items (id int, qty int);
INSERT INTO items VALUES (1, 10), (2, 20);
sql
CREATE TEMP TABLE before AS SELECT id, ctid::text AS old_ctid, xmin::text::bigint AS old_xmin FROM items; SELECT id, ctid FROM items ORDER BY id;

Result:

text
 id |  ctid
----+-------
 1  | (0,1)
 2  | (0,2)
(2 rows)
sql
UPDATE items SET qty = qty + 1 WHERE id = 1; SELECT i.id, i.ctid AS new_ctid, b.old_ctid, i.xmin::text::bigint > b.old_xmin AS newer_xmin FROM items i JOIN before b USING (id) ORDER BY i.id;

Output:

text
 id | new_ctid | old_ctid | newer_xmin
----+----------+----------+------------
 1  | (0,3)    | (0,1)    | t
 2  | (0,2)    | (0,2)    | f
(2 rows)
sql
UPDATE items SET qty = qty WHERE id = 2; SELECT id, ctid FROM items ORDER BY id;

PostgreSQL returns:

text
 id |  ctid
----+-------
 1  | (0,3)
 2  | (0,4)
(2 rows)

The two rows start at positions (0,1) and (0,2), page 0 slots 1 and 2. After the update, row 1 lives at (0,3) with a newer xmin, while row 2 is untouched. Even an update that changes nothing, such as setting qty to itself, writes a new version, moving row 2 to (0,4). The old versions at (0,1) and (0,2) remain on the page as dead rows until VACUUM. Raw xmin values are shown only as comparisons because transaction ids differ between runs. ctid changes, so it must never be used as a permanent row identifier.

sql
CREATE TABLE items (id int, qty int);
INSERT INTO items VALUES (1, 10), (2, 20);

CREATE TEMP TABLE before AS SELECT id, ctid::text AS old_ctid, xmin::text::bigint AS old_xmin FROM items; SELECT id, ctid FROM items ORDER BY id;

UPDATE items SET qty = qty + 1 WHERE id = 1; SELECT i.id, i.ctid AS new_ctid, b.old_ctid, i.xmin::text::bigint > b.old_xmin AS newer_xmin FROM items i JOIN before b USING (id) ORDER BY i.id;

UPDATE items SET qty = qty WHERE id = 2; SELECT id, ctid FROM items ORDER BY id;

Run on PostgreSQL 17.12 (Debian 17.12-0+deb13u1) in a fresh schema, twice, with identical output.

Key points

  • UPDATE writes a new row version
  • ctid is the physical location
  • xmin records the creating transaction
  • No-op updates still create versions
  • VACUUM reclaims dead versions

Common mistakes

  • Using ctid as a stable key
  • Running no-op updates in loops

Follow-ups

  • What are HOT updates?
  • How does VACUUM decide a row is dead?

Tips

  • Show the no-op update