CASE — Conditional Expressions in SQL
If-then in SQL: bucket, pivot, custom-sort
CASE is SQL’s conditional value: simple form matches one value (CASE x WHEN 1 THEN …), searched form tests conditions (CASE WHEN salary > 90000 THEN …). It returns a value anywhere values go — SELECT, WHERE, ORDER BY, GROUP BY. Always include ELSE (default NULL surprises) and close with END.
Searched CASE buckets
WHEN conditions tested in order; first TRUE wins. Always ELSE + END.
Simple CASE matches
CASE x WHEN val THEN … — equality shorthand for one column.
Pivot in one pass
SUM(CASE WHEN … THEN 1 ELSE 0 END) counts categories without N queries.
Sort custom orders
ORDER BY CASE status WHEN … encodes priority sequences indexes cannot.
1SELECT name, CASE WHEN salary >= 90000 THEN 'senior' WHEN salary >= 60000 THEN 'mid' ELSE 'junior' END AS band FROM employees;
| name | band |
|---|---|
| Alice | mid |
| Bob | junior |
| Cynthia | senior |
| David | junior |
| Elena | junior |
| Farid | mid |
Each row is bucketed by its salary. Cynthia clears 90k → senior; Alice and Farid land mid; the rest junior. Same pattern pivots rows to columns and encodes custom sort orders.
Salary bands
Bucket every row into senior/mid/junior.
1SELECT name, CASE WHEN salary >= 90000 THEN 'senior' WHEN salary >= 60000 THEN 'mid' ELSE 'junior' END AS band FROM employees;
| name | band |
|---|---|
| Alice | mid |
| Bob | junior |
| Cynthia | senior |
| David | junior |
| Elena | junior |
| Farid | mid |
Pivot + custom sort
Count Engineering in one scan; sort urgent first.
1SELECT SUM(CASE WHEN department = 'Engineering' THEN 1 ELSE 0 END) AS eng FROM employees;
| eng |
|---|
| 3 |
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Take the queries you just visualized and see the data structures that power real databases.