An automatic execution of a defined block of SQL code known as a trigger occurs in reaction to specific events, such as the addition, modification, or deletion of a record in a table. Among other things, triggers are employed to uphold data integrity or to enforce business standards.
The SQL syntax for building a trigger is as follows:
CREATE TRIGGER trigger_name
FOR EACH ROW
-- trigger code goes here
For instance, you could use the following sentence to build a trigger called “update_salary_history” that updates the “salary_history” table anytime an employee’s salary is updated in the “employees” table:
CREATE TRIGGER update_salary_history
AFTER UPDATE OF salary
FOR EACH ROW
INSERT INTO salary_history (employee_id, salary, update_date)
VALUES (OLD.employee_id, OLD.salary, CURRENT_TIMESTAMP);
To drop a trigger, you can use the following statement:
DROP TRIGGER trigger_name;
Triggers can be helpful for automating specific processes or maintaining data integrity, but they can also be difficult to build and manage, so they should only be used in limited circumstances. In general, it is a good practice to utilize triggers sparingly and to substitute other methods, including foreign keys and stored procedures, whenever possible.