Trigger is a statement that a system executes automatically when there is any modification to the database. In a trigger, we first specify when the trigger is to be executed and then the action to be performed when the trigger executes. Triggers are used to specify certain integrity constraints and referential constraints that cannot be specified using the constraint mechanism of SQL.
Example -
Suppose, we are adding a tuple to the 'Donors' table that is some person has donated blood. So, we can design a trigger that will automatically add the value of donated blood to the 'Blood_record' table.
Types of Triggers -
We can define 6 types of triggers for each table:
- AFTER INSERT activated after data is inserted into the table.
- AFTER UPDATE: activated after data in the table is modified.
- AFTER DELETE: activated after data is deleted/removed from the table.
- BEFORE INSERT: activated before data is inserted into the table.
- BEFORE UPDATE: activated before data in the table is modified.
- BEFORE DELETE: activated before data is deleted/removed from the table.
Examples showing implementation of Triggers:
1. Write a trigger to ensure that no employee of age less than 25 can be inserted in the database.
delimiter $$
CREATE TRIGGER Check_age BEFORE INSERT ON employee
FOR EACH ROW
BEGIN
IF NEW.age < 25 THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'ERROR:
AGE MUST BE ATLEAST 25 YEARS!';
END IF;
END; $$
delimiter;
Explanation: Whenever we want to insert any tuple to table 'employee', then before inserting this tuple to the table, trigger named 'Check_age' will be executed. This trigger will check the age attribute. If it is greater than 25 then this tuple will be inserted into the table otherwise an error message will be printed stating "ERROR: AGE MUST BE ATLEAST 25 YEARS!"
2. Create a trigger which will work before deletion in employee table and create a duplicate copy of the record in another table employee_backup.
Before writing trigger, we need to create table employee_backup.
create table employee_backup (employee_no int,
employee_name varchar(40), job varchar(40),
hiredate date, salary int,
primary key(employee_no));
delimiter $$
CREATE TRIGGER Backup BEFORE DELETE ON employee
FOR EACH ROW
BEGIN
INSERT INTO employee_backup
VALUES (OLD.employee_no, OLD.name,
OLD.job, OLD.hiredate, OLD.salary);
END; $$
delimiter;
Explanation: We want to create a backup table that holds the value of those employees who are no more the employee of the institution. So, we create a trigger named Backup that will be executed before the deletion of any Tuple from the table employee. Before deletion, the values of all the attributes of the table employee will be stored in the table employee_backup.
3. Write a trigger to count number of new tuples inserted using each insert statement.
Declare count int
Set count=0;
delimiter $$
CREATE TRIGGER Count_tupples
AFTER INSERT ON employee
FOR EACH ROW
BEGIN
SET count = count + 1;
END; $$
delimiter;
Explanation: We want to keep track of the number of new Tuples in the employee table. For that, we first create a variable 'count' and initialize it to 0. After that, we create a trigger named Count_tuples that will increment the value of count after insertion of any new Tuple in the table employee.
Similar Reads
SQL Triggers
SQL triggers are essential in database management systems (DBMS). They enable SQL statements to run when specific database events occur such as when someone adds, changes, or removes data. Triggers are commonly used to maintain data integrity, track changes, and apply business rules automatically, w
8 min read
What is SQL?
SQL stands for Structured Query Language. It is a standardized programming language used to manage and manipulate relational databases. It enables users to perform a variety of tasks such as querying data, creating and modifying database structures, and managing access permissions. SQL is widely use
10 min read
SQL Stored Procedures
Stored procedures are precompiled SQL statements that are stored in the database and can be executed as a single unit. SQL Stored Procedures are a powerful feature in database management systems (DBMS) that allow developers to encapsulate SQL code and business logic. When executed, they can accept i
7 min read
MySQL | Common MySQL Queries
MySQL server is a open-source relational database management system which is a major support for web based applications. Databases and related tables are the main component of many websites and applications as the data is stored and exchanged over the web. Even all social networking websites mainly
9 min read
Different types of MySQL Triggers (with examples)
A MySQL trigger is a stored program (with queries) which is executed automatically to respond to a specific event such as insertion, updation or deletion occurring in a table. There are 6 different types of triggers in MySQL: 1. Before Update Trigger: As the name implies, it is a trigger which enact
6 min read
Query Processing in SQL
Query Processing includes translations of high-level Queries into low-level expressions that can be used at the physical level of the file system, query optimization, and actual execution of the query to get the actual result. High-level queries are converted into low-level expressions during query
4 min read
Integrity Rules in DBMS
In DBMS systems, integrity rules, which take a prime place, are designed to ensure that the quality of data is always high, with no inconsistencies or errors. The set of principles, also known as the integrity rules or constraints, helps to manage the data stored in the system in the right way and d
5 min read
SQL | UPDATE with JOIN
In SQL, the UPDATE with JOIN statement is a powerful tool that allows updating one table using data from another table based on a specific JOIN condition. This technique is particularly useful when we need to synchronize data, merge records, or update specific columns in one table by referencing rel
4 min read
Nested Queries in SQL
Nested queries, also known as subqueries, are an essential tool in SQL for performing complex data retrieval tasks. They allow us to embed one query within another, enabling us to filter, aggregate, and perform sophisticated calculations. Whether we're handling large datasets or performing advanced
7 min read
Introduction to PostgreSQL PL/pgSQL
PostgreSQL is an open-source, strong and highly extensible object-relational database system. It combines the power of SQL with additional procedural features, making it ideal for handling complex workloads. In PostgreSQL, PL/pgSQL (Procedural Language/PostgreSQL) enhances the SQL functionality by e
4 min read