SQL CASE WHEN: conditional logic in queries
CASE WHEN is SQL's if/else. It returns a value per row based on conditions, so you can label rows, bucket numbers or build pivot columns.
Branches are checked in order
Postgres returns the first WHEN that's true and ignores the rest, so put the narrowest condition first. Without ELSE, unmatched rows get NULL.
SELECT name, salary,
CASE
WHEN salary >= 170000 THEN 'high'
WHEN salary >= 120000 THEN 'mid'
ELSE 'entry'
END AS band
FROM employees;Pivoting with CASE
SUM(CASE WHEN category = 'travel' THEN amount END) turns one category into its own column. One expression per column gives you a pivot table.
Try it
This runs real PostgreSQL in your browser on the practice tables. Change it and run it again.
try it
Starting Postgres in your browser…
Real Postgres in your browser. Edit the query and run it, or open it in the full playground.
Common mistakes
- Broad conditions first, so later branches never fire.
- Missing ELSE, leaving NULLs where you wanted a label or 0.
- Using > where the boundary value should be included (>=).
Practice drills
Reading it isn't enough. Solve these and it'll still be there in an interview.