Skip to main content
Back to Academy🩹 0. Analytics Foundations (Start Here)
5 min read
Try Hands-on Lab
VISUAL LESSON0. Analytics Foundations (Start Here)

How NULL Values Break Math & Comparisons (and How COALESCE Fixes It)

Learn why NULL represents missing/unknown data (not zero or empty string), why `= NULL` fails silently, how `NULL` affects `AVG` and `NOT IN`, and how `COALESCE` and `NULLIF` protect production pipelines.

SQL NULL handlingCOALESCE vs IFNULLNULLIF prevent divide by zeroCOUNT(*) vs COUNT(column)Three-Valued Logic SQLIS NULL vs equals NULL

Explain Like I'm New: The Locked Mystery Envelope

Suppose you hold a sealed envelope labeled "Monthly Bonus". You do not know what number is inside.

  • Is it $0? No — you might have received $500 or $0, it is simply *unknown*.
  • If someone asks you: "Does Alice's sealed envelope contain the exact same amount as Bob's sealed envelope?", you cannot answer TRUE or FALSE — you have to answer `UNKNOWN`.

That is exactly how SQL treats `NULL`. NULL is not zero (`0`), and NULL is not a blank text string (`''`). NULL means *missing or unknown*.

Key Beginner Takeaway: Because NULL means *unknown*, writing WHERE email = NULL or WHERE email != NULL ALWAYS evaluates to UNKNOWN and returns zero rows. Always use IS NULL and IS NOT NULL.

Key Terminology & NULL Functions Reference

Concept / FunctionPlain-English MeaningExample
`NULL`Absence of a known value (not 0, not '').Phone number was never collected at signup.
Three-Valued Logic (3VL)SQL expressions evaluate to TRUE, FALSE, or UNKNOWN.NULL = NULL returns UNKNOWN, not TRUE!
`IS NULL` / `IS NOT NULL`The ONLY standard operators that check whether a field is missing.WHERE discount_code IS NULL
`COALESCE(a, b, c)`Returns the first non-NULL value from left to right.COALESCE(mobile_phone, home_phone, 'None')
`NULLIF(a, b)`Returns NULL if a = b, otherwise returns a. Prevents / 0 crashes!revenue / NULLIF(orders, 0)
COUNT(*) vs COUNT(col)COUNT(*) counts every row; COUNT(col) skips rows where col is NULL.Used carefully to avoid understated denominators.

Step-by-Step Concrete Examples (Trace Every Row!)

Consider a miniature `sales_rep_bonuses` table:

rep_idrep_namebase_salarycommissiondeals_closed
1Maya60000500010
2Liam6000002
3Noor60000NULL0

Trap 1: Arithmetic Poisoning (`+`, `-`, `*`) What happens if you run `SELECT rep_name, base_salary + commission AS total_pay FROM sales_rep_bonuses;`?

  • Maya: 60000 + 5000 = 65000
  • Liam: 60000 + 0 = 60000
  • Noor: `60000 + NULL = NULL`!

Any math operation touching a NULL turns the entire answer into NULL! Wrap nullable numbers with `COALESCE(commission, 0)`:

SELECT
  rep_name,
  base_salary + COALESCE(commission, 0) AS total_pay
FROM sales_rep_bonuses;

Trap 2: Divide-by-Zero Crashes & `NULLIF` Suppose you want average deal size (`commission / deals_closed`). For Noor (`deals_closed = 0`), strict engines like DuckDB, Postgres, or Spark ANSI mode **crash with Division by Zero**!

Fix it permanently with NULLIF(deals_closed, 0):

SELECT
  rep_name,
  ROUND(COALESCE(commission, 0) * 1.0 / NULLIF(deals_closed, 0), 2) AS avg_commission_per_deal
FROM sales_rep_bonuses;

Look how clean that works: - For Maya (10): NULLIF(10, 0) returns 10 -> 5000.0 / 10 = 500.00. - For Noor (0): NULLIF(0, 0) returns NULL, and 0 / NULL = NULL (no crash!). Combine with outer COALESCE(..., 0) if dashboards require 0.

Trap 3: `AVG()` and `COUNT()` Quietly Drop NULLs Using our exact 3 rows above (`5000`, `0`, `NULL`): - `COUNT(*)` = **3** (all reps) - `COUNT(commission)` = **2** (only Maya & Liam!) - `AVG(commission)` = `(5000 + 0) / 2` = **2,500** (ignoring Noor!) - `AVG(COALESCE(commission, 0))` = `(5000 + 0 + 0) / 3` = **1,666.67** (true team average!)

Both numbers are mathematically valid, depending on whether Noor truly earned $0 or had unrecorded data — which is why analysts MUST inspect NULL behavior before writing KPIs.


The Silent `NOT IN` Killer Bug

This is one of the deadliest SQL bugs in production pipelines:

-- Suppose blocked_users contains: (101, 102, NULL)
SELECT user_id
FROM active_users
WHERE user_id NOT IN (SELECT user_id FROM blocked_users);

What happens? It returns 0 rows! Why? Because user_id NOT IN (101, 102, NULL) expands to: user_id != 101 AND user_id != 102 AND user_id != NULL -> since user_id != NULL is UNKNOWN, the whole AND expression becomes UNKNOWN and filters out every user!

Two Safe Fixes: 1. Use `NOT EXISTS` (immune to NULLs!):

SELECT a.user_id
   FROM active_users a
   WHERE NOT EXISTS (
     SELECT 1 FROM blocked_users b WHERE b.user_id = a.user_id
   );
  1. Or filter NULLs explicitly in subqueries (WHERE user_id IS NOT NULL), or use a LEFT JOIN ... WHERE b.user_id IS NULL.

Common Beginner Mistakes & Defensive Checklist

Broken PatternWhy It FailsClean Production Pattern
WHERE status != 'CANCELLED'Silently drops rows where status IS NULL!WHERE COALESCE(status, 'ACTIVE') != 'CANCELLED' or WHERE status IS DISTINCT FROM 'CANCELLED'
a / bCrashes query when b = 0.a / NULLIF(b, 0)
COALESCE(col, 'N/A') inside numeric columnMixing text 'N/A' and numbers breaks schema/types.Keep numeric columns numeric (COALESCE(col, 0)), format 'N/A' only in UI layer.
WHERE col = NULLAlways returns 0 rows.WHERE col IS NULL

Quick Cheat Sheet

  1. Check NULLs with `IS NULL` / `IS NOT NULL` — never = or !=.
  2. Protect math with `COALESCE(col, 0)` and division with `NULLIF(denom, 0)`.
  3. Remember **COUNT(*) vs COUNT(col)**: aggregates ignore NULL!
  4. Never use NOT IN (subquery) if the subquery might return a single NULL — prefer `NOT EXISTS`.

Comprehension & Architecture Check (3 Questions)

Test your understanding of the concepts covered in this lesson.

1. Why does `WHERE email = NULL` return 0 rows in SQL?
2. What does `NULLIF(TRIM(email), '')` return when `email` is `' '`?
3. What does `COALESCE(NULL, NULL, 42, 99)` return?
Practice What You Learned

FOUNDATIONS-5: Handling Missing Data: NULL, COALESCE & Blank Strings

Query bronze.contacts and return contact_id, full_name, and a cleaned column contact_email. If email is NULL or blank/spaces only, replace it with 'no-email@on-file.invalid'. Otherwise, lowercase and trim the email. Order by contact_id ASC.

Solve Challenge