133

I have the following table schema;

CREATE TABLE `db1`.`sms_queue` (
  `Id` INTEGER UNSIGNED NOT NULL AUTO_INCREMENT,
  `Message` VARCHAR(160) NOT NULL DEFAULT 'Unknown Message Error',
  `CurrentState` VARCHAR(10) NOT NULL DEFAULT 'None',
  `Phone` VARCHAR(14) DEFAULT NULL,
  `Created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `LastUpdated` TIMESTAMP NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  `TriesLeft` tinyint NOT NULL DEFAULT 3,
  PRIMARY KEY (`Id`)
)
ENGINE = InnoDB;

It fails with the following error:

ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause.

My question is, can I have both of those fields? or do I have to manually set a LastUpdated field during each transaction?

OMG Ponies
  • 325,700
  • 82
  • 523
  • 502
Xenph Yan
  • 83,019
  • 16
  • 48
  • 55
  • Hey, @Xenph Yan, would you mind changing the "Accepted" answer from the current wrong one to the right one? This accepted, wrong answer made me lose about 15 minutes trying to figure out what was happening... – Bruno Reis Oct 15 '11 at 12:54

12 Answers12

136

From the MySQL 5.5 documentation:

One TIMESTAMP column in a table can have the current timestamp as the default value for initializing the column, as the auto-update value, or both. It is not possible to have the current timestamp be the default value for one column and the auto-update value for another column.

Changes in MySQL 5.6.5:

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.

kingjeffrey
  • 14,894
  • 6
  • 42
  • 47
Robert Gamble
  • 106,424
  • 25
  • 145
  • 137
  • That has changed (at least in MySQL 5.0). See the documentation: http://dev.mysql.com/doc/refman/5.0/en/timestamp.html – SimonSimCity Jan 21 '12 at 11:32
  • Countering @SimonSimCity: The docs for 5.0 say the exact same thing as above. – davemyron Apr 04 '12 at 22:43
  • 7
    @RobertGamble I think the more interesting question would be WHY THE HECK DON'T they've not provided a way do this very commonly requested/needed functionality. – Ray Aug 02 '12 at 17:20
  • 23
    This seems a bit arbitrary on the part of MySQL. Can anyone explain *why* this is the case? – humble_coder Aug 22 '12 at 14:10
  • 13
    Really really old comment, BUT, it finally was changed: `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.` – Mauricio Vargas Dec 28 '13 at 13:18
  • I believe in the year 2016, the LastUpdated column will also need a default. So the above query will work when updated to the following:
    `LastUpdated` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,`
    – dewtea Nov 08 '16 at 18:03
93

There is a trick to have both timestamps, but with a little limitation.

You can use only one of the definitions in one table. Create both timestamp columns like so:

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 null 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 test_table; 
+----+---------------------+---------------------+ 
| 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)  
Ishpreet
  • 5,230
  • 2
  • 19
  • 35
Bogdan Gusiev
  • 8,027
  • 16
  • 61
  • 81
  • Here's a link from the MySQL-Documentation that describes that function: http://dev.mysql.com/doc/refman/5.0/en/timestamp.html – SimonSimCity Jan 21 '12 at 11:31
  • 6
    the first code box, when entered manually worked perfectly for me. Thanks! I wish I had enough 'karma' to upvote this answer as it saved my bacon. mmmmm saved bacon. – amatusko Jun 30 '12 at 18:30
  • You need to make sure that `stamp_created ` is also set as NOT NULL. MySQL will automatically replace the NULL with the current timestamp. – Valentin Despa Jan 29 '14 at 19:51
  • Why don't you also make the `stamp_created` field as: `stamp_created timestamp default now()` instead of using a 'ZERO' value? – Sebastian Scholle Apr 30 '18 at 11:49
27

You can have them both, just take off the "CURRENT_TIMESTAMP" flag on the created field. Whenever you create a new record in the table, just use "NOW()" for a value.

Or.

On the contrary, remove the 'ON UPDATE CURRENT_TIMESTAMP' flag and send the NOW() for that field. That way actually makes more sense.

Stephen Walcher
  • 2,565
  • 1
  • 21
  • 22
  • 2
    Is this the only way? I can't have the database look after all that detail? – Xenph Yan Nov 06 '08 at 04:46
  • 2
    According to the MySql manual, CURRENT_TIMESTAMP is a synonym for NOW() so I don't think this will work. – tvanfosson Nov 06 '08 at 04:48
  • I'm sure you can, it's just that CURRENT_TIMESTAMP is a flag reserved for only one field. Either way, if you had that flag in there, regardless what value you have for that field when you add a record, it will always be the current timestamp, hence the name. – Stephen Walcher Nov 06 '08 at 04:48
  • @tvanfosson, I think he meant as part of the insert statement. – Xenph Yan Nov 06 '08 at 04:49
  • 1
    @tvanfosson: Using 'NOW()' in a query passes the current time to the database. What that value actually is depends on the language, engine, and probably a hundred other things I don't know. The flag I was referring to sets it so that when a record is created, the time is added to that field. – Stephen Walcher Nov 06 '08 at 04:50
  • I see. I thought he meant in the definition. Either way, I'd be happy to be wrong. – tvanfosson Nov 06 '08 at 04:50
  • 2
    I went with the insert NOW() way, mostly as other code might touch these tables and I don't trust people to update them correctly. :) – Xenph Yan Nov 06 '08 at 04:55
