Data-Modifying CTEs Share One Snapshot
Data-modifying CTEs and the outer query share one snapshot: the outer SELECT still counts rows a WITH DELETE removed; only later statements see them gone.
Code
-- data-modifying CTEs share one snapshot with the outer query:
-- WITH 里的 DELETE 与外层 SELECT 同语句并发执行,互相看不到对方的效果
CREATE TEMP TABLE alerts (
id int PRIMARY KEY,
resolved boolean NOT NULL
);
INSERT INTO alerts VALUES
(1, true), (2, true), (3, false);
WITH cleared AS (
DELETE FROM alerts
WHERE resolved
RETURNING id
)
SELECT
(SELECT count(*) FROM cleared) AS deleted_rows,
-- 外层仍按语句开始的快照读取:被删的行还数得出来
(SELECT count(*) FROM alerts) AS alerts_seen_by_outer;
-- 语句结束后才可见:同一事务的下一句读到的才是删完的表
SELECT count(*) AS alerts_after_statement FROM alerts;One statement, one shared snapshot
The WITH cleared AS (DELETE FROM alerts WHERE resolved RETURNING id) statement runs the delete and the outer SELECT concurrently over the same snapshot — the comment’s rule is that they cannot see each other’s effects mid-statement. Three alerts exist (two resolved, one not), so the CTE deletes rows 1 and 2 and its RETURNING output reports both.
The two counts that disagree on purpose
deleted_rows | alerts_seen_by_outer
--------------+----------------------
2 | 3
count(*) FROM cleared reads the CTE’s own output (2), while count(*) FROM alerts in the outer query still sees all 3 rows — the delete has not “happened yet” from the outer query’s point of view, even though both run in one statement. The next statement in the same transaction then reports alerts_after_statement = 1: only after the statement completes does the removal become visible to following reads.
The line that carries the deleted rows
DELETE FROM alerts
WHERE resolved
RETURNING id
RETURNING is what makes the CTE’s effect a consumable dataset — the outer statement can count, join, or insert from it while the base-table view of the same statement stays frozen at its start snapshot.
Interactive Tools for This Topic
FAQ
- What relations does the SQL touch?
- The references are `alerts`, `cleared`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.