
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Order of MySQL Trigger Invocation for Same Event and Action Time
In MySQL, triggers allow automatic execution of specified actions in response to INSERT, UPDATE or DELETE events on a table. Often, multiple triggers may be created for the same event and action time (e.g.; multiple BEFORE INSERT triggers on the same table).
By default, MySQL invokes these triggers in the order they have created. However, the FOLLOWS and PRECEDES option allows control over the sequence of execution which can be critical in complex data handling.
In this article, we will explore how to set the order of multiple triggers for the same event and action time in MySQL with examples illustrating FOLLOWS and PRECEDES.
How MySQL Handles Trigger Execution Order
When multiple events are created for the same events like (INSERT) and action time like (BEFORE OR AFTER), MySQL executes them in the order of creation. But if we use FOLLOWS or PRECEDES options you can specify the order explicitly ?
-
FOLLOWS: The new trigger runs after the specified trigger.
-
PRECEDES: The new trigger runs before the specified trigger.
These options are essential when the triggers depend on each other and want to run in a specified order to help maintain data accuracy and avoid inconsistencies in the database.
Let us understand this with an example
Example: Creating Multiple Triggers for Same Event and Action Time
Setting Order of Triggers for Product Data Validation and Logging
This example shows you how to use FOLLOWS clause, in order to manage the execution order of triggers. It consists of a products table and an additional product_logs table for storing log messages.
Creating products tableLet us create a Product table to store ID, Product_name, and Price.
CREATE TABLE Products ( Product_id INT AUTO_INCREMENT PRIMARY KEY, Product_name VARCHAR(50), Price DECIMAL(10, 2) );Creating Product_logs table
Let us create a Products_logs table to store log_id and log_message.
CREATE TABLE Product_logs ( Log_id INT AUTO_INCREMENT PRIMARY KEY, Log_message VARCHAR(255) );Creating First Trigger
product validate Trigger: This will execute first and verify that the price for the product is greater than zero. It would generate an error and cancel the insertion if the price were invalid i.e., less than or equal to zero.
DELIMITER # CREATE TRIGGER product_validate BEFORE INSERT ON Products FOR EACH ROW BEGIN IF NEW.Price <= 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Price must be greater than zero'; END IF; END # DELIMITER ;Creating Second Trigger
log_product Trigger: This Specifies FOLLOWS validate_product so that this trigger is called after the first trigger; it logs only the insert attempt if the validate_product succeeds.
DELIMITER # CREATE TRIGGER log_product BEFORE INSERT ON Products FOR EACH ROW FOLLOWS Product_validate BEGIN INSERT INTO Product_logs (Log_message) VALUES (CONCAT('Inserting product: ', NEW.Product_name)); END # DELIMITER ;Inserting Records
Let us insert the sample data which is valid, into products to activate the trigger.
INSERT INTO Products (Product_name, Price) VALUES ('Drone', 100.00), ('Tablet', 200.00), ('Speakers', 300.00);Verification
Let us check the data in the Products table after trigger activation.
SELECT * FROM Products;
Following is the output of the above query ?
Product_id | Product_name | Price |
---|---|---|
1 | Drone | 100.00 |
2 | Tablet | 200.00 |
3 | Speakers | 300.00 |
Let us check the data in the Product_logs table.
SELECT * FROM Product_logs;
output of the above query is as follows ?
Log_id | Product_name |
---|---|
1 | Inserting product: Drone |
2 | Inserting product: Tablet |
1 | Inserting product: Speakers |
The above outputs show that two triggers executed one after the other, and then after validate_product verifies the product price, if it is valid the records will be added for both tables to ensure data integrity.
By inserting invalid values ?
INSERT INTO products (product_name, price) VALUES ('Phone', 0);
Following is the output of the above code ?
Error: Price must be greater than zero
As we have inserted the price which is invalid both the triggers will fail and will not insert the record into the table.
-
FOLLOWS ensures log_product logs only valid insertions and keeps data correct by depending on validate_product to execute first.
-
If you want log_product to run before validate_product, specify PRECEDES validate_product when constructing it.
-
The flexibility also ensures that it executes triggers in the proper order to prevent data integrity compromise.