DSPython Logo DSPython

SQL Triggers

Learn BEFORE, AFTER triggers with real-world examples.

SQL Intermediate 60 min

🧠 Introduction: SQL Triggers

A SQL Trigger is a special database object that automatically executes when a specific event occurs on a table.

Triggers are commonly used to enforce business rules, validate data, maintain audit logs, and ensure consistency without manual execution.

πŸ“ Trigger Executes Automatically On:

INSERT
UPDATE
DELETE

🎯 Topic 1: Trigger Events & Timing

Triggers fire based on event and timing.

βœ… Trigger Types:

β€’ BEFORE INSERT
β€’ AFTER INSERT
β€’ BEFORE UPDATE
β€’ AFTER UPDATE
β€’ BEFORE DELETE
β€’ AFTER DELETE

πŸ’» Example: BEFORE INSERT Trigger

CREATE TRIGGER before_employee_insert
BEFORE INSERT ON Employees
FOR EACH ROW
BEGIN
  IF NEW.Salary < 0 THEN
    SIGNAL SQLSTATE '45000';
  END IF;
END;

πŸ” Topic 2: NEW & OLD Keywords

MySQL provides NEW and OLD keywords to access row values inside triggers.

β€’ NEW.column β†’ New row value (INSERT / UPDATE)
β€’ OLD.column β†’ Old row value (UPDATE / DELETE)

πŸ’» Example: AFTER UPDATE Trigger

IF OLD.Salary <> NEW.Salary THEN
  INSERT INTO Salary_Log VALUES (...);
END IF;

↩️ Topic 3: BEFORE Triggers

BEFORE triggers run before data modification. They are mainly used for validation and restriction.

β€’ Validate data
β€’ Prevent invalid operations
β€’ Modify incoming values

πŸ’» Example: BEFORE DELETE

IF OLD.Department = 'HR' THEN
  SIGNAL SQLSTATE '45000';
END IF;

🧷 Topic 4: AFTER Triggers

AFTER triggers execute after the data change. Mostly used for logging and audit tracking.

β€’ Maintain audit tables
β€’ Track changes
β€’ Business analytics

πŸ’» Example: AFTER INSERT

INSERT INTO Employee_Audit
VALUES (NEW.EmployeeID, 'INSERT', NOW());

🚦 Topic 5: Trigger Rules & Limitations

Triggers have strict rules in MySQL / MariaDB.

β€’ COMMIT / ROLLBACK ❌ not allowed
β€’ FOR EACH ROW is mandatory
β€’ Cannot call another trigger
β€’ No parameters allowed

πŸ“š Module Summary

  • Triggers execute automatically
  • Used for validation and logging
  • BEFORE β†’ validation
  • AFTER β†’ auditing
  • NEW & OLD access row values

πŸ€” Interview Q&A

A trigger is an automatic SQL program that executes when an event occurs on a table.

BEFORE triggers run before data change, AFTER triggers run after data change.

NEW refers to new row values, OLD refers to existing row values.

No. Transaction control statements are not allowed inside triggers.

πŸ€–
DSPython AI Assistant βœ–
πŸ‘‹ Hi! I’m your AI assistant. Paste your code here, I will find bugs for you.