Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause? Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause? mysql mysql

Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?


This limitation, which was only due to historical, code legacy reasons, has been lifted in recent versions of MySQL:

Changes in MySQL 5.6.5 (2012-04-10, Milestone 8)

Previously, at most one TIMESTAMP column per table could be automatically initialized or updated to the current date and time. This restriction has been lifted. Any TIMESTAMP column definition can have any combination of DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP clauses. In addition, these clauses now can be used with DATETIME column definitions. For more information, see Automatic Initialization and Updating for TIMESTAMP and DATETIME.

http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html


I also wondered that long time ago. I searched a bit in my history and I think that this post: http://lists.mysql.com/internals/34919 represents the semi-official position of MySQL (before Oracle's intervention ;))

In short:

this limitation stems only from the way in which this feature is currently implemented in the server and there are no other reasons for its existence.

So their explanation is "because it is implemented like this". Doesn't sound very scientific. I guess it all comes from some old code. This is suggested in the thread above: "carry-over from when only the first timestamp field was auto-set/update".

Cheers!


We can give a default value for the timestamp to avoid this problem.

This post gives a detailed workaround:http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/

create table test_table( id integer not null auto_increment primary key, stamp_created timestamp default '0000-00-00 00:00:00', stamp_updated timestamp default now() on update now() );

Note that it is necessary to enter nulls into both columns during "insert":

mysql> insert into test_table(stamp_created, stamp_updated) values(null, null); Query OK, 1 row affected (0.06 sec)mysql> select * from t5; +----+---------------------+---------------------+ | id | stamp_created       | stamp_updated       |+----+---------------------+---------------------+|  2 | 2009-04-30 09:44:35 | 2009-04-30 09:44:35 |+----+---------------------+---------------------+2 rows in set (0.00 sec)  mysql> update test_table set id = 3 where id = 2; Query OK, 1 row affected (0.05 sec) Rows matched: 1  Changed: 1  Warnings: 0  mysql> select * from test_table;+----+---------------------+---------------------+| id | stamp_created       | stamp_updated       | +----+---------------------+---------------------+ |  3 | 2009-04-30 09:44:35 | 2009-04-30 09:46:59 | +----+---------------------+---------------------+ 2 rows in set (0.00 sec)