SQL ORDER BY Customizeed sorting order

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!

Example

To sort this table Employee by department, you would use ORDER BY Department. However, if you want a different sort order that is not alphabetical, you have to map the Department values into different values that sort correctly; this can be done with a CASE expression:

NameDepartment
HasanIT
YusufHR
HillaryHR
JoeIT
MerryHR
KenAccountant
SELECT *
FROM Employee
ORDER BY CASE Department
         WHEN 'HR'         THEN 1
         WHEN 'Accountant' THEN 2
         ELSE                   3
         END;
NameDepartment
YusufHR
HillaryHR
MerryHR
KenAccountant
HasanIT
JoeIT


Got any SQL Question?