Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL is not allowing ON UPDATE CURRENT_TIMESTAMP for a DATETIME field

I have seen a lot of related questions, but I cannot place my finger on this specific question:

I have a MySQL table with both a TIMESTAMP (for when the field was created) and a DATETIME (for each time the field gets updated). It looks like this:

CREATE TABLE 'vis' (
ID BIGINT PRIMARY KEY AUTO_INCREMENT NOT NULL,
ENTRY VARCHAR(255),
AUTHOR VARCHAR(255),
CREATED_AT TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UPDATED_AT DATETIME ON UPDATE CURRENT_TIMESTAMP,
UPDATED_BY VARCHAR(255)
)

When I try this though, the error I am getting is: (SQL Error: 1294 SQL State: HY000) - Invalid ON UPDATE clause for 'updated_at' field

Everywhere I have read (even on Stack Overflow) suggests I should be able to do this, yet I am getting this error. Perhaps there is another way to have a field that automatically updates the time each time I update it?

I am using MySQL Server 5.5.

like image 667
Michael Plautz Avatar asked Oct 14 '12 13:10

Michael Plautz


People also ask

How do I change a date field in MySQL?

To update with the current date and time: UPDATE table_name SET date_field = CURRENT_TIMESTAMP; To update with a specific date value: UPDATE table_name SET date_field = 'YYYY-MM-DD HH:MM:SS.

What does a TIMESTAMP do on UPDATE CURRENT_TIMESTAMP data type?

With both DEFAULT CURRENT_TIMESTAMP and ON UPDATE CURRENT_TIMESTAMP , the column has the current timestamp for its default value and is automatically updated to the current timestamp.

How do I add a TIMESTAMP to a column in MySQL?

Here is the SQL you can use to add the column in: ALTER TABLE `table1` ADD `lastUpdated` TIMESTAMP ON UPDATE CURRENT_TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ; This adds a column called 'lastUpdated' with a default value of the current date/time.


2 Answers

DATETIME cannot use CURRENT_TIMESTAMP on update. Instead, change it to a TIMESTAMP.

Or, consider using a trigger for this situation: http://dev.mysql.com/doc/refman/5.0/en/trigger-syntax.html

EDIT: As in the comments (thanks @АлександрФишер!), this is no longer the case since MySQL 5.6.5, so another solution is to upgrade your server if possible.

like image 70
slugonamission Avatar answered Oct 05 '22 06:10

slugonamission


That feature appears to have been introduced in 5.6. Works as expected on my default OS X install.

Reference: Automatic Timestamp Properties Before MySQL 5.6.5

like image 40
rich remer Avatar answered Oct 05 '22 07:10

rich remer