shuffleet
Home
Practice
Problems
Lessons
Plans
Compete
Challenges
Interviews
Leaderboard
Progress
Skills
Analytics
Submissions
Account
Settings

NULLs and missing values

Beginner · 3 min read

In two sentences

NULL means "we don't know", not zero and not empty, so any comparison with it is neither true nor false but unknown, and WHERE keeps only rows that are true. That's why NULLs vanish from filters, never match in joins, and quietly change counts and averages.

See it

customer_idemail
c1ana@shop.com
c2(empty string)
c3(three spaces)
c4NULL
queryrows returnedwhy
WHERE email = NULLnone= NULL is always unknown
WHERE email IS NULLc4the right test
WHERE email <> 'ana@shop.com'c2, c3c4 is unknown, so it's dropped too
count(*)4counts rows
count(email)3skips NULLs, but counts the blanks as real emails

c2, c3 and c4 all mean "no email", but SQL sees three different things.

Every comparison with NULL gives UNKNOWN and is dropped by WHERE; only TRUE is kept

In SQL

Turn every flavour of "missing" into one NULL first, then count:

SQL
SELECT
  customer_id,
  nullif(lower(trim(email)), '') AS email     -- '' and '   ' become NULL
FROM customers;

Then decide what missing means for each output, explicitly:

SQL
SELECT
  count(*)                       AS customers,
  count(email)                   AS with_email,
  coalesce(sum(amount), 0)       AS revenue       -- sum of only NULLs is NULL, not 0
FROM ...

To compare two columns where NULL should equal NULL (for example "did this value change?"):

SQL
WHERE old.email IS DISTINCT FROM new.email

old.email <> new.email would miss a change from NULL to a value, and from a value to NULL.

Common mistakes

  • NOT IN with a NULL in the list. WHERE id NOT IN (SELECT customer_id FROM blocked) returns nothing if any customer_id in blocked is NULL. Use NOT EXISTS.
  • avg ignores NULLs. The average of 10, NULL, 20 is 15, not 10. Decide if missing means 0 or "excluded".
  • Joins never match on NULL. Two rows with a NULL key don't join to each other. Usually that's what you want; sometimes it hides unmatched data.
  • Treating blanks as values. '' and ' ' pass IS NOT NULL and get counted. Normalise first.
  • GROUP BY puts all NULLs in one group. Unlike =, grouping treats NULLs as equal, so a single NULL bucket appears in reports. Label it.

What an interviewer asks next

  • "Is a missing amount zero, or unknown?" The answer changes the report. Say which you chose and why.
  • "How would you catch this in production?" A data-quality check on the NULL rate per column, with a threshold.

Go further

Modern SQL's page on three-valued logic is short and precise. The Trino pages list IS DISTINCT FROM, coalesce and nullif.

Practise it

Clean Customer Contact Data is this lesson as a problem. Daily Revenue Report has the sum of only NULLs trap.