Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I correctly compare dates using to_char?

I have a query similar to :

SELECT STUFF 
FROM TABLENAME
WHERE TO_CHAR(STARTDATE, 'DD-MON-YYYY') > '01-OCT-2015'

My result set contains STARTDATEs that all are less than '01-OCT-2015'

What am I doing wrong? Thanks so much!

like image 240
Brian M Avatar asked Dec 03 '25 09:12

Brian M


2 Answers

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

like image 113
nabeel Avatar answered Dec 05 '25 01:12

nabeel


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.

like image 24
rp372 Avatar answered Dec 05 '25 00:12

rp372



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!