100% found this document useful (1 vote)
61 views

L 26 MYSQL Triggers

Here is the trigger to update the total salary in SalaryBudgets after a row is deleted from Salaries: DELIMITER $$ CREATE TRIGGER update_salary_budget AFTER DELETE ON Salaries FOR EACH ROW BEGIN UPDATE SalaryBudgets SET total = total - OLD.salary; END$$ DELIMITER ; To test it: DELETE FROM Salaries WHERE employeeNumber = 1002; SELECT * FROM SalaryBudgets; This trigger uses the OLD row to access the salary of the deleted row and subtracts it from the total in SalaryBudgets.

Uploaded by

sarthaksainia12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
61 views

L 26 MYSQL Triggers

Here is the trigger to update the total salary in SalaryBudgets after a row is deleted from Salaries: DELIMITER $$ CREATE TRIGGER update_salary_budget AFTER DELETE ON Salaries FOR EACH ROW BEGIN UPDATE SalaryBudgets SET total = total - OLD.salary; END$$ DELIMITER ; To test it: DELETE FROM Salaries WHERE employeeNumber = 1002; SELECT * FROM SalaryBudgets; This trigger uses the OLD row to access the salary of the deleted row and subtracts it from the total in SalaryBudgets.

Uploaded by

sarthaksainia12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 28

Database Systems

and Web
(15B11CI312)
Database Systems and Web

Lecture: MYSQL Triggers


Contents to be covered
▪ MYSQL Trigger
▪ Types of Triggers
▪ Advantages of Triggers
▪ Creating Trigger
▪ Drop Trigger
▪ MYSQL BEFORE INSERT trigger
▪ MYSQL AFTER INSERT trigger
▪ MYSQL BEFORE UPDATE trigger
▪ MYSQL AFTER UPDATE trigger
▪ MYSQL BEFORE DELETE trigger
▪ MYSQL AFTER DELETE trigger
MYSQL Trigger
❑ Triggers are stored programs.

❑ Automatically executed or fired when specified events occur.

❑ Trigger is stored into database and invoked repeatedly, when specific condition match.

❑ Triggers are written to be executed in response to any of the following events:

❖ 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.

❑ Handle errors from the database layer.

❑ Provide an alternative way to run scheduled tasks.

❑ Useful for auditing the data changes in tables.


Creating Triggers

CREATE TRIGGER trigger_name


{BEFORE | AFTER} {INSERT | UPDATE|
DELETE }
ON table_name FOR EACH ROW
FOLLOWS | PRECEDES
trigger_body;
❑ CREATE TRIGGER trigger_name − Creates a trigger with the trigger_name.

❑ {BEFORE | AFTER} − Specifies when the trigger will be executed.

❑{INSERT [OR] | UPDATE [OR] | DELETE} − Specifies the DML operation.

❑ [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;

trigger_name: specify the name of the Trigger to be dropped.


schema_name: specify the name of the schema to which the trigger belongs. Skipping the
schema name lead to drop the trigger in the current database.
IF EXISTS: To drop a trigger that does not exist without using the IF EXISTS clause, MySQL
issues an error. Otherwise, MySQL issues a NOTE.
MySQL BEFORE INSERT triggers
DELIMITER $$
CREATE TRIGGER trigger_name
BEFORE INSERT ON table_name
FOR EACH ROW
BEGIN
- - statements
END
$$ DELIMITER ;

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.

DROP TABLE IF EXISTS WorkCenters; DROP TABLE IF EXISTS WorkCenterStats;


CREATE TABLE WorkCenters ( CREATE TABLE WorkCenterStats(
id INT AUTO_INCREMENT PRIMARY KEY, totalCapacity INT NOT NULL );
name VARCHAR(50) NOT NULL,
capacity INT NOT NULL );
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.
1. Create Trigger: before_workcenters_insert

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.

INSERT INTO WorkCenters(name,


INSERT INTO WorkCenters(name,
capacity)
capacity) VALUES ('Machine Y', 200);
VALUES ('Machine X', 100);

SELECT * FROM SELECT * FROM


WorkCenterStats; WorkCenterStats;
MySQL AFTER INSERT triggers
DELIMITER $$
CREATE TRIGGER trigger_name
AFTER INSERT ON table_name
FOR EACH ROW
BEGIN
- - statements
END
$$ DELIMITER ;

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.

Id Name Age Salary


11 John 35 20,000
12 Deo 30 25,000
13 Duce 32 30,000
14 Jack36 25,000

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;

When a record is updated in the “CUSTOMERS” table, trigger ” salary_changes ” will be


fired and update table “DisplaySalaryChanges”
SELECT * FROM CUSTOMER SELECT * FROM DisplaySalaryChanges

Id Name Age Salary Id OldSalary NewSalary DiffSalary


11 John 35 20,000 12 25,000 27,000 2,000
12 Deo 30 25,000
13 Duce 32 30,000
14 Jack36 25,000
MySQL BEFORE DELETE triggers
DELIMITER $$
CREATE TRIGGER trigger_name
BEFORE DELETE ON table_name
FOR EACH ROW
BEGIN
- - statements
END
$$ DELIMITER ;

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.

DROP TABLE IF EXISTS Salaries; DROP TABLE IF EXISTS SalaryBudgets;


CREATE TABLE Salaries ( CREATE TABLE SalaryBudgets(
employeeNumber INT PRIMARY KEY, total DECIMAL(15,2) NOT NULL );
salary DECIMAL(10,2) NOT NULL DEFAULT
0 );
INSERT INTO SalaryBudgets(total)
SELECT SUM(salary)
INSERT INTO Salaries(employeeNumber, salary) FROM Salaries;
VALUES
(1002,5000), SELECT * FROM SalaryBudgets;
(1056,7000),
(1076,8000);
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 ;

DELETE FROM Salaries


WHERE employeeNumber = 1002;
Example
contacts (contact_id int (11) NOT NULL AUTO_INCREMENT, last_name VARCHAR(30) NOT
NULL, first_name VARCHAR(25), birthday DATE)

contacts_audit (contact_id integer, created_date date, created_by varchar (30));

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.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy