// conditional reference

SQL NOT EXISTS operator

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

Categoría
Condicional
Returns
boolean
In this category
20 of 43

Sintaxis

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

Soporte del motor

MotorSupportNotas
SQL Server Sí Supported under this name.
PostgreSQL Sí Supported under this name.
MySQL Sí Supported under this name.
SQLite Sí Supported under this name.
Oracle Sí Supported under this name.

Ejemplos

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;

Conviene saberlo

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