Triggers & Automated Reactions

Triggers & Automated Reactions in MySQL: A Trigger is a specialized stored program that executes automatically in response to a specific Data Manipulation…

A Trigger is a specialized stored program that executes automatically in response to a specific Data Manipulation Language (DML) event—INSERT, UPDATE, or DELETE—on a designated table.

Triggers represent the database tier's event-driven programming model. They operate autonomously behind the scenes, ensuring that business rules, security audits, and data integrity guarantees cannot be bypassed, even if an application developer forgets to write validation code.


1. Trigger Anatomy: Timing & Events

A trigger is defined by two fundamental axes:

  1. Timing:
  • BEFORE: Executes before changes are validated or written to disk. Used for data sanitization, formatting, and custom validation.
  • AFTER: Executes after the row change has been successfully committed to the table buffer. Used for audit logging and cascading updates.
  1. Event: INSERT, UPDATE, or DELETE.

This creates 6 fundamental trigger combinations: BEFORE INSERT, AFTER INSERT, BEFORE UPDATE, AFTER UPDATE, BEFORE DELETE, AFTER DELETE.


2. The NEW and OLD Pseudo-Records

Inside trigger logic, MySQL provides access to the state of the row before and after the modification:

EventOLD.column Available?NEW.column Available?
INSERTNo (NULL)Yes (The new value being inserted)
UPDATEYes (The existing value before update)Yes (The modified value being saved)
DELETEYes (The value right before deletion)No (NULL)

3. Real-World Production Triggers

A. Production Audit Log Trigger (Tracking Changes)

Automatically record every customer profile change into an immutable historical audit ledger:

-- Audit ledger table
CREATE TABLE user_audit_log (
  id INT AUTO_INCREMENT PRIMARY KEY,
  user_id INT NOT NULL,
  changed_column VARCHAR(50),
  old_value TEXT,
  new_value TEXT,
  modified_by VARCHAR(50),
  modified_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

DELIMITER $$

CREATE TRIGGER trg_user_audit_update
AFTER UPDATE ON users
FOR EACH ROW
BEGIN
  -- Check if email was updated
  IF OLD.email != NEW.email THEN
    INSERT INTO user_audit_log (user_id, changed_column, old_value, new_value, modified_by)
    VALUES (OLD.id, 'email', OLD.email, NEW.email, USER());
  END IF;
  
  -- Check if username was updated
  IF OLD.username != NEW.username THEN
    INSERT INTO user_audit_log (user_id, changed_column, old_value, new_value, modified_by)
    VALUES (OLD.id, 'username', OLD.username, NEW.username, USER());
  END IF;
END$$

DELIMITER ;

B. Business Validation Trigger (BEFORE INSERT)

Enforce complex domain logic that cannot be expressed in standard CHECK constraints, using SIGNAL SQLSTATE to reject invalid operations:

DELIMITER $$

CREATE TRIGGER trg_validate_order_amount
BEFORE INSERT ON orders
FOR EACH ROW
BEGIN
  IF NEW.amount > 50000.00 THEN
    -- Throw a custom SQL exception that aborts the transaction!
    SIGNAL SQLSTATE '45000' 
    SET MESSAGE_TEXT = 'Transaction rejected: Orders exceeding $50,000 require manual manager pre-approval.';
  END IF;
END$$

DELIMITER ;

4. Trigger Best Practices & Critical Caveats

⚠️ Warnings for Production Architecture:

  1. Hidden Side-Effects: Triggers are invisible to developers looking strictly at backend application code. If an UPDATE statement mysteriously takes 2 seconds or modifies 3 other tables, developers will struggle to debug the issue without database introspection.
  2. No Cascading Trigger Loops: Avoid writing a trigger on Table A that updates Table B, which has a trigger that updates Table A.
  3. Transaction Overhead: Triggers run inside the same transaction as the triggering statement. If a trigger fails or throws an exception, the entire parent query is rolled back!