Jan
09
MySQL, the strange case of a timestamp field
I discovered a feature (or bug) of MySQL timestamp fields. Maybe is documented in some place what I not read yet:
When I add a new timestamp field to a table, MySQL magically adds some features to new timestamp field like a “trigger” and a default value to CURRENT_TIMESTAMP.
There is test-case script:
-- CREATING TABLE AND INSERT SOME DUMMY DATA mysql> CREATE TABLE t( -> id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, -> val VARCHAR(50) -> ); Query OK, 0 ROWS affected (0.15 sec) mysql> INSERT INTO t (val) VALUES ("foo") ,("var"); Query OK, 2 ROWS affected (0.08 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> SELECT * FROM t; +----+------+ | id | val | +----+------+ | 1 | foo | | 2 | var | +----+------+ 2 ROWS IN SET (0.00 sec) -- ADDING NEW TIMESTAMP FIELD AND ADD MORE DUMMY DATA mysql> ALTER TABLE t ADD ts_field TIMESTAMP; Query OK, 2 ROWS affected (0.35 sec) Records: 2 Duplicates: 0 Warnings: 0 mysql> INSERT INTO t (val) VALUES ("foo 2") ,("var 2"); Query OK, 2 ROWS affected (0.06 sec) Records: 2 Duplicates: 0 Warnings: 0 -- THERE IS THE MAGIC: mysql> SELECT * FROM t; +----+-------+---------------------+ | id | val | ts_field | +----+-------+---------------------+ | 1 | foo | 0000-00-00 00:00:00 | | 2 | var | 0000-00-00 00:00:00 | | 3 | foo 2 | 2013-01-09 23:20:01 | <--- | 4 | var 2 | 2013-01-09 23:20:01 | <--- +----+-------+---------------------+ 4 ROWS IN SET (0.00 sec)
What happened? I dont know.
The new table structure is:
CREATE TABLE `t` ( `id` int(11) NOT NULL AUTO_INCREMENT, `val` varchar(50) DEFAULT NULL, `ts_field` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1
It only happens if the table doesn’t have another timestamp field yet.
Now, this is useful? maybe. This is a bug? maybe.
Update: This is a feature documented in https://dev.mysql.com/doc/refman/5.5/en/timestamp-initialization.html, sorry about my lapsus-post.