Combining various answers :
In MySQL 5.5, DEFAULT CURRENT_TIMESTAMP
and ON UPDATE CURRENT_TIMESTAMP
cannot be added on DATETIME
but only on TIMESTAMP
.
Rules:
1) at most one TIMESTAMP
column per table could be automatically (or manually[My addition]) initialized or updated to the current date and time. (MySQL Docs).
So only one TIMESTAMP
can have CURRENT_TIMESTAMP
in DEFAULT
or ON UPDATE
clause
2) The first NOT NULL
TIMESTAMP
column without an explicit DEFAULT
value like created_date timestamp default '0000-00-00 00:00:00'
will be implicitly given a DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
and hence subsequent TIMESTAMP
columns cannot be given CURRENT_TIMESTAMP
on DEFAULT
or ON UPDATE
clause
CREATE TABLE `address` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`village` int(11) DEFAULT NULL,
`created_date` timestamp default '0000-00-00 00:00:00',
`updated_date` timestamp null on update current_timestamp,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
INSERT INTO address (village,created_date) VALUES (100,null);
mysql> select * from address;
+-----+---------+---------------------+--------------+
| id | village | created_date | updated_date |
+-----+---------+---------------------+--------------+
| 132 | 100 | 2017-02-18 04:04:00 | NULL |
+-----+---------+---------------------+--------------+
1 row in set (0.00 sec)
UPDATE address SET village=101 WHERE village=100;
mysql> select * from address;
+-----+---------+---------------------+---------------------+
| id | village | created_date | updated_date |
+-----+---------+---------------------+---------------------+
| 132 | 101 | 2017-02-18 04:04:00 | 2017-02-18 04:06:14 |
+-----+---------+---------------------+---------------------+
1 row in set (0.00 sec)
Other option (But updated_date
is the first column):
CREATE TABLE `address` (
`id` int(9) NOT NULL AUTO_INCREMENT,
`village` int(11) DEFAULT NULL,
`updated_date` timestamp null on update current_timestamp,
`created_date` timestamp not null ,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=132 DEFAULT CHARSET=utf8;
CURRENT_TIMESTAMP
inDEFAULT
orON UPDATE
clause once there's a column withTIMESTAMP
data type, no matter if it got an extra clause! – Nicolas BuduroiCREATE TABLE foo (created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_on TIMESTAMP)
, but not this:CREATE TABLE foo (updated_on TIMESTAMP, created_on TIMESTAMP DEFAULT CURRENT_TIMESTAMP)
– Nicolas Buduroitimestamp
column is nullable i.enull
. If the firsttimestamp
column isnot null
then by defaultDEFAULT CURRENT_TIMESTAMP
andON UPDATE CURRENT_TIMESTAMP
will be added. stackoverflow.com/a/13544181/2859238 – user104309timestamp
column has an explicit default value set likedefault '0000-00-00 00:00:00'
. If the column is nullable or explicitly default value is set,thenDEFAULT CURRENT_TIMESTAMP
andON UPDATE CURRENT_TIMESTAMP
will NOT be added – user104309