November 20, 2009 | In: BSD/Mac OSX, Linux, MySQL, Windows

MySQL Default DATETIME Value – A Quick Rant

I was reviewing a year old code which I am adding a feature to. It so happened I came to a familiar issue about having two timestamp/datetime columns, one which should have the CURRENT_DATE / NOW() as default value and the other with an ‘ON UPDATE CURENT_TIMESTAMP’. Examine the simple structure below:

CREATE TABLE `stories` (
`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`title` VARCHAR( 255 ) NOT NULL ,
`text` TEXT NOT NULL ,
`creationdate` DATETIME NOT NULL ,
`lastupdate` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP
) ENGINE = MYISAM

When you want to store stories, you would also want to record when it was originally created as well track the last time it was updated. The problem here is that adding a `DEFAULT NOW()` clause will not work for the `CREATE TABLE` query above as it is not supported. So when your insert a new story you will have to explicitly add a `NOW()` function for the `creationdate` row so it will reflect the current date as creation date. This should’ve been a simple schema functionality, turns out after more than a year MySQL seems to ignore for some reason.

Go on have yourself a read here http://bugs.mysql.com/bug.php?id=27645

How about you, how many times have you have to work around this from your application code?

Comment Form