0% found this document useful (0 votes)
39 views

Triggers in MySQL

The document discusses different types of MySQL triggers including before insert, after insert, before update, after update, before delete, and after delete triggers. It provides examples of creating each trigger type and how they work. Triggers allow executing SQL statements automatically in response to data changes in a table.

Uploaded by

Rajesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
39 views

Triggers in MySQL

The document discusses different types of MySQL triggers including before insert, after insert, before update, after update, before delete, and after delete triggers. It provides examples of creating each trigger type and how they work. Triggers allow executing SQL statements automatically in response to data changes in a table.

Uploaded by

Rajesh Kumar
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 16

Reosurces:-

MySQL Trigger - javatpoint

Different types of MySQL Triggers (with examples) - GeeksforGeeks

MySQL Triggers (mysqltutorial.org)


MySQL Trigger
A trigger in MySQL is a set of SQL statements that reside in a system catalog. It is a
special type of stored procedure that is invoked automatically in response to an
event. Each trigger is associated with a table, which is activated on any DML
statement such as INSERT, UPDATE, or DELETE.

A trigger is called a special procedure because it cannot be called directly like a


stored procedure. The main difference between the trigger and procedure is that a
trigger is called automatically when a data modification event is made against a
table. In contrast, a stored procedure must be called explicitly.

Generally, triggers are of two types according to the SQL standard: row-level


triggers and statement-level triggers.

Row-Level Trigger: It is a trigger, which is activated for each row by a triggering


statement such as insert, update, or delete. For example, if a table has inserted,
updated, or deleted multiple rows, the row trigger is fired automatically for each row
affected by the insert, update, or delete statement.

Play Videox

Statement-Level Trigger: It is a trigger, which is fired once for each event that
occurs on a table regardless of how many rows are inserted, updated, or deleted.

NOTE: We should know that MySQL doesn't support statement-level triggers. It provides
supports for row-level triggers only.

Why we need/use triggers in MySQL?


We need/use triggers in MySQL due to the following features:

o Triggers help us to enforce business rules.


o Triggers help us to validate data even before they are inserted or updated.
o Triggers help us to keep a log of records like maintaining audit trails in tables.
o SQL triggers provide an alternative way to check the integrity of data.
o Triggers provide an alternative way to run the scheduled task.
o Triggers increases the performance of SQL queries because it does not need
to compile each time the query is executed.
o Triggers reduce the client-side code that saves time and effort.
o Triggers help us to scale our application across different platforms.
o Triggers are easy to maintain.

Limitations of Using Triggers in MySQL

o MySQL triggers do not allow to use of all validations; they only provide
extended validations. For example, we can use the NOT NULL, UNIQUE,
CHECK and FOREIGN KEY constraints for simple validations.
o Triggers are invoked and executed invisibly from the client application.
Therefore, it isn't easy to troubleshoot what happens in the database layer.
o Triggers may increase the overhead of the database server.

Types of Triggers in MySQL?


We can define the maximum six types of actions or events in the form of triggers:

1. Before Insert: It is activated before the insertion of data into the table.
2. After Insert: It is activated after the insertion of data into the table.
3. Before Update: It is activated before the update of data in the table.
4. After Update: It is activated after the update of the data in the table.
5. Before Delete: It is activated before the data is removed from the table.
6. After Delete: It is activated after the deletion of data from the table.

When we use a statement that does not use INSERT, UPDATE or DELETE query to
change the data in a table, the triggers associated with the trigger will not be
invoked.

Naming Conventions
Naming conventions are the set of rules that we follow to give appropriate unique
names. It saves our time to keep the work organize and understandable.
Therefore, we must use a unique name for each trigger associated with a table.
However, it is a good practice to have the same trigger name defined for different
tables.

The following naming convention should be used to name the trigger in MySQL:

1. (BEFOR | AFTER) table_name (INSERT | UPDATE | DELETE)  

Thus,

Trigger Activation Time: BEFORE | AFTER

