Search code examples
mysqlsql-updateeventtrigger

MySQL how to timestamp only one column update in same table


Here is my code so far

DELIMITER $$
    CREATE TRIGGER status AFTER UPDATE ON users
        FOR EACH ROW BEGIN
            IF NEW.status != OLD.status
            THEN INSERT INTO users (status_change_date)
            VALUES (NOW());
            ENDIF;
END$$

DELIMITER;

What we are trying to do is to update a field with the current date when that specified field is changed and save that date in that same table under status_change_date. The above code throws errors with MySQL. Its screaming at me that it cannot call itself to update the same table. Any help would be greatly appreciated.


Solution

  • I you want to modify the same table, try with using the BEFORE UPDATE trigger instead of AFTER UPDATE , like so:

    DELIMITER $$
        CREATE TRIGGER status BEFORE UPDATE ON users
            FOR EACH ROW BEGIN
                IF NEW.status != OLD.status
                THEN INSERT INTO users (status_change_date)
                VALUES (NOW());
                ENDIF;
    END$$
    
    DELIMITER;