Sub topic 7
Chaining statements with data-modifying CTEs
This chapter assumes you can read basic INSERT, UPDATE and DELETE statements, and that you know what a common table expression (CTE) is, meaning a named subquery introduced with WITH. It also assumes you have seen RETURNING on a single statement. Here you will connect several statements into one by passing the rows from one statement's RETURNING list to the next.
From SELECT-only CTEs to data-modifying CTEs
A WITH clause is not limited to SELECT. Each CTE can be an INSERT, UPDATE or DELETE, as long as it has a RETURNING clause when you want to use its rows. The RETURNING list becomes the CTE's output columns, and later parts of the statement can read them like any other table.
This gives you a way to pass rows between statements without leaving the database. The whole thing is one SQL statement, so it is atomic: either every part takes effect, or none does.
Moving rows: delete and insert in one statement
The standard example is archiving. Without CTEs you would need a transaction, a SELECT, an INSERT and a DELETE. With a data-modifying CTE it is a single statement:
CREATE TABLE tasks (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
title text NOT NULL UNIQUE,
status text NOT NULL DEFAULT 'open',
updated_at timestamptz NOT NULL DEFAULT now()
);
CREATE TABLE tasks_archive (
id bigint PRIMARY KEY,
title text NOT NULL,
status text NOT NULL
);
INSERT INTO tasks (title, status)
VALUES ('Write report', 'done'), ('Review PR', 'open');
WITH removed AS (
DELETE FROM tasks
WHERE status = 'done'
RETURNING id, title, status
)
INSERT INTO tasks_archive (id, title, status)
SELECT id, title, status FROM removed;The DELETE runs first in the sense that matters: its RETURNING rows are the input of the INSERT. If the insert fails, for example because an id already exists in the archive, the delete is rolled back too. No row is lost and none is duplicated.
The main statement can also report on what happened. Here the main statement is a plain SELECT:
WITH removed AS (
DELETE FROM tasks
WHERE status = 'done'
RETURNING id
)
SELECT count(*) AS rows_deleted FROM removed;This deletes the rows and returns only the count. Because the CTE ran, the deletion happened even though the final query only counted.
Inserting a parent and its children together
A second common use is creating a parent row and getting its generated key into child rows without a round trip to the client.
CREATE TABLE orders (
id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
customer text NOT NULL
);
CREATE TABLE order_items (
order_id bigint NOT NULL REFERENCES orders (id),
sku text NOT NULL,
qty integer NOT NULL,
PRIMARY KEY (order_id, sku)
);
WITH new_order AS (
INSERT INTO orders (customer)
VALUES ('Ada')
RETURNING id
)
INSERT INTO order_items (order_id, sku, qty)
SELECT new_order.id, v.sku, v.qty
FROM new_order
CROSS JOIN (VALUES ('A-1', 2), ('B-7', 1)) AS v (sku, qty)
RETURNING order_id, sku, qty;The CROSS JOIN repeats the single new order id once per item. The final RETURNING belongs to the main INSERT, so it returns the item rows, and order_id in that list tells the caller which order was created.
The foreign key works here even though the parent and children are created in the same statement. PostgreSQL checks foreign keys at the end of the statement, after all the CTEs have done their work.
Chaining more than one CTE
CTEs can build on each other. A later CTE can read the RETURNING output of an earlier one. This example updates tasks and writes a log row for each one it changed:
CREATE TABLE task_log (
task_id bigint NOT NULL,
status text NOT NULL,
logged_at timestamptz NOT NULL DEFAULT now()
);
WITH updated AS (
UPDATE tasks
SET status = 'done', updated_at = now()
WHERE status = 'open'
RETURNING id, status
),
logged AS (
INSERT INTO task_log (task_id, status)
SELECT id, status FROM updated
RETURNING task_id
)
SELECT count(*) AS rows_logged FROM logged;The log gets exactly one row per updated task. Reading updated from logged is what ties them together.
What each part can and cannot see
The most important rule is about visibility. All sub-statements in a WITH query, and the main query, run against the same snapshot of the database. They do not see each other's changes to the target tables. The only way one part learns what another did is through RETURNING.
The next example makes this concrete. Suppose task 1 currently has status open:
WITH changed AS (
UPDATE tasks
SET status = 'blocked'
WHERE id = 1
RETURNING id, status
)
SELECT t.status AS table_status, c.status AS returned_status
FROM tasks AS t
JOIN changed AS c ON c.id = t.id;The row shows table_status as open and returned_status as blocked. Reading the tasks table in the main query gives the old row. Reading changed gives the new one. If you want to know what the update did, read the CTE, not the table.
The next table summarizes the rules.
| Question | Answer |
|---|---|
| Does a data-modifying CTE run if nothing reads it? | Yes. It always runs exactly once, to completion. |
| In what order do sub-statements run? | Unspecified. Do not rely on it. Dependencies through `RETURNING` are the only ordering you get. |
| Can the main query see table changes made by a CTE? | No. It sees the snapshot from before the statement. Use `RETURNING` output. |
| Where can `WITH` hold a data-modifying statement? | Only at the top level of the statement, not inside a subquery. |
| Can a CTE modify a table and be recursive? | No. Data-modifying statements are not allowed in `WITH RECURSIVE` parts. |
How many rows are processed
A data-modifying CTE without a reference runs to completion. If the main query does read it, the CTE still processes all its rows. A LIMIT in the main query limits only what the main query reads, not what the CTE modified:
WITH removed AS (
DELETE FROM tasks
WHERE status = 'done'
RETURNING id, title
)
SELECT * FROM removed
LIMIT 1;If three rows match the WHERE clause, all three are deleted. The caller only sees one. This surprises people who treat LIMIT as limiting the work. To limit the work, put the limit inside the CTE, using a subquery on the primary key:
WITH removed AS (
DELETE FROM tasks
WHERE id IN (
SELECT id FROM tasks
WHERE status = 'done'
ORDER BY id
LIMIT 1
)
RETURNING id, title
)
SELECT * FROM removed;PostgreSQL's DELETE has no LIMIT clause of its own, so this pattern is the usual way to delete a batch.
Pitfalls
Two statements touching the same row
If two sub-statements try to change the same row, only one of the changes is performed, and you cannot predict which one. PostgreSQL does not raise an error. Avoid this by making each row the target of at most one statement per query.
Triggers, rules and the final row
RETURNING in a CTE reports the row as the statement left it, including the effect of BEFORE triggers and defaults. It does not reflect later changes made by other sub-statements of the same query, because of the snapshot rule above. Also, a target table with a conditional DO INSTEAD rule cannot be the target of a data-modifying CTE.
Forgetting RETURNING
If a CTE has no RETURNING clause, it still runs, but nothing can read it. If you reference it in a later part, PostgreSQL reports an error that the CTE does not return data. That error usually means the RETURNING list is missing.
Wrong placement
Putting a data-modifying WITH inside a subquery fails with an error saying that a WITH clause containing a data-modifying statement must be at the top level. Move the WITH to the start of the statement.
Large batches
A CTE that moves millions of rows holds all of them in one transaction and may spill rows to disk. For large archives, run the statement in batches with the limit pattern shown above.
Exercises
Exercise
A statement is WITH removed AS (DELETE FROM tasks WHERE status = 'done' RETURNING id) SELECT count(*) FROM tasks WHERE status = 'done'. Assume two rows have status 'done' before it runs. What count does it return, and how many rows does the table hold with that status afterward?
Show answer
It returns 2, because the main query reads the snapshot taken before the statement and cannot see the delete. Afterward no rows have status 'done', since the CTE ran to completion. To count the deleted rows, use SELECT count(*) FROM removed.
Exercise
Write one statement that inserts a customer into a table customers (id bigint identity primary key, name text) and then inserts a row into customernotes (customerid bigint, note text) for the new customer with the note 'created'. Return the new customer id.
Show answer
WITH newcustomer AS (INSERT INTO customers (name) VALUES ('Grace') RETURNING id), noted AS (INSERT INTO customernotes (customerid, note) SELECT id, 'created' FROM newcustomer) SELECT id FROM new_customer;