Skip to main content
Albero Academy

CASE Expressions

Conditional logic inside a query — if/else for SQL.

Advanced Queries7 min

CASE is SQL's if/else. It returns different values based on conditions — for bucketing values into categories, conditional aggregation, and cleaning data inline.

CASE WHEN

bucket a value
SELECT name, package,
CASE
WHEN package >= 10 THEN 'High'
WHEN package >= 6 THEN 'Mid'
ELSE 'Entry'
END AS band
FROM students;

Conditional aggregation

CASE inside an aggregate
SELECT programme,
COUNT(*) AS total,
COUNT(CASE WHEN status = 'placed' THEN 1 END) AS placed,
AVG(CASE WHEN status = 'placed' THEN package END) AS avg_placed_pkg
FROM students
GROUP BY programme;

Key takeaways

  1. 01CASE WHEN … THEN … ELSE … END is SQL's conditional (if/else) expression.
  2. 02Use it to bucket values into categories inline.
  3. 03CASE inside an aggregate computes conditional counts/averages per group (pivoting).
  4. 04ELSE is optional and defaults to NULL.

Finished this chapter?

Mark it complete to track your progress through SQL.