Skill 1.3.1

Write common table expressions (CTEs)

Key Concepts

A CTE is defined with WITH name (columns) AS (SELECT ...) immediately before the statement that uses it, which can be a SELECT, INSERT, UPDATE, DELETE or MERGE. Several CTEs can be chained, each referring to earlier ones, and a CTE can be referenced more than once in the statement. Unlike a temporary table, a CTE is not materialized; the optimizer expands it into the query, so a CTE referenced twice may be computed twice.

A recursive CTE has an anchor member, UNION ALL and a recursive member that references the CTE itself, and it walks hierarchies such as organization charts, bills of materials or category trees. Recursion stops when the recursive member returns no rows, and OPTION (MAXRECURSION n) limits the depth (the default is 100; 0 means no limit), which protects against cycles in the data.