SQLMentor // glossary

Trigger

A trigger is procedural code that runs automatically in response to a data event — an INSERT, UPDATE, or DELETE on a table. You never call it directly; the database fires it.

Triggers enforce rules that constraints can't express, maintain audit trails, and derive values automatically. A BEFORE trigger can validate or modify the row before it is written; an AFTER trigger reacts once the change is applied.

Overusing triggers makes behavior hard to trace, because effects happen invisibly on every write. Reach for them when the logic truly must fire regardless of which application touches the table.

Example

CREATE TRIGGER trg_audit
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
  INSERT INTO salary_audit(emp_id, old_sal, new_sal)
  VALUES (:OLD.employee_id, :OLD.salary, :NEW.salary);
END;