Sanjoy Roy

[MCM, MCP, SCJP] – Senior PHP Programmer

Update and create timestamps 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: