Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 328
RustyHamster Avatar asked Jan 10 '23 12:01

RustyHamster


1 Answers

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
like image 115
Michael Berkowski Avatar answered Jan 22 '23 19:01

Michael Berkowski