WITH

constructsupportedQueries & DML

docs.snowflake.com ↗

The WITH clause is an optional clause that precedes the body of the SELECT statement, and defines one or more CTEs (common table expressions) that can be used later in the statement. For example, CTEs can be referenced in the FROM clause. Note You can use a WITH clause when creating and calling an anonymous procedure similar to a stored procedure. That clause modifies a CALL command rather than a SELECT command. For more information, see CALL (with anonymous procedure). The WITH clause is used with machine learning model objects to create an alias to a specific version of the model, which can then be used to call the methods of that version. See Calling model methods.

Syntax

supportedpartialnot supportednot scored

Subquery

[ WITH
       <cte_name1> [ ( <cte_column_list> ) ] AS ( SELECT ...  )
   [ , <cte_name2> [ ( <cte_column_list> ) ] AS ( SELECT ...  ) ]
   [ , <cte_nameN> [ ( <cte_column_list> ) ] AS ( SELECT ...  ) ]
]
SELECT ...

Recursive CTE

[ WITH [ RECURSIVE ]
       <cte_name1> ( <cte_column_list> ) AS ( anchorClause UNION ALL recursiveClause )
   [ , <cte_name2> ( <cte_column_list> ) AS ( anchorClause UNION ALL recursiveClause ) ]
   [ , <cte_nameN> ( <cte_column_list> ) AS ( anchorClause UNION ALL recursiveClause ) ]
]
SELECT ...

Where

anchorClause ::=
    SELECT <anchor_column_list> FROM ...

recursiveClause ::=
    SELECT <recursive_column_list> FROM ... [ JOIN ... ]

Parameters

NameRequiredDescription
cte_name1 , cte_nameNThe CTE name must follow the rules for views and similar object identifiers.
cte_column_listThe names of the columns in the CTE (common table expression).
anchor_column_listThe columns used in the anchor clause for the recursive CTE. The columns in this list must correspond to the columns defined in cte_column_list.
recursive_column_listThe columns used in the recursive clause for the recursive CTE. The columns in this list must correspond to the columns defined in cte_column_list.

Usage notes

Parameters

cte_name1 , cte_nameN: The CTE name must follow the rules for views and similar object identifiers. cte_column_list: The names of the columns in the CTE (common table expression). anchor_column_list: The columns used in the anchor clause for the recursive CTE. The columns in this list must correspond to the columns defined in cte_column_list. recursive_column_list: The columns used in the recursive clause for the recursive CTE. The columns in this list must correspond to the columns defined in cte_column_list. For more details, see Anchor Clause and Recursive Clause (in this topic). For a detailed explanation of how the anchor clause and recursive clause work together, see Working with CTEs (Common Table Expressions).

See also

Referenced by