What is a trigger in MySQL?
Answer
A trigger is a database object that automatically executes a specified SQL statement in response to certain events on a table: INSERT, UPDATE, or DELETE. Triggers fire either BEFORE or AFTER the event, giving six combinations: BEFORE INSERT, AFTER INSERT, BEFORE UPDATE, AFTER UPDATE, BEFORE DELETE, AFTER DELETE. Inside a trigger, NEW refers to the new row data (available in INSERT and UPDATE), and OLD refers to the old row data (available in UPDATE and DELETE). Example — automatically set updated_at on update: CREATE TRIGGER before_user_update BEFORE UPDATE ON users FOR EACH ROW SET NEW.updated_at = NOW();. Use cases: audit logging (log changes to a separate audit table), enforcing business rules (prevent a salary from exceeding a limit), maintaining denormalized counts (update a counter table when a row is inserted). Limitations: triggers execute invisibly — they can cause unexpected behavior and make debugging harder; they can slow down DML operations; complex business logic in triggers is hard to test. Best practice: use triggers sparingly and document them clearly.