0% found this document useful (0 votes)
7 views7 pages

Inbound 5671427164622185979

IT about database
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
0% found this document useful (0 votes)
7 views7 pages

Inbound 5671427164622185979

IT about database
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/ 7

1.

Introduction to Triggers
✅ What is a Trigger?
●​ A trigger is a database object that is automatically executed or fired when certain
events occur in a table.​

●​ Used for:​

○​ Maintaining data integrity​

○​ Automating tasks​

○​ Enforcing business rules​

🔑 Key Points:
●​ Triggers are always associated with a table.​

●​ They respond to INSERT, UPDATE, or DELETE events.​

●​ They can run BEFORE or AFTER the event.​

📝 Syntax (basic form)


CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- SQL statements
END;

🎓 Example: Basic Trigger


Suppose we want to log whenever a new student is added.

CREATE TABLE StudentLogs (


log_id INT AUTO_INCREMENT PRIMARY KEY,
student_name VARCHAR(100),
action_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

CREATE TRIGGER after_student_insert


AFTER INSERT ON Students
FOR EACH ROW
BEGIN
INSERT INTO StudentLogs(student_name)
VALUES (NEW.name);
END;

🔍 Explanation:
●​ AFTER INSERT means trigger fires after new student is inserted.​

●​ NEW.name → refers to the inserted row.​

●​ Creates an automatic log entry.

2. Types of Triggers
✅ By timing:
●​ BEFORE triggers → Run before action is executed​

●​ AFTER triggers → Run after action is executed​

✅ By event:
●​ INSERT → Fires when inserting data​

●​ UPDATE → Fires when updating data​

●​ DELETE → Fires when deleting data​

⚡ MySQL supports 6 types in total:


●​ BEFORE INSERT​

●​ AFTER INSERT​
●​ BEFORE UPDATE​

●​ AFTER UPDATE​

●​ BEFORE DELETE​

●​ AFTER DELETE

🎓 Example 1: BEFORE INSERT Trigger


Prevent inserting students younger than 15 years old:

CREATE TRIGGER check_student_age

BEFORE INSERT ON Students

FOR EACH ROW

BEGIN

IF NEW.age < 15 THEN

SIGNAL SQLSTATE '45000'

SET MESSAGE_TEXT = 'Student age must be 15 or older';

END IF;

END;

🎓 Example 2: AFTER UPDATE Trigger


Track changes when a student updates their email:

CREATE TABLE StudentUpdates (

update_id INT AUTO_INCREMENT PRIMARY KEY,

student_id INT,

old_email VARCHAR(100),

new_email VARCHAR(100),

updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP


);

CREATE TRIGGER after_student_update

AFTER UPDATE ON Students

FOR EACH ROW

BEGIN

IF OLD.email <> NEW.email THEN

INSERT INTO StudentUpdates(student_id, old_email, new_email)

VALUES (OLD.student_id, OLD.email, NEW.email);

END IF;

END;

3. Managing Triggers (10 minutes)

✅ Viewing Triggers
SHOW TRIGGERS;

✅ Dropping a Trigger
DROP TRIGGER IF EXISTS trigger_name;

✅ Replacing / Altering a Trigger


MySQL does not allow ALTER TRIGGER directly.

Must DROP and then CREATE again.

DROP TRIGGER IF EXISTS after_student_insert;


4. Use Cases of Triggers
📌 Common Scenarios:
Audit Logging​

●​ Keep track of changes (who changed what and when).​

Enforcing Business Rules​

●​ E.g., no negative balance in accounts.​

Cascading Changes​

●​ E.g., if a parent record is deleted, also clean up related tables.​

Data Validation​

●​ E.g., restrict invalid data before it gets stored.

🎓 Example Use Cases


1. Logging Deletions

CREATE TABLE StudentDeletions (

student_id INT,

deleted_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP

);

CREATE TRIGGER log_student_deletion

AFTER DELETE ON Students

FOR EACH ROW


BEGIN

INSERT INTO StudentDeletions(student_id)

VALUES (OLD.student_id);

END;

2. Prevent Negative Balances

CREATE TRIGGER check_balance

BEFORE UPDATE ON Accounts

FOR EACH ROW

BEGIN

IF NEW.balance < 0 THEN

SIGNAL SQLSTATE '45000'

SET MESSAGE_TEXT = 'Balance cannot be negative';

END IF;

END;

5. Limitations & Best Practices (5 minutes)

⚠️ Limitations:
●​ One trigger per table per event per timing (e.g., only one BEFORE INSERT).​

●​ Can’t directly commit/rollback inside triggers.​

●​ Excessive triggers can hurt performance.​

✅ Best Practices:
●​ Keep triggers simple and focused.​
●​ Use them for data integrity and automation, not for complex logic.​

●​ Document your triggers (since they run “behind the scenes”).

You might also like