Details about the trigger.
When we work with databases, certain actions—like inserting, updating, or deleting data—often need an automatic response.
For example, if a new student is added, maybe we also want to update the total count.
Or if an employee’s salary is changed, we may want to log that change for audit purposes.
Instead of relying on a user or developer to remember these extra steps, SQL gives us a feature that performs them automatically.
This automatic action is called a trigger.
A trigger is a special kind of stored program in the database that runs automatically whenever a specific event happens on a table.
How I Explain It to Students
Think of a trigger like a sensor-light in a room:
The moment someone walks in (event), the light turns on (action), without anyone touching a switch.
Similarly, in a database:
- Event → Insert, Update, Delete
- Action → Whatever SQL code the trigger contains
The important part is:
you do not explicitly call a trigger; it fires on its own.
Key Points About Triggers
- They run automatically based on events
- They are attached to a specific table
- They can execute before or after an INSERT, UPDATE, or DELETE
- They help maintain data accuracy, auditing, and business rules
Simple Example
Suppose you want to keep a history of salary changes.
A trigger could look like this:
CREATE TRIGGER LogSalaryChange
ON Employees
AFTER UPDATE
AS
BEGIN
INSERT INTO SalaryHistory(EmpID, OldSalary, NewSalary, ChangeDate)
SELECT EmpID, deleted.Salary, inserted.Salary, GETDATE()
FROM inserted
JOIN deleted ON inserted.EmpID = deleted.EmpID;
END;
Now, whenever someone’s salary is updated:
- The trigger fires automatically
- It records the old salary and new salary in the history table
No developer has to write extra code each time—SQL handles it.
Why Are Triggers Useful?
Triggers are commonly used for:
- Auditing (tracking changes)
- Enforcing rules (preventing invalid changes)
- Maintaining related tables automatically
- Logging actions for security
- Cascading updates or checks
Essentially, triggers help the database “react” intelligently to changes, without requiring manual action from users.
A trigger is a set of SQL statements that are automatically executed in response to a specific event or action in the database.