A trigger is a stored program that MySQL automatically executes in response to a specific event on a table. Triggers are used to enforce business rules, maintain audit logs, synchronize related data, and prevent invalid data from being stored.
When Triggers Fire
Triggers are associated with three DML events: INSERT, UPDATE, and DELETE. For each event, you can define a BEFORE trigger (fires before the row change) or an AFTER trigger (fires after the row change). This gives you six possible trigger combinations per table.
Key Concepts
- NEW: A pseudo-row representing the new values (available in INSERT and UPDATE triggers)
- OLD: A pseudo-row representing the old values (available in UPDATE and DELETE triggers)
- BEFORE triggers: Can modify NEW values before they are written
- AFTER triggers: Commonly used for audit logging and cascade updates