WITH Clause

Clickhouse supports Common Table Expressions (CTE), that is provides to use results of WITH clause in the rest of SELECT query. Named subqueries can be included to the current and child query context in places where table objects are allowed. Recursion is prevented by hiding the current level CTEs from the WITH expression.

Syntax

  1. WITH <expression> AS <identifier>

or

  1. WITH <identifier> AS <subquery expression>

Examples

Example 1: Using constant expression as “variable”

  1. WITH '2019-08-01 15:23:00' as ts_upper_bound
  2. SELECT *
  3. FROM hits
  4. WHERE
  5. EventDate = toDate(ts_upper_bound) AND
  6. EventTime <= ts_upper_bound;

Example 2: Evicting a sum(bytes) expression result from the SELECT clause column list

  1. WITH sum(bytes) as s
  2. SELECT
  3. formatReadableSize(s),
  4. table
  5. FROM system.parts
  6. GROUP BY table
  7. ORDER BY s;

Example 3: Using results of a scalar subquery

  1. /* this example would return TOP 10 of most huge tables */
  2. WITH
  3. (
  4. SELECT sum(bytes)
  5. FROM system.parts
  6. WHERE active
  7. ) AS total_disk_usage
  8. SELECT
  9. (sum(bytes) / total_disk_usage) * 100 AS table_disk_usage,
  10. table
  11. FROM system.parts
  12. GROUP BY table
  13. ORDER BY table_disk_usage DESC
  14. LIMIT 10;

Example 4: Reusing expression in a subquery

  1. WITH test1 AS (SELECT i + 1, j + 1 FROM test1)
  2. SELECT * FROM test1;

Original article