O'Reilly logo

MySQL Stored Procedure Programming by Steven Feuerstein, Guy Harrison

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required