Data-Modifying CTE Archive Rows
Move expired rows into an archive atomically: a data-modifying CTE feeds DELETE RETURNING output straight into the outer INSERT.
Code
-- 归档表与主表同构,主键直接搬过去
CREATE TABLE IF NOT EXISTS orders_archive (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
total_cents integer NOT NULL,
created_at timestamptz NOT NULL
);
-- data-modifying CTE:一条语句把过期 rows 原子搬进归档
-- WITH 里的 DELETE ... RETURNING 吐出被删行,外层 INSERT 接住
WITH archived AS (
DELETE FROM orders
WHERE created_at < NOW() - INTERVAL '90 days'
RETURNING id, customer_id, total_cents, created_at
)
INSERT INTO orders_archive (id, customer_id, total_cents, created_at)
SELECT id, customer_id, total_cents, created_at
FROM archived
RETURNING id; -- 写入几行就返回几个 idHow the snippet works
Several statements share this file — SELECT / INSERT / DELETE / CREATE, with orders, orders_archive and archived among the objects involved.
Concretely, the SQL combines: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause narrowing which rows one statement affects; a RETURNING clause that hands the affected rows back to the caller; NOT NULL qualifiers on the required columns; a PRIMARY KEY that enforces row identity.
Applying it
Run the statement against the orders table.
Statements that matter
CREATE TABLE IF NOT EXISTS orders_archive (
id bigint PRIMARY KEY,
customer_id bigint NOT NULL,
total_cents integer NOT NULL,
created_at timestamptz 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 objects does the SQL touch?
- `orders`, `orders_archive`, `archived`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.