Training
Module
Create tables, views, and temporary objects - Training
This content is a part of Create tables, views, and temporary objects.
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
Applies to: Databricks SQL
Databricks Runtime
Defines a temporary result set that you can reference possibly multiple times within the scope of a SQL statement. A CTE is used mainly in a SELECT
statement.
WITH common_table_expression [, ...]
common_table_expression
view_identifier [ ( column_identifier [, ...] ) ] [ AS ] ( query )
view_identifier
An identifier by which the common_table_expression
can be referenced
column_identifier
An optional identifier by which a column of the common_table_expression
can be referenced.
If column_identifier
s are specified their number must match the number of columns returned by the query
.
If no names are specified the column names are derived from the query
.
A query producing a result set.
-- CTE with multiple column aliases
> WITH t(x, y) AS (SELECT 1, 2)
SELECT * FROM t WHERE x = 1 AND y = 2;
1 2
-- CTE in CTE definition
> WITH t AS (
WITH t2 AS (SELECT 1)
SELECT * FROM t2)
SELECT * FROM t;
1
-- CTE in subquery
> SELECT max(c) FROM (
WITH t(c) AS (SELECT 1)
SELECT * FROM t);
1
-- CTE in subquery expression
> SELECT (WITH t AS (SELECT 1)
SELECT * FROM t);
1
-- CTE in CREATE VIEW statement
> CREATE VIEW v AS
WITH t(a, b, c, d) AS (SELECT 1, 2, 3, 4)
SELECT * FROM t;
> SELECT * FROM v;
1 2 3 4
-- CTE names are scoped
> WITH t AS (SELECT 1),
t2 AS (
WITH t AS (SELECT 2)
SELECT * FROM t)
SELECT * FROM t2;
2
Training
Module
Create tables, views, and temporary objects - Training
This content is a part of Create tables, views, and temporary objects.
Documentation
SELECT (subselect) - Azure Databricks - Databricks SQL
Learn how to use the subselect syntax in the SQL language in Databricks SQL and Databricks Runtime.
PIVOT clause - Azure Databricks - Databricks SQL
Learn how to use the PIVOT syntax of the SQL language in Databricks SQL and Databricks Runtime.
VALUES clause - Azure Databricks - Databricks SQL
Learn how to use the VALUES syntax of the SQL language in Databricks SQL and Databricks Runtime.