Skip to content

NULL handling

Know how NULL behaves in filters, joins, aggregates and sorting, and write queries that stay correct when data is missing.

Practise: 11 questions

When you need it

Every real table has missing values. The question may say it outright ("customers with no email", "treat missing as zero") or hide it ("average rating", "how many orders had a coupon"). Words that signal it: "missing", "unknown", "not given", "blank", "if any", "never".

NULL means "unknown", not zero and not an empty string. Any comparison with an unknown gives unknown, and WHERE keeps only rows where the test is true.

The shape of the query

select coalesce(col, 'unknown') as label,
       count(*) as rows_total,
       count(col) as rows_with_value
from t
where col is null or col <> 'x'
group by 1;

Step by step:

  1. Ask which columns can be NULL. The world notes say so.
  2. Test with IS NULL and IS NOT NULL, never = NULL.
  3. Replace NULL with a label or default using COALESCE where the prompt asks for it.
  4. Pick the right count: COUNT(*) for rows, COUNT(col) for rows that have a value.
select coalesce(referral_source, 'unknown') as source,
       count(*) as customers,
       count(email) as with_email
from customers
group by coalesce(referral_source, 'unknown')
order by customers desc, source;

Why <> loses rows:

select count(*) filter (where referral_source <> 'organic') as naive,
       count(*) filter (where referral_source is distinct from 'organic') as null_safe,
       count(*) filter (where referral_source is null) as unknown_source
from customers;

The null_safe column is the number most people mean by "not organic". The naive <> skips every customer whose source is unknown, so null_safe is larger by exactly unknown_source.

Traps interviewers look for

Variations

In other warehouses

Practise null handling