2021-11-12 20:02:26 +00:00
|
|
|
# EXISTS {#exists-operator}
|
|
|
|
|
|
|
|
The `EXISTS` operator tests how many records are in the result of a subquery. If it is empty, then the operator returns `0`. Otherwise it returns `1`.
|
|
|
|
|
2021-11-13 20:00:00 +00:00
|
|
|
`EXISTS` can be used in a [WHERE](../../sql-reference/statements/select/where.md) clause.
|
|
|
|
|
2021-11-12 20:02:26 +00:00
|
|
|
!!! warning "Warning"
|
|
|
|
References to main query tables and columns are not supported in a subquery.
|
|
|
|
|
|
|
|
**Syntax**
|
|
|
|
|
|
|
|
```sql
|
|
|
|
WHERE EXISTS(subquery)
|
|
|
|
```
|
|
|
|
|
|
|
|
**Example**
|
|
|
|
|
|
|
|
Query:
|
|
|
|
|
|
|
|
``` sql
|
|
|
|
SELECT 'Exists' WHERE EXISTS (SELECT * FROM numbers(10) WHERE number < 2);
|
|
|
|
SELECT 'Empty subquery' WHERE EXISTS (SELECT * FROM numbers(10) WHERE number > 12);
|
|
|
|
```
|
|
|
|
|
2021-11-13 19:47:50 +00:00
|
|
|
The first query returns one row while the second query does not return rows because the result of the subquery is empty:
|
2021-11-12 20:02:26 +00:00
|
|
|
|
|
|
|
``` text
|
|
|
|
┌─'Exists'─┐
|
|
|
|
│ Exists │
|
|
|
|
└──────────┘
|
|
|
|
```
|