I am looking for the syntax to add a column to a MySQL table with the current time as a default value.
Asked
Active
Viewed 4.6k times
10
-
1Read the [mysql doumatation](http://dev.mysql.com/doc/refman/5.6/en/alter-table.html) about alter table syntax – Jens Jul 31 '15 at 10:10
-
I love that someone upvoted this. Hooray for democracy. – Strawberry Jul 31 '15 at 10:29
5 Answers
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
-
-
Even there is time datatype in mysql but it is not with auto fill property, buty yes you can keep column property timestamp for auto fill and then select only time from that. – Zafar Malik Jul 31 '15 at 10:28
-
-
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
-
-
-
I can change it, it is not a problem, I can fit it to the type of the return value function – RedPe4rl Jul 31 '15 at 10:25
-
-
"MySQL retrieves and displays `DATETIME` values in `YYYY-MM-DD HH:MM:SS` format." This is from mysql site. You can store only this type, but you can use one of the many time format functions to change it, when you need to display it. For excample: `SELECT TIME_FORMAT(ts, '%T') FROM test` – Roman Marusyk Jul 31 '15 at 10:30
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