// conditional reference

SQL NOT IN operator

True when the value matches no member, and silently true for no rows when a NULL sneaks in.

Category
Conditional
Returns
boolean
In this category
18 of 43

Syntax

x NOT IN (1, 2, 3) | x NOT IN (SELECT ...)

Engine support

EngineSupportNotes
SQL Server Yes Supported under this name.
PostgreSQL Yes Supported under this name.
MySQL Yes Supported under this name.
SQLite Yes Supported under this name.
Oracle Yes Supported under this name.

Examples

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);

Good to know

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