CASE, COALESCE & Handling NULLs
Add conditional logic directly into your query results and gracefully handle missing data with the right tools.
CASE is SQL's if/else. COALESCE replaces NULLs with a fallback. Together they make your output clean and meaningful.
EXERCISE
1CASE — Conditional Logic Inside SQL
CASE is SQL's if/else statement. It lets you return different values based on conditions — right inside your SELECT, WHERE, or ORDER BY clause.
Simple CASE — match a specific value:
SELECT name,
CASE department_id
WHEN 1 THEN 'IT'
WHEN 2 THEN 'HR'
WHEN 3 THEN 'Finance'
ELSE 'Other'
END AS department_name
FROM employees;
Searched CASE — evaluate conditions (more flexible):
SELECT name, salary,
CASE
WHEN salary >= 80000 THEN 'Senior'
WHEN salary >= 60000 THEN 'Mid-Level'
WHEN salary >= 40000 THEN 'Junior'
ELSE 'Trainee'
END AS salary_band
FROM employees;
CASE in ORDER BY — custom sort order:
-- Sort by status priority (active first, then pending, then inactive):
SELECT name, status FROM employees
ORDER BY
CASE status
WHEN 'active' THEN 1
WHEN 'pending' THEN 2
WHEN 'inactive' THEN 3
ELSE 4
END;
CASE in aggregate — conditional counting:
-- Count employees per salary band in one query:
SELECT
COUNT(CASE WHEN salary >= 80000 THEN 1 END) AS senior_count,
COUNT(CASE WHEN salary >= 60000 AND salary < 80000 THEN 1 END) AS mid_count,
COUNT(CASE WHEN salary < 60000 THEN 1 END) AS junior_count
FROM employees;
CASE with UPDATE — update different rows differently:
UPDATE employees
SET salary = salary *
CASE
WHEN department_id = 1 THEN 1.15 -- IT gets 15% raise
WHEN department_id = 2 THEN 1.10 -- HR gets 10% raise
ELSE 1.05 -- everyone else gets 5%
END;
Pro Tip: CASE always evaluates conditions top to bottom and returns the first match. Order your conditions from most specific to least specific — put the tightest conditions first.
EXERCISE
2COALESCE, IFNULL & NULLIF — Handling Missing Data
NULL is not zero, not an empty string, and not false — it is unknown. These three functions let you handle NULLs gracefully instead of letting them break your results.
COALESCE — return the first non-NULL value:
-- COALESCE(expr1, expr2, expr3, ...)
-- Returns the first expression that is NOT NULL
SELECT name,
COALESCE(phone, email, 'No contact info') AS contact
FROM customers;
-- If phone exists → use phone
-- If phone is NULL but email exists → use email
-- If both are NULL → use 'No contact info'
IFNULL — simpler two-argument version (MySQL-specific):
-- IFNULL(expression, fallback_if_null)
SELECT name, IFNULL(manager_id, 0) AS manager_id
FROM employees;
-- NULL manager_id becomes 0
-- Cleaner than COALESCE when you have only one fallback
NULLIF — turn a specific value INTO NULL:
-- NULLIF(expr1, expr2) returns NULL if they are equal, otherwise returns expr1
SELECT name, NULLIF(score, 0) AS score
FROM test_results;
-- Turns scores of 0 into NULL (useful to exclude from AVG, for example)
-- Prevent division by zero:
SELECT total_sales / NULLIF(num_transactions, 0) AS avg_transaction
FROM daily_summary;
-- If num_transactions = 0, returns NULL instead of crashing with division-by-zero error
IS NULL / IS NOT NULL in WHERE:
-- Find employees without a manager (top of hierarchy):
SELECT name FROM employees WHERE manager_id IS NULL;
-- Find customers with a phone number on file:
SELECT name, phone FROM customers WHERE phone IS NOT NULL;
-- ❌ These never work — NULL = NULL is not TRUE:
WHERE manager_id = NULL -- always returns 0 rows!
WHERE manager_id != NULL -- always returns 0 rows!
Pro Tip:
COALESCEis the ANSI standard (works in all databases).IFNULLis MySQL-specific but slightly cleaner for the simple "one fallback" case. PreferCOALESCEif portability matters.
EXERCISE
3NULL Behaviour Across SQL Operations
NULL propagates through almost every SQL operation in ways that catch beginners off guard — understanding this prevents a whole class of silent bugs.
NULL arithmetic always returns NULL:
SELECT 10 + NULL; -- NULL
SELECT 10 * NULL; -- NULL
SELECT NULL / 5; -- NULL
SELECT CONCAT('Hi ', NULL); -- NULL ← very common gotcha with names
The name concatenation trap:
-- ❌ If middle_name is NULL, full name becomes NULL:
SELECT CONCAT(first_name, ' ', middle_name, ' ', last_name) AS full_name
FROM employees;
-- Output: 'Ada NULL Lovelace' or just NULL for rows with no middle name
-- ✅ Use COALESCE to handle it:
SELECT CONCAT(first_name, ' ',
COALESCE(middle_name || ' ', ''),
last_name) AS full_name
FROM employees;
-- Or use CONCAT_WS (with separator — skips NULLs automatically):
SELECT CONCAT_WS(' ', first_name, middle_name, last_name) AS full_name
FROM employees;
-- CONCAT_WS skips NULL values and does not produce double spaces
NULL in comparisons:
-- NULL = NULL is UNKNOWN (not TRUE):
SELECT NULL = NULL; -- NULL (not 1/TRUE)
SELECT NULL != NULL; -- NULL
SELECT NULL > 5; -- NULL
-- The only way to test for NULL:
SELECT NULL IS NULL; -- 1 (TRUE)
SELECT NULL IS NOT NULL; -- 0 (FALSE)
NULL in GROUP BY — treated as one group:
-- GROUP BY treats all NULLs as the same group:
SELECT manager_id, COUNT(*) FROM employees GROUP BY manager_id;
-- All employees with NULL manager_id are grouped together
Excluding NULLs from aggregates:
-- AVG ignores NULLs — can be misleading:
-- salaries: 50000, 60000, NULL, NULL, NULL
SELECT AVG(salary) FROM employees;
-- Output: 55000 (not 22000) — divides by 2, not 5
-- To include NULLs as 0:
SELECT AVG(COALESCE(salary, 0)) FROM employees;
-- Output: 22000
Pro Tip: Treat NULL as "the unknown". Unknown + anything = unknown. Unknown = anything = unknown. The only operations that handle NULL correctly are
IS NULL,IS NOT NULL,COALESCE, andIFNULL.
