Using ‘AFTER UPDATE’ trigger in MySQL 8: Tutorial & Examples

Updated: January 27, 2024 By: Guest Contributor Post a comment

Introduction

Triggers in MySQL are stored programs that automatically execute or fire when certain events occur. An AFTER UPDATE trigger happens immediately after a specified update operation is performed on a table. This tutorial will walk you through the concept of AFTER UPDATE triggers in MySQL 8, showing how they can be an essential tool for maintaining data integrity, automating processes, and monitoring database changes.

Prerequisites

  • A working MySQL 8 installation
  • Basic understanding of SQL and MySQL syntax
  • Optionally, a SQL client or command-line interface to run the examples

Understanding Triggers

Before delving into the code examples, it’s important to understand the trigger’s role in MySQL. A trigger is like a sentinel, watching for events to occur. When the specified event happens, the trigger leaps into action, executing its defined code.

The basic syntax for defining a trigger is as follows:

CREATE TRIGGER trigger_name
AFTER UPDATE ON table_name
FOR EACH ROW
BEGIN
  -- trigger body
END;

Let’s get started by exploring various examples, progressing from basic to advanced usage of AFTER UPDATE triggers in MySQL 8.

Creating a Basic AFTER UPDATE Trigger

Suppose we have a table called employees that records the data of employees in a company:

CREATE TABLE employees (
    id INT AUTO_INCREMENT,
    name VARCHAR(100),
    position VARCHAR(100),
    salary DECIMAL(10,2),
    last_update TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);

Now, we will create an AFTER UPDATE trigger that automatically updates a column last_update whenever a salary is changed:

DELIMITER //
CREATE TRIGGER update_salary_trigger
AFTER UPDATE ON employees
FOR EACH ROW 
BEGIN
    IF OLD.salary != NEW.salary THEN
        NEW.last_update = NOW();
    END IF;
END; //
DELIMITER ;

Note: The DELIMITER command is necessary to define triggers with multiple statements.

The above code checks if the old salary differs from the new salary and, if so, it updates the last_update timestamp accordingly. Let’s see it in action:

UPDATE employees SET salary = 12000 WHERE id = 1;

The trigger fires right after the update query successfully executes, updating the last_update column for the affected row.

Using AFTER UPDATE Triggers to Maintain Audit Trails

A common use case for triggers is maintaining audit trails. Let’s assume we have an audit table:

CREATE TABLE employee_salary_audit (
    id INT AUTO_INCREMENT,
    employee_id INT,
    old_salary DECIMAL(10,2),
    new_salary DECIMAL(10,2),
    update_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
    PRIMARY KEY (id)
);

The following AFTER UPDATE trigger will insert a new record into the audit table whenever an employee’s salary is updated:

DELIMITER //
CREATE TRIGGER salary_audit_trigger
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
    IF OLD.salary != NEW.salary THEN
        INSERT INTO employee_salary_audit(employee_id, old_salary, new_salary)
        VALUES(OLD.id, OLD.salary, NEW.salary);
    END IF;
END; //
DELIMITER ;

Now, whenever an employee’s salary is updated, a corresponding entry will be created in the employee_salary_audit table, allowing for easy tracking of salary changes over time:

UPDATE employees SET salary = 12500 WHERE id = 1;

Complex AFTER UPDATE Triggers

In more complex databases, triggers might need to perform multiple actions or interact with multiple tables. Consider the scenario where a change in salary also affects the budget of the department:

CREATE TABLE department_budget (
    department_id INT,
    budget DECIMAL(10,2),
    PRIMARY KEY (department_id)
);

The trigger in this case would adjust the department’s budget accordingly:

DELIMITER //
CREATE TRIGGER complex_salary_update_trigger
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
    IF OLD.salary != NEW.salary THEN
        UPDATE department_budget
        SET budget = budget + (NEW.salary - OLD.salary)
        WHERE department_id = NEW.department_id;
    END IF;
END; //
DELIMITER ;

This trigger considers the difference between the new and old salaries and alters the department’s budget by the same amount.

Advanced: Conditional Logic in AFTER UPDATE Triggers

Triggers can also employ conditional logic. Suppose you want to apply a different logic when the salary is increased versus when it is decreased:

DELIMITER //
CREATE TRIGGER advanced_salary_update_trigger
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
    IF OLD.salary != NEW.salary THEN
      -- Decreasing salary logic
        IF NEW.salary < OLD.salary THEN
            INSERT INTO audit_table (change_description) VALUES ('Salary Decrease');
        -- Increasing salary logic
        ELSEIF NEW.salary > OLD.salary THEN
            INSERT INTO audit_table (change_description) VALUES ('Salary Increase');
            -- Potentially add more actions like bonus calculations, etc.
        END IF;
    END IF;
END; //
DELIMITER ;

This trigger checks if the salary has been increased or decreased and inserts a corresponding description into an audit_table to track these salary adjustment reasons.

Best Practices and Limitations

Here are some best practices and limitations to keep in mind when working with AFTER UPDATE triggers:

  • Avoid complex logic in triggers as it can slow down database operations.
  • Remember that triggers execute within the context of a transaction. If the transaction fails, the trigger’s actions are rolled back.
  • Be aware of the potential for recursive triggers, which can lead to an infinite loop.
  • Ensure that your triggers respect the ACID properties of the database.

Error Handling in AFTER UPDATE Triggers

Error handling is essential in triggers to prevent unintended consequences from errors during execution. MySQL provides signaling support in stored programs, which can be used like this:

DELIMITER //
CREATE TRIGGER error_handling_trigger
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
    DECLARE exit handler for sqlexception
    BEGIN
        -- Handle the error
        SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'An error occurred.';
    END;
    -- Trigger logic
    IF OLD.salary != NEW.salary THEN
        -- Do something
    END IF;
END; //
DELIMITER ;

In this trigger, a handler is declared that catches any SQL exceptions that occur during the trigger’s execution and signals a generic error.

Conclusion

We have explored the functionality and practical usage of AFTER UPDATE triggers in MySQL 8 through various examples. Mastering triggers can significantly enhance the reliability and efficiency of database operations, providing a powerful means of automating complex requirements. However, use them judiciously to maintain database performance and avoid overcomplicating your schema designs.