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.

A database trigger
Figure 2-17. A database trigger

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 sales table.

7

Include the (currently) mandatory FOR EACH ROW clause, indicating that the statements within the trigger will be executed once for every row inserted into the sales table.

8

Use BEGIN to start the block containing statements to be executed by the trigger.

9-13

If the sale_value is greater than $500, set the value of the free_shipping column to 'Y'. Otherwise, set it to 'N'.

15-19

If the sale_value is greater than ...

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.