A common table expression (CTE) is a named temporary result set that exists within the scope of a single statement and that can be referred to later within that statement, possibly multiple times.
To specify common table expressions, use a WITH
clause that has one or more comma-separated subclauses. Each subclause provides a subquery that produces a result set, and associates a name with the subquery.
WITH
cte_name
[(col_name
[, col_name
] ...)] AS (subquery
)
[, cte_name
[(col_name
[, col_name
] ...)] AS (subquery
)] ...
cte_name
names a single common table expression and can be used as a table reference in the statement containing the WITH
clause.
The subquery
part of AS (subquery
)
is called the “subquery of the CTE” and is what produces the CTE result set. The parentheses following AS
are required.
A common table expression is recursive if its subquery refers to its own name.
The following example defines CTEs named cte1
and cte2
in the WITH
clause, and refers to them in the top-level SELECT
that follows the WITH
clause:
WITH
cte1 AS (SELECT a, b FROM table1),
cte2 AS (SELECT c, d FROM table2)
SELECT b, d FROM cte1 JOIN cte2
WHERE cte1.a = cte2.c;
In the statement containing the WITH
clause, each CTE name can be referenced to access the corresponding CTE result set.
A CTE name can be referenced in other CTEs, enabling CTEs to be defined based on other CTEs.
A CTE can refer to itself to define a recursive CTE. Common applications of recursive CTEs include series generation and traversal of hierarchical or tree-structured data.