CASE Expressions in ORDER BY
Sort employees so a specific department appears first, then by salary.
Overview
CASE isn't limited to SELECT — you can use it in ORDER BY to apply custom
sorting logic that isn't a simple column order. Here we force the Engineering
department to the top of the list regardless of salary, then sort the rest by
pay.
The Query
Employees & Departments
Loading database engine...
Step-by-Step Breakdown
CASE WHEN d.name = 'Engineering' THEN 0 ELSE 1 END— assigns 0 to Engineering rows and 1 to all others, so Engineering sorts first.e.salary DESC— the secondary sort, applied within each group.- The two-key
ORDER BYproduces Engineering (highest paid first), then everyone else (highest paid first).
Multi-key custom sort
You can stack several CASE expressions in ORDER BY to define a fully
custom priority without altering the data.
Variations
Sort movies: Sci-Fi first, then newest:
Movies (Movies/Actors/Ratings)
Loading database engine...
Common Mistakes
- Mismatched THEN types. All
THEN/ELSEbranches must return the same data type or theCASEerrors. - Forgetting the secondary sort. A single
CASEinORDER BYleaves ties unsorted — add a second key. - Assuming it changes values.
CASEinORDER BYonly affects ordering, never the returned column values.