RustyHamster RustyHamster - 6 months ago 21
SQL Question

SQL Custom Order By Clause

A quick Question. I have a query that brings back 2 columns 'Description' and 'Amount'
In the Description we have 3 outcomes.

'Gold - owned', 'Bronze - no land' and 'Silver - identified / offered'

I would like the result to show in an order of
Gold,Silver,Bronze

Order By Asc or Desc does not achieve this. Is there a way to customize a Order by clause?

Any Help on this Would be appreciated thanks
Rusty

Answer

Inside of a CASE, you may ascribe a numeric value to each and order those ascending. If you will need to query a large table, consider adding an index on Description to improve sorting performance.

ORDER BY
  CASE 
    WHEN Description = 'Gold - owned' THEN 0
    WHEN Description = 'Silver - identified / offered' THEN 1
    WHEN Description = 'Bronze - no land' THEN 2
    ELSE 99 /* Any other value (which you should not have) sorts after all */
  END ASC  /* And don't forget to be explicit about ASC order though it's the default */

Since this works like a normal column in the ORDER BY, if you needed to then sort by the Amount or other column, it can be appended with a comma.

ORDER BY 
  CASE
    WHEN Description = 'Gold '...
  END ASC,
  Amount DESC,
  AnotherColumn ASC