Triggers are SQL statements (or blocks of statements) that automatically execute when certain events occur on a table β typically INSERT, UPDATE, or DELETE. Theyβre tied to a table and fire either before or after the event, depending on how you define them.
Example
Table: Employees
CREATE TABLE Employees (
EmpID INT PRIMARY KEY,
Name VARCHAR(50),
Salary DECIMAL(10,2)
);
Audit Log Table
CREATE TABLE SalaryLog (
EmpID INT,
OldSalary DECIMAL(10,2),
NewSalary DECIMAL(10,2),
ChangeDate TIMESTAMP
);
Trigger
CREATE TRIGGER log_salary_change
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
INSERT INTO SalaryLog (EmpID, OldSalary, NewSalary, ChangeDate)
VALUES (OLD.EmpID, OLD.Salary, NEW.Salary, NOW());
END;
π Whenever a salary is updated in Employees, this trigger automatically records the change in SalaryLog.
- Triggers = automatic execution based on events.
- Events = INSERT, UPDATE, DELETE (sometimes BEFORE/AFTER).
- Use cases: auditing, enforcing rules, maintaining consistency.
- Caution: too many or complex triggers can hurt performance.
Top comments (0)