10

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

Mureinik
  • 297,002
  • 52
  • 306
  • 350
RedPe4rl
  • 185
  • 1
  • 2
  • 10

5 Answers5

13

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;
Akash Kumar Verma
  • 3,185
  • 2
  • 16
  • 32
Zafar Malik
  • 6,734
  • 2
  • 19
  • 30
8

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)
Community
  • 1
  • 1
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
4

You can specify a default clause:

ALTER TABLE mytable ADD COLUMN (mytimestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP);
Mureinik
  • 297,002
  • 52
  • 306
  • 350
0

I think these sql will useful to you.

create table test (column_name varchar(32), time_column TIMESTAMP DEFAULT CURRENT_TIMESTAMP);

mysql> insert into test (column_name) values ("demo");
Query OK, 1 row affected (0.00 sec)

mysql> select column_name as name, time_column as ts from  test;
+------+---------------------+
| name | ts                  |
+------+---------------------+
| demo | 2014-07-31 15:42:52 | 
+------+---------------------+

1 row in set (0.00 sec)

Thank you.

Venkatesh Panabaka
  • 2,064
  • 4
  • 19
  • 27
0
create table test (col1 varchar(10), lastaccessdate TIMESTAMP(6) DEFAULT CURRENT_TIMESTAMP(6) ON UPDATE CURRENT_TIMESTAMP(6));

this will update time with fractional seconds in time, and also update when record is last inserted or updated.

Manish Sapkal
  • 5,591
  • 8
  • 45
  • 74