Triggers
A trigger in SQL is a stored program that automatically executes or fires when a specific event occurs in the database. It's a kind of stored procedure, but rather than running only when explicitly invoked, it runs in response to an event such as an INSERT, UPDATE, or DELETE command on a particular table or view.
Triggers are useful for maintaining the integrity of the data in the database. They can be used to perform tasks such as:
Enforcing business rules
Validating input data
Keeping an audit trail (i.e., logging changes)
Replicating data
Event logging and storing system statistics
Triggers have three main parts:
Event: This is the specific database operation that activates the trigger, such as INSERT, UPDATE, or DELETE.
Timing: This specifies whether the trigger should fire before or after the event.
Action: This is the set of tasks or commands that the trigger performs when it fires.
Here is a general example of a trigger in SQL:
CREATE TRIGGER trigger_name
BEFORE|AFTER|INSTEAD OF INSERT|UPDATE|DELETE
ON table_name
FOR EACH ROW
BEGIN
-- SQL commands to be executed
END;
Here is a specific example in MySQL:
CREATE TRIGGER before_employee_update
BEFORE UPDATE
ON employees
FOR EACH ROW
BEGIN
INSERT INTO employees_audit
SET action = 'update',
employee_id = OLD.employee_id,
datetime = NOW();
END;
This trigger, before_employee_update
, is activated before any UPDATE operation on the employees
table. For each row that gets updated, it inserts a new row into the employees_audit
table, recording the action type ('update'), the id of the employee being updated, and the current time.
Keep in mind that while triggers can be very powerful and useful, they can also make debugging and understanding the behavior of your database more complex because they are activated automatically by events, not explicitly called by your application code. Therefore, it's important to document them well and use them judiciously.