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.
Related on SQLly
Cheat sheets for the engines that have it: SQL Server, PostgreSQL, MySQL, SQLite, Oracle.
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.