SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 12 / 37

Middle

What are the NULL pitfalls in SQL, and why can NOT IN return nothing?

Short answer

SQL uses three-valued logic: comparing with NULL yields UNKNOWN, and WHERE keeps only TRUE. So x NOT IN (1, 2, NULL) is never TRUE, and AVG, SUM, COUNT(col) ignore NULL, which easily skews numbers.

x NOT IN 1, 2, NULLx != NULLgives UNKNOWNTRUE AND UNKNOWN= UNKNOWNWHERE keeps only TRUEempty result

3 points to say:

  1. Comparing with NULL gives UNKNOWN; WHERE keeps only TRUE, so test for NULL with IS NULL.
  2. Use NOT EXISTS, never NOT IN on a column that can be NULL.
  3. AVG, SUM, COUNT(col) ignore NULL; the best defense is NOT NULL on every column with no reason to be empty.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.