// conditional reference

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.

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.