Wednesday, January 6, 2010

"Created on" and "Updated on" columns in Mysql

In mysql there is a limitation: You can have only one time stamp column with "Default" value "now()". Almost every table is system has created_on and updated_on columns. So how we can manage to have both with minimum efforts in our coding and mysql queries. Here is a way which I use to do this:

create table dummy_table(
id integer not null auto_increment primary key,
created_on timestamp NOT NULL default '0000-00-00 00:00:00',
updated_on timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP
);

Insert data:
insert into dummy_table(created_on) values(null);

Data inserted:
+----+---------------------+---------------------+
| id | created_on | updated_on |
+----+---------------------+---------------------+
| 1 | 2010-01-06 23:22:16 | 2010-01-06 23:22:16 |
+----+---------------------+---------------------+

Update Data:
update dummy_table set id = 3;

Data updated:

+----+---------------------+---------------------+
| id | created_on | updated_on |
+----+---------------------+---------------------+
| 3 | 2010-01-06 23:22:16 | 2010-01-06 23:23:26 |
+----+---------------------+---------------------+

So without using updated_on column in update query, it is being automatically updated. I hope this would be helpful for lots of the new mysql users.

No comments:

Post a Comment