L 26 MYSQL Triggers
L 26 MYSQL Triggers
and Web
(15B11CI312)
Database Systems and Web
❑ Trigger is stored into database and invoked repeatedly, when specific condition match.
❖ MySQL supports triggers that are invoked in response to DELETE, INSERT, or UPDATE
event.
Types of Triggers
❑ The SQL standard defines two types of triggers: row-level triggers and statement-level triggers.
❖ Row- level Trigger: Activated for each row that is inserted, updated, or deleted.
For example, if a table has 50 rows inserted, updated, or deleted, the trigger is automatically
invoked 50 times for each affected row.
❖ Statement-level Trigger: Activated once for each transaction irrespective of the number of
rows are inserted, updated, or deleted.
For example, if a table has 50 rows inserted, updated, or deleted, the trigger is invoked only
once.
Note: MySQL supports only row-level triggers. It doesn’t support statement-level triggers.
Advantages of Triggers
❑ To check the integrity of data.
❑ [ON table_name] − Specifies the name of the table associated with the trigger.
Creating Triggers
❑[REFERENCING OLD AS o NEW AS n] - Allows to refer new and old values for various
DML statements, such as INSERT, UPDATE, and DELETE.
❑ [FOR EACH ROW] − Specifies a row-level trigger. The trigger will be executed for each row
being affected..
❑ FOLLOWS | PRECEDES -- For each triggering event e.g., INSERT, UPDATE, or DELETE,
you can define multiple triggers to fire. In this case, you need to specify the firing sequence using
the FOLLOWS or PRECEDES option.
Drop a trigger
DROP TRIGGER [IF EXISTS] [schema_name.]
trigger_name;
Note:
❑ Can access and change the NEW values.
❑ Cannot access the OLD values because OLD values obviously do not exist.
Example
Create a MySQL trigger for the WorkCenters table that would fire for before INSERT operation performed
on the WorkCenters table and trigger will store the summary of the capacity of the work centers into
WorkCenterStats table.
DELIMITER $$
CREATE TRIGGER before_workcenters_insert
BEFORE INSERT ON WorkCenters
FOR EACH ROW
BEGIN
DECLARE rowcount INT;
SELECT COUNT(*) INTO rowcount FROM WorkCenterStats;
IF rowcount > 0 THEN
UPDATE WorkCenterStats SET totalCapacity = totalCapacity + new.capacity;
ELSE
INSERT INTO WorkCenterStats(totalCapacity) VALUES(new.capacity);
END IF;
END $$
DELIMITER ;
Create a MySQL trigger for the WorkCenters table that would fire for before INSERT operation
performed on the WorkCenters table and trigger will store the summary of the capacity of the
work centers into WorkCenterStats table.
Note:
❑ Can access the NEW values but cannot change them.
❑ Cannot access the OLD values because there is no OLD on INSERT triggers.
MySQL BEFORE UPDATE triggers
DELIMITER $$
CREATE TRIGGER trigger_name
BEFORE UPDATE ON table_name
FOR EACH ROW
BEGIN
- - statements
END
$$ DELIMITER ;
Note:
❑ Can update the NEW values but cannot update the OLD values
MySQL AFTER UPDATE triggers
DELIMITER $$
CREATE TRIGGER trigger_name
AFTER UPDATE ON table_name
FOR EACH ROW
BEGIN
- - statements
END
$$ DELIMITER ;
Note:
❑ Can access OLD and NEW rows but cannot update them.
Example
Creates a MYSQL trigger for the customers table that would fire for AFTER
UPDATE operations performed on the CUSTOMERS table and trigger will store
id, old salary, new salary and salary difference in DisplaySalaryChanges table.
CUSTOMERS Table
Creates a MYSQL trigger for the customers table that would fire for AFTER UPDATE
operations performed on the CUSTOMERS table and trigger will store id, old salary, new salary
and salary difference.
1. Create Trigger: salary_changes
DELIMITER $$
CREATE TRIGGER salary_changes
AFTER UPDATE
ON customers FOR EACH ROW
BEGIN
DECLARE Sal_diff INT;
IF NEW.salary > OLD.salary THEN
SET Sal_diff = NEW.salary - OLD.salary;
INSERT INTO DisplaySalaryChanges(Id, OldSalary, NewSalary, DiffSalary)
VALUES(OLD.Id, OLD.salary, NEW.Salary, Sal_diff);
ELSE
SET Sal_diff = OLD.salary - NEW.salary ;
INSERT INTO DisplaySalaryChanges(Id, OldSalary, NewSalary, DiffSalary)
VALUES(OLD.Id, OLD.salary, NEW.Salary, Sal_diff);
END IF;
END $$
DELIMITER ;
Creates a MYSQL trigger for the customers table that would fire for AFTER UPDATE
operations performed on the CUSTOMERS table and trigger will store id, old salary, new salary
and salary difference.
2. Triggering Trigger
❑ UPDATE statement : update an existing record in the table
UPDATE CUSTOMER
SET salary = salary + 2,000
WHERE id = 12;
Note:
❑ Can access the OLD row but cannot update it.
❑ There is no NEW row in the BEFORE DELETE trigger.
MySQL AFTER DELETE triggers
DELIMITER $$
CREATE TRIGGER trigger_name
AFTER DELETE ON table_name
FOR EACH ROW
BEGIN
- - statements
END
$$ DELIMITER ;
Note:
❑ Can access the OLD row but cannot change it.
❑ There is no NEW row in the AFTER DELETE trigger.
Example
Create a MySQL trigger for the Salaries table that would updates the total salary in
the SalaryBudgets table after a row is deleted from the Salaries table.
DELIMITER $$
CREATE TRIGGER SELECT * FROM SalaryBudgets;
after_salaries_delete
AFTER DELETE
ON Salaries FOR EACH ROW
UPDATE SalaryBudgets
SET total = total - old.salary;
END $$
DELIMITER ;
Create a Trigger to insert contact_id and contact creation-date and user information into
contacts_audit record after an insertion in contacts table.
insert into contacts values(“Sharma",“Amit", ‘1990-1-01’);
Trigger to insert contact_id and contact
deletion-date/user information into
contacts_audit record before a delete occurs
create table contacts_audit (contact_id integer, deleted_date date, deleted_by varchar(20));
delimiter //
create trigger contacts_before_delete
-> before delete
-> on contacts for each row
-> begin
-> DECLARE vUser varchar(50);
->
-> -- Find username of person performing the DELETE into table
-> SELECT USER() into vUser;
->
-> -- Insert record into audit table
-> INSERT into contacts_audit VALUES ( OLD.contact_id, SYSDATE(), vUser );
-> end; //
Trigger to insert contact_id and contact
deletion-date/user information into
contacts_audit record after a delete occurs
create trigger contacts_after_delete
-> after delete
-> on contacts for each row
-> begin
->
-> DECLARE vUser varchar(50);
->
-> -- Find username of person performing the DELETE into table
-> SELECT USER() into vUser;
->
-> -- Insert record into audit table
-> INSERT into contacts_audit VALUES ( OLD.contact_id, SYSDATE(), vUser );
-> end; //
References
1. https://www.mysqltutorial.org/
2. https://www.javatpoint.com/
3. https://www.geeksforgeeks.org/
4. Murach's MySQL, 3rd edition by Joel Murach.