Trigger Event: INSERT | UPDATE | DELETE

How to create triggers in MySQL?


We can use the CREATE TRIGGER statement for creating a new trigger in MySQL.
Below is the syntax of creating a trigger in MySQL:

1. CREATE TRIGGER trigger_name    
2.     (AFTER | BEFORE) (INSERT | UPDATE | DELETE)  
3.          ON table_name FOR EACH ROW    
4.          BEGIN    
5.         --variable declarations    
6.         --trigger code    
7.         END;    
Different types of MySQL Triggers (with
examples)
 Difficulty Level : Medium
 Last Updated : 04 Jul, 2019

 Read

 Discuss
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 enacts before an update is invoked. If we
write an update statement, then the actions of the trigger will be performed before the
update is implemented.
Example:
Considering tables:
create table customer (acc_no integer primary key,
cust_name varchar(20),
avail_balance decimal);
create table mini_statement (acc_no integer,
avail_balance decimal,
foreign key(acc_no) references customer(acc_no)
on delete cascade);
Inserting values in them:
insert into customer values (1000, "Fanny", 7000);
insert into customer values (1001, "Peter", 12000);
Trigger to insert (old) values into a mini_statement record (including account number
and available balance as parameters) before updating any record in customer
record/table:
delimiter //
create trigger update_cus
-> before update on customer
-> for each row
-> begin
-> insert into mini_statement values (old.acc_no,
old.avail_balance);
-> end; //
Making updates to invoke trigger:
delimiter;
update customer set avail_balance = avail_balance + 3000 where
acc_no = 1001;
update customer set avail_balance = avail_balance + 3000 where
acc_no = 1000;
Output:
select *from mini_statement;
+--------+---------------+
| acc_no | avail_balance |
+--------+---------------+
| 1001 | 12000 |
| 1000 | 7000 |
+--------+---------------+
2 rows in set (0.0007 sec)

2. After Update Trigger:


As the name implies, this trigger is invoked after an updation occurs. (i.e., it gets
implemented after an update statement is executed.).
Example:
We create another table:
create table micro_statement (acc_no integer,
avail_balance decimal,
foreign key(acc_no) references customer(acc_no) on
delete cascade);
Insert another value into customer:
insert into customer values (1002, "Janitor", 4500);
Query OK, 1 row affected (0.0786 sec)
Trigger to insert (new) values of account number and available balance into
micro_statement record after an update has occurred:
delimiter //
create trigger update_after
-> after update on customer
-> for each row
-> begin
-> insert into micro_statement values(new.acc_no,
new.avail_balance);
-> end; //
Making an update to invoke trigger:
delimiter ;
update customer set avail_balance = avail_balance + 1500 where
acc_no = 1002;
Output:
select *from micro_statement;
+--------+---------------+
| acc_no | avail_balance |
+--------+---------------+
| 1002 | 6000 |
+--------+---------------+
1 row in set (0.0007 sec)

3. Before Insert Trigger:


As the name implies, this trigger is invoked before an insert, or before an insert
statement is executed.
Example:
Considering tables:
create table contacts (contact_id INT (11) NOT NULL AUTO_INCREMENT,
last_name VARCHAR (30) NOT NULL,
first_name VARCHAR (25),
->birthday DATE, created_date DATE,
created_by VARCHAR(30),
CONSTRAINT contacts_pk PRIMARY KEY
(contact_id));
Trigger to insert contact information such as name, birthday and creation-date/user
into a table contact before an insert occurs:
delimiter //
create trigger contacts_before_insert
-> before insert
-> on contacts for each row
-> begin
-> DECLARE vUser varchar(50);
->
-> -- Find username of person performing INSERT into
table
-> select USER() into vUser;
->
-> -- Update create_date field to current system date
-> SET NEW.created_date = SYSDATE();
->
-> -- Update created_by field to the username of the
person performing the INSERT
-> SET NEW.created_by = vUser;
-> end; //
Making an insert to invoke the trigger:
delimiter;
insert into contacts values (1, "Newton", "Enigma",
str_to_date ("19-08-1999", "%d-%m-%Y"),
str_to_date ("17-03-2018", "%d-%m-%Y"),
"xyz");
Output:
select *from contacts;
+------------+-----------+------------+------------+--------------
+----------------+
| contact_id | last_name | first_name | birthday | created_date |
created_by |
+------------+-----------+------------+------------+--------------
+----------------+
| 1 | Newton | Enigma | 1999-08-19 | 2019-05-11 |
root@localhost |
+------------+-----------+------------+------------+--------------
+----------------+

