PostgreSQL CTEs (WITH)
A common table expression (CTE) is a named subquery written at the start of a statement with WITH. It turns a deeply nested query into a series of readable, named steps, and in its RECURSIVE form it can walk hierarchies and generate series.
WITH step_one AS (
SELECT …
),
step_two AS (
SELECT … FROM step_one …
)
SELECT … FROM step_two;A first CTE
The average order value from the previous lesson, rewritten with a named step:
WITH order_totals AS (
SELECT order_id, sum(quantity * unit_price) AS total
FROM order_items
GROUP BY order_id
)
SELECT round(avg(total), 2) AS avg_order_value,
count(*) FILTER (WHERE total > 50) AS orders_over_50
FROM order_totals; avg_order_value | orders_over_50
-----------------+----------------
43.95 | 5
(1 row)
Several CTEs in a row
Each CTE can use the ones defined before it. Who are the best customers, and how do they compare with the average customer?
WITH delivered AS (
SELECT o.customer_id, oi.quantity * oi.unit_price AS amount
FROM orders o
JOIN order_items oi ON oi.order_id = o.id
WHERE o.status = 'delivered'
),
per_customer AS (
SELECT customer_id, sum(amount) AS spent
FROM delivered
GROUP BY customer_id
),
average AS (
SELECT avg(spent) AS avg_spent FROM per_customer
)
SELECT c.first_name, p.spent, round(p.spent - a.avg_spent, 2) AS above_average
FROM per_customer p
JOIN customers c ON c.id = p.customer_id
CROSS JOIN average a
WHERE p.spent > a.avg_spent
ORDER BY p.spent DESC; first_name | spent | above_average
------------+--------+---------------
Ben | 153.40 | 94.23
Anna | 127.30 | 68.13
Jamal | 79.00 | 19.83
Farid | 66.00 | 6.83
(4 rows)
Reading from top to bottom tells the whole story, which is the main benefit of CTEs.
Recursive CTEs
A WITH RECURSIVE query has two parts joined by UNION ALL:
- the anchor, which produces the starting rows, and
- the recursive part, which refers to the CTE itself and produces the next rows from the previous ones.
PostgreSQL repeats the recursive part until it returns no new rows. The simplest example counts from 1 to 5:
WITH RECURSIVE counter (n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM counter WHERE n < 5
)
SELECT n FROM counter; n
---
1
2
3
4
5
(5 rows)
Walking a hierarchy
The real power shows with tree-shaped data such as employees.manager_id. Starting from the managing director, each step finds the people who report to the previous level:
WITH RECURSIVE org AS (
SELECT id, name, job_title, 1 AS level, name AS path
FROM employees
WHERE manager_id IS NULL
UNION ALL
SELECT e.id, e.name, e.job_title, org.level + 1, org.path || ' > ' || e.name
FROM employees e
JOIN org ON e.manager_id = org.id
)
SELECT repeat(' ', level - 1) || name AS employee, job_title, level
FROM org
ORDER BY path; employee | job_title | level
--------------------+---------------------+-------
Rachel Adams | Managing Director | 1
Nadia Hussein | Head of Online | 2
Omar Farouk | Web Developer | 3
Sara Lindqvist | Support Agent | 3
Victor Chen | Store Manager | 2
Lucy Evans | Bookseller | 3
Paul Becker | Bookseller | 3
Tim Novak | Warehouse Assistant | 3
(8 rows)
And the opposite direction: the chain of managers above one employee:
WITH RECURSIVE chain AS (
SELECT id, name, manager_id FROM employees WHERE name = 'Omar Farouk'
UNION ALL
SELECT e.id, e.name, e.manager_id
FROM employees e JOIN chain ON e.id = chain.manager_id
)
SELECT string_agg(name, ' reports to ') AS chain FROM chain; chain
--------------------------------------------------------------
Omar Farouk reports to Nadia Hussein reports to Rachel Adams
(1 row)
Warning: A recursive CTE on data with a cycle (A manages B, B manages A) never ends. Add a stop condition such as
WHERE level < 20, or use PostgreSQL'sCYCLEclause.
Data-modifying CTEs
In PostgreSQL a CTE may contain INSERT, UPDATE or DELETE … RETURNING, and the main query can use the returned rows. This moves cancelled orders into an archive table in one statement:
CREATE TABLE orders_archive (LIKE orders);
WITH moved AS (
DELETE FROM orders WHERE status = 'cancelled'
RETURNING *
)
INSERT INTO orders_archive SELECT * FROM moved;
SELECT id, customer_id, status FROM orders_archive ORDER BY id;
SELECT count(*) AS orders_left FROM orders;CREATE TABLE
INSERT 0 2
id | customer_id | status
----+-------------+-----------
5 | 4 | cancelled
20 | 10 | cancelled
(2 rows)
orders_left
-------------
18
(1 row)
Test yourself
What is the main benefit of a non-recursive CTE?
- It always runs faster
- It names intermediate steps, making complex queries readable
- It stores data permanently
- It creates an index
What are the two parts of a recursive CTE?
- SELECT and WHERE
- An anchor query and a recursive query combined with UNION ALL
- Two separate WITH clauses
- A view and a table
When does a recursive CTE stop?
- After 100 iterations
- When the recursive part returns no new rows
- After the anchor
- Never