0% found this document useful (0 votes)
15 views11 pages

Experiment 5

The document provides an overview of MySQL triggers, including their definitions, advantages, and disadvantages. It details the creation and management of various types of triggers such as BEFORE and AFTER INSERT, UPDATE, and DELETE, along with examples of their implementation. Additionally, it explains the importance of triggers for data integrity, error handling, and auditing changes in database tables.

Uploaded by

omdinde123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views11 pages

Experiment 5

The document provides an overview of MySQL triggers, including their definitions, advantages, and disadvantages. It details the creation and management of various types of triggers such as BEFORE and AFTER INSERT, UPDATE, and DELETE, along with examples of their implementation. Additionally, it explains the importance of triggers for data integrity, error handling, and auditing changes in database tables.

Uploaded by

omdinde123
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Experiment No - 5

MySQL TRIGGERS
A MySQL trigger is a database object that is associated with a table. It will be
activated when a defined action is executed for the table. The trigger can be
executed when you run one of the following MySQL statements on the table: INSERT,
UPDATE and DELETE and it can be invoked before or after the event.

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.

The SQL standard defines two types of triggers:

1. Row-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.

2. Statement-level triggers:
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.
Managing MySQL triggers
1. Create triggers
2. Drop triggers
3. Create a BEFORE INSERT trigger
4. Create an AFTER INSERT trigger
5. Create a BEFORE UPDATE trigger
6. Create an AFTER UPDATE trigger
7. Create a BEFORE DELETE trigger
8. Create an AFTER DELETE trigger
9. Create multiple triggers for a table that have the same trigger event and time
10.Show triggers

Create database and tables

CREATE TABLE person (name varchar(45), age int);


INSERT INTO person VALUES ('Aditya', 25), ('Swati', 20);
SELECT * FROM person;
CREATE TABLE average_age (average double);
INSERT INTO average_age SELECT AVG(age) FROM person;
SELECT * FROM average_age;

CREATE TABLE person_archive (


name varchar(45),
age int,
time timestamp DEFAULT NOW());

1. Create a BEFORE INSERT trigger

CREATE TRIGGER <trigger name> BEFORE INSERT


ON <table name>
FOR EACH ROW
<trigger body>;

The BEFORE INSERT trigger gives control over data modification before committing
into a database table. Capitalizing names for consistency, checking the length of an
input, or catching faulty inputs with BEFORE INSERT triggers further provides value
limitations before entering new data.
Q1. Create a BEFORE INSERT trigger to check the age value before inserting data
intothe person table:

delimiter $$
CREATE TRIGGER person_bi BEFORE INSERT
ON person
FOR EACH ROW
IF NEW.age < 18 THEN
SIGNAL SQLSTATE '50001' SET MESSAGE_TEXT = 'Person must be older than 18.';
END IF; $$
delimiter ;

Note - A MySQL client program such as MySQL Workbench or mysql program uses the
delimiter (;) to separate statements and executes each statement separately.
However, a stored procedure consists of multiple statements separated by a semicolon (;).
If you use a MySQL client program to define a stored procedure that contains semicolon
characters, the MySQL client program will not treat the whole stored procedure as a single
statement, but many statements.
Therefore, you must redefine the delimiter temporarily so that you can pass the whole stored
procedure to the server as a single statement. In above code $$ is a new delimeter, at the
end restored to default ;

INSERT INTO person VALUES ('Sachin', 14);

The console displays the descriptive error message.


The data does not insert into the table because of the failed trigger check.
2. Create an AFTER INSERT Trigger

CREATE TRIGGER <trigger name> AFTER INSERT


ON <table name>
FOR EACH ROW
<trigger body>;

The AFTER INSERT trigger is useful when the entered row generates a value
needed to update another table.

Q2. AFTER INSERT Trigger Example


Inserting a new row into the person table does not automatically update the average
in the average_age table. Create an AFTER INSERT trigger on the person table to
update the average_age table after insert:

delimiter $$
CREATE TRIGGER person_ai AFTER INSERT
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(age) FROM person); $$
delimiter ;
INSERT INTO person VALUES ('Sachin', 34);
SELECT * FROM person;
SELECT * FROM average_age;

3. Create a BEFORE UPDATE Trigger


CREATE TRIGGER <trigger name> BEFORE UPDATE
ON <table name>
FOR EACH ROW
<trigger body>;

The BEFORE UPDATE triggers go together with the BEFORE INSERT triggers. If any
restrictions exist before inserting data, the limits should be there before updating as
well.
If there is an age restriction for the person table before inserting data, the age
restriction should also exist before updating information. Without the BEFORE
UPDATE trigger, the age check trigger is easy to avoid. Nothing restricts editing to a
faulty value.
delimiter $$
CREATE TRIGGER person_bu BEFORE UPDATE
ON person
FOR EACH ROW
IF NEW.age < 18 THEN
SIGNAL SQLSTATE '50002' SET MESSAGE_TEXT = 'Person must be older than 18.';
END IF; $$
delimiter ;

UPDATE person SET age = 17 WHERE name = 'Sachin';

4. Create an AFTER UPDATE Trigger


CREATE TRIGGER <trigger name> AFTER UPDATE
ON <table name>
FOR EACH ROW
<trigger body>;
The AFTER UPDATE trigger helps keep track of committed changes to data. Most
often, any changes after inserting information also happen after updating data.

Q4. AFTER UPDATE Trigger Example


Any successful updates to the age data in the table person should also update the
intermediate average value calculated in the average_age table.
delimiter $$
CREATE TRIGGER person_au AFTER UPDATE
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(age) FROM person); $$
delimiter ;
UPDATE person SET age = 28 WHERE name = 'Sachin';
SELECT * FROM person;
SELECT * FROM average_age;

5. Create a BEFORE DELETE Trigger


CREATE TRIGGER <trigger name> BEFORE DELETE
ON <table name>
FOR EACH ROW
<trigger body>;
The BEFORE DELETE trigger is essential for security reasons. If a parent table has
any children attached, the trigger helps block deletion and prevents orphaned tables.
The trigger also allows archiving data before deletion.
Q5. BEFORE DELETE Trigger Example
Archive deleted data by creating a BEFORE DELETE trigger on the table person and
insert the values into the person_archive table:
delimiter $$
CREATE TRIGGER person_bd BEFORE DELETE
ON person
FOR EACH ROW
INSERT INTO person_archive (name, age)
VALUES (OLD.name, OLD.age); $$
delimiter ;

DELETE FROM person WHERE name = 'Swati';


SELECT * FROM person;
select * from person_archive;
The BEFORE DELETE trigger is useful for logging any table change attempts.

INSERT INTO person VALUES ('Swati', 40);


SELECT * FROM person_archive;
SELECT * FROM person;

6. Create an AFTER DELETE Trigger


CREATE TRIGGER <trigger name> AFTER DELETE
ON <table name>
FOR EACH ROW
<trigger body>;
The AFTER DELETE triggers maintain information updates that require the data row
to disappear before making the updates.
Q6. AFTER DELETE Trigger Example
Create an AFTER DELETE trigger on the table person to update the average_age table
with the new information:
delimiter $$
CREATE TRIGGER person_ad AFTER DELETE
ON person
FOR EACH ROW
UPDATE average_age SET average = (SELECT AVG(person.age) FROM person); $$
delimiter ;
DELETE FROM person WHERE name='Aditya';
SELECT * FROM person;
SELECT * FROM average_age;
SELECT * FROM person_archive;

Add, delete users fom database and observe the changes in respective tables.

show triggers;
drop trigger <trigger_name> ;

You might also like