Ano-Tech Computers
Enter keyword:

MySQL: Comparing datetime columns
Problem:
The column type 'datetime' can be a real time-saver, but selecting records of a certain age can be tricky.
 
Solution:
First of all, make 100% sure time is perfectly syncronized between the mysql server and its clients.

SUBDATE() only accepts datetime objects or the INTERVAL keyword:
"SELECT * FROM table WHERE column BETWEEN SUBDATE(NOW(), INTERVAL 7 DAY) AND NOW()"
The INTERVAL keyword accepts one (and only one) of the following: YEAR, MONTH, DAY, HOUR, MINUTE and SECOND.

SUBTIME on the other hand lets you specify the time as a string:
"SELECT * FROM table WHERE column BETWEEN SUBTIME(NOW(), '7 0:0:0.0000') AND NOW();"
This allows more fine-grained control but can't express months or years.

Note: While you COULD reverse the expression like so;
"SUBDATE(column, INTERVAL 7 DAY)"
but this would be a BIG MISTAKE because you would make one expensive SUBDATE() call for every single record. The SUBDATE(NOW(),...) expression needs only be called once.

Finally, resist the temptation to use > and < for datetime comparison. The documentation does in fact explain that this is possible because of silent conversion between string and numerical form. Unfortunately, in real life it doesn't work as expected. If you really must use comparison instead of the excellent BETWEEN...AND form, then I suggest you first convert to unixtime.
 
Discuss this solution
Did this article solve your problem? Yes No Did not apply

We welcome anyone who is willing to contribute to this public knowledge base, contact siteadmin@atc.no if you have information you would like to share. The idea is not to replace the commercial support sites, but to publish those hard-to-find solutions you've found yourself looking for over and over again.

Show all articles