CASE is SQL's if/then/else — it lets a query make decisions row by row, bucketing values, relabelling data and even pivoting rows into columns. Paired with the NULL-handling functions, it's one of the most useful tools for turning raw data into a report.
The CASE expression
SELECTname,package,CASEWHEN package >= 10 THEN 'High'WHEN package >= 6 THEN 'Mid'ELSE 'Entry'END AS bandFROM students;-- CASE works anywhere an expression does: SELECT, WHERE, ORDER BY, GROUP BY.ORDER BY CASE WHEN placed THEN 0 ELSE 1 END; -- placed students first
COALESCE & NULLIF
COALESCE returns the first non-NULL argument — perfect for fallbacks. NULLIF turns a value into NULL when it equals something (handy to avoid divide-by-zero):
SELECT COALESCE(email, phone, 'no contact') AS contact FROM students;SELECT COALESCE(package, 0) AS package FROM students; -- treat NULL as 0-- Avoid division by zero: NULLIF(denominator, 0) → NULL instead of an errorSELECT wins * 1.0 / NULLIF(games, 0) AS win_rate FROM teams;
Conditional aggregation
Combining CASE inside an aggregate lets you pivot — turn row categories into columns, a common reporting need:
SELECTprogramme,COUNT(*) AS total,SUM(CASE WHEN placed THEN 1 ELSE 0 END) AS placed,ROUND(AVG(CASE WHEN placed THEN package END), 1) AS avg_placed_pkgFROM studentsGROUP BY programme;
Practice
Add a salary band column with CASE. Use COALESCE to show "N/A" for missing emails. Then write a per-programme report that counts total students, placed students (conditional SUM), and the average package of only the placed ones.
Key takeaways
- 01CASE WHEN … THEN … ELSE … END is SQL's if/then/else; usable in SELECT, WHERE, ORDER BY, GROUP BY.
- 02COALESCE returns the first non-NULL argument — great for fallbacks/defaults.
- 03NULLIF(x, y) returns NULL when x = y — classic divide-by-zero guard.
- 04SUM(CASE WHEN cond THEN 1 ELSE 0 END) counts matching rows per group.
- 05Conditional aggregation pivots row categories into columns for reports.
