MYSQL Triggers
MYSQL Triggers
INSERT
UPDATE
DELETE
Security Alarm: When a door (table) is opened (INSERT), the alarm (trigger) goes off
(executes ac ons like sounding a siren and no fying the authori es).
Automa c Email: When you complete an online purchase (UPDATE order status), the system
automa cally sends you a confirma on email (trigger ac on).
Spreadsheet Formula: When you change a value in one cell (UPDATE), a formula in another
cell (trigger) automa cally recalculates the result.
OLD
NEW
2. You want to validate or prevent the opera on → You can use SIGNAL to raise an
error and stop the opera on if condi ons aren’t met.
3. You need access to and want to modify NEW values before they are stored.
1. You need to perform ac ons only a er the actual change is successfully made.
→ E.g., logging, no fica ons, interac ng with other tables that rely on the
updated data.
2. You don’t need to change the data being wri en, only react to it.
BEFORE INSERT
AFTER INSERT
BEFORE UPDATE
AFTER UPDATE
BEFORE DELETE
AFTER DELETE
USE studentgrade;
name VARCHAR(100),
marks INT,
grade CHAR(1)
);
DELIMITER $$
BEGIN
ELSE
END IF;
END $$
DELIMITER ;
DELIMITER $$
BEGIN
IF NEW.marks >= 90 THEN
ELSE
END IF;
END $$
DELIMITER ;
Insert Value
Update Value
student_id INT,
name VARCHAR(100),
marks INT,
grade CHAR(1),
);
DELIMITER $$
BEGIN
END $$
DELIMITER ;
DELIMITER $$
BEGIN
END $$
DELIMITER ;