Triggers and Events

Lesson 20 of 20

Make the database react on its own — watch an UPDATE fire a trigger that quietly writes an audit row.

The big picture

SQL that fires itself

A trigger is a mini-program welded to a table event. When the event happens, the database runs it automatically — no one has to remember to call it.

CREATE TRIGGER

CREATE TRIGGER name AFTER UPDATE ON table attaches the program to that event.

BEFORE or AFTER

BEFORE runs first — handy for checks; AFTER runs after — handy for logs.

FOR EACH ROW

If one statement touches five rows, the trigger fires five times, once per row.

OLD and NEW

Inside the trigger, OLD is the row before the change and NEW is the row after.