How to use MySQL triggers?
MySQL triggers are a type of special stored procedure that automatically executes when specific events occur in the database. These triggers can be activated when certain events take place in the database.
- Before or after inserting, updating, or deleting operations.
- After executing INSERT, UPDATE, or DELETE statements on the table.
Here are the general steps to use MySQL triggers:
- Create a trigger, specifying the trigger’s name, trigger timing (BEFORE or AFTER), and event type (INSERT, UPDATE, or DELETE).
- Specify the name of the table to which the trigger belongs.
- Specify the action to be performed by the trigger. This could be a SQL statement, stored procedure, or function.
Below is an example demonstrating the creation of a trigger that automatically updates the creation time before inserting a new record.
CREATE TRIGGER update_create_time BEFORE INSERT ON your_table
FOR EACH ROW
BEGIN
SET NEW.create_time = NOW();
END;
In the above example, update_create_time is the name of the trigger, BEFORE INSERT means it will be triggered before an insert operation, your_table is the name of the table the trigger belongs to, and NEW.create_time refers to the create_time field of a newly inserted record.
Please note that the creation of triggers must be done when the option to enable triggers in the database is open, which can be checked by the following command:
SHOW VARIABLES LIKE 'trigger%';
If the value of trigger% is ON, the trigger function has been enabled.
For more detailed information and usage of MySQL triggers, please refer to the official MySQL documentation.