WITH (Common Table Expression)
Last updated: 2026-11-04
WITH (Common Table Expression)
WITH lets you define named intermediate result sets (CTEs) ahead of a statement, which the main query then references like tables. Adding the RECURSIVE keyword enables recursive queries that expand row by row from a seed — the natural tool for hierarchical data such as org charts, directory trees, and dependency graphs.
| Kind | command |
|---|---|
| Example Language | SQL |
📝 Syntax
WITH [RECURSIVE] <name> [(<column>, ...)] AS ( <query> )
[, <name2> [(<column>, ...)] AS ( <query2> ) [, ...] ]
<main query>
-- a recursive CTE joins itself with UNION ALL
WITH RECURSIVE <tree> AS (
<anchor query>
UNION ALL
<recursive query, referencing <tree> itself>
)
SELECT * FROM <tree>;
⚙️ Parameters
| WITH | Declares one or more CTEs |
|---|---|
| RECURSIVE | Lets a CTE reference itself for recursion |
| AS (query) | The query that defines the CTE |
| MATERIALIZED / NOT MATERIALIZED | Forces materialization or forces inlining |
Returns:The result set of the main query. A CTE is only an intermediate result and may be referenced several times.
▶ Example
Runs real PostgreSQL 18 right in your browser (PGlite WASM, nothing to install). Press ▶ Run and the result appears in the panel below.
Output:
DROP TABLE
CREATE TABLE
INSERT 0 6
manager | reports
--------+--------
Alice | 2
Bob | 2
Dave | 1
depth | path
------+-----------------------
1 | {Alice}
2 | {Alice,Bob}
3 | {Alice,Bob,Dave}
4 | {Alice,Bob,Dave,Frank}
3 | {Alice,Bob,Eve}
2 | {Alice,Carol}
📌 Key Points
- On PostgreSQL 12+ a CTE is materialized by default and computed once even when referenced several times; NOT MATERIALIZED forces it to be inlined instead.
- Column types in a recursive CTE must unify — write NULL::int explicitly in the non-recursive term, or you get recursive query ... column N has type text in non-recursive term but type integer overall.
- The recursive arm must use UNION ALL, and a condition must guarantee termination.
- CTEs also work in front of UPDATE, DELETE and INSERT, and with RETURNING they can limit output to the changed rows.
- A CTE name is visible only to the single statement that immediately follows it.
💡 Related Cases
More case studies coming soon.
📚 Related Reference
❓ FAQ
QHow do I write a recursive CTE?
AWITH RECURSIVE name AS (seed SELECT UNION ALL self-referencing SELECT) SELECT ...; the recursive arm needs a WHERE clause to bound the depth, or it will recurse forever.
QWhen should I use a CTE instead of a temporary table?
AUse a CTE for reuse within one statement or for recursion; use a temporary table when the result is needed across statements or sessions, or when you want to index it.