Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

two date columns comparison oracle do not work as expected

I have a query that involves a where clause which i compare two columns that have DATE as their data type. these are last_collected_date and update_date.

SELECT *
FROM mytable
WHERE last_collected_date < update_date;

The weird thing is that this does not work as expected and I get dates of last_collected_date that have the same day as update_date.

However when I use to_date function:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

SELECT *
FROM mytable
WHERE to_date(last_collected_date) < to_date(update_date);

It works as expected. Why is that ? Does oracle convert dates into strings internally in a select statement ?

This is my NLS settings. Is that reason I dont see my hh:mi:ss ?

enter image description here

>Solution :

DATE in Oracle is a misnomer; it is a datetime really. This means it always consists of a date and a time, and if we want to look at dates only, we set the time to midnight.

With

WHERE last_collected_date < update_date

you may be comparing 2023-02-27 09:00 with 2023-02-27 11:00. Same date, but the WHERE clause results in true, because of the different times.

This:

WHERE to_date(last_collected_date) < to_date(update_date)

is kind of dangerous, because of hidden implicit conversions, and only happens to work for you coincidentally. TO_DATE is a function applied on a string you want to convert to a datetime. What Oracle does is convert your datetimes to strings according to your session settings and then back to datetimes. Your session setting seems to be date-only, so you happen to lose the time part in the process and set your two dates to midnight thus.

If you want to compare dates, truncate the datetime to midnight:

WHERE last_collected_date < TRUNC(update_date)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading