// 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.