A Common Table Expression (CTE) lets you define a temporary, reusable result set within a query using the WITH clause.
A Common Table Expression (CTE) is a named subquery defined with WITH
. It simplifies complex logic, improves readability, and allows recursion without creating temporary tables.
Start with WITH alias AS (subquery)
, then reference alias
in the main query.Place the CTE before the main SELECT
, INSERT
, UPDATE
, or DELETE
.
The CTE recent_customers
selects customers created this month, making the outer query easier to read.
Yes. Separate each CTE with a comma. Later CTEs can reference earlier ones, enabling step-by-step transformations.
Add the RECURSIVE
keyword after WITH
. Provide an anchor member and a recursive member joined by UNION ALL
.PostgreSQL repeats the recursive member until no new rows appear.
Use CTEs for hierarchical data, multi-step aggregations, or to break down long JOIN chains. ParadeDB’s PostgreSQL core executes CTEs efficiently, especially when materialize
is disabled in v12+.
1) Keep CTEs short and purpose-driven. 2) Name them descriptively. 3) Avoid overly large result sets; consider temp tables if reused across many queries.
See below.
.
Not inherently. Performance depends on the planner. CTEs can be optimized like subqueries in v12+, but may be slower if forced to materialize.
Yes. Define the CTE, then reference it in an UPDATE
or DELETE
. This pattern streamlines complex modifications.