WITH Clause

This section provides support for Common Table Expressions (CTE), so the results of WITH clause can be used in the rest of SELECT query.

Limitations

  1. Recursive queries are not supported.
  2. When subquery is used inside WITH section, it’s result should be scalar with exactly one row.
  3. Expression’s results are not available in subqueries.

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 sum(bytes) expression result from 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 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: Re-using expression in subquery

As a workaround for current limitation for expression usage in subqueries, you may duplicate it.

  1. WITH ['hello'] AS hello
  2. SELECT
  3. hello,
  4. *
  5. FROM
  6. (
  7. WITH ['hello'] AS hello
  8. SELECT hello
  9. )
  1. ┌─hello─────┬─hello─────┐
  2. ['hello'] ['hello']
  3. └───────────┴───────────┘