SQL · Module 02: Filtering, NULL Logic & SortingTutorial 5 of 24

2.2 Mastering NULL, Three-Valued Logic & COALESCE

Master the #1 source of silent SQL bugs: NULL vs 0 vs empty string, Three-Valued Logic truth tables, COALESCE vs IFNULL, NULLIF division-by-zero protection, and how NULL affects COUNT and NOT IN.

01 Intuition: Plain-English mental model
02 Visuals: Step-by-step diagrams
03 Practice: Clean examples & tradeoffs

1. What NULL Actually Represents

Beginners often confuse NULL, 0, and '' (empty string). They are completely different things in a database:

ValueMeaningReal-World Example (discount or phone)
0Known numeric value of zeroCustomer explicitly received ₹0 discount
''Known string of length 0User explicitly saved an empty middle name
NULLUnknown / Missing / Not ApplicableCustomer hasn't entered a phone number yet

Because you cannot say whether one unknown value equals another unknown value, SQL uses Three-Valued Logic: every expression evaluates to TRUE, FALSE, or UNKNOWN.

❌ WRONG: Using = or != with NULLWHERE phone = NULLEvaluates to UNKNOWN (returns 0 rows!)Because NULL means "I don't know" — not 0 or ""✅ RIGHT: Use IS NULL / IS NOT NULLWHERE phone IS NULLEvaluates cleanly to TRUE or FALSEBonus: COALESCE(phone, 'N/A') replaces NULL
WHERE keeps ONLY rows that evaluate to TRUE — both FALSE and UNKNOWN are rejected!

2. Three-Valued Logic Truth Table (Memorize This!)

ExpressionResultWhy?
NULL = NULLUNKNOWNTwo unknown values aren't guaranteed to be equal!
NULL != 5UNKNOWNAn unknown value might be 5!
TRUE AND UNKNOWNUNKNOWNStill depends on the unknown side
FALSE AND UNKNOWNFALSEFALSE AND anything is always FALSE
TRUE OR UNKNOWNTRUETRUE OR anything is always TRUE
NULL IS NULLTRUEIS NULL specifically checks for the absence of a value
SQL
-- ❌ WRONG: Returns 0 rows every single time!
SELECT name FROM customers WHERE phone = NULL;

-- ✅ RIGHT: Always use IS NULL / IS NOT NULL
SELECT name FROM customers WHERE phone IS NULL;
SELECT name FROM customers WHERE phone IS NOT NULL;

-- ✅ PRO (PostgreSQL / SQL Standard): NULL-safe equality!
-- Treats NULL as equal to NULL (returns TRUE when both are NULL)
SELECT * FROM customers WHERE referral_code IS NOT DISTINCT FROM NULL;

3. The 4 Classic NULL Traps in Interviews & Production

Trap 1: Arithmetic & String Concatenation with NULL

100 + NULL → NULL!
'Hello ' || NULL (PostgreSQL) → NULL!

Fix: Wrap nullable columns in COALESCE(a, b, ...), which returns the first non-NULL value from left to right:

SQL
SELECT
    product_name,
    price,
    COALESCE(discount, 0) AS safe_discount,
    price - COALESCE(discount, 0) AS final_price
FROM products;

COALESCE vs IFNULL / NVL (Important Difference!)

FunctionSupported InMax ArgumentsRecommendation
COALESCE(a, b, c, ...)ALL SQL databases (ANSI Standard)Unlimited (checks left → right)✅ Always prefer COALESCE!
IFNULL(a, b)MySQL & SQLite onlyExactly 2Avoid — breaks in PostgreSQL/SQL Server
NVL(a, b)Oracle onlyExactly 2Avoid — Oracle-specific

Trap 2: COUNT(*) vs COUNT(column_name)

QueryCounts NULLs?What It Actually Returns
COUNT(*)✅ YesTotal number of rows in the table
COUNT(phone)❌ No!Number of rows where phone IS NOT NULL
COUNT(DISTINCT city)❌ No!Number of unique non-NULL cities

Trap 3: NOT IN with a NULL Returns ZERO Rows!

Why? Because x NOT IN (1, 2, NULL) expands to x != 1 AND x != 2 AND x != NULL → TRUE AND TRUE AND UNKNOWN → UNKNOWN → 0 rows returned!

SQL
-- 🚨 SILENT BUG if banned_users.user_id ever contains a NULL!
SELECT * FROM users
WHERE user_id NOT IN (SELECT user_id FROM banned_users);

-- ✅ SAFE FIX #1: Filter NULLs out of the subquery
SELECT * FROM users
WHERE user_id NOT IN (
    SELECT user_id FROM banned_users WHERE user_id IS NOT NULL
);

-- ✅ SAFE FIX #2 (Best practice): Use NOT EXISTS (immune to NULLs!)
SELECT u.*
FROM users u
WHERE NOT EXISTS (
    SELECT 1 FROM banned_users b WHERE b.user_id = u.user_id
);

Trap 4: Division by Zero → Solved with NULLIF(a, b)

NULLIF(a, b) returns NULL if a = b, otherwise returns a. Wrapping a denominator in NULLIF(col, 0) prevents division-by-zero crashes cleanly:

SQL
SELECT
    campaign,
    COALESCE(ROUND(revenue / NULLIF(clicks, 0), 2), 0) AS revenue_per_click
FROM ad_campaigns;

4. Watch IS NOT NULL & COALESCE Transform a Table Live

Tracing IS NOT NULL & COALESCE
Interactive SQL Execution Tracer · Step 1 of 3 (1. FROM customers)
1SELECT name, COALESCE(phone, 'Not Provided') AS contact
2→FROM customers
3WHERE email IS NOT NULL;
Live Table State · 1. FROM customers3 rows
nameemailphone
Aaravaarav@mail.com9876543210
Meerameera@mail.comNULL
KabirNULL9123456789
What the DB engine just did: The raw table contains NULLs in both email (Kabir) and phone (Meera).

5. Quick Check Your Understanding

Module 2.2 Quick Quiz

Q1.A table has 100 rows, and 15 of them have phone = NULL. What do COUNT(*) and COUNT(phone) return?
Q2.Why does WHERE id NOT IN (1, 2, NULL) return 0 rows even if id = 5?
Q3.What does NULLIF(10, 10) return?

Keep Exploring: Related Lessons & Tools

All Courses →