I have a text field that is a date, although sometimes it also has the time component. Ex:
"23/1/1999"
"25/2/2003 05:18:00"
Now, i simply want to query them and order by the date component only. My attempt
TO_DATE(
TO_CHAR(
TO_DATE(mytextfield , 'DD-MM-YYYY HH:MI:SS')
,'DD-MM-YYYY')
,'MON-YYYY')
The above fails on the outer TO_DATE (ORA-01843 invalid month.)
TO_CHAR(
TO_DATE(mytextfield , 'DD-MM-YYYY HH:MI:SS')
,'DD-MM-YYYY')
The above works, but i’m left with a string, not a date.
——– Solution using accepted answer
Just use
EXTRACT(MONTH FROM TO_DATE(timetable.string_time) , 'DD-MM-YYYY HH24:MI:SS'))
EXTRACT(YEAR FROM TO_DATE(timetable.string_time) , 'DD-MM-YYYY HH24:MI:SS'))
As stated on the answer, you can swap the order you use it in the ORDER BY and in the SELECT.
Will need a little number formatting on the month, and some concats, but this works very well.
NLS_DATE_FORMATspecifies the default date format to use with theTO_CHARandTO_DATEfunctions. Let’s change it to get nice output from SQL*Plus:First we use
TO_DATEto convert the textual representation of date into real date type (note that the date format below accepts the shorter text):Second – we want to truncate the date to get rid of unnecessary fields (
TRUNCfunction):Now you can use this in
ORDER BYorGROUP BYprovided that you want the ordering based on year/month/day (and so on).If you want to do some exotic sorting (for grouping you don’t care:
{year,month}isn’t any different from{month, year})- e.g. month/year, then I think you need to compose the individual fields and use the following: