Triggers in MySQL
CREATION AND WORKING OF TRIGGERS IN MYSQL
1. AIM
To understand the concept of Triggers in SQL and to create various types of triggers in MySQL.
2. THEORY
✔ What is a Trigger?
A trigger is a stored program that is automatically executed (fires) when a specific event occurs on a table.
Triggers work on:
-
INSERT
-
UPDATE
-
DELETE
Triggers can fire:
-
BEFORE
-
AFTER
✔ Why Use Triggers?
-
Enforce business rules
-
Maintain audit logs
-
Automatically update values
-
Prevent invalid data modification
-
Maintain referential integrity
✔ Trigger Syntax (MySQL)
Where:
-
timing → BEFORE or AFTER
-
event → INSERT, UPDATE, DELETE
3. EXAMPLES FOR LAB
⭐ Example 1: BEFORE INSERT Trigger (Validate Data)
Aim: Prevent insertion of negative salary.
Table Setup:
Trigger Creation:
Test Trigger:
Output:
⭐ Example 2: AFTER INSERT Trigger (Audit Log)
Aim: Store every inserted employee into a log table.
Create log table:
Trigger Creation:
Test Trigger:
⭐ Example 3: BEFORE UPDATE Trigger (Prevent Salary Decrease)
Aim: Prevent salary reduction of an employee.
Test:
Output:
⭐ Example 4: AFTER DELETE Trigger (Record Deleted Data)
Aim: Store deleted employee record in a backup table.
Create backup table:
Create Trigger:
Test:
⭐ Example 5: UPDATE Trigger to Maintain Last Modified Time
Modify table:
Create Trigger:
⭐ Example 6: Trigger Using OLD and NEW
| Operation | NEW | OLD |
|---|---|---|
| INSERT | NEW | null |
| UPDATE | NEW | OLD |
| DELETE | null | OLD |
Example:
4. HOW TO VIEW AND DROP TRIGGERS
✔ View triggers:
✔ Drop a trigger:
5. RESULT
Triggers were successfully created, executed, tested and verified in MySQL.
Comments
Post a Comment