What is a Trigger?

SQL Triggers

A trigger is code that the database runs automatically when a specified event happens on a table: INSERT, UPDATE or DELETE. You do not call it; the event fires it.

CREATE TRIGGER trigger_name
{BEFORE | AFTER | INSTEAD OF} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
  -- statements
END;

Common Uses

  • Audit trails: record who changed what and when.
  • Enforcing complex rules that CHECK constraints cannot express.
  • Keeping denormalized values (totals, counters) in sync.
  • Setting UpdatedAt timestamps automatically.