Follow Version Chain With Recursive CTE

Walk a prev_id pointer chain with a recursive CTE to reconstruct the revision history of a document, newest version first.

SqlData Integrity

Code

snippet
-- Follow a version chain with a recursive CTE: prev_id points at the prior revision
CREATE TABLE document_versions (
    version_id int PRIMARY KEY,
    prev_id    int REFERENCES document_versions(version_id),  -- NULL = first revision
    author     text NOT NULL,
    title      text NOT NULL
);

INSERT INTO document_versions VALUES
    (1, NULL, 'ada', 'draft'),
    (2, 1,    'raj', 'draft v2'),
    (3, 2,    'ada', 'reviewed'),
    (4, 3,    'kim', 'published');

WITH RECURSIVE history AS (
    -- anchor: start from the latest version
    SELECT version_id, prev_id, author, title, 1 AS depth
    FROM document_versions
    WHERE version_id = 4

    UNION ALL

    SELECT v.version_id, v.prev_id, v.author, v.title, h.depth + 1
    FROM document_versions v
    JOIN history h ON v.version_id = h.prev_id
)
SELECT depth, version_id, author, title
FROM history
ORDER BY depth;   -- the JOIN misses once prev_id is NULL, so the chain ends at the oldest version

What the code does

The file runs SELECT / INSERT / CREATE statements, touching document_versions and history.

Breaking the statements into their working parts: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a UNION joining up the outputs of separate queries; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity; a foreign-key REFERENCES guard holding rows to the parent table.

Applying it

Run the statement against the document_versions table.

Statements that matter

CREATE TABLE document_versions (
    version_id int PRIMARY KEY,
    prev_id    int REFERENCES document_versions(version_id),  -- NULL = first revision
    author     text NOT NULL,
    title      text NOT NULL
);
INSERT INTO document_versions VALUES
    (1, NULL, 'ada', 'draft'),
    (2, 1,    'raj', 'draft v2'),
    (3, 2,    'ada', 'reviewed'),
    (4, 3,    'kim', 'published');

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`document_versions`, `history` — joined via one JOIN clause.