2020-05-15 11:25:18 +00:00
---
2022-08-28 14:53:34 +00:00
slug: /en/sql-reference/statements/select/with
2022-04-09 13:29:05 +00:00
sidebar_label: WITH
2020-05-15 11:25:18 +00:00
---
2022-06-02 10:55:18 +00:00
# WITH Clause
2020-05-15 04:34:54 +00:00
2021-05-27 19:49:41 +00:00
ClickHouse supports Common Table Expressions ([CTE](https://en.wikipedia.org/wiki/Hierarchical_and_recursive_queries_in_SQL)), 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.
2020-05-15 04:34:54 +00:00
2020-10-29 18:22:28 +00:00
## Syntax
2020-05-15 04:34:54 +00:00
2020-10-29 18:22:28 +00:00
``` sql
WITH < expression > AS < identifier >
```
or
``` sql
WITH < identifier > AS < subquery expression >
```
2020-05-15 04:34:54 +00:00
2022-06-02 10:55:18 +00:00
## Examples
2020-05-15 04:34:54 +00:00
**Example 1:** Using constant expression as “variable”
``` sql
WITH '2019-08-01 15:23:00' as ts_upper_bound
SELECT *
FROM hits
WHERE
EventDate = toDate(ts_upper_bound) AND
2020-10-29 18:22:28 +00:00
EventTime < = ts_upper_bound;
2020-05-15 04:34:54 +00:00
```
2020-10-29 18:22:28 +00:00
**Example 2:** Evicting a sum(bytes) expression result from the SELECT clause column list
2020-05-15 04:34:54 +00:00
``` sql
WITH sum(bytes) as s
SELECT
formatReadableSize(s),
table
FROM system.parts
GROUP BY table
2020-10-29 18:22:28 +00:00
ORDER BY s;
2020-05-15 04:34:54 +00:00
```
2020-10-29 18:22:28 +00:00
**Example 3:** Using results of a scalar subquery
2020-05-15 04:34:54 +00:00
``` sql
/* this example would return TOP 10 of most huge tables */
WITH
(
SELECT sum(bytes)
FROM system.parts
WHERE active
) AS total_disk_usage
SELECT
(sum(bytes) / total_disk_usage) * 100 AS table_disk_usage,
table
FROM system.parts
GROUP BY table
ORDER BY table_disk_usage DESC
2020-10-29 18:22:28 +00:00
LIMIT 10;
2020-05-15 04:34:54 +00:00
```
2020-10-29 18:22:28 +00:00
**Example 4:** Reusing expression in a subquery
2020-05-15 04:34:54 +00:00
``` sql
2021-07-29 15:20:55 +00:00
WITH test1 AS (SELECT i + 1, j + 1 FROM test1)
2020-10-29 18:22:28 +00:00
SELECT * FROM test1;
2020-05-15 04:34:54 +00:00
```