A trigger is used to activate something before or after the trigger event. For example, you can have a trigger activate before each row that is inserted into a table or after each row that is updated.
Triggers are highly useful while altering a table without downtime (Refer to Chapter 10, Table Maintenance, in the Alter table using online schema change tool section) and also for auditing purposes. Suppose you want to find out the previous value of a row, you can write a trigger that saves those rows in another table before updating. The other table serves as an audit table that has the previous records.
The trigger action time can be BEFORE
or AFTER
, which indicates whether the trigger activates before or after each row to be modified.
Trigger events can be INSERT
, DELETE
, or UPDATE
:
INSERT
: Whenever a new row gets inserted throughINSERT
,REPLACE
, orLOAD DATA
, the trigger gets activatedUPDATE
: Through theUPDATE
statementDELETE
: Through theDELETE
orREPLACE
statements
From MySQL 5...