Skip to content
Advertisement

Custom sorting in oracle

I am trying to sort a particular column “TENOR” on the basis on maturity (group by Currencies) for eg – it should be sorted in the following order ON, SW, 1M, 2M, 3M, 6M, 9M, 1Y, 18M, 2Y and so on.. where ON = Overnight, SW = Single week and 1M = 1 month. i have tried using order by case but not sure what I am missing it always gives 18M on the top of the result.

enter image description here

enter image description here

Advertisement

Answer

You can use a DECODE (or CASE) statement (and could put meaningful values) and, since you are getting a 3-character sub-string, you need to include the trailing space:

If a simplified version of your query is:

For the test data:

This outputs:

TENOR | NAME                  
:---- | :---------------------
1M    | ARZ USD 1M FX FORWARD 
2M    | ARZ USD 2M FX FORWARD 
3M    | ARZ USD 3M FX FORWARD 
6M    | ARZ USD 6M FX FORWARD 
9M    | ARZ USD 9M FX FORWARD 
1Y    | ARZ USD 1Y FX FORWARD 
18M   | ARZ USD 18M FX FORWARD
1M    | BRZ USD 1M FX FORWARD 
1Y    | BRZ USD 1Y FX FORWARD 
10Y   | BRZ USD 10Y FX FORWARD

db<>fiddle here

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement