1.3 Nulls, Case, and Conditional Logic
🪄 Step 1: Intuition & Real-World Analogy
🎯 Core Idea:
SQL’s NULL doesn’t mean zero, blank, or empty string — it means “unknown”.
And once something is “unknown”, SQL treats it differently in every operation — comparisons, aggregates, and even joins.
🌍 Real-Life Analogy:
Think of NULL as a “mystery box 🎁”.
If someone asks:
“Does this box contain chocolate?”
You can’t say yes or no — you simply don’t know!
That’s SQL’s behavior too.
Every comparison involving a mystery box (NULL) results in another mystery (NULL).
💬 Conversational Hook:
So when you filter with WHERE column <> 'X', you might think you’re getting everything except X…
but surprise! You just lost all the rows with NULL values. 😅
Let’s unpack why.
🌱 Step 2: The Core Concept Explained
Let’s tackle three pillars here: NULL behavior, conditional logic, and how to handle missing values.
1️⃣ Understanding NULL — The Unknown Value
NULLmeans unknown, not zero or empty.- Any arithmetic or comparison involving
NULLresults in… you guessed it…NULL.
Example:
| Expression | Result |
|---|---|
5 + NULL | NULL |
NULL = NULL | NULL (not TRUE!) |
NULL <> 10 | NULL |
That’s because SQL follows three-valued logic:
TRUEFALSEUNKNOWN (NULL)
Hence, filters like WHERE column = 'X' exclude NULL rows — because NULL comparisons are neither true nor false.
To explicitly test for NULL:
Use IS NULL or IS NOT NULL.
WHERE discount IS NULL2️⃣ Conditional Logic — The CASE Statement
The CASE expression adds if-else reasoning to SQL — allowing custom logic during queries.
Syntax:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
ENDIt evaluates conditions top-down, returning the first true match.
Example:
SELECT
customer_id,
CASE
WHEN total_spent >= 10000 THEN 'VIP'
WHEN total_spent >= 5000 THEN 'Loyal'
ELSE 'New'
END AS customer_segment
FROM customers;3️⃣ Combining NULL and CASE — Handling Missing Data Gracefully
When data is missing, you can replace or flag it using conditional logic:
SELECT
order_id,
CASE
WHEN discount IS NULL THEN 'No Discount'
ELSE 'Discount Applied'
END AS discount_flag
FROM orders;Or simply use COALESCE() — a shortcut for “pick the first non-null value”:
SELECT COALESCE(discount, 0) AS safe_discount FROM orders;💻 Step 3: Code Demonstration & Explanation
Let’s walk through practical examples that highlight subtle NULL behaviors and conditional tricks.
Example 1: Filtering with NULLs
SELECT *
FROM orders
WHERE discount IS NULL;Explanation:
You must use IS NULL, because discount = NULL will never match anything.
That’s the golden rule: NULL is not equal to anything — not even another NULL.
Example 2: Conditional Flagging
SELECT
order_id,
CASE
WHEN discount IS NULL THEN 'No Discount'
WHEN discount = 0 THEN 'Zero Discount'
ELSE 'Discount Applied'
END AS discount_status
FROM orders;Explanation: Notice how we distinguish between missing, zero, and non-zero values — something most analysts miss.
Example 3: Using COALESCE to Handle NULLs
SELECT
order_id,
amount,
COALESCE(discount, 0) AS adjusted_discount,
amount - COALESCE(discount, 0) AS net_amount
FROM orders;Explanation:
COALESCE() replaces missing values on the fly.
It’s your best friend when computing numeric or string results without losing rows to NULL.
Example 4: NULL in Aggregations
SELECT
COUNT(*) AS total_orders,
COUNT(discount) AS non_null_discounts
FROM orders;Explanation:
COUNT(*)counts all rows.COUNT(discount)counts only rows wherediscount IS NOT NULL.
That’s an easy way to compute data completeness in interviews or analytics audits.
⚙️ Step 4: Performance Insights & Optimization
NULLand Indexing: Some database engines (e.g., MySQL, PostgreSQL) treatNULLspecially in indexes. Indexes can include or excludeNULLentries depending on configuration — so always check execution plans.COALESCEvsCASE: Both perform similarly, butCOALESCE()is more concise for simple replacements. However, excessive use inWHEREclauses can prevent index usage.WHERE COALESCE(column, 'X') = 'Y' -- ❌ Avoid, breaks index usage WHERE column = 'Y' OR column IS NULL -- ✅ BetterAggregation & Memory: Null-handling functions (
COALESCE,IFNULL) are evaluated row-by-row, so apply them before grouping to save memory.
🎯 Step 5: Interview Perspective & Reasoning
Common Interview Questions
- “What is the difference between
NULL,0, and an empty string?” - “How does
COUNT(column)treatNULL?” - “What does
COALESCE()do?” - “Write a query that replaces NULLs with default values.”
Reasoning Expectation
Interviewers look for conceptual clarity — especially around the three-valued logic and impact on aggregations.
✅ Great answer:
“
NULLmeans unknown, so any comparison with it becomes unknown too. That’s why we must useIS NULL.COUNT(column)skips nulls, whileCOUNT(*)doesn’t.”
Bonus Challenge
Find customers who have never used a discount, including those with missing values.
SELECT customer_id
FROM orders
WHERE COALESCE(discount, 0) = 0;Can you explain why COALESCE is necessary here?
Without it, customers with NULL discounts would be excluded!
🧩 Step 6: Common Mistakes & Debugging Insights
🚨 Common Mistakes (Click to Expand)
- ❌ Writing
WHERE column = NULL→ Always useIS NULL. - ❌ Assuming
COUNT(column)counts all rows. → It ignores nulls! - ❌ Forgetting to handle
NULLin arithmetic. →100 + NULL=NULL. - ❌ Using
COALESCEin indexed filters. → Breaks index optimization.
💡 Debug Tip:
Run small test queries to inspect NULL behavior — they reveal surprises faster than debugging production queries.
🧠 Step 7: Key Takeaways
🧠 Main Idea:
NULL= “unknown”. It’s neither 0 nor empty, and behaves differently in comparisons and aggregations.
💻 How It Works: SQL uses three-valued logic (TRUE, FALSE, UNKNOWN).
CASEandCOALESCElet you transform or replace missing values explicitly.
🚀 Why It Matters: Handling
NULLcorrectly prevents silent logic errors — a hallmark of professional SQL writing and interview success.