A common table expression, or CTE, is a set of query results obtained from a simple query specified within a WITH clause and which immediately precedes a SELECT or INSERT keyword. A CTE exists only within the scope of a single SQL statement. One or more CTEs can be used with the following SQL statements:
SELECT
INSERT
CREATE TABLE AS SELECT
CREATE VIEW AS SELECT
The following example demonstrates the use CTE in a SELECT statement:
WITH q1 AS (SELECTkeyfrom src wherekey='5') SELECT*from q1;
The following example demonstrates the use of q1 as a CTE in an INSERT statement:
CREATETABLEs1LIKE src WITH q1 AS (SELECTkey, valueFROM src WHEREkey='5') FROM q1 INSERT OVERWRITE TABLE s1 SELECT*;
The following example demonstrates the use of ql as a CTE in a CREATE TABLE AS SELECT clause:
CREATETABLEs2ASWITH q1 AS (SELECTkeyFROM src WHEREkey='4') SELECT*FROM q1;
The following example demonstrates the use of q1 as a CTE in a CREATE TABLE AS VIEW clause:
CREATEVIEWv1ASWITH q1 AS (SELECTkeyFROM src WHEREkey='5') SELECT*from q1;
Limitations
Common Table Expressions have the following limitations:
Recursive queries are not supported.
The WITH clause is not supported within subquery blocks.