Timestamp for row creation and last modification

10,482

Solution 1

Ya this is a lame limitation on MySQL. If you are going through an application you can add a time() call for the created_at column, and let the updated_at column use the CURRENT_TIMESTAMP.

$sql = "INSERT INTO my_table SET name = 'Mike', created_at = " . time();

I'd opt to do this on the created_at column as it probably won't be touched as often as the updated_at column.

-- Edit --

Better yet, use MySQL's built in now() function. This way you only need to be concerned with the timezone of the mysql server, and not the timezones of the app server AND the mysql server.

$sql = "INSERT INTO my_table SET name = 'Mike', created_at = NOW()";

Solution 2

You can use a trigger. The application can also set the value, but if do, it will be overwritten by the database.

delimiter //
CREATE TRIGGER def_bef_update BEFORE UPDATE ON def FOR EACH ROW BEGIN
    SET NEW.modification = CURRENT_TIMESTAMP;
END//
delimiter ;

You can also use it to check the data and update your modification date only if has important changes.

Share:
10,482
Matt Fenwick
Author by

Matt Fenwick

Cloud native engineer & Kubernetes member. Check out some of my work on github: Cyclonus: conformance test suite for kubernetes CNIs for network policy implementations NMRPyStar: an API for accessing archived NMR data files in the NMR-Star format used by the BMRB. Miscue-js: validation of JSON files to deal with obnoxious and tricky interoperability issues such as number overflows and duplicate keys Some cool technologies that I use: Python Javascript Haskell MySQL golang kubernetes

Updated on June 05, 2022

Comments

  • Matt Fenwick
    Matt Fenwick about 2 years

    I need to keep track of the time a row was inserted into the database, and the time it was last modified.

    I tried to create two separate columns, and use CURRENT_TIMESTAMP:

    create table def (
      id int, 
      creation timestamp 
        default CURRENT_TIMESTAMP, 
      modification timestamp 
        on update CURRENT_TIMESTAMP
    );
    

    However, this produced an error:

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

    What is the best way to do this?

    I'm thinking stored procedure, but looking for a standard solution. I'm also concerned with access privileges -- as few programs/things should be able to touch the timestamps as possible.


    Although I would prefer MySQL answers, solutions for other RDBMS's are also appreciated!

  • Mike Purcell
    Mike Purcell over 10 years
    @kevin: You are correct, and tbh, NOW() is the preferred alternative, that way you are only dealing with the mysql server's timezone, instead of the server running the app code AND the mysql server.