Wednesday, October 22, 2008

MySQL - Default values in created and updated columns

Found this comment on the MySQL ref site very helpful for adding both a created and updated timestamp columns with default values.

MySQL :: MySQL 5.0 Reference Manual :: 10.3.1.1 TIMESTAMP Properties: "'TIMESTAMP columns are NOT NULL by default, cannot contain NULL values, and assigning NULL assigns the current timestamp.'

What I do, is declare my created_at column as NOT NULL, then assign the column as NULL when I do the insert.. which populates it with the current timestamp.

Then on updates, the second timestamp column with the ON UPDATE...etc updates on it's own. However, the update code must not alter the created_at column at all (obviously).

created_at timestamp NOT NULL default '0000-00-00 00:00:00'
updated_at timestamp NOT NULL default CURRENT_TIMESTAMP on update CURRENT_TIMESTAMP

INSERT INTO table(created_at,updated_at) VALUES (NULL,NULL);

populates BOTH columns with same timestamp for creation."

No comments: