What is a trigger in a database?
MediumConceptDBMS Fundamentals
Answer
A trigger is a block of SQL that the database runs automatically when a specified event happens on a table, such as an INSERT, UPDATE or DELETE. Nobody calls a trigger directly; the event fires it.
- It runs
BEFOREorAFTERthe event, usually once for every affected row (FOR EACH ROW). - Inside a row trigger,
NEWrefers to the new version of the row andOLDto the previous version (MySQL and PostgreSQL syntax). - Common uses are audit logs, enforcing complex business rules and keeping derived values, such as totals, up to date.
- Drawbacks: the logic is hidden from application code, which makes debugging harder, and every write does extra work.
Example: In MySQL:
CREATE TRIGGER log_salary
AFTER UPDATE ON employees
FOR EACH ROW
INSERT INTO salary_log (emp_id, old_sal, new_sal)
VALUES (OLD.id, OLD.salary, NEW.salary);
Every update of an employee row now adds a row to salary_log automatically.