Skip to main content
Albero Academy

CASE & Conditional Logic

Add if/then logic to queries with CASE, handle NULLs with COALESCE and NULLIF, and pivot data with conditional aggregation.

Chapter 8SQL14 min readBeginner friendly
  • #SQL
  • #CASE
  • #Conditional

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

if/then/else in SQL
SELECT
name,
package,
CASE
WHEN package >= 10 THEN 'High'
WHEN package >= 6 THEN 'Mid'
ELSE 'Entry'
END AS band
FROM 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):

NULL helpers
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 error
SELECT 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:

rows → columns
SELECT
programme,
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_pkg
FROM students
GROUP 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

  1. 01CASE WHEN … THEN … ELSE … END is SQL's if/then/else; usable in SELECT, WHERE, ORDER BY, GROUP BY.
  2. 02COALESCE returns the first non-NULL argument — great for fallbacks/defaults.
  3. 03NULLIF(x, y) returns NULL when x = y — classic divide-by-zero guard.
  4. 04SUM(CASE WHEN cond THEN 1 ELSE 0 END) counts matching rows per group.
  5. 05Conditional aggregation pivots row categories into columns for reports.