In TSQL I recently discovered how to use the CASE command in the ORDER BY clause to sort results in custom ways.
For example, to order countries with the UK and USA at the top then the rest alphabetically would in the past have caused me to either generate a calculated ‘CountrySort’ column or UNION two queries.
Now I can do this …
ORDER BY CASE WHEN countryid = 1 THEN 'AAA' WHEN countryid = 23 THEN 'AAB' ELSE countryname END
Which translates as …
‘Order by countryname
having first replaced the countryname with ‘AAA’ where the countryid is 1
and ‘AAB’ where its 23′.
Here are the results (including countryid for clarity)…