// conditional reference

SQL NOT EXISTS operator

True when no row in the subquery matches: the standard anti-join.

카테고리
조건부
Returns
boolean
In this category
20 of 43

구문

NOT EXISTS (SELECT 1 FROM t WHERE ...) | LEFT JOIN ... WHERE t.id IS NULL

엔진 지원

엔진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.id FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);

Any engine

SELECT c.id FROM customers c LEFT JOIN orders o ON o.customer_id = c.id WHERE o.id IS NULL;

알아 두면 좋은 정보

  • NULLs in the subquery cannot empty the result: NOT EXISTS compares rows, not membership, so there is no NOT IN trap.
  • The LEFT JOIN ... WHERE right IS NULL anti-join can duplicate outer rows when the right side matches several times.
  • Planners implement NOT EXISTS as a hash or merge anti-join, so it scales like a join rather than like a loop.

Questions about NOT EXISTS

NOT EXISTS vs NOT IN?

NOT EXISTS is NULL-safe and usually planned better for anti-joins; NOT IN empties out on a single NULL.

NOT EXISTS vs LEFT JOIN IS NULL?

Same result when the join key is unique; the LEFT JOIN form duplicates rows when it is not.

Does the subquery need LIMIT 1?

No. EXISTS short-circuits at the first row on every modern engine.

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

Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.

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