Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Auto update DATETIME column on insert with SQL?

Tags:

mysql

I am currently just inserting NOW() into the date field on my database which works just fine but it got me wondering, is there a way to automatically update a DATETIME row upon inserting data?

I found online in some places that I should set the extras to ON UPDATE CURRENT_TIMESTAMP but when doing this I get the following error:

An error occurred when trying to change the field 'uploaded' via

ALTER TABLE `uploads` CHANGE `uploaded` `uploaded` DATETIME
 NOT NULL
 ON UPDATE CURRENT_TIMESTAMP
 COMMENT 'Upload Datetime'

MySQL said:

Invalid ON UPDATE clause for 'uploaded' column

like image 458
Joe Scotto Avatar asked Nov 15 '16 21:11

Joe Scotto


1 Answers

This is what I do and it has always worked

create table if not exists my_table (
    index1 char(32) not null primary key,
    title varchar(50),
    my_timestamp timestamp not null default current_timestamp on update current_timestamp
)

This will have the timestamp on inserts and on updates, it also is valid sql, maybe you are missing the default statement in your query?

like image 180
santiago arizti Avatar answered Nov 05 '22 03:11

santiago arizti