How do you set a default value for a MySQL Datetime column?
In SQL Server it's getdate()
. What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.
How do you set a default value for a MySQL Datetime column?
In SQL Server it's getdate()
. What is the equivalant for MySQL? I'm using MySQL 5.x if that is a factor.
I was able to solve this using this alter statement on my table that had two datetime fields.
This works as you would expect the now() function to work. Inserting nulls or ignoring the created_dt and updated_dt fields results in a perfect timestamp value in both fields. Any update to the row changes the updated_dt. If you insert records via the MySQL query browser you needed one more step, a trigger to handle the created_dt with a new timestamp.
The trigger can be whatever you want I just like the naming convention [trig]_[my_table_name]_[insert]
Use the following code
If you have already created the table then you can use
To change default value to current date time
To change default value to '2015-05-11 13:01:01'
Take for instance If I had a table named 'site' with a created_at and an update_at column that were both DATETIME and need the default value of now, I could execute the following sql to achieve this.
The sequence of statements is important because a table can not have two columns of type TIMESTAMP with default values of CUREENT TIMESTAMP
You can use triggers to do this type of stuff.
While you can't do this with
DATETIME
in the default definition, you can simply incorporate a select statement in your insert statement like this:Note the lack of quotes around the table.
For MySQL 5.5