Common table expressions
- Version
- 19
- Since
- 8.4
- Review
- Draft
Summary#
A WITH clause names queries that exist for one statement. Its parts can also be INSERT, UPDATE, DELETE or MERGE statements that pass rows on through RETURNING.
Syntax#
WITH name AS [NOT MATERIALIZED | MATERIALIZED] (
SELECT ...
),
changed AS (
DELETE FROM table_name WHERE condition RETURNING column_list
)
SELECT column_list FROM changed;
Example#
The output below is from PostgreSQL 19.0, produced with psql -X -q -A -P null=NULL -v ON_ERROR_STOP=1 -f example.sql in a scratch database. The script rolls back at the end, so it leaves nothing behind.
BEGIN;
CREATE TEMPORARY TABLE tickets (
ticket_id integer PRIMARY KEY,
owner text NOT NULL,
state text NOT NULL
);
CREATE TEMPORARY TABLE ticket_archive (LIKE tickets);
INSERT INTO tickets VALUES
(1, 'kim', 'closed'), (2, 'lee', 'open'),
(3, 'kim', 'closed'), (4, 'kim', 'open');
-- Name intermediate results and reuse them in the main query.
WITH open_tickets AS (
SELECT owner, count(*) AS open_count
FROM tickets
WHERE state = 'open'
GROUP BY owner
),
busiest AS (
SELECT max(open_count) AS open_count FROM open_tickets
)
SELECT o.owner, o.open_count
FROM open_tickets AS o
JOIN busiest AS b USING (open_count)
ORDER BY o.owner;
-- Move closed rows in one statement with a data-modifying CTE.
WITH moved AS (
DELETE FROM tickets
WHERE state = 'closed'
RETURNING ticket_id, owner, state
),
archived AS (
INSERT INTO ticket_archive
SELECT ticket_id, owner, state FROM moved
RETURNING ticket_id
)
SELECT ticket_id FROM archived ORDER BY ticket_id;
SELECT (SELECT count(*) FROM tickets) AS active,
(SELECT count(*) FROM ticket_archive) AS archived;
ROLLBACK;
Expected output#
owner|open_count
kim|1
lee|1
(2 rows)
ticket_id
1
3
(2 rows)
active|archived
2|2
(1 row)
Common mistakes#
All parts of one statement use the same snapshot. Pass changed rows through RETURNING and read the CTE by name to see those changes. A data-modifying CTE runs to completion even if the outer query reads only some of its output. Make each write target a separate set of rows because the order of writes is unpredictable.
Version applicability#
PostgreSQL 8.4 added WITH, and 9.1 allowed data-changing statements inside it. Since PostgreSQL 12, a non-recursive, side-effect-free CTE referenced once can be merged into the outer query; MATERIALIZED and NOT MATERIALIZED control that choice. Earlier versions always evaluated the CTE separately. Passing rows on from MERGE with RETURNING requires PostgreSQL 17.
Sources#
- Attribution
- DevLookup contributors
- License
- CC-BY-4.0