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.
MySQL 5.6 has fixed this problem.
You can use now() to set the value of a datetime column, but keep in mind that you can't use that as a default value.
For me the trigger approach has worked the best, but I found a snag with the approach. Consider the basic trigger to set a date field to the current time on insert:
This is usually great, but say you want to set the field manually via INSERT statement, like so:
What happens is that the trigger immediately overwrites your provided value for the field, and so the only way to set a non-current time is a follow up UPDATE statement--yuck! To override this behavior when a value is provided, try this slightly modified trigger with the IFNULL operator:
This gives the best of both worlds: you can provide a value for your date column and it will take, and otherwise it'll default to the current time. It's still ghetto relative to something clean like DEFAULT GETDATE() in the table definition, but we're getting closer!
While defining multi-line triggers one has to change the delimiter as semicolon will be taken by MySQL compiler as end of trigger and generate error. e.g.
In version 5.6.5, it is possible to set a default value on a datetime column, and even make a column that will update when the row is updated. The type definition:
Reference: http://optimize-this.blogspot.com/2012/04/datetime-default-now-finally-available.html
I'm running MySql Server 5.7.11 and this sentence:
is not working. But the following:
just works.
As a sidenote, it is mentioned in the mysql docs:
even if they also say: