How do I correctly compare dates using to_char?
Solution 1
it is more recommended to compare dates in this case and not strings
if you compare strings, the query will have to convert all dates in the table relevant column into strings instead of converting a single string into date.
And this way dates are compared correctly for sure regardless of the printing format
SELECT STUFF
FROM TABLENAME
WHERE STARTDATE > to_date('01-OCT-2015 00:00:00' , 'DD-MON-YYYY HH24:MI:SS')
And you can try the query:
select to_date('01-OCT-2015 00:00:00' , 'DD-MON-YYYY HH24:MI:SS') from dual;
to check if the result is as expected before continuing with main query
Solution 2
This will compare the dates as strings, which will be ordered alphabetically. If you want to compare them as strings, you should use the format 'YYYY-MM-DD' which will correctly order alphabetically. Note that 'MM' is month as a zero-padded integer, not as the month abbreviation.
Related videos on Youtube
Brian M
Updated on June 13, 2022Comments
-
Brian M almost 2 years
I have a query similar to :
SELECT STUFF FROM TABLENAME WHERE TO_CHAR(STARTDATE, 'DD-MON-YYYY') > '01-OCT-2015'
My result set contains
STARTDATE
s that all are less than '01-OCT-2015'What am I doing wrong? Thanks so much!
-
Mark Sholund over 8 yearswhat database are you using?
-
Brian M over 8 yearsWe are using an Oracle DB
-
-
Brian M over 8 yearsOK, I tried that. Now I get nothing for a result set. This is my exact query select TO_CHAR(actstartdate, 'DD-MON-YYYY') from lawgen9.queuedjob where username ='sspradli' and jobname = 'MA1802300' and TO_CHAR(actstartdate, 'YYYY-MM-DD') > '2015-10-01' and rownum < 100 order by actstartdate;
-
rp372 over 8 yearsI am not sure why you aren't getting results, but you should look at this post for a complete explanation: stackoverflow.com/questions/10178292/…
-
Brian M over 8 yearsThank you, I will look at it.,
-
Brian M over 8 yearsI tried different variations of what they say but none seem to work.