What is a MySQL Trigger?
A MySQL trigger is a database object that is associated with a table. It will
be activated when a defined action is executed for the table.
The trigger can be executed when you run one of the following MySQL
statements on the table: INSERT, UPDATE and DELETE and it can be invoked
before or after the event.
A trigger in MySQL is a set of SQL statements that reside in a system
catalog. It is a special type of stored procedure that is invoked
automatically in response to an event. Each trigger is associated with a
table, which is activated on any DML statement such as INSERT, UPDATE,
or DELETE.
We need/use triggers in MySQL due to the following features:
Triggers help us to enforce business rules.
Triggers help us to validate data even before they are inserted or
updated.
Triggers help us to keep a log of records like maintaining audit trails
in tables.
SQL triggers provide an alternative way to check the integrity of
data.
Triggers provide an alternative way to run the scheduled task.
Triggers increases the performance of SQL queries because it does
not need to compile each time the query is executed.
Triggers reduce the client-side code that saves time and effort.
Triggers help us to scale our application across different platforms.
Triggers are easy to maintain.
Trigger Syntax
CREATE TRIGGER trigger_name
(AFTER | BEFORE) (INSERT | UPDATE | DELETE)
ON table_name FOR EACH ROW
BEGIN
--variable declarations
--trigger code
END;
Example-1
mysql> CREATE TABLE people (age INT, name varchar(150))
Next, define the trigger. It will be executed before every INSERT
statement for the people table:
mysql> delimiter //
mysql> CREATE TRIGGER agecheck BEFORE INSERT ON people
FOR EACH ROW
IF NEW.age < 0 THEN
SET NEW.age = 0;
END IF;//
Query OK, 0 rows affected (0.00 sec) mysql> delimiter ;
Insert two records to check the trigger functionality.
mysql> INSERT INTO people VALUES (-20, ‘Sid’), (30, ‘Josh’);
Query OK, 2 rows affected (0.00 sec)
Records: 2 Duplicates: 0 Warnings: 0
In the end, check the result.
mysql> SELECT * FROM people;
+——-+——-+
| age | name |
+——-+——-+
| 0 | Sid |
| 30 | Josh |
+——-+——-+
2 rows in set (0.00 sec)
Example -2
1. CREATE TABLE student_info (
2. stud_id int NOT NULL,
3. stud_code varchar(15) DEFAULT NULL,
4. stud_name varchar(35) DEFAULT NULL,
5. subject varchar(25) DEFAULT NULL,
6. marks int DEFAULT NULL,
7. phone varchar(15) DEFAULT NULL,
8. PRIMARY KEY (stud_id)
9. )
1. CREATE TABLE student_detail (
2. stud_id int NOT NULL,
3. stud_code varchar(15) DEFAULT NULL,
4. stud_name varchar(35) DEFAULT NULL,
5. subject varchar(25) DEFAULT NULL,
6. marks int DEFAULT NULL,
7. phone varchar(15) DEFAULT NULL,
8. Lasinserted Time,
9. PRIMARY KEY (stud_id)
10. );
1. mysql> DELIMITER //
2. mysql> Create Trigger after_insert_details
3. AFTER INSERT ON student_info FOR EACH ROW
4. BEGIN
5. INSERT INTO student_detail VALUES (new.stud_id, new.stud_code,
6. new.stud_name, new.subject, new.marks, new.phone, CURTIME());
7. END //
mysql> INSERT INTO student_info VALUES (10, 110, 'Alexandar', 'Biolo
gy', 67, '2347346438');
The table that has been modified after the update query executes is
student_detail. We can verify it by using the SELECT statement as follows:
mysql> SELECT * FROM student_detail;
AFTER UPDATE Trigger Example -3
1. DELIMITER $$
2. CREATE TRIGGER trigger_name AFTER UPDATE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
1. mysql> CREATE TABLE students(
2. id int NOT NULL AUTO_INCREMENT,
3. name varchar(45) NOT NULL,
4. class int NOT NULL,
5. email_id varchar(65) NOT NULL,
6. PRIMARY KEY (id)
7. );
Next, we will insert some records into this table using the below
statement:
1. INSERT INTO students (name, class, email_id)
2. VALUES ('Stephen', 6, '
[email protected]'),
3. ('Bob', 7, '
[email protected]'),
4. ('Steven', 8, '
[email protected]'),
5. ('Alexandar', 7, '
[email protected]');
1. mysql> CREATE TABLE students_log(
2. user varchar(45) NOT NULL,
3. descreptions varchar(65) NOT NULL
4. );
1. DELIMITER $$
2.
3. CREATE TRIGGER after_update_studentsInfo
4. AFTER UPDATE
5. ON students FOR EACH ROW
6. BEGIN
7. INSERT into students_log VALUES (user(),
8. CONCAT('Update Student Record ', OLD.name, ' Previous Class :',
9. OLD.class, ' Present Class ', NEW.class));
10. END $$
11. DELIMITER ;
First, we will update the "students" table using the following statements
that invoke the above-created trigger:
mysql> UPDATE students SET class = class + 1;
Example -4
1. DELIMITER $$
2. CREATE TRIGGER trigger_name BEFORE DELETE
3. ON table_name FOR EACH ROW
4. BEGIN
5. variable declarations
6. trigger code
7. END$$
8. DELIMITER ;
1. CREATE TABLE salaries (
2. emp_num INT PRIMARY KEY,
3. valid_from DATE NOT NULL,
4. amount DEC(8 , 2 ) NOT NULL DEFAULT 0
5. );
Next, we will insert some records into this table using the below
statement:
1. INSERT INTO salaries (emp_num, valid_from, amount)
2. VALUES
3. (102, '2020-01-10', 45000),
4. (103, '2020-01-10', 65000),
5. (105, '2020-01-10', 55000),
6. (107, '2020-01-10', 70000),
7. (109, '2020-01-10', 40000);
Execute the SELECT query to see the table data.
Third, we will create another table named salary_archives that keeps the
information of deleted salary.
1. CREATE TABLE salary_archives (
2. id INT PRIMARY KEY AUTO_INCREMENT,
3. emp_num INT,
4. valid_from DATE NOT NULL,
5. amount DEC(18 , 2 ) NOT NULL DEFAULT 0,
6. deleted_time TIMESTAMP DEFAULT NOW()
7. );
1. DELIMITER $$
2. CREATE TRIGGER before_delete_salaries
3. BEFORE DELETE
4. ON salaries FOR EACH ROW
5. BEGIN
6. INSERT INTO salary_archives (emp_num, valid_from, amount)
7. VALUES(OLD. emp_num, OLD.valid_from, OLD.amount);
8. END$$
9. DELIMITER ;
mysql> DELETE FROM salaries WHERE emp_num = 105;
Second, we will query data from the salary_archives table to verify the
above-created trigger is invoked or not by using the select statement:
mysql> SELECT * FROM salary_archives;