Site icon The Knowledge Adda – Information That You Want

How to Custom Sort in SQL ORDER BY Clause?

Custom Sort in SQL ORDER BY Clause

This article show you how to use custom sorting using SQL ORDER BY CLAUSE in SQL Query. In SQL Query mostly there will be a need to sort data either in ASC order or DESC order. Sometime we have a requirement to sort result in Custom Order. We’ll be creating a custom sort order on the following table , ranked by their order of importance:

idcurrencycodecurrencynamecurrencysymbol
1AUDAustralian$
2CADCanadian$
3EUREuros
4GBPGreat Britian Pound£
5JPYYen¥
6USDUS Dollars$

Using CASE Operator:

SELECT * FROM currency
ORDER BY case when currencycode = 'CAD' then 1
              when currencycode = 'AUD' then 2
              when currencycode = 'EUR' then 3
              when currencycode = 'USD' then 4
              else 5
         end asc

IF / ELSE Construct:

SELECT * FROM currency ORDER BY IF(currencycode = 'USD', 1, 2) ASC

Using FIELD() Function:

SELECT * FROM currency ORDER BY FIELD(currencycode, 'USD', 'EUR', 'JPY', 'GBP', 'CAD', 'AUD') ASC
Exit mobile version