Trigger
In one line
A trigger is a stored procedure that fires automatically when INSERT, UPDATE, or DELETE occurs on a table.
In simple words
A trigger is a special kind of stored procedure that runs automatically when a specific event happens on a table. You define the event (INSERT, UPDATE, or DELETE) and the timing (BEFORE or AFTER the event), and the trigger's code runs every time that event occurs.
Common uses for triggers:
- Audit logging: record every change to a table in an audit table.
- Enforcing complex rules: check conditions that cannot be expressed with simple constraints.
- Auto-updating timestamps: set
updated_atwhenever a row changes. - Cascading updates: update related data when a row changes.
Triggers are powerful but can make behavior hard to trace — changes happen "magically" without an explicit call. Use them sparingly and document them well.
Example
CREATE TRIGGER update_timestamp
BEFORE UPDATE ON users
FOR EACH ROW
BEGIN
NEW.updated_at = NOW();
END;
-- Now every UPDATE on users automatically sets updated_atThis trigger automatically updates the updated_at column whenever a user row is modified.
Related terms
Related Resources
Related Lessons
- Triggers
Learn how to create and use triggers.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.