tags:

views:

222

answers:

2

I've had some bizarre results from queries I've been testing out with the DATE function, culminating in these little beauties:

mysql> SELECT id FROM job WHERE DATE(due)=CURRENT_DATE;
Empty set (0.00 sec)

mysql> SELECT id FROM job WHERE DATE(due)=CURRENT_DATE AND id>2022;
Empty set (0.00 sec)

mysql> SELECT id FROM job WHERE DATE(due)=CURRENT_DATE AND id=2023;
+------+
| id   |
+------+
| 2023 | 
+------+

and for a bit more comedy

mysql> SELECT id, DATE(due) FROM job WHERE DATE(due) IS NULL AND id>2022;

gives us:

+------+------------+
| id   | DATE(due)  |
+------+------------+
| 2023 | 2009-08-24 | 
| 2024 | 2009-08-24 | 
| 2025 | NULL       | 
| 2026 | 2009-08-24 | 
| 2027 | NULL       | 
| 2032 | NULL       | 
| 2031 | NULL       | 
| 2033 | NULL       | 
| 2034 | NULL       | 
| 2035 | NULL       | 
| 2036 | NULL       | 
| 2037 | NULL       | 
| 2038 | NULL       | 
+------+------------+

this is on 5.0.45

Is the DATE() function completely unreliable, or am I missing something?

Clarifications:

The due field is of type datetime, and there hasn't been a date rollover in the intervening period between the queries - all queries mentioned above are still giving the same results and NOW() is currently 2009-08-24 22:54:17

In answer to Eric's query:

mysql> SELECT id, due, DATE(due) FROM job WHERE id>2022;
+------+---------------------+------------+
| id   | due                 | DATE(due)  |
+------+---------------------+------------+
| 2023 | 2009-08-24 00:00:00 | 2009-08-24 | 
| 2024 | 2009-08-24 17:20:56 | 2009-08-24 | 
| 2025 | NULL                | NULL       | 
| 2026 | 2009-08-24 17:22:07 | 2009-08-24 | 
| 2027 | NULL                | NULL       | 
| 2032 | NULL                | NULL       | 
| 2031 | NULL                | NULL       | 
| 2033 | NULL                | NULL       | 
| 2034 | NULL                | NULL       | 
| 2035 | NULL                | NULL       | 
| 2036 | NULL                | NULL       | 
| 2037 | NULL                | NULL       | 
| 2038 | NULL                | NULL       | 
+------+---------------------+------------+
+1  A: 

This worked for me:

SELECT id FROM (SELECT * FROM job WHERE due IS NOT NULL) job_not_null WHERE DATE(due) = CURRENT_DATE

I was able to reproduce the behavior where the comparison failed after the first NULL value in the column.

Andrew Barnett
Thanks - it also looks like I can have `WHERE due IS NOT NULL AND ...` instead of the subquery, but I'm a bit hesitant to use `DATE` at all now.
Cebjyre
A: 

It looks like the TO_DAYS function is a whole lot more reliable for my purposes - a straight replacement of DATE with TO_DAYS seems to be going alright.

Cebjyre