SQL NOT IN operator
True when the value matches no member, and silently true for no rows when a NULL sneaks in.
- 카테고리
- 조건부
- Returns
boolean- In this category
- 18 of 43
구문
x NOT IN (1, 2, 3) | x NOT IN (SELECT ...)
엔진 지원
| 엔진 | 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 * FROM customers c WHERE c.id NOT IN (SELECT o.customer_id FROM orders o WHERE o.customer_id IS NOT NULL);
Any engine
SELECT * FROM customers c WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
알아 두면 좋은 정보
- One NULL in the list or subquery makes every comparison UNKNOWN, so no row can satisfy NOT IN and the result is empty without any error.
- Safe rewrites: NOT EXISTS correlated on the join key, or NOT IN (SELECT y FROM t WHERE y IS NOT NULL).
- Literal lists are safe because you can see there is no NULL in them.
- LEFT JOIN ... WHERE right.key IS NULL is a third anti-join, but it can duplicate outer rows on multi-match keys.
Questions about NOT IN
Why does NOT IN return zero rows?
The subquery contains a NULL: x NOT IN (...) needs every comparison FALSE, and the NULL one is UNKNOWN instead.
NOT IN or NOT EXISTS?
NOT EXISTS: NULL-safe, and modern planners run it as an efficient anti-join.
When is NOT IN fine?
With literal lists, or a subquery over a NOT NULL column: visible, no NULL, no trap.
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.