Data-Modifying CTE Executes Exactly Once
Data-modifying statements in WITH execute exactly once to completion even when the primary query never references them; SELECT CTEs stay lazy.
Code
-- 数据修改型(DML)CTE 恰好执行一次、必定跑完,即使主查询完全不引用它——
-- PostgreSQL 文档:data-modifying statements in WITH are executed exactly once,
-- and always to completion, independently of whether the primary query reads
-- all (or indeed any) of their output
CREATE TEMP TABLE stale_carts (cart_id bigint, added_at date);
INSERT INTO stale_carts VALUES
(1, date '2026-01-01'),
(2, date '2026-02-01'),
(3, date '2026-11-01');
-- 主查询根本没引用 purge,DELETE 依然真实发生
WITH purge AS (
DELETE FROM stale_carts
WHERE added_at < date '2026-03-01'
RETURNING cart_id
)
SELECT 'cleanup ran' AS result; -- 删除已执行:stale_carts 只剩 1 行
SELECT count(*) AS rows_after FROM stale_carts; -- 1
-- 反差:SELECT 型 CTE 是惰性的,只按主查询索取的量执行
WITH big_series AS (
SELECT g FROM generate_series(1, 1000000) g
)
SELECT g FROM big_series LIMIT 5; -- 只物化前 5 行How the code behaves
SELECT / INSERT / DELETE / CREATE statements share the script, touching stale_carts, generate_series and big_series.
stale_carts is a temp table the script builds for itself, scoped to this session — no prior setup, no residue afterwards.
Mechanically, the statements are built from: a CTE (WITH … AS) that names an intermediate result before the main query; a WHERE clause constraining which rows the statement operates on; COUNT aggregation; a row cap (LIMIT) bounding the result size; a RETURNING clause that hands the affected rows back to the caller.
Using it
The file sets up its own scratch surface: it builds the session-local tables it works with (stale_carts), so one full run against a throwaway database is enough.
Key statements
WITH purge AS (
DELETE FROM stale_carts
WHERE added_at < date '2026-03-01'
RETURNING cart_id
)
SELECT 'cleanup ran' AS result; -- 删除已执行:stale_carts 只剩 1 行
WITH big_series AS (
SELECT g FROM generate_series(1, 1000000) g
)
SELECT g FROM big_series LIMIT 5; -- 只物化前 5 行
INSERT INTO stale_carts VALUES
(1, date '2026-01-01'),
(2, date '2026-02-01'),
(3, date '2026-11-01');
Interactive Tools for This Topic
FAQ
- Name the tables involved in this file.
- `stale_carts`, `generate_series`, `big_series`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.