How do you create a trigger to automatically update a timestamp column on row updates?
Posted by FrankMl
Last Updated: July 04, 2024
To automatically update a timestamp column whenever a row is updated in a database, you can use a trigger. The exact syntax for creating a trigger depends on the database system you are using (e.g., MySQL, PostgreSQL, SQL Server, Oracle, etc.). Below are examples for MySQL, PostgreSQL, and SQL Server.
MySQL
In MySQL, you can create a trigger as follows:
CREATE TRIGGER before_update_timestamp
BEFORE UPDATE ON your_table
FOR EACH ROW
SET NEW.updated_at = NOW();
In this example: - Replace your_table with the name of your table. - updated_at is the timestamp column that will be updated. - NOW() retrieves the current timestamp.
PostgreSQL
In PostgreSQL, you need to first define a function and then create the trigger: 1. Define the function:
CREATE OR REPLACE FUNCTION update_timestamp()
RETURNS TRIGGER AS $$
BEGIN
    NEW.updated_at = CURRENT_TIMESTAMP;
    RETURN NEW;
END;
$$ LANGUAGE plpgsql;
2. Create the trigger:
CREATE TRIGGER before_update_timestamp
BEFORE UPDATE ON your_table
FOR EACH ROW
EXECUTE FUNCTION update_timestamp();
SQL Server
In SQL Server, you can create an AFTER UPDATE trigger as follows:
CREATE TRIGGER trg_UpdateTimestamp
ON your_table
AFTER UPDATE
AS
BEGIN
    UPDATE your_table
    SET updated_at = GETDATE()
    FROM INSERTED
    WHERE your_table.id = INSERTED.id;
END;
In this example: - id should be replaced with the primary key of your table. - GETDATE() is used to get the current date and time.
General Notes
- Ensure that the timestamp column (updated_at) is defined in your table schema. - You may also want to handle edge cases, ensure that the trigger does not lead to recursive updates, and test thoroughly in a development environment before applying to production.