Sanjoy Roy

[MCM, MCP, SCJP] – Senior PHP Programmer

Monthly Archives: May 2007

Create and Update Timestamp with MySQL


A lot of relational tables need created and update timestamps columns. I prefer having them for all tables with no exception. However, most of applications I am working on are running MySQL. MySQL has minor limitation on timestamps. Unfortunately you can create only one time stamp column that has DEFAULT NOW() value. Read more to see how to avoid this limitation. The simplest way to do this is create the following columns in the table:

stamp_created timestamp default now(), stamp_updated timestamp default now() on update now()

But MySQL will return the following error:

ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_ in DEFAULT or ON UPDATE clause
Example:
CREATE TABLE `test`.`test` (
`id` TINYINT NOT NULL AUTO_INCREMENT ,
`name` VARCHAR( 200 ) NOT NULL ,
`created` TIMESTAMP NULL ,
`modified` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ,
PRIMARY KEY ( `id` )
) ENGINE = InnoDB ;

INSERT INTO `test`.`test` (
`id` ,
`name` ,
`created` ,
`modified`
)
VALUES (
NULL , ’sanjoy roy’, NOW( ) ,
CURRENT_TIMESTAMP
);

id name created modified
1 sanjoy roy 2010-02-09 10:22:18 2010-02-09 10:22:18

After I modified my name

id name created modified
1 sanjoy kumar roy 2010-02-09 10:24:03 2010-02-09 10:25:36