Relational Data - Operators - Exists

From FojiSoft Docs
Revision as of 18:52, 28 August 2024 by Chris.Hansen (talk | contribs) (Import ClickHouse Docs: Wed Aug 28 2024 14:52:43 GMT-0400 (Eastern Daylight Time))
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

The EXISTS operator checks how many records are in the result of a subquery. If it is empty, then the operator returns 0. Otherwise, it returns 1.

EXISTS can also be used in a WHERE clause.

References to main query tables and columns are not supported in a subquery.


Syntax

EXISTS(subquery)

Example

Query checking existence of values in a subquery:

SELECT EXISTS(SELECT * FROM numbers(10) WHERE number > 8), EXISTS(SELECT * FROM numbers(10) WHERE number > 11)

Result:

┌─in(1, _subquery1)─┬─in(1, _subquery2)─┐
│                 1 │                 0 │
└───────────────────┴───────────────────┘

Query with a subquery returning several rows:

SELECT count() FROM numbers(10) WHERE EXISTS(SELECT number FROM numbers(10) WHERE number > 8);

Result:

┌─count()─┐
│      10 │
└─────────┘

Query with a subquery that returns an empty result:

SELECT count() FROM numbers(10) WHERE EXISTS(SELECT number FROM numbers(10) WHERE number > 11);

Result:

┌─count()─┐
│       0 │
└─────────┘