Skip to content
We areTOP 1%

What is a trigger in a database?

MediumConceptDBMS Fundamentals
Track your progress
First attempt
Re-solve after a few days
Final pass before interviews

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 BEFORE or AFTER the event, usually once for every affected row (FOR EACH ROW).
  • Inside a row trigger, NEW refers to the new version of the row and OLD to 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.

More in DBMS Fundamentals

Sign in to track your progress

Your checkboxes, streak and activity heatmap are saved to your account and sync across devices. It is free.
Sign in with email

New here? Create an account