Data-Modifying CTEs (WITH deleted AS (DELETE ... RETURNING *))
Chain DELETE/UPDATE/INSERT inside CTEs and capture RETURNING rows.
In plain words
You can delete or update rows inside a WITH, get back the rows you changed, and use them in the same statement.
Think of it like…
Moving files from an inbox to an archive folder with one "move" action instead of copying them and then deleting the originals: there's no moment where a file is in both places or in neither.
Where you’ve seen it
Archiving orders older than two years: WITH moved AS (DELETE FROM orders WHERE created_at < now() - interval '2 years' RETURNING *) INSERT INTO orders_archive SELECT * FROM moved;. If the insert fails, the delete is rolled back too.
Words you’ll hear
- Data-modifying CTE
- A WITH clause containing INSERT, UPDATE or DELETE.
- RETURNING
- Hands the changed rows to the rest of the statement.
- Single snapshot
- All parts see the data as it was before the statement started.
- Atomic
- The whole statement succeeds or fails together.
Visual diagram
Theory & example queries
How it works
Each data-modifying CTE runs exactly once, whether or not the main query reads its output, and its RETURNING clause provides rows to later parts of the statement. The whole statement is one atomic unit: if any part fails, every change is rolled back.
All parts run against the same snapshot, so they can't see each other's changes directly. A SELECT from orders in the main query would still see the rows the CTE is deleting. Use the RETURNING output to pass data between steps. Avoid modifying the same row twice in one statement, because which change wins is unpredictable.
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
WITH new_order AS ( INSERT INTO orders (customer_id, amount) VALUES (42, 1500) RETURNING id )INSERT INTO order_items (order_id, product_id, qty)SELECT new_order.id, p.product_id, p.qtyFROM new_order, ( VALUES (11, 2), (42, 1) ) AS p (product_id, qty);PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output
Note: Representative PostgreSQL status for two generated order-item rows; the inner RETURNING rows feed the outer INSERT rather than being returned to the client.
Key takeaway: One statement, one snapshot, data passed through RETURNING.
Common patterns and limits
Moving rows (DELETE … RETURNING into INSERT), audit logging (UPDATE … RETURNING old and new values into a log table), parent-plus-children inserts, and upsert reporting (counting how many rows an INSERT … ON CONFLICT inserted vs updated) are the classic uses.
For very large moves, batch them (DELETE … WHERE id IN (SELECT id … LIMIT 10000) inside the CTE) to keep transactions and locks short. The feature is PostgreSQL-specific: SQL Server offers OUTPUT … INTO for similar results, and MySQL needs separate statements inside a transaction.
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
WITH changed AS ( UPDATE products SET price = price * 1.1 WHERE category = 'books' RETURNING id, price )INSERT INTO price_log (product_id, new_price, changed_at)SELECT id, price, now()FROM changed;PostgreSQL is the lesson baseline unless noted otherwise.
Read this line together with the surrounding statement as part of the same SQL expression.
Expected output
Note: Illustrative case where 36 book products were updated and one audit row was inserted for each.
Key takeaway: Great for move, log and parent-child inserts; batch large moves.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Write the modification with RETURNING
Put the INSERT, UPDATE or DELETE in a CTE and return the columns later steps need.
WITH movedAS (DELETE …RETURNING *)When to use it & trade-offs
What it is
In PostgreSQL, a CTE can contain INSERT, UPDATE or DELETE with RETURNING, and the rest of the statement can use the rows it returns: WITH moved AS (DELETE FROM orders WHERE … RETURNING *) INSERT INTO orders_archive SELECT * FROM moved;. All the parts run as one atomic statement, so the archive and delete can't get out of step.
Why it matters: Moving rows between tables, creating a parent and its children together, or logging what an update changed normally takes several statements and round trips. A data-modifying CTE does it in one statement, atomically, which is both faster and safer. It's a PostgreSQL-specific skill that comes up in senior backend work.
When to reach for it
- Archiving rows (move, not copy)
- Inserting a parent row and its children together
- Logging exactly what an UPDATE changed
When to avoid or be careful
- Expecting the main query to see changes made by a CTE
- Updating the same row twice in one statement
- Moving millions of rows in one statement on a busy table
Data-modifying CTE vs separate statements vs triggers
Strengths: One statement, one round trip, atomic.
Watch out: PostgreSQL-specific; parts share one snapshot.
Strengths: Portable; each step can read the previous step's changes.
Watch out: More round trips and code.
Strengths: Automatic.
Watch out: Hidden logic; harder to reason about.
Interview signals & numbers to know
When this topic comes up
- “Move old rows to an archive table”
- “Insert an order and its items atomically”
- DELETE … RETURNING
- Audit logging
- PostgreSQL-specific SQL
Benchmarks & rules of thumb
- 1
- statement, atomic
- 1
- snapshot shared by every part
- Exactly once
- how often a data-modifying CTE runs
Common mistakes & follow-ups
Common interview mistakes
- Selecting from orders in the main query and expecting the deleted rows to be gone already.
- Assuming a data-modifying CTE that isn't referenced won't run.
- Using the pattern in MySQL, which doesn't support DML inside CTEs.
Likely interviewer follow-ups
- How would you move rows from one table to another atomically?
- Can the main query see rows inserted by a CTE in the same statement?
- How would you insert an order and its items in one statement?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Data-Modifying CTEs (WITH deleted AS (DELETE ... RETURNING *)) with hands-on SQL practice and interview Q&A.