Skip to the page

Querying · core

NULL and three-valued logic

NULL means 'unknown', so any comparison with NULL (even NULL = NULL) gives unknown rather than true, WHERE keeps only rows where the condition is true, and aggregates like COUNT(column) and AVG skip NULLs.

The notes

What you must know

  • Test with IS NULL / IS NOT NULL. column = NULL is never true. Postgres also has IS DISTINCT FROM for NULL-safe comparison.
  • WHERE city <> 'Pune' does not return rows where city is NULL (unknown is not true).
  • COUNT(*) counts rows; COUNT(col) counts non-NULL values; SUM/AVG/MIN/MAX ignore NULLs (AVG divides by the non-NULL count). SUM of no rows is NULL, not 0: use COALESCE(SUM(x), 0).
  • COALESCE(a, b, c) returns the first non-NULL value; NULLIF(a, b) returns NULL when a = b (handy to avoid division by zero).
  • NOT IN (subquery) returns no rows if the subquery contains a NULL. Use NOT EXISTS.
  • Sort order of NULLs differs: Postgres puts NULLs last in ASC and first in DESC; SQLite and MySQL put them first in ASC. Write NULLS FIRST/LAST when it matters.
  • UNIQUE allows many NULLs in Postgres by default (NULLS NOT DISTINCT changes that); a CHECK constraint passes when its expression is NULL.

The red pen

Common traps: mistake → fix

  • Mistake: WHERE x = NULL finds missing values

    Fix: it finds nothing; use IS NULL.

  • Mistake: COUNT(col) counts all rows

    Fix: it skips NULLs; COUNT(*) counts rows.

  • Mistake: NOT IN is the same as NOT EXISTS

    Fix: with a NULL in the list, NOT IN returns nothing.

Easy to hard

Questions interviewers ask, easy to hard

  1. What does NULL mean in SQL? What is NULL = NULL?
  2. COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)?
  3. Why did my NOT IN query return zero rows?
  4. How do you show 0 instead of NULL for a user with no orders?

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview