Sub topic 12
Chaining changes with data-modifying CTEs
This chapter assumes you can write UPDATE ... FROM and DELETE ... USING, and that you know RETURNING from the previous chapter. It also assumes you know basic WITH queries. It reuses the customers, orders, products, and price_updates tables from the first chapter.
What a data-modifying CTE is
A common table expression (CTE) is a named subquery introduced with WITH. In PostgreSQL, the body of a CTE can be an INSERT, UPDATE, or DELETE as well as a SELECT. Such a CTE is called a data-modifying CTE.
A data-modifying CTE needs a RETURNING clause if anything else is going to use its rows. RETURNING turns the changed rows into a result set that the outer query can read like a table.
This lets one statement do several things at once: change rows, then count them, copy them, or feed them into another change.
WITH removed AS (
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
RETURNING o.*
)
SELECT count(*) AS deleted_orders FROM removed;The DELETE runs and removes the orders of closed customers. RETURNING o.* hands every deleted row to the name removed. The outer SELECT counts them. You get the number of deleted rows without a second query.
Why use one statement instead of several
Running a delete and then an insert as two statements has a gap. Another session can change data between them, and your client can crash after the first statement. You can close the gap with a transaction, but a single statement with a CTE is also atomic. If any part fails, none of it takes effect.
The pattern also avoids a round trip through the client. The deleted rows never leave the server, which matters when there are many of them.
Moving rows: delete and archive in one statement
The most common use is archiving. Suppose you keep old orders in a table named orders_archive with the same columns as orders.
CREATE TABLE orders_archive (LIKE orders);
WITH removed AS (
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
RETURNING o.*
)
INSERT INTO orders_archive
SELECT * FROM removed;CREATE TABLE ... (LIKE orders) copies the column names and types, so SELECT * from removed matches the archive's columns in order. Here the main statement is itself an INSERT, so no outer SELECT is needed.
If the insert fails, for example because of a constraint, the whole statement fails and the delete is undone. You cannot lose rows by deleting them without archiving them.
Chaining two modifications
A CTE can also feed another CTE. This example cancels open orders for closed customers, then records the cancelled orders in a log table.
CREATE TABLE order_log (
order_id integer NOT NULL,
note text NOT NULL,
logged_at timestamptz NOT NULL DEFAULT now()
);
WITH cancelled AS (
UPDATE orders AS o
SET status = 'cancelled'
FROM customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
AND o.status = 'open'
RETURNING o.id
)
INSERT INTO order_log (order_id, note)
SELECT id, 'cancelled because customer is closed'
FROM cancelled;RETURNING o.id gives the ids of the rows that were actually updated. Only those rows get a log entry. If no order matched, cancelled is empty and the log gets nothing.
Rules you must know
Every sub-statement sees the same snapshot
All parts of a WITH statement run against the same snapshot of the database, taken when the statement starts. Sub-statements do not see each other's changes to the tables. The only way to pass data between them is RETURNING.
Consider this example.
WITH moved AS (
DELETE FROM orders
WHERE status = 'cancelled'
RETURNING *
)
SELECT count(*) AS still_in_orders
FROM orders
WHERE status = 'cancelled';The outer SELECT still counts the cancelled rows, because it reads the snapshot taken before the delete. The delete does take effect, but the query cannot observe it. Use SELECT count(*) FROM moved to see the deleted rows.
Data-modifying CTEs always run to completion
PostgreSQL runs a data-modifying CTE exactly once, whether or not the outer query reads from it. A plain SELECT CTE that nothing references is not executed, but an UPDATE CTE is. The outer query may read only part of the RETURNING output, for instance with LIMIT, and the modification still covers every row it matched.
Do not touch the same row twice
Do not let two sub-statements modify the same row in one statement. The order in which they run is unpredictable, and only one of the changes takes effect. If you need two changes to one row, combine them into a single UPDATE.
Order of execution is not guaranteed
The sub-statements run at the same time from the point of view of the snapshot, and PostgreSQL does not promise the order in which they execute. A statement that depends on the order of two changes needs a different design, such as separate statements in a transaction. Data flowing through RETURNING is the one dependency PostgreSQL respects.
Triggers and constraints
Row-level triggers on the target table fire as usual. Foreign key checks happen at the end of the statement for deferrable constraints and immediately for the others, so a delete that archives child rows should consider the order in which parent and child tables are modified.
Previewing before you commit
A data-modifying CTE is still a bulk change, so the safety habits from the previous chapter apply. Wrap it in a transaction and look at the result before committing.
BEGIN;
WITH removed AS (
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
RETURNING o.id, o.customer_id, o.total
)
SELECT customer_id, count(*) AS orders_removed, sum(total) AS value_removed
FROM removed
GROUP BY customer_id
ORDER BY customer_id;
-- Check the summary, then:
ROLLBACK; -- or COMMIT;This gives a summary per customer and leaves the decision to you. It is often more useful than the raw rows when thousands of them were affected.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| `WITH clause containing a data-modifying statement must be at the top level` | The CTE is nested inside a subquery or another CTE. | Move the data-modifying `WITH` to the top of the statement. |
| `INSERT` into the archive inserts nothing | The `DELETE` matched no rows, or `RETURNING` was left out. | Run the delete's `WHERE` as a `SELECT` first. Add `RETURNING`. |
| Outer `SELECT` shows old data | Sub-statements share one snapshot. | Read the CTE's `RETURNING` output, not the table. |
| Column count mismatch on archive insert | `SELECT *` does not match the archive's columns. | List the columns explicitly in both places. |
| Unique violation or lost update | Two sub-statements touch the same row. | Merge them into one statement. |
The first error is worth a note. A data-modifying WITH is allowed only at the top level of a statement, so you cannot place one inside a subquery in FROM.
When not to use a CTE
- For a simple single change, plain
UPDATE ... FROMorDELETE ... USINGis easier to read. - If you need to run a long chain of steps where each one depends on the effects of the last, use several statements in a transaction instead.
- If the delete is huge, one statement holds locks and generates a lot of write-ahead log until it ends. Batch the work, as the later chapter on locks and batching describes, and apply the CTE to each batch.
Exercise
Write one statement that deletes all rows from orders whose status is 'cancelled', and inserts exactly those rows into orders_archive. Why is this safer than running a DELETE followed by an INSERT ... SELECT?
Show answer
WITH removed AS (DELETE FROM orders WHERE status = 'cancelled' RETURNING ) INSERT INTO orders_archive SELECT FROM removed; It is safer because the statement is atomic. If the insert fails, the delete is undone, so no row is removed without being archived. With two statements, another session could change data between them, and a failure after the delete would lose rows unless you wrapped both in a transaction.
Exercise
In a single statement, a CTE named cancelled updates open orders to 'cancelled', and the outer query is SELECT count(*) FROM orders WHERE status = 'cancelled'. Does the count include the rows just updated? How do you count them correctly?
Show answer
No. All parts of the statement use the same snapshot, so the outer query does not see the update's changes to the table. Add RETURNING id to the update and count from the CTE: SELECT count(*) FROM cancelled.