Sub topic 12
Chaining Changes with Data-Modifying CTEs
Assume you know SELECT, WHERE, JOIN, UPDATE, DELETE, table aliases, and PostgreSQL transactions. This chapter shows how to combine a change with a query or another change by using a data-modifying common table expression (CTE).
A common table expression is a named query introduced with WITH. A data-modifying CTE contains INSERT, UPDATE, or DELETE instead of SELECT. Its RETURNING clause exposes the affected rows to the statement that follows it.
Delete rows and inspect the result
Suppose closed customers should have their open orders removed. The DELETE can return the deleted rows, and the outer query can count them:
WITH removed AS (
DELETE FROM orders AS o
USING customers AS c
WHERE o.customer_id = c.id
AND c.status = 'closed'
AND o.status = 'open'
RETURNING o.id, o.customer_id, o.total
)
SELECT count(*) AS deleted_orders,
coalesce(sum(total), 0) AS deleted_value
FROM removed;The CTE named removed runs the deletion. The outer SELECT reads the rows produced by RETURNING. The query returns one summary row while still performing the deletion.
This pattern is useful when an application needs an audit record, a count, or a message about the rows changed.
Move changed rows into an archive
You can use the rows returned by one change as input to another change. For example, first delete closed orders, then insert those deleted rows into an archive table:
CREATE TABLE order_archive (
id integer PRIMARY KEY,
customer_id integer NOT NULL,
total numeric(10,2) NOT NULL,
status text NOT NULL,
archived_at timestamptz NOT NULL DEFAULT now()
);
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, o.status
)
INSERT INTO order_archive (id, customer_id, total, status)
SELECT id, customer_id, total, status
FROM removed;The deleted rows flow directly into the INSERT. No application code needs to fetch the rows and send them back in a second statement.
Important execution rules
A data-modifying CTE runs as part of one top-level statement. PostgreSQL gives the statement a consistent snapshot. The outer query sees rows through the CTE's RETURNING output, not by rereading the changed base table.
Data-modifying CTEs execute once, even if the CTE name is referenced more than once. The changes are part of the same transaction as the outer statement. If a later constraint or statement error aborts the transaction, the changes roll back unless you handle the transaction differently.
Avoid modifying the same row more than once in one statement. If several data-modifying CTEs target overlapping rows, do not rely on their apparent textual order. Design the statement so each target row is changed by at most one operation.
A safe testing pattern
Use RETURNING to inspect the affected rows, then commit only after checking the result:
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.*
)
SELECT *
FROM removed;
-- If the rows are correct:
-- COMMIT;
-- If the rows are wrong:
ROLLBACK;Exercise
Why does the outer query use the removed CTE instead of selecting the deleted rows from orders again?
Show answer
The CTE's RETURNING output contains the rows affected by the delete. A later read of orders cannot reliably retrieve rows that no longer exist and follows the statement's snapshot rules.