A trigger is a set of SQL statements that automatically execute or fire when certain events occur in the database. Triggers are used to enforce data integrity, automate processes, and maintain historical data.
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- SQL statements
END;
This syntax creates a trigger that executes the specified SQL statements when the defined event occurs on the specified table.
Here’s an example of a trigger that automatically updates the last_modified
field of a table whenever a record is updated:
CREATE TRIGGER UpdateLastModified
AFTER UPDATE ON Employees
FOR EACH ROW
BEGIN
SET NEW.last_modified = NOW();
END;
This trigger sets the last_modified
field to the current timestamp whenever an employee record is updated.
Triggers are commonly used for:
Create a trigger for a sample table to enforce a business rule. For example, automatically set a field when a record is inserted or updated.