Sub topic 10
Data-modifying CTEs with INSERT, UPDATE, and DELETE (PostgreSQL)
This chapter assumes you can write a basic WITH query, chain several CTEs, and read an INSERT, UPDATE, or DELETE statement. It also assumes you know what a transaction is. Everything here is PostgreSQL behavior. Other databases differ, and the dialect section near the end lists the main differences.
What a data-modifying CTE is
In the earlier chapters, every CTE contained a SELECT. In PostgreSQL, the body of a CTE can also be an INSERT, UPDATE, or DELETE statement. Such a CTE is called a data-modifying CTE.
On its own, a modifying statement returns no rows. Add a RETURNING clause and it returns the rows it inserted, updated, or deleted. The CTE then acts like a table holding those rows. The rest of the statement can read from it.
This lets you do several related changes in one statement. A common case is moving rows from one table to another:
WITH moved AS (
DELETE FROM orders
WHERE order_date < DATE '2020-01-01'
RETURNING *
)
INSERT INTO orders_archive
SELECT * FROM moved;The DELETE removes old orders and hands the deleted rows to moved through RETURNING *. The outer INSERT copies those rows into orders_archive. Both actions happen in a single statement, so they succeed or fail together. There is no window in which a row has been deleted but not yet archived.
The example assumes orders_archive has the same columns, in the same order, as orders. SELECT * into an INSERT with no column list depends on that. In real code, list the columns explicitly.
Where the modifying part can go
The WITH clause can be attached to the main statement in two ways:
- The CTE is data-modifying, and the main statement is a
SELECT,INSERT,UPDATE, orDELETE. - The CTE is a
SELECT, and the main statement is data-modifying. This works in every major database that supports CTEs.
PostgreSQL requires data-modifying CTEs to be at the top level of the statement. You cannot put one inside a sub-SELECT or inside another CTE's body, except as the direct body of a top-level WITH item.
A data-modifying CTE does not have to be referenced by the main statement. It runs anyway, to completion. This is different from a SELECT CTE, which the planner can skip when nothing reads it.
WITH audit AS (
INSERT INTO price_audit (product_id, changed_at)
VALUES (42, now())
)
UPDATE products
SET price = price * 1.05
WHERE id = 42;Here audit is never read, yet the audit row is still inserted. Without RETURNING, the CTE could not be read even if you wanted to.
RETURNING is the link between steps
The only way for data to flow out of a modifying CTE is RETURNING. It can return:
- Whole rows with
RETURNING *. - Chosen columns, such as
RETURNING id, status. - Expressions, such as
RETURNING id, price * 1.2 AS price_with_tax.
For UPDATE, RETURNING shows the row after the change. For DELETE, it shows the row as it was before deletion. PostgreSQL 18 added OLD and NEW aliases so UPDATE ... RETURNING can show both versions. Earlier versions give you only the new row.
Passing generated keys to child rows
The most useful pattern is inserting a parent row and its children together. The database generates the parent's key, and you need it for the child rows:
WITH new_order AS (
INSERT INTO orders (customer_id, order_date)
VALUES (7, CURRENT_DATE)
RETURNING id
)
INSERT INTO order_items (order_id, product_id, quantity)
SELECT new_order.id, v.product_id, v.quantity
FROM new_order
CROSS JOIN (VALUES (101, 2), (205, 1)) AS v(product_id, quantity);new_order returns one row with the generated id. The cross join pairs that id with each item row. The result is one order and two items, created atomically, in one round trip to the server.
Updating and logging in one statement
You can also chain an update into an insert. This example lowers the stock of a product and records the movement:
WITH changed AS (
UPDATE products
SET stock = stock - 3
WHERE id = 42
RETURNING id, stock
)
INSERT INTO stock_log (product_id, new_stock, logged_at)
SELECT id, stock, now()
FROM changed;If the UPDATE matches no row, changed is empty and nothing is logged. That is usually the behavior you want.
How execution works
Data-modifying CTEs have rules that differ from ordinary queries. Getting them wrong produces results that look like bugs.
All sub-statements see the same snapshot
All the sub-statements in one WITH query run concurrently, with the same snapshot of the data. They do not see each other's changes to the tables. The main statement and each CTE read the tables as they were when the whole statement started.
The only way one part sees another's effects is through RETURNING. Consider this:
WITH t AS (
UPDATE products
SET price = price * 2
WHERE id = 42
RETURNING id, price
)
SELECT p.price AS table_price, t.price AS returned_price
FROM products p
JOIN t ON t.id = p.id;The outer SELECT reads products using the old snapshot. table_price shows the old price, and returned_price shows the new one. If you want the new value, take it from the CTE's RETURNING output, not from the table.
The order of execution is not defined
Because the sub-statements run as if at the same time, you cannot rely on the order in which they happen. The one guarantee is that RETURNING data is produced before the statement that reads it consumes it. Beyond that, order is unspecified.
The practical consequence: do not write two modifying CTEs that touch the same row and expect a particular result. If two sub-statements try to update the same row, only one of the modifications takes place, and you cannot predict which. The same applies to deleting a row that another sub-statement updates. Keep each row's modification to one sub-statement.
One related rule involves foreign keys. Constraint checks that are not deferred happen at the end of each sub-statement, not the end of the whole statement. So inserting a parent and a child in separate CTEs can fail on a foreign key check, even though the final state would be valid, because the child's check may run before the parent is visible. The generated-key pattern above avoids this problem. The child INSERT is the main statement and reads the parent id from RETURNING, which forces the parent to exist first.
Execution continues to completion
A SELECT CTE is evaluated only as far as the main query needs. For instance, if the main query reads a few rows and stops with LIMIT, the CTE may stop early. A data-modifying CTE always runs to completion, whether or not the main query reads all of its output.
WITH deleted AS (
DELETE FROM sessions
WHERE expires_at < now()
RETURNING id
)
SELECT id FROM deleted LIMIT 1;This returns one id, but every expired session is deleted.
Combining modification with a conditional step
A pattern worth knowing is the "upsert plus follow-up" statement. INSERT ... ON CONFLICT is itself a single statement, but a CTE lets you act on what happened:
WITH upserted AS (
INSERT INTO counters (name, hits)
VALUES ('home', 1)
ON CONFLICT (name) DO UPDATE SET hits = counters.hits + 1
RETURNING name, hits
)
INSERT INTO hit_milestones (name, hits)
SELECT name, hits
FROM upserted
WHERE hits % 1000 = 0;Each call bumps the counter. A row lands in hit_milestones only when the new total is a multiple of 1000. The whole thing is one atomic statement, so concurrent callers do not double-count.
Recursive CTEs and data modification
A WITH RECURSIVE query cannot have a data-modifying statement inside the recursive CTE itself. Modifying statements are allowed as separate, non-recursive CTEs in the same WITH list. A common use is deleting a whole subtree, found with a recursive CTE, in one statement:
WITH RECURSIVE subtree AS (
SELECT id FROM categories WHERE id = 10
UNION ALL
SELECT c.id
FROM categories c
JOIN subtree s ON c.parent_id = s.id
)
DELETE FROM categories
WHERE id IN (SELECT id FROM subtree);Here the recursive CTE only reads. The DELETE is the main statement. If the parent_id column has a foreign key with ON DELETE RESTRICT, deleting a parent and its children together still works. Constraint checks happen at the end of the statement, after all the rows are gone.
Differences from other databases
Data-modifying CTEs are mostly a PostgreSQL feature. Do not assume the syntax is portable.
| Database | `INSERT`/`UPDATE`/`DELETE` inside `WITH` | Closest alternative |
|---|---|---|
| PostgreSQL | Yes, with `RETURNING` | Native feature |
| SQL Server | No. A CTE must be a `SELECT`. | `OUTPUT` clause on the statement, often into a table variable |
| Oracle | No | `RETURNING ... INTO` in PL/SQL, or `MERGE` |
| MySQL, MariaDB | No. A CTE must be a `SELECT`. | Several statements in a transaction |
In all of these databases, you can still put a WITH clause in front of an INSERT, UPDATE, or DELETE as long as the CTE itself is a SELECT. The restriction is on what the CTE body can be.
Common pitfalls
- Reading the table instead of RETURNING. The outer query sees the old snapshot. Always take changed values from the CTE.
- Forgetting that the CTE always runs. An unreferenced
DELETECTE still deletes. Review each modifying CTE as if it were a standalone statement. - Touching the same row twice. Two sub-statements that modify one row give unpredictable results. Combine them into one.
- Relying on order. Do not assume the first CTE in the text runs first.
- Skipping the column list.
INSERT INTO t SELECT * FROM ctebreaks silently when someone adds a column. Name the columns. - Large moves in one statement. Moving millions of rows holds locks and creates a long transaction. Batch the work, for example with
WHERE id IN (SELECT id FROM orders WHERE ... LIMIT 10000), and repeat until no rows move. - Testing on real data. Run the statement inside a transaction first, check the result, then
ROLLBACKorCOMMIT.
BEGIN;
WITH moved AS (
DELETE FROM orders
WHERE order_date < DATE '2020-01-01'
RETURNING id, customer_id, order_date, amount
)
INSERT INTO orders_archive (id, customer_id, order_date, amount)
SELECT id, customer_id, order_date, amount
FROM moved;
SELECT COUNT(*) FROM orders_archive;
ROLLBACK;Replace ROLLBACK with COMMIT once the counts look right.
Execution flow
The diagram shows how the archive statement from the start of the chapter works. The deleted rows flow through RETURNING into the insert.
Exercises
Exercise
A statement starts with WITH u AS (UPDATE products SET price = 10 WHERE id = 1 RETURNING price) SELECT price FROM products WHERE id = 1;. The old price was 5. What price does the final SELECT return, and how would you get the new price instead?
Show answer
It returns 5, the old price, because every part of the statement reads the same snapshot taken at the start, and the outer query does not see the update. To get the new price, select from the CTE: SELECT price FROM u, which returns 10 from the RETURNING clause.
Exercise
Write a single statement that deletes all rows from tasks where done = true and inserts their id and title into tasks_history (task_id, title).
Show answer
WITH removed AS (DELETE FROM tasks WHERE done = true RETURNING id, title) INSERT INTO taskshistory (taskid, title) SELECT id, title FROM removed;
Exercise
You write WITH d AS (DELETE FROM logs WHERE created_at < now() - interval '30 days' RETURNING id) SELECT 1;. Nothing reads d. Are any rows deleted?
Show answer
Yes. A data-modifying CTE always runs to completion, even if the main statement never references it. All matching log rows are deleted.