← Back to SQL, page 3

sql-0043 · Medium mid

What does 3 IN (1, 2, NULL) return? What about 1 IN (1, 2, NULL) and 3 NOT IN (1, 2, NULL)?

1 IN (1, 2, NULL) is TRUE because a match was found. 3 IN (1, 2, NULL) is UNKNOWN (shown as NULL), because 3 might equal the unknown value. 3 NOT IN (1, 2, NULL) is also UNKNOWN, so a WHERE clause using it keeps no rows.

Full answer

x IN (a, b, c) is shorthand for x = a OR x = b OR x = c. With a NULL in the list, one of the comparisons is always UNKNOWN, and the OR rules decide the result:

  • If some other comparison is TRUE, then TRUE OR UNKNOWN is TRUE.
  • If every other comparison is FALSE, then FALSE OR UNKNOWN is UNKNOWN.

NOT IN is the negation: x <> a AND x <> b AND x <> c. One UNKNOWN in an AND chain with no FALSE makes the whole result UNKNOWN.

sql
CREATE TABLE vals (v INTEGER);
INSERT INTO vals VALUES (1), (3);
sql
SELECT 1 IN (1, 2, NULL)     AS one_in,
       3 IN (1, 2, NULL)     AS three_in,
       3 NOT IN (1, 2, NULL) AS three_not_in;
one_inthree_inthree_not_in
1NULLNULL

Applied to a small table, row by row:

sql
SELECT v,
       v IN (1, 2, NULL)     AS in_result,
       v NOT IN (1, 2, NULL) AS not_in_result
FROM vals
ORDER BY v;
vin_resultnot_in_result
110
3NULLNULL

For v = 1, IN is true and NOT IN is false. For v = 3, both are UNKNOWN. In a WHERE clause UNKNOWN behaves like FALSE, so WHERE v NOT IN (1, 2, NULL) would return nothing, not even 3, which is clearly not 1 or 2. This is the same mechanism behind the NOT IN subquery trap, shown here with a literal list so the logic is easier to see.

sql
CREATE TABLE vals (v INTEGER);
INSERT INTO vals VALUES (1), (3);

SELECT 1 IN (1, 2, NULL)     AS one_in,
       3 IN (1, 2, NULL)     AS three_in,
       3 NOT IN (1, 2, NULL) AS three_not_in;

SELECT v,
       v IN (1, 2, NULL)     AS in_result,
       v NOT IN (1, 2, NULL) AS not_in_result
FROM vals
ORDER BY v;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • IN expands to OR of equality checks; NOT IN to AND of inequality checks
  • A NULL in the list makes non-matches UNKNOWN
  • IN still returns TRUE when a real match exists
  • NOT IN with a NULL in the list never returns TRUE

Common mistakes

  • Building an IN list from user input that may contain NULL
  • Reading UNKNOWN as FALSE when the result is used inside NOT

Follow-ups

  • What does NOT (3 IN (1, 2, NULL)) return?
  • How do you write the same filter so NULLs in the list are ignored?

Tips

  • Expand the IN into ORs out loud; it makes the answer easy to defend