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.

Kindcommand
Example LanguageSQL

📝 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

WITHDeclares one or more CTEs
RECURSIVELets a CTE reference itself for recursion
AS (query)The query that defines the CTE
MATERIALIZED / NOT MATERIALIZEDForces 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

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.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

Content reviewed by MOTO · Found an error? Report it

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