MySQL

Chapter 9 - Advanced Topics

DB Trigger

Triggers in MySQL are a powerful feature used to automatically execute a set of SQL statements in response to specific events on a table. These events include INSERT, UPDATE, and DELETE operations. Triggers can enforce complex business rules and ensure data integrity without requiring application logic. They are particularly useful for tasks such as maintaining audit trails, validating data, or updating related tables. This section covers advanced topics related to MySQL triggers, including their types, use cases, and best practices.

  1. Types of Triggers
    1. BEFORE Trigger
      • Executes before an INSERT, UPDATE, or DELETE operation on a table.
      • Useful for modifying or validating data before it is committed.
    2. AFTER Trigger
      • Executes after an INSERT, UPDATE, or DELETE operation on a table.
      • Ideal for tasks like logging changes or updating related tables.
    3. INSTEAD OF Trigger
      • Not supported in MySQL but available in other databases like SQL Server.
      • Replaces the action of the INSERT, UPDATE, or DELETE operation.
  2. Creating Triggers To create a trigger, use the CREATE TRIGGER statement. Here's an example:
    CREATE TRIGGER  update_employee_salary
    BEFORE UPDATE ON employees
    FOR EACH ROW
    BEGIN
    IF  NEW.salary  < 0 THEN
    SIGNAL SQLSTATE '45000'
    SET MESSAGE_TEXT =  'Salary cannot be negative';
    END IF ;
    END;
    
  3. In this example, the trigger update_employee_salary ensures that the salaryfield in the employees table cannot be set to a negative value before an update occurs.

  4. Trigger Examples and Use Cases
    1. Auditing Changes
      • To track changes in the employees table, you can create a trigger that inserts a record into an audit table:
        CREATE TRIGGER  audit_employee_changes
        AFTER UPDATE ON employees
        FOR EACH ROW
        BEGIN
        INSERT INTO employee_audit (employee_id, old_salary, new_salary, changed_at)
        VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW ());
        END;
        
    2. This trigger logs the old and new salaries whenever an employee's salary is updated.

    3. Maintaining Data Integrity
      • Ensure that the departments table has a valid department ID when an employee is added or updated:
        CREATE TRIGGER  validate_department_id
        BEFORE INSERT ON employees
        FOR EACH ROW
        BEGIN
        DECLARE  dept_count  INT;
        SELECT COUNT (*)  INTO dept_count FROM departments WHERE department_id =  NEW.department_id;
        IF  dept_count =  0 THEN
        SIGNAL SQLSTATE '45000'
        SET MESSAGE_TEXT =  'Invalid department ID';
        END IF ;
        END;
        
  5. Best Practices
    1. Performance Considerations
      • Triggers can impact performance, especially if they perform complex operations or are used excessively.
      • Monitor trigger performance and optimize SQL queries inside triggers as needed.
    2. Avoiding Recursive Triggers
      • Be cautious of triggers that might invoke other triggers, potentially leading to recursive loops.
      • Ensure that your triggers do not unintentionally create such loops.
    3. Testing Triggers
      • Thoroughly test triggers in a development environment before deploying them to production.
      • Verify that they behave as expected and do not introduce unintended side effects.

By understanding and using MySQL triggers effectively, you can greatly enhance the functionality and reliability of your database operations.

Trigger Types with Examples

  1. INSERT Trigger:

    An INSERT trigger is fired automatically when a new record is inserted into the table.

    Example:
    CREATE TRIGGER log_new_employee
    AFTER INSERT ON employees
    FOR EACH ROW
    BEGIN
        INSERT INTO employee_logs (action, employee_id, employee_name, salary)
        VALUES ('INSERT', NEW.id, NEW.name, NEW.salary);
    END;
    
  2. UPDATE Trigger:

    An UPDATE trigger is fired automatically when a record in the table is updated.

    Example:
    CREATE TRIGGER log_employee_update
    AFTER UPDATE ON employees
    FOR EACH ROW
    BEGIN
        INSERT INTO audit_trail (action, employee_id, old_salary, new_salary)
        VALUES ('UPDATE', OLD.id, OLD.salary,NEW.salary);
    END;
    
  3. DELETE Trigger:

    A DELETE trigger is fired automatically when a record is deleted from the table.

    Example:
    CREATE TRIGGER move_deleted_employee
    AFTER DELETE ON employees
    FOR EACH ROW
    BEGIN
        INSERT INTO deleted_employees (employee_id, employee_name, deleted_at)
        VALUES (OLD.id, OLD.name, NOW());
    END;
    

In each example:

  • CREATE TRIGGERstatement is used to define the trigger.
  • AFTER INSERT/UPDATE/DELETE ON table_namespecifies the trigger event.
  • FOR EACH ROWindicates that the trigger will be executed for each row affected by the operation.
  • BEGIN...ENDencloses the trigger's actions.
  • OLDandNEWare aliases for the old and new row values, respectively, available in UPDATE and DELETE triggers.
  • NOW()function is used to get the current timestamp.
Comments(0 comments)

Comments Not Found