4. After Insert Trigger:


As the name implies, this trigger gets invoked after an insert is implemented.
Example:
Consider tables:
create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT,
last_name VARCHAR(30) NOT NULL,
first_name VARCHAR(25), birthday DATE,
->CONSTRAINT contacts_pk PRIMARY KEY
(contact_id));
create table contacts_audit (contact_id integer,
created_date date,
created_by varchar (30));
Trigger to insert contact_id and contact creation-date/user information into
contacts_audit record after an insert occurs:
delimiter //
create trigger contacts_after_insert
-> after insert
-> on contacts for each row
-> begin
-> DECLARE vUser varchar(50);
->
-> -- Find username of person performing the INSERT
into table
-> SELECT USER() into vUser;
->
-> -- Insert record into audit table
-> INSERT into contacts_audit
-> ( contact_id,
-> created_date,
-> created_by)
-> VALUES
-> ( NEW.contact_id,
-> SYSDATE(),
-> vUser );
-> END; //
Making an insert to invoke the trigger:
insert into contacts values (1, "Kumar", "Rupesh",
str_to_date("20-06-1999", "%d-%m-%Y"));
Output:
select *from contacts_audit;
+------------+--------------+----------------+
| contact_id | created_date | created_by |
+------------+--------------+----------------+
| 1 | 2019-05-11 | root@localhost |
+------------+--------------+----------------+
1 row in set (0.0006 sec)

5. Before Delete Trigger:


As the name implies, this trigger is invoked before a delete occurs, or before deletion
statement is implemented.
Example:
Consider tables:
create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT,
last_name VARCHAR (30) NOT NULL,
first_name VARCHAR (25),
birthday DATE, created_date DATE,
created_by VARCHAR(30),
CONSTRAINT contacts_pk PRIMARY KEY
(contact_id));
create table contacts_audit (contact_id integer, deleted_date date,
deleted_by varchar(20));
Trigger to insert contact_id and contact deletion-date/user information into
contacts_audit record before a delete occurs:
delimiter //
create trigger contacts_before_delete
-> before delete
-> on contacts for each row
-> begin
->
-> DECLARE vUser varchar(50);
->
-> -- Find username of person performing the DELETE
into table
-> SELECT USER() into vUser;
->
-> -- Insert record into audit table
-> INSERT into contacts_audit
-> ( contact_id,
-> deleted_date,
-> deleted_by)
-> VALUES
-> ( OLD.contact_id,
-> SYSDATE(),
-> vUser );
-> end; //
Making an insert and then deleting the same to invoke the trigger:
delimiter;
insert into contacts values (1, "Bond", "Ruskin",
str_to_date ("19-08-1995", "%d-%m-%Y"),
str_to_date ("27-04-2018", "%d-%m-%Y"),
"xyz");
delete from contacts where last_name="Bond";
Output:
select *from contacts_audit;
+------------+--------------+----------------+
| contact_id | deleted_date | deleted_by |
+------------+--------------+----------------+
| 1 | 2019-05-11 | root@localhost |
+------------+--------------+----------------+
1 row in set (0.0007 sec)

6. After Delete Trigger:


