Skip to main content
The WITH operation, also known as a Common Table Expression (CTE) creates a set of data that can be assigned table & column aliases and used one or more times in subsequent operations. The aliased set can be used within the SELECT, FROM, or WHERE clauses of a subsequent query or a subsequent CTE within the same WITH operation.
WITH Syntax

Parameters

RECURSIVE

Allow one or more of the <cte definition> queries to be self-referential, providing for the possibility of recursive queries.

<cte definition>

The subquery or one of the subqueries defined within this WITH clause, structured as follows:
ParameterDescription
<cte name>Table alias given to the data set returned by the CTE.
<column alias list>List of aliases assigned to the columns the CTE returns.
<subquery>SELECT statement to associate with the corresponding <cte name>.
Each column alias in <column alias list> is matched to each column returned by the corresponding <subquery> in the order that each were defined; e.g., for column aliases (A, B, C) used with a subquery SELECT x, y, z ..., alias A will reference column x, B will reference y, and C will reference z. If no aliases are used, the names of the source columns themselves can be used to reference the data set returned by the subquery.

<select statement>

The SELECT statement to run with the defined WITH subqueries.
The column aliases must be unique within the WITH statement—no other column or column alias can be similarly named, for example. Also, when used in a FROM clause and given a table alias, the table alias must be preceded with AS. A CTE can be made available to a DML or DDL statement by having the WITH statement follow the CREATE TABLE ... AS, INSERT, UPDATE, or DELETE statement (not precede it).

Examples

To define a simple CTE subquery using a WITH clause:
WITH Example
To apply the CTE to an INSERT statement while using multiple CTE definitions, follow the INSERT clause with the WITH clause:
WITH Defining Multiple Subqueries in INSERT Example

Recursive Queries

Common table expressions are used to create recursive queries, via the RECURSIVE option, using the following form:
Recursive WITH Syntax
Use UNION to remove duplicate records from the result set; use UNION ALL to return all records from the recursion.
There is no check on queries that recurse infinitely. Ensure that recursive queries are constructed with an appropriate limit.
For instance, to query all of a given manager’s subordinates:
Recursive Query Example
To show the management chain for each employee in a company:
Recursive Query with Recursion Trail Example