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.

SqlData Integrity

Code

snippet
-- 归档表与主表同构,主键直接搬过去
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;  -- 写入几行就返回几个 id

How 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

FAQ

Which objects does the SQL touch?
`orders`, `orders_archive`, `archived`.