DEV Community

Kiran Kumar
Kiran Kumar

Posted on

Triggers in SQL

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)
);
Enter fullscreen mode Exit fullscreen mode
Audit Log Table

CREATE TABLE SalaryLog (
    EmpID INT,
    OldSalary DECIMAL(10,2),
    NewSalary DECIMAL(10,2),
    ChangeDate TIMESTAMP
);
Enter fullscreen mode Exit fullscreen mode
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;
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰ 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)