The WITH Clause and Recursive Queries
WITH name AS (query) gives a name to a query fragment (CTE, Common Table Expression). The name works like a temporary table used only within that statement. Unlike an inline view, which you read from the inside out, WITH reads top to bottom.
Naming a fragment
Naming a per-customer aggregate
WITH cust_sum AS (
SELECT cust_id, COUNT(*) AS orders, SUM(amt) AS total_amt
FROM orders
WHERE cust_id BETWEEN 101 AND 200
GROUP BY cust_id
)
SELECT c.cust_id, c.grade, s.orders, s.total_amt
FROM cust_sum s
JOIN customers c ON c.cust_id = s.cust_id
WHERE s.orders >= 20
ORDER BY s.total_amt DESC
Chaining several
Define several, separated by commas; a later one can refer to an earlier one.
Comparing per-customer totals with their average
WITH cust_sum AS (
SELECT cust_id, SUM(amt) AS total_amt
FROM orders
WHERE cust_id BETWEEN 101 AND 200
GROUP BY cust_id
),
overall AS (
SELECT AVG(total_amt) AS avg_total FROM cust_sum
)
SELECT s.cust_id, s.total_amt, o.avg_total
FROM cust_sum s
CROSS JOIN overall o
WHERE s.total_amt > o.avg_total * 1.5
ORDER BY s.total_amt DESC
Recursive WITH
A WITH that refers to itself is recursive. It joins two parts with UNION ALL.
- Anchor part: produces the first rows.
- Recursive part: reads the rows produced in the previous step and produces the next rows. It stops when no new row is produced.
The syntax differs slightly per DB.
| DB | Keyword | Column name list r (n) |
|---|---|---|
| Standard, PostgreSQL | WITH RECURSIVE | optional |
| Oracle | WITH (RECURSIVE is an error) | required |
| SQL Server | WITH (RECURSIVE is an error) | optional |
PostgreSQL · 1 through 10
WITH RECURSIVE r (n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM r WHERE n < 10
)
SELECT n FROM r
Oracle, SQL Server · 1 through 10
WITH r (n) AS (
SELECT 1
UNION ALL
SELECT n + 1 FROM r WHERE n < 10
)
SELECT n FROM r
The WHERE n < 10 in the recursive part is the stop condition. Without it, the query loops forever. SQL Server stops with an error at 100 levels by default (changed with OPTION (MAXRECURSION n)).
Monthly totals with empty months filled
A month with no orders has no row in the GROUP BY result. Generating months 1–12 recursively and attaching them with an outer join also shows the months with 0 orders.
PostgreSQL · Monthly orders of customer 101 in 2024
WITH RECURSIVE months (m) AS (
SELECT 1
UNION ALL
SELECT m + 1 FROM months WHERE m < 12
),
monthly AS (
SELECT EXTRACT(MONTH FROM ord_dt) AS m, COUNT(*) AS orders, SUM(amt) AS total_amt
FROM orders
WHERE cust_id = 101
AND ord_dt >= DATE '2024-01-01' AND ord_dt < DATE '2025-01-01'
GROUP BY EXTRACT(MONTH FROM ord_dt)
)
SELECT mo.m, COALESCE(x.orders, 0) AS orders, COALESCE(x.total_amt, 0) AS total_amt
FROM months mo
LEFT JOIN monthly x ON x.m = mo.m
ORDER BY mo.m
Oracle · Monthly orders of customer 101 in 2024
WITH months (m) AS (
SELECT 1
UNION ALL
SELECT m + 1 FROM months WHERE m < 12
),
monthly AS (
SELECT EXTRACT(MONTH FROM ord_dt) AS m, COUNT(*) AS orders, SUM(amt) AS total_amt
FROM orders
WHERE cust_id = 101
AND ord_dt >= DATE '2024-01-01' AND ord_dt < DATE '2025-01-01'
GROUP BY EXTRACT(MONTH FROM ord_dt)
)
SELECT mo.m, COALESCE(x.orders, 0) AS orders, COALESCE(x.total_amt, 0) AS total_amt
FROM months mo
LEFT JOIN monthly x ON x.m = mo.m
ORDER BY mo.m
SQL Server · Monthly orders of customer 101 in 2024
WITH months (m) AS (
SELECT 1
UNION ALL
SELECT m + 1 FROM months WHERE m < 12
),
monthly AS (
SELECT MONTH(ord_dt) AS m, COUNT(*) AS orders, SUM(amt) AS total_amt
FROM orders
WHERE cust_id = 101
AND ord_dt >= CAST('2024-01-01' AS date) AND ord_dt < CAST('2025-01-01' AS date)
GROUP BY MONTH(ord_dt)
)
SELECT mo.m, COALESCE(x.orders, 0) AS orders, COALESCE(x.total_amt, 0) AS total_amt
FROM months mo
LEFT JOIN monthly x ON x.m = mo.m
ORDER BY mo.m
NOTE Recursive WITH is most often used to follow a hierarchy linked by parent-child relationships, such as an org chart or a bill of materials. The anchor part picks the top-level rows, and the recursive part goes down one level at a time with
child.parent_id = r.id. Oracle also has theCONNECT BYsyntax, which does the same thing. Examples are in Following a Hierarchy with Recursive WITH.