Triggers
A trigger is a special type of stored program that fires
when a table is modified by an INSERT
, UPDATE
, or DELETE
(DML) statement. Triggers implement
functionality that must take place whenever a certain change occurs to
the table. Because triggers are attached directly to the table, application code
cannot bypass database triggers.
Typical uses of triggers include the implementation of critical business logic, the denormalization of data for performance reasons, and the auditing of changes made to a table. Triggers can be defined to fire before or after a specific DML statement executes.
In Figure 2-17, we
create a trigger that fires before any INSERT
statement completes against the
sales
table. It automatically
applies free shipping and discounts to orders of a specified
value.
Here is an explanation of the trigger definition:
Line(s) | Explanation |
5 | Specify the trigger name. |
6 | Specify that the trigger fires
before an insert on the |
7 | Include the (currently) mandatory
|
8 | Use |
9-13 | If the |
15-19 | If the |
Get MySQL Stored Procedure Programming now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.