WITH introduces Common Table Expressions, named subqueries that you can reference later in the same statement as if they were tables. A CTE improves readability, eliminates duplicate subqueries, and supports recursion. Multiple CTEs can be declared, separated by commas, and each may specify an optional column list. Many dialects accept the RECURSIVE modifier before the first CTE to enable recursive queries that iterate until no new rows are produced. CTEs exist only for the statement that follows the WITH clause; they are not stored objects. Some engines materialize a CTE, while others inline it, so performance can vary. Recursive CTEs must include a UNION [ALL] between an anchor member and a recursive member and require a termination condition to avoid infinite loops. CTEs obey the same privilege rules as the underlying tables and cannot reference each other in a cycle.
RECURSIVE
(keyword) - Allows self-referencing CTEscte_name
(identifier) - Name of the temporary result setcolumn_list
(identifiers) - Optional explicit column names for the CTE outputsubquery
(SQL query) - Defines the rows returned by the CTECTE, RECURSIVE, MATERIALIZED, NOT MATERIALIZED, VIEW, SUBQUERY, UNION ALL
SQL:1999 standard
A Common Table Expression (CTE) is a temporary, named result set defined with WITH and used within the same SQL statement. It works like an inline view but with better readability.
CTEs do not replace subqueries entirely but offer a cleaner, reusable alternative. You can reference the CTE multiple times without duplicating code.
Use RECURSIVE when you need to traverse hierarchical or graph-like data, such as organizational charts or parent-child structures. Ensure you add a termination condition.
You cannot add indexes directly on a CTE because it is not a stored object. Indexing must be applied to the underlying base tables instead.