Thursday, November 30, 2023
HomeAcademicTrigger in SQL

Trigger in SQL

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
AFTER/BEFORE INSERT/UPDATE/DELETE
ON table_name
FOR EACH ROW
BEGIN
-- trigger code goes here
END;

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
ON employees
FOR EACH ROW
BEGIN
INSERT INTO salary_history (employee_id, salary, update_date)
VALUES (OLD.employee_id, OLD.salary, CURRENT_TIMESTAMP);
END;

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.

datasagarhttp://www.DataSagar.com
The author of this blog post is a technology fellow, an IT entrepreneur, and Educator in Kathmandu Nepal. With his keen interest in Data Science and Business Intelligence, he writes on random topics occasionally in the DataSagar blog.
RELATED ARTICLES
- Advertisment -

Most Popular