Custom Sorting in SQL

At some point everyone using SQL has come to the point where they need to make a special sorting of a few columns because of a business rule.

You have this code

SELECT CategoryID, CategoryName, ShownName, UpdatedTime
FROM tbl_Categories
WHERE Published = 1
ORDER BY CategoryName

Fx: I want the categories sorted as this except for News and SpotMarket results that should be placed on the top in the described order.

I will show how to do this with this case. Replace the ORDER BY with the following code:

ORDER BY CASE WHEN CategoryName = 'News' THEN 'AAAA'
CASE WHEN CategoryName = 'SpotMarket' THEN 'AAAB'
ELSE CategoryName END

Leave a Reply

Your email address will not be published. Required fields are marked *