BTA Blog Rotating Header Image

March, 2011:

MySQL: Setting date field default to current date

In MySQL, creating a date/time stamp field that defaults to the current date/time has been a problem in the past.  MySQL restricted you to one timestamp field per table that is automatically updated with the current date/time.  Early versions of MySQL allowed multiple updating timestamp fields contrary to the specification, but this was “fixed” in later versions.  Then triggers were added to MySQL v5.0.2 and can be used as a solution for this common issue.

CREATE TRIGGER `TableName_dtColumn_default` BEFORE INSERT ON `TableName`  FOR EACH ROW SET NEW.dtColumn = CURRENT_TIMESTAMP;

Replace “TableName” with your table’s name and “dtColumn” with your date/time column’s name.  Also the trigger name, “TableName_dtColumn_default” in this example, must be unique within a schema.

MySQL triggers are a very versatile feature.  For more details about creating and using triggers see the MySQL documentation for CREATE TRIGGER syntax.