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
RECURSIVE
Allow one or more of the
<cte definition> queries to be self-referential, providing for the
possibility of recursive queries.<cte definition>
<cte definition>
The subquery or one of the subqueries defined within this
Each column alias in
WITH clause, structured as follows:| Parameter | Description |
|---|---|
<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>. |
<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>
<select statement>
The
SELECT statement to run with the defined WITH subqueries.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 aWITH clause:
WITH Example
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 theRECURSIVE option, using the following form:
Recursive WITH Syntax
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.
Recursive Query Example
Recursive Query with Recursion Trail Example