2

In a MySQL table, we can't have 2 columns type timestamp with default values is current_timestamp.

SO is there anyway to have 2 or more columns in a same table with default value is current time. This can be done easily in Postgres, with now().

Many thanks.

novo
  • 356
  • 1
  • 6
  • 17

3 Answers3

2

if timestamp column is defined as NOT NULL MySQL stores current timestamp in the column if you assign it a value of NULL

CREATE TABLE `t1` (
  `name` varchar(100) DEFAULT NULL,
  `created` timestamp NOT NULL DEFAULT 0,
  `updated` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

INSERT INTO `t1` SET name='abc', created=null;
mysql> select * from t1;
+------+---------------------+---------------------+
| name | created             | updated             |
+------+---------------------+---------------------+
| abc  | 2013-10-04 10:48:03 | 2013-10-04 10:48:03 |
+------+---------------------+---------------------+

UPDATE `t1` SET name='abc2' WHERE name = 'abc';
mysql> select * from t1;
+------+---------------------+---------------------+
| name | created             | updated             |
+------+---------------------+---------------------+
| abc2 | 2013-10-04 10:48:03 | 2013-10-04 11:42:04 |
+------+---------------------+---------------------+
b.b3rn4rd
  • 8,494
  • 2
  • 45
  • 57
  • 1
    WARNING: I couldn't believe `DEFAULT 0` meant "now", and on my installation it doesn't. I get created="0000-00-00 00:00:00". Presumably a config-setting changes that. – Richard Huxton Oct 04 '13 at 10:18
  • CORRECTION: it relies on inserting `null` for `created`. If you don't specify it then you get a 0 date. The `NOT NULL` seems to be ignored no matter what you do. Bizarre. – Richard Huxton Oct 04 '13 at 10:39
0

Not sure if this would work, but maybe make FieldA default current_timestamp and have FieldB default be FieldA (or FieldA + 0 days if need formula).

Create Table Tbl1 
(
    ...
    , TS1 TimeStamp Default Current_TimeStamp
    , TS2 TimeStamp Default TS1
    ...
);
asantaballa
  • 3,919
  • 1
  • 21
  • 22
0

It seems that this page is referring to the same issue and it's a well-known bug in MySQL have a look to see if it helps MySQL two column timestamp default NOW value ERROR 1067

Community
  • 1
  • 1
Siavosh
  • 2,314
  • 4
  • 26
  • 50