A trigger is a named database object that is associated with a table, and that activates when a particular event occurs for the table. Some uses for triggers are to perform checks of values to be inserted into a table or to perform calculations on values involved in an update.
A trigger is defined to activate when a statement inserts, updates, or deletes rows in the associated table. These row operations are trigger events. For example, rows can be inserted by INSERT or LOAD DATA statements, and an insert trigger activates for each inserted row. A trigger can be set to activate either 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.
Important:MySQL triggers activate only for changes made to tables by SQL statements. This includes changes to base tables that underlie updatable views. Triggers do not activate for changes to tables made by APIs that do not transmit SQL statements to the MySQL Server. This means that triggers are not activated by updates made using the NDB API.
Here is an example of a MySQL trigger. First we will create the table for which the trigger will be set than Next we will define the trigger. It will be executed before every INSERT statement for the people table:
mysql> CREATE TABLE people (age INT, name varchar(150)); mysql> delimiter // mysql> CREATE TRIGGER agecheck BEFORE INSERT ON people FOR EACH ROW IF NEW.age < 0 THEN SET NEW.age = 0; END IF;// mysql> delimiter ; mysql> INSERT INTO people VALUES (-20, 'abc'), (30, 'Ron'); SELECT * FROM people; mysql> SELECT * FROM people; +——-+——-+ | age | name | +——-+——-+ | 0 | abc | | 30 | Ron | +——-+——-+