Or copy link
Copy link
MySQL triggers are a powerful feature that allows automatic actions to be taken when certain events occur within a database table. These events can be INSERT, UPDATE, or DELETE operations. Triggers can help maintain data integrity, enforce business rules, and automate repetitive tasks.
In this article, we will look into the concept of MySQL triggers, explain how they work, and provide examples to illustrate their usage.
A trigger is a named MySQL database object that is associated with a table. It is activated or “triggered” by specified events. Triggers can be categorized into two types based on the timing of their activation:
Triggers are defined using the CREATE TRIGGER statement and can contain SQL statements that execute whenever the trigger is fired.
CREATE TRIGGER
Triggers can be used for various purposes, including:
Build Blazing-fast Websites with MySQL Hosting!
Ultahost’s high-performance pre-configured servers ensure fast MySQL websites and apps with easy setup, scalability, and expert support!
For demonstration purposes of MySQL triggers, we will use the MySQL Workbench interface.
Following are the basic examples of how to CREATE and DROP MySQL triggers:
Let’s start with basic examples of MySQL triggers. Suppose we have a table employees where we want to log any changes made to employee records in a audit_log table.
employees
audit_log
CREATE TABLE employees ( emp_id INT PRIMARY KEY, emp_name VARCHAR(100), emp_salary DECIMAL(10, 2) ); CREATE TABLE audit_log ( log_id INT AUTO_INCREMENT PRIMARY KEY, emp_id INT, action VARCHAR(10), old_salary DECIMAL(10, 2), new_salary DECIMAL(10, 2), change_date TIMESTAMP DEFAULT CURRENT_TIMESTAMP );
Now, let’s creating MySQL triggers that log any changes to an employee’s salary in the audit_log table:
DELIMITER $$ CREATE TRIGGER before_employee_update BEFORE UPDATE ON employees FOR EACH ROW BEGIN IF NEW.emp_salary <> OLD.emp_salary THEN INSERT INTO audit_log (emp_id, action, old_salary, new_salary) VALUES (OLD.emp_id, 'UPDATE', OLD.emp_salary, NEW.emp_salary); END IF; END$$ DELIMITER ;
In this, MySQL triggers examples:
BEFORE UPDATE ON employees
FOR EACH ROW
NEW.emp_salary
OLD.emp_salary
Currently, MySQL doesn’t support direct modification of triggers. You have to drop the existing trigger and create a new one with the desired changes. You can’t disable a trigger directly. However, you can achieve this by modifying the table definition or trigger code. Use the DROP TRIGGER statement.
DROP TRIGGER
DROP TRIGGER IF EXISTS before_employee_update;
Following are some real use cases MySQL triggers with examples described below:
Assume we have a products table where we want to ensure that the price of a product cannot be negative. We can use a BEFORE INSERT trigger to validate this:
products
BEFORE INSERT
CREATE TABLE products ( product_id INT PRIMARY KEY, product_name VARCHAR(100), product_price DECIMAL(10, 2) ); DELIMITER $$ CREATE TRIGGER validate_product_price BEFORE INSERT ON products FOR EACH ROW BEGIN IF NEW.product_price < 0 THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Product price cannot be negative'; END IF; END$$ DELIMITER ;
In this example, the trigger validate_product_price ensures that before a new product is inserted, the product_price must be non-negative. If the price is negative, it raises an error using the SIGNAL statement.
validate_product_price
product_price
SIGNAL
Let’s extend our employees example to log both insertions and deletions:
DELIMITER $$ CREATE TRIGGER after_employee_insert AFTER INSERT ON employees FOR EACH ROW BEGIN INSERT INTO audit_log (emp_id, action, new_salary) VALUES (NEW.emp_id, 'INSERT', NEW.emp_salary); END$$ CREATE TRIGGER before_employee_delete BEFORE DELETE ON employees FOR EACH ROW BEGIN INSERT INTO audit_log (emp_id, action, old_salary) VALUES (OLD.emp_id, 'DELETE', OLD.emp_salary); END$$ DELIMITER ;
In this example:
after_employee_insert
before_employee_delete
Also, Read How to Create and Schedule Events in MySQL.
While triggers are powerful they can impact performance especially if they perform complex operations or are triggered frequently. It is essential to:
MySQL triggers are a versatile tool that can help enforce business rules maintain data integrity and automate repetitive tasks. By understanding how to create and manage triggers, you can use their power to enhance your database applications. However, it’s essential to use triggers carefully to streamline the performances.
We hope this guide has empowered you to use triggers in MySQL effectively. Consider using Ultahost dedicated server hosting, which provides the control and security needed for a smooth database experience. With root access to your server, you can easily install and configure MySQL and set up triggers to automate your database tasks efficiently.
A MySQL trigger is a database object that automatically runs a specific action when certain events occur in a table.
Triggers help automate repetitive tasks like logging changes or enforcing rules in a database.
You can create a trigger using the CREATE TRIGGER statement, specifying the event (INSERT, UPDATE, DELETE) and the timing (BEFORE or AFTER).
A BEFORE trigger runs before an event (like INSERT), while an AFTER trigger runs after the event occurs.
Yes, you can create multiple triggers for different events and timings on the same table.
Triggers cannot call other triggers and may add complexity to debugging and maintenance.
You can delete a trigger using the DROP TRIGGER statement followed by the trigger name.
PostgreSQL, also known as Postgres is a powerful open-s...
Automating tasks in MySQL, like backups, data cleaning,...
phpPgAdmin is a free, web-based interface for managing ...
SQL Server Management Studio (SSMS) is a comprehensive,...
Making a copy of your MySQL database, also known as a b...
Save my name, email, and website in this browser for the next time I comment.
Δ