27

If you do decide to have MySQL handle the update of timestamps, you can set up a trigger to update the field on insert.

CREATE TRIGGER <trigger_name> BEFORE INSERT ON <table_name> FOR EACH ROW SET NEW.<timestamp_field> = CURRENT_TIMESTAMP;

MySQL Reference: http://dev.mysql.com/doc/refman/5.0/en/triggers.html

webkraller
  • 370
  • 3
  • 4
23

This is how can you have automatic & flexible createDate/lastModified fields using triggers:

First define them like this:

CREATE TABLE `entity` (
  `entityid` int(11) NOT NULL AUTO_INCREMENT,
  `createDate` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `lastModified` timestamp NOT NULL DEFAULT '0000-00-00 00:00:00',
  `name` varchar(255) DEFAULT NULL,
  `comment` text,
  PRIMARY KEY (`entityid`),
)

Then add these triggers:

DELIMITER ;;
CREATE trigger entityinsert BEFORE INSERT ON entity FOR EACH ROW BEGIN SET NEW.createDate=IF(ISNULL(NEW.createDate) OR NEW.createDate='0000-00-00 00:00:00', CURRENT_TIMESTAMP, IF(NEW.createDate<CURRENT_TIMESTAMP, NEW.createDate, CURRENT_TIMESTAMP));SET NEW.lastModified=NEW.createDate; END;;
DELIMITER ;
CREATE trigger entityupdate BEFORE UPDATE ON entity FOR EACH ROW SET NEW.lastModified=IF(NEW.lastModified<OLD.lastModified, OLD.lastModified, CURRENT_TIMESTAMP);
  • If you insert without specifying createDate or lastModified, they will be equal and set to the current timestamp.
  • If you update them without specifying createDate or lastModified, the lastModified will be set to the current timestamp.

But here's the nice part:

  • If you insert, you can specify a createDate older than the current timestamp, allowing imports from older times to work well (lastModified will be equal to createDate).
  • If you update, you can specify a lastModified older than the previous value ('0000-00-00 00:00:00' works well), allowing to update an entry if you're doing cosmetic changes (fixing a typo in a comment) and you want to keep the old lastModified date. This will not modify the lastModified date.
alien
  • 247
  • 2
  • 3
22

As of MySQL 5.6 its easy-peasy... give it a try:

create table tweet ( 
    id integer not null auto_increment primary key, 
    stamp_created timestamp default now(), 
    stamp_updated timestamp default now() on update now(),
    message varchar(163)
)
Shaheen Ghiassy
  • 7,397
  • 3
  • 40
  • 40
  • Probably great solution What i am searching create & update time issue without trigger – matinict Nov 08 '16 at 05:38
  • I can't believe it took this long for this little nuisance to be resolved. I didn't even realize they'd fixed this and it's 2018... Thanks. – hsanders Mar 16 '18 at 13:39
4

This issue seemed to have been resolved in MySQL 5.6. I have noticed this until MySQL 5.5; here is an example code:

DROP TABLE IF EXISTS `provider_org_group` ;
CREATE TABLE IF NOT EXISTS `provider_org_group` (
  `id` INT NOT NULL,
  `name` VARCHAR(100) NOT NULL,
  `type` VARCHAR(100) NULL,
  `inserted` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `insert_src_ver_id` INT NULL,
  `updated` TIMESTAMP NULL ON UPDATE CURRENT_TIMESTAMP,
  `update_src_ver_id` INT NULL,
  `version` INT NULL,
  PRIMARY KEY (`id`),
  UNIQUE INDEX `id_UNIQUE` (`id` ASC),
  UNIQUE INDEX `name_UNIQUE` (`name` ASC))
ENGINE = InnoDB;

Running this on MySQL 5.5 gives:

ERROR 1293 (HY000): Incorrect table definition; there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause

Running this on MySQL 5.6

0 row(s) affected   0.093 sec
Kingz
  • 5,086
  • 3
  • 36
  • 25
4
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() 
); 

source: http://gusiev.com/2009/04/update-and-create-timestamps-with-mysql/

3

i think this is the better query for stamp_created and stamp_updated

CREATE TABLE test_table( 
    id integer not null auto_increment primary key, 
    stamp_created TIMESTAMP DEFAULT now(), 
    stamp_updated TIMESTAMP DEFAULT '0000-00-00 00:00:00' ON UPDATE now() 
); 

because when the record created, stamp_created should be filled by now() and stamp_updated should be filled by '0000-00-00 00:00:00'

Josua Marcel C
  • 3,122
  • 6
  • 45
  • 87
2

For mysql 5.7.21 I use the following and works fine:

CREATE TABLE Posts ( modified_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, created_at timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP )

2

this will add two column for creation and updation. both will get updated while inserting and updating.

   create table users( 
      id integer not null auto_increment primary key, 
      created_date timestamp default now(), 
      modified_date timestamp default now() on update now() 
    ); 
Flash Noob
  • 352
  • 3
  • 7
0

My web host is stuck on version 5.1 of mysql so anyone like me that doesn't have the option of upgrading can follow these directions:

http://joegornick.com/2009/12/30/mysql-created-and-modified-date-fields/

Nathan Prather
  • 2,098
  • 1
  • 18
  • 15