Common Table Expression (CTE)

Description

A Common Table Expression (CTE) is a temporary result set derived from a query specified in a WITH clause, which immediately precedes a SELECT or INSERT keyword. The CTE is defined only with the execution scope of a single statement, and can be referred in the scope.

Syntax

  1. withClause: WITH cteClause [ , ... ]
  2. cteClause: cte_name AS (select statement)

Note:

  • The WITH clause is not supported within Sub-Query block
  • CTEs are supported in Views, CTAS and INSERT statement
  • Recursive Queries are not supported

Examples

  1. WITH q1 AS ( SELECT key FROM src WHERE key = '5')
  2. SELECT *
  3. FROM q1;
  4. -- chaining CTEs
  5. WITH q1 AS ( SELECT key FROM q2 WHERE key = '5'),
  6. q2 AS ( SELECT key FROM src WHERE key = '5')
  7. SELECT * FROM (SELECT key FROM q1) a;
  8. -- insert example
  9. WITH q1 AS ( SELECT key, value FROM src WHERE key = '5')
  10. FROM q1
  11. INSERT OVERWRITE TABLE t1
  12. SELECT *;
  13. -- ctas example
  14. CREATE TABLE t2 AS
  15. WITH q1 AS ( SELECT key FROM src WHERE key = '4')
  16. SELECT * FROM q1;