Writable CTE snapshot visibility in PostgreSQL
In a single statement with a data-modifying CTE, what does the outer SELECT see when reading from the same table?
Code Snippet
-- tasks has 1 row: (id=1, status='pending')
WITH moved AS (
UPDATE tasks SET status = 'done' WHERE id = 1 RETURNING id, status
)
SELECT (SELECT status FROM tasks WHERE id = 1) AS table_status,
(SELECT status FROM moved) AS cte_status;Expected Output & Explanation
table_status: 'pending' | cte_status: 'done' In PostgreSQL, all sub-statements in a WITH query share the same snapshot of the underlying tables taken at the start of the statement. The outer SELECT cannot see effects of the UPDATE on tasks directly—only via the RETURNING output of moved.