Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 74/ 160
04. Subqueries & Common Table Expressions (CTEs)

Data-Modifying CTEs (WITH deleted AS (DELETE ... RETURNING *))

Chain DELETE/UPDATE/INSERT inside CTEs and capture RETURNING rows.

AdvancedRETURNING · Writable CTE3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Create an order and its items togetherQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  new_order AS (3    INSERT INTO4      orders (customer_id, amount)5    VALUES6      (42, 1500)7    RETURNING8      id9  )10INSERT INTO11  order_items (order_id, product_id, qty)12SELECT13  new_order.id,14  p.product_id,15  p.qty16FROM17  new_order,18  (19    VALUES20      (11, 2),21      (42, 1)22  ) AS p (product_id, qty);
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/22
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
INSERT 0 2

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.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Logging what an update changedQuery example
1Input dataStart from the source rows or state that the statement sees.
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1WITH2  changed AS (3    UPDATE products4    SET5      price = price * 1.16    WHERE7      category = 'books'8    RETURNING9      id,10      price11  )12INSERT INTO13  price_log (product_id, new_price, changed_at)14SELECT15  id,16  price,17  now()18FROM19  changed;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · SQL expression

Read this line together with the surrounding statement as part of the same SQL expression.

1/19
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output
INSERT 0 36

Note: Illustrative case where 36 book products were updated and one audit row was inserted for each.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Great for move, log and parent-child inserts; batch large moves.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1CTE

Write the modification with RETURNING

Put the INSERT, UPDATE or DELETE in a CTE and return the columns later steps need.

SQL at this stepReadable preview
1WITH moved2AS (DELETE …3RETURNING *)
What to watch at this step
Runs
exactly once
Tip: use ← → to move between steps

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

Data-modifying CTE
Best for: Multi-step changes that must be atomic, in PostgreSQL

Strengths: One statement, one round trip, atomic.

Watch out: PostgreSQL-specific; parts share one snapshot.

Separate statements in a transaction
Best for: Any database

Strengths: Portable; each step can read the previous step's changes.

Watch out: More round trips and code.

Triggers
Best for: Side effects that must happen for every writer

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?
Interview tip: Show the archive example and mention the single-snapshot rule. It's a compact, senior-level PostgreSQL answer.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
Graph Traversal & Cycle Detection in Recursive CTEs
Next topic
Multi-Step Cohort & Retention Analysis Using CTEs