Skip to content
Advertisement

SORT dates that are not in same format – SQL

I have below table and I want to sort it by ascending order. Below command would work except not all of my dates are in correct format. Majority of them are in YYYY-MM-DD and few are in DD/MM/YYYY format. How would i sort them? Can i convert all of them in to on standard format and do the sorting?

order by saledata desc

ID_NUMBER SALEDATA SALEAMOUNT
1 2020-09-07 47,000
2 2020-03-25 51,470
3 2021-06-12 32,000
4 08/11/2019 21,000
5 2018-10-12 37,560

Advertisement

Answer

You could use:

order by (case when saledata like '%/%/%'
               then to_date(saledata, 'MM/DD/YYYY')
               else to_date(saledata, 'YYYY-MM-DD')
          end)

But you should fix the data model! Don’t store dates as strings.

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