Structuring Queries with CTEs
Name intermediate query results without assuming a fixed execution strategy.
database, postgresql, sql, cte, with, queryName an intermediate idea
A common table expression (CTE) names a query for use inside a statement. This can make a multi-stage question easier to read without creating a permanent table. Naming stages is a reasoning aid, not a promise that PostgreSQL will physically execute them in that order.
SQL illustration
Use the fictional books setup in the same disposable session:
WITH known_pages AS (
SELECT id, title, pages
FROM books
WHERE pages IS NOT NULL
)
SELECT id, title, pages
FROM known_pages
WHERE pages >= 120
ORDER BY id;
Prepared result — not live execution:
| id | title | pages |
|---|---|---|
| 1 | Kite | 120 |
| 3 | Tide | 200 |
| 4 | Fern | 120 |
The named query describes rows with known page counts. The outer query keeps those with at least 120 pages and orders the result. Oak is excluded by the inner condition.
See the reasoning
Follow the example one step at a time
Trace the named query and its outer filter without assuming a physical plan. This is a prepared teaching demonstration, not live code execution.
Start with books
Kite 120 | Oak NULL | Tide 200 | Fern 120
The fictional source has four rows, including one missing page count.
Scope and execution
The name exists for that statement, not later statements. PostgreSQL may
fold an eligible non-recursive, side-effect-free CTE into the parent query;
MATERIALIZED and NOT MATERIALIZED affect applicable cases and have
trade-offs. Data-modifying and recursive CTEs have different rules.
WITH RECURSIVE can express repeated traversal, but termination, duplicate
handling, and cycles need explicit thought. Inspect a plan rather than
assuming a CTE is always faster or always materialized.
Reflect on the concept
Four fixed questions to reinforce the reasoning. Answers are not saved or scored.