As the name implies, this trigger is invoked after a delete occurs, or after a delete
operation is implemented.
Example:
Consider the tables:
create table contacts (contact_id int (11) NOT NULL AUTO_INCREMENT,
last_name VARCHAR (30) NOT NULL,
first_name VARCHAR (25),
birthday DATE, created_date DATE,
created_by VARCHAR (30),
CONSTRAINT contacts_pk PRIMARY KEY
(contact_id));
create table contacts_audit (contact_id integer, deleted_date date,
deleted_by varchar(20));
Trigger to insert contact_id and contact deletion-date/user information into
contacts_audit record after a delete occurs:
create trigger contacts_after_delete
-> after delete
-> on contacts for each row
-> begin
->
-> DECLARE vUser varchar(50);
->
-> -- Find username of person performing the DELETE
into table
-> SELECT USER() into vUser;
->
-> -- Insert record into audit table
-> INSERT into contacts_audit
-> ( contact_id,
-> deleted_date,
-> deleted_by)
-> VALUES
-> ( OLD.contact_id,
-> SYSDATE(),
-> vUser );
-> end; //
Making an insert and deleting the same to invoke the trigger:
delimiter;
insert into contacts values (1, "Newton", "Isaac",
str_to_date ("19-08-1985", "%d-%m-%Y"),
str_to_date ("23-07-2018", "%d-%m-%Y"),
"xyz");
delete from contacts where first_name="Isaac";
Output:
select *from contacts_audit;
+------------+--------------+----------------+
| contact_id | deleted_date | deleted_by |
+------------+--------------+----------------+
| 1 | 2019-05-11 | root@localhost |
+------------+--------------+----------------+
1 row in set (0.0009 sec)
MySQL Triggers
ADVERTISING

In MySQL, a trigger is a stored program invoked automatically in response to an


event such as insert, update, or delete that occurs in the associated table. For
example, you can define a trigger that is invoked automatically before a new row is
inserted into a table.

MySQL supports triggers that are invoked in response to


the INSERT, UPDATE or DELETE event.

The SQL standard defines two types of triggers: row-level triggers and statement-
level triggers.

 A row-level trigger is activated for each row that is inserted, updated, or deleted.  For
example, if a table has 100 rows inserted, updated, or deleted, the trigger is
automatically invoked 100 times for the 100 rows affected.
 A statement-level trigger is executed once for each transaction regardless of how
many rows are inserted, updated, or deleted.

MySQL supports only row-level triggers. It doesn’t support statement-level triggers.

Advantages of triggers

 Triggers provide another way to check the integrity of data.


 Triggers handle errors from the database layer.
 Triggers give an alternative way to run scheduled tasks. By using triggers, you don’t
have to wait for the scheduled events to run because the triggers are invoked
automatically before or after a change is made to the data in a table.
 Triggers can be useful for auditing the data changes in tables.

Disadvantages of triggers

 Triggers can only provide extended validations, not all validations. For simple
validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN
KEY constraints.
 Triggers can be difficult to troubleshoot because they execute automatically in the
database, which may not invisible to the client applications.
 Triggers may increase the overhead of the MySQL Server.

Managing MySQL triggers

 Create triggers  – describe steps of how to create a trigger in MySQL.


 Drop triggers – show you how to drop a trigger.
 Create a BEFORE INSERT trigger – show you how to create a BEFORE INSERT trigger
to maintain a summary table from another table.
 Create an AFTER INSERT trigger – describe how to create an AFTER INSERT trigger to
insert data into a table after inserting data into another table.
 Create a BEFORE UPDATE trigger – learn how to create a BEFORE UPDATE trigger that
validates data before it is updated to the table.
 Create an AFTER UPDATE trigger – show you how to create an AFTER UPDATE trigger
to log the changes of data in a table.
 Create a BEFORE DELETE trigger – show how to create a BEFORE DELETE trigger.
 Create an AFTER DELETE trigger – describe how to create an AFTER DELETE trigger.
 Create multiple triggers for a table that have the same trigger event and time  –
MySQL 8.0 allows you to define multiple triggers for a table that have the same
trigger event and time.
 Show triggers – list triggers in a database, table by specific patterns.

You might also like