ctid And xmin Reveal Row Versions
Every UPDATE writes a new row version: ctid moves to fresh storage and xmin records the writing transaction, which is the bloat VACUUM later reclaims.
Code
-- MVCC: UPDATE does not modify in place, it writes a new version; the old one stays put until VACUUM reclaims it
-- xmin records the transaction id that wrote the version; ctid is the row's physical location
CREATE TEMP TABLE drafts (
id integer PRIMARY KEY,
title text NOT NULL
);
INSERT INTO drafts VALUES (1, 'v1');
-- after two UPDATEs: still 1 visible row, but 3 versions already exist underneath
UPDATE drafts SET title = 'v2' WHERE id = 1;
UPDATE drafts SET title = 'v3' WHERE id = 1;
-- ctid changes with every update: new versions land at new physical locations
SELECT ctid, xmin, title FROM drafts;
-- read-only access adds no versions: two SELECTs in a row report the exact same ctid
SELECT ctid, title FROM drafts;
SELECT ctid, title FROM drafts;
-- many small updates stretch the version chain: the source of table bloat; VACUUM reclaims the old versionsWhat the code does
Several statements share this file — SELECT, with drafts among the objects involved.
Applying it
Run the statement against the drafts table.
Statements that matter
UPDATE drafts SET title = 'v2' WHERE id = 1;
UPDATE drafts SET title = 'v3' WHERE id = 1;
CREATE TEMP TABLE drafts (
id integer PRIMARY KEY,
title text NOT NULL
);
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- Which relations are involved here?
- The references are `drafts`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.