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.
Code
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
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 objects does the SQL touch?
- The references are `current_revisions`, `archived`, `inserted`, with one join tying the pair together.
Report a problem with this exampleOpens a pre-filled issue on GitHub.