A Common Table Expression (CTE) is a temporary, named result set you can reference within a single PostgreSQL statement to simplify complex logic and enable recursion.
A Common Table Expression (CTE) is a temporary, named result set that lasts only for one SQL statement.It boosts readability, supports recursion, and prevents repeating subqueries.
CTEs let you reference the same derived data multiple times, chain logical steps, and give each step a descriptive name—making maintenance far easier than nested subqueries.
Begin with WITH
, name the CTE, place the query in parentheses, then write the main query that uses it.
WITH recent_orders AS (
SELECT id, customer_id, total_amount
FROM Orders
WHERE order_date >= CURRENT_DATE - INTERVAL '30 days'
)
SELECT * FROM recent_orders;
Yes.Separate each CTE with commas. Later CTEs can query earlier ones, forming a clear data pipeline.
Add RECURSIVE
after WITH
when the CTE must reference itself, useful for hierarchies like category trees or referral chains.
Filter rows early inside the CTE, project only needed columns, index join keys, and use MATERIALIZED
or NOT MATERIALIZED
(PostgreSQL 12+) to guide planner choices.
.
Since PostgreSQL 12 you can control this with MATERIALIZED
or NOT MATERIALIZED
. Before that, PostgreSQL sometimes inlines the CTE when safe.
Yes. Write the CTE, then run an UPDATE
, DELETE
, or INSERT
that references the CTE just like a regular table.
No. A CTE exists only for the duration of the statement in which it is defined and is not stored permanently.