Sub topic 10
Data-Modifying CTEs with INSERT, UPDATE, and DELETE in PostgreSQL
This chapter assumes that you know basic INSERT, UPDATE, DELETE, SELECT, and WITH syntax. It focuses on PostgreSQL behavior, which differs from many other SQL databases.
A data-modifying CTE is a CTE whose body runs an INSERT, UPDATE, or DELETE instead of a SELECT. PostgreSQL can use the rows returned by that statement in the main statement. The RETURNING clause provides those rows.
Moving deleted rows into an archive
Suppose orders contains old orders and orders_archive has the same columns. You can delete old rows and insert the deleted rows into the archive in one statement:
WITH moved AS (
DELETE FROM orders
WHERE order_date < DATE '2020-01-01'
RETURNING *
)
INSERT INTO orders_archive
SELECT *
FROM moved;The moved CTE performs the DELETE. Its RETURNING * output becomes a temporary result set. The main INSERT reads that result and stores it in orders_archive.
The CTE exists only for this statement. It does not create a permanent table or view.
Updating rows and returning changed data
UPDATE CTEs can pass changed rows to another operation. For example, an application may mark pending jobs as claimed and record the claimed jobs in a log:
WITH claimed AS (
UPDATE jobs
SET status = 'claimed',
claimed_at = CURRENT_TIMESTAMP
WHERE status = 'pending'
AND priority >= 5
RETURNING id, claimed_at
)
INSERT INTO job_events (job_id, event_type, event_time)
SELECT id, 'claimed', claimed_at
FROM claimed;The RETURNING list controls the columns available to the next statement. The CTE does not expose columns that are not included there.
You can also use a modifying CTE with a final SELECT:
WITH changed AS (
UPDATE accounts
SET status = 'closed'
WHERE last_login < DATE '2024-01-01'
RETURNING id, status
)
SELECT COUNT(*) AS closed_accounts
FROM changed;This statement changes the accounts and reports how many rows were changed.
Execution and ordering rules
Data-modifying CTEs have important PostgreSQL semantics:
- Each modifying CTE runs exactly once, even if the main statement does not read its result.
- The CTE and the main statement use the same transaction snapshot.
- PostgreSQL does not guarantee the order in which sibling modifying CTEs run.
- A modifying CTE passes data to another part of the statement through
RETURNING, not through ordinary table visibility. - Do not modify the same row twice in one statement. The result is unpredictable because only one modification may take effect.
For example, this pattern is unsafe:
WITH first_change AS (
UPDATE products
SET price = price * 1.10
WHERE id = 7
),
second_change AS (
UPDATE products
SET price = price + 5
WHERE id = 7
)
SELECT 1;Both CTEs target the same row. Combine the changes into one UPDATE, or use separate statements in a deliberate transaction.
Transactions and error handling
A modifying CTE is part of one SQL statement. If any part of the statement fails, PostgreSQL rolls back the statement's changes. You can also place the statement inside an explicit transaction when it belongs with other work:
BEGIN;
WITH moved AS (
DELETE FROM orders
WHERE order_date < DATE '2020-01-01'
RETURNING *
)
INSERT INTO orders_archive
SELECT *
FROM moved;
COMMIT;The archive table should have compatible columns and constraints. If the archive insert fails, the delete is rolled back with it.
Portability
PostgreSQL supports data-modifying statements inside a WITH clause. Other database systems may support only read-only CTEs, or may use different syntax and execution rules. Check the target database before using this feature in portable application code.
For a simple operation, a normal statement is often clearer. Use a data-modifying CTE when the rows changed by one operation must directly feed another operation and one atomic statement is useful.
Exercise
Write a PostgreSQL statement that deletes sessions whose expires_at is before CURRENT_TIMESTAMP and inserts their id values into expired_session_log(session_id).
Show answer
Use RETURNING in the deleting CTE: WITH expired AS (DELETE FROM sessions WHERE expires_at < CURRENT_TIMESTAMP RETURNING id) INSERT INTO expired_session_log (session_id) SELECT id FROM expired;