Skip to main content
PostgreSQL & Redis Engineering Predict Output P1 Hard

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?

Official Reference

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.

Follow-up Interview Question · Why is this single-statement snapshot rule useful when archiving rows with DELETE ... RETURNING into INSERT?

Module Context & References

SQL & PostgreSQL · Query behavior & trap drills Predict query results for NULL logic, JOIN filters, aggregates and window functions
Personal Notes · Markdown

Technologies & Interview Topics Covered

Switch between short-term interview tracks and long-term 80/20 engineering depth to practice JavaScript internals, React rendering and hooks, timed frontend machine coding UI challenges, MeetaPro FG300, Blind 75 & NeetCode 150 DSA patterns, Python & FastAPI APIs, PostgreSQL query optimization & MVCC, Redis caching, Applied AI RAG pipelines & evaluations, and distributed system design.