Selecting empty mysql datetime fields

Is there a better way to select empty datetime fields than this?

SELECT * FROM `table` WHERE `datetime_field` = '0000-00-00 00:00:00'

Answer

Better in what way? That query does everything you ask of it and, provided there’s an index on datetime_field, it’s as fast as it’s going to get.

If you’re worried about the query looking “ugly”, don’t be. Its intent is quite clear.

The only possible improvement you could consider is to use NULLs for these zero-date/time rows, in which case your query becomes:

SELECT * FROM `table` WHERE `datetime_field` IS NULL

That’s what I’d do with a standards-compliant DBMS. My understanding is that MySQL may represent true NULL datetime fields in this horrific manner, in which case I guess the IS NULL may not work.

Leave a Reply

Your email address will not be published. Required fields are marked *