Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding a new column with the current time as a default value

I am looking for the syntax to add a column to a MySQL table with the current time as a default value.

like image 671
RedPe4rl Avatar asked Jul 31 '15 10:07

RedPe4rl


2 Answers

Even so many persons have provided solution but this is just to add more information-

If you just want to insert current timestamp at the time of row insertion-

    ALTER TABLE mytable ADD mytimestampcol TIMESTAMP DEFAULT CURRENT_TIMESTAMP;

If you also want that this column should update if any update this row then use this-

    ALTER TABLE mytable ADD mytimestampcol TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP;
like image 116
Zafar Malik Avatar answered Oct 13 '22 21:10

Zafar Malik


IMPORTANT EDIT: It is now possible to achieve this with DATETIME fields since MySQL 5.6.5, take a look at the other post below...

It is now possible to achieve this with DATETIME fields since MySQL 5.6.5
But you can do it with TIMESTAMP:

 create table test (str varchar(32), ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
like image 43
Roman Marusyk Avatar answered Oct 13 '22 23:10

Roman Marusyk