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
SELECT name, package,CASEWHEN package >= 10 THEN 'High'WHEN package >= 6 THEN 'Mid'ELSE 'Entry'END AS bandFROM students;
Conditional aggregation
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_pkgFROM studentsGROUP BY programme;
Key takeaways
- 01CASE WHEN … THEN … ELSE … END is SQL's conditional (if/else) expression.
- 02Use it to bucket values into categories inline.
- 03CASE inside an aggregate computes conditional counts/averages per group (pivoting).
- 04ELSE is optional and defaults to NULL.
