CTE Swaps Revision Rows In One Statement

Run a data-modifying CTE chain that archives the current row and inserts its replacement, sharing one snapshot and one commit.

SqlData Integrity

Code

snippet
WITH archived AS (
    -- 第一步:把当前版本搬进历史表,拿到版本号
    DELETE FROM current_revisions
    WHERE doc_id = 42
    RETURNING doc_id, revision_no
),
inserted AS (
    -- 第二步:写入新版本,沿用原 doc_id,版本号 +1
    INSERT INTO current_revisions (doc_id, revision_no, body)
    SELECT doc_id, revision_no + 1, 'draft v3 content'
    FROM archived
    RETURNING doc_id, revision_no
)
-- 第三步:同一语句里引用两步的输出
SELECT
    a.doc_id,
    a.revision_no AS archived_revision,
    i.revision_no AS new_revision
FROM archived a
CROSS JOIN inserted i;

How it works

What runs is SELECT / INSERT / DELETE, with current_revisions, archived and inserted as the object involved.

What the statements actually assemble: a CTE (WITH … AS) that names an intermediate result before the main query; one JOIN combining rows across tables; a WHERE clause filtering the rows one statement applies to; a RETURNING clause that hands the affected rows back to the caller.

Using it

Run the statement against the current_revisions table.

Interactive Tools for This Topic

FAQ

Which objects does the SQL touch?
The references are `current_revisions`, `archived`, `inserted`, with one join tying the pair together.