// conditional reference

SQL EXISTS operator

True when the subquery returns at least one row, regardless of what those rows contain.

カテゴリ
条件付き
Returns
boolean
In this category
19 of 43

構文

EXISTS (SELECT 1 FROM t WHERE ...) | NOT EXISTS (...)

エンジンサポート

エンジンSupportメモ
SQL Server はい Supported under this name.
PostgreSQL はい Supported under this name.
MySQL はい Supported under this name.
SQLite はい Supported under this name.
Oracle はい Supported under this name.

例

Any engine

SELECT c.name FROM customers c WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

PostgreSQL

SELECT 1 WHERE EXISTS (SELECT 1 FROM pg_catalog.pg_tables);

知っておくと便利なこと

  • The inner SELECT list is ignored: SELECT 1, SELECT * and SELECT NULL all behave the same; pick the one your team reads best.
  • EXISTS is two-valued: TRUE or FALSE, never UNKNOWN, so it composes with NOT cleanly where IN does not.
  • Correlated EXISTS stops scanning the subquery at the first match for each outer row.

Questions about EXISTS

Why SELECT 1 inside EXISTS?

The column list is never read; 1 just says 'row count only'. SELECT * is equally correct.

EXISTS vs IN for subqueries?

Correlated logic reads naturally as EXISTS, it is NULL-immune, and planners turn both into joins in most cases.

Can EXISTS return NULL?

No: TRUE or FALSE only, which is why NOT EXISTS sidesteps the NOT IN trap.

Browse every function in the SQL function reference, or see what the SQLly desktop app does for your database.

// fewer lookups

Functions your engine actually has

SQLly's completion lists the built-in functions of the engine you're connected to, whether that's SQL Server, PostgreSQL, MySQL, SQLite or Oracle. Hover a function for help, and signature hints show each argument as you type.