实现说明
这个文件依次执行 SELECT / INSERT / DELETE / CREATE 语句,涉及 stale_carts、generate_series、big_series。
stale_carts 是这个文件自己建的会话级临时表——建表动作就在文件里,会话一结束它们就消失。
机制上由这些部分组成:先用 WITH … AS 把中间结果命名成 CTE,主查询再引用它;WHERE 把语句的作用范围收窄到满足条件的行;用 COUNT 做聚合;LIMIT 限制返回行数;RETURNING 把受影响的行交回调用方。
常见问题
说出这个文件涉及的表。
stale_carts、generate_series、big_series。
核心语句
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');
代码示例
-- 数据修改型(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 行