Sub topic 7
Chaining Statements with Data-Modifying CTEs
This chapter assumes you know SELECT, INSERT, UPDATE, and DELETE, along with primary keys and PostgreSQL clients. A data-modifying common table expression, or CTE, is a named substatement in a WITH clause that can change data. Its RETURNING rows can become input to another statement.
Use `RETURNING` as a temporary result
A normal CTE contains a query that reads data:
WITH open_tasks AS (
SELECT id, title
FROM tasks
WHERE status = 'open'
)
SELECT *
FROM open_tasks;A data-modifying CTE instead contains INSERT, UPDATE, or DELETE. PostgreSQL runs that operation and makes its RETURNING output available to the main statement.
This lets you pass changed rows directly between statements. For example, the following statement deletes completed tasks and inserts those same rows into an archive:
CREATE TABLE tasks_archive (
id bigint PRIMARY KEY,
title text NOT NULL,
status text NOT NULL
);
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 removed name represents the rows produced by DELETE ... RETURNING. The outer INSERT reads that result as if it were a temporary table.
Why this is useful
Without a data-modifying CTE, an application might need to:
- Select the rows to archive.
- Insert those rows into the archive table.
- Delete the original rows.
That approach creates race conditions unless the application carefully manages a transaction and locks. It can also require transferring rows through application code.
The CTE keeps the row movement inside PostgreSQL. The delete and insert belong to one statement. If the statement fails, PostgreSQL rolls back the whole statement.
The execution model
Data-modifying CTEs have rules that differ from ordinary read-only CTEs:
- The modifying operation runs exactly once.
- It runs to completion, even if the outer query reads only some of its returned rows.
- The CTE and the main statement use the same statement snapshot.
- The outer statement cannot usually see the CTE's table changes by querying the table again. It sees the changes through the CTE's
RETURNINGoutput. - All modifying parts are part of the same statement and transaction.
For example, this pattern is correct because the outer INSERT consumes the rows returned by removed:
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;Do not try to delete a row in one CTE and update that same row again in another CTE. The order of data-modifying substatements is not a safe coordination mechanism, and modifying the same row more than once in one statement is unsupported as a design.
Choosing columns for the handoff
Return only the columns required by the next operation. If the archive also stores a deletion time, calculate it in the outer statement:
WITH removed AS (
DELETE FROM tasks
WHERE status = 'done'
RETURNING id, title, status
)
INSERT INTO tasks_archive (id, title, status, archived_at)
SELECT id, title, status, now()
FROM removed;Expressions in the outer query use the returned CTE columns just like columns from any other relation.
Exercise
In the archive example, which part supplies the rows that the outer INSERT consumes?
Show answer
The DELETE statement's RETURNING list supplies them through the CTE named removed.