A database trigger is a type of stored procedure that is automatically executed in response to a specific database event or action. Triggers can be used to enforce business rules, maintain data integrity, and perform complex database operations.
Here is an example of a database trigger:
CREATE TRIGGER update_employee_salary
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
IF NEW.salary > OLD.salary THEN
INSERT INTO salary_history (employee_id, old_salary, new_salary, change_date)
VALUES (OLD.employee_id, OLD.salary, NEW.salary, NOW());
END IF;
END
In this example, the trigger is called update_employee_salary and is fired after an update is made to the employees table. The trigger checks whether the new salary is greater than the old salary and inserts a new record into the salary_history table if it is.
Some common use cases for database triggers include:
Enforcing business rules: Triggers can be used to enforce business rules and ensure that data is entered correctly into the database. For example, a trigger could be used to ensure that a customer’s age is greater than 18 before adding them to the database.
Maintaining data integrity: Triggers can be used to maintain data integrity by preventing invalid data from being added to the database. For example, a trigger could be used to prevent a product from being added to an order if it is out of stock.
Auditing and logging: Triggers can be used to log changes made to the database for auditing purposes. For example, a trigger could be used to log changes made to a customer’s account information.
Data synchronization: Triggers can be used to synchronize data between different tables or databases. For example, a trigger could be used to update a sales summary table whenever a new order is added to the database.
Overall, database triggers provide a powerful mechanism for enforcing business rules, maintaining data integrity, and performing complex database operations. By using triggers, you can automate database tasks and ensure that data is consistently and reliably updated, making it a valuable tool for database developers and administrators.