Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom Order in Oracle SQL

I need to order transaction based on the currency. However I need to implement a custom order by, which makes the USD to always comes on the top, and the rest should be ordered asc.

for example :

  • BHT
  • USD
  • MYR
  • JYP

should be sorted like :

  • USD
  • BHT
  • JPY
  • MYR

Is there a simple way to handle this?

like image 599
Rudy Avatar asked Nov 12 '12 07:11

Rudy


People also ask

How do I create a custom order in SQL?

By default SQL ORDER BY sort, the column in ascending order but when the descending order is needed ORDER BY DESC can be used. In case when we need a custom sort then we need to use a CASE statement where we have to mention the priorities to get the column sorted.

What is ORDER BY in Oracle SQL?

It can also be used in an INSERT statement or a CREATE VIEW statement. An ORDER BY clause allows you to specify the order in which rows appear in the result set.

What is the default ORDER BY in Oracle?

By default, the ORDER BY clause sorts rows in ascending order whether you specify ASC or not. If you want to sort rows in descending order, you use DESC explicitly. NULLS FIRST places NULL values before non-NULL values and NULLS LAST puts the NULL values after non-NULL values.

What does ORDER BY 2 desc means in SQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.


1 Answers

Don't know if this qualifies as simple:

order by      case         when currency = 'USD' then 1         when currency = 'BHT' then 2        when currency = 'JPY' then 3        when currency = 'MYR' then 4        else 5     end 

or a bit more compact but Oracle specific:

order by decode(currency, 'USD', 1, 'BHT', 2, 'JPY', 3, 'MYR', 4, 5) 

The above solution using numbers to defined the sort order will not automatically sort currencies correctly that aren't mentioned in the case/decode expression.

To simply put USD at the front and don't care about the rest, the "generated" order criteria must be a character value as well. You can use the following in that case:

order by      case         when currency = 'USD' then '001'         else currency     end 

Which uses an "alphabetical" ordering. This works because characters are sorted after the number digits. (Using 'AAA' instead of '001' would work as well).

like image 196
a_horse_with_no_name Avatar answered Oct 04 '22 18:10

a_horse_with_no_name