0% found this document useful (0 votes)
59 views28 pages

MySQL Trigger Overview and Examples

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

MySQL Trigger Overview and Examples

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

MySQL Triggers

GV: Phạm Thị Quỳnh Trang


Introduction
- 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.


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 be visible to the client applications.
● Triggers may increase the overhead of the MySQL server.
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.
MySQL Create Trigger
CREATE TRIGGER trigger_name

{BEFORE | AFTER} {INSERT | UPDATE | DELETE}

ON table_name

FOR EACH ROW

BEGIN

-- Trigger body (SQL statements)

END;
MySQL Create Trigger:
The availability of the OLD and NEW modifiers
MySQL trigger example
- First, create a new table called items:

CREATE TABLE items (

id INT PRIMARY KEY,

name VARCHAR(255) NOT NULL,

price DECIMAL(10, 2) NOT NULL

);

- Second, insert a row into the items table:

INSERT INTO items(id, name, price)

VALUES (1, 'Item', 50.00);


MySQL trigger example

- Third, create the item_changes table to store the changes made to the data in the items table:

CREATE TABLE item_changes (

change_id INT PRIMARY KEY AUTO_INCREMENT,

item_id INT,

change_type VARCHAR(10),

change_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

FOREIGN KEY (item_id) REFERENCES items(id)

);
MySQL trigger example
- Fourth, create a trigger called update_items_trigger associated with the items table:F
DELIMITER //

CREATE TRIGGER update_items_trigger

AFTER UPDATE

ON items

FOR EACH ROW

BEGIN

INSERT INTO item_changes (item_id, change_type)

VALUES (NEW.id, 'UPDATE');

END;

//

DELIMITER ;
MySQL trigger example
- Fifth, update a row in the items table:

UPDATE items

SET price = 60.00

WHERE id = 1;

- Finally, retrieve data from the item_changes table to see the logged changes:

SELECT * FROM item_changes;

Output:
MySQL DROP TRIGGER

- Syntax:

DROP TRIGGER [IF EXISTS] [schema_name.]trigger_name;

In this syntax:

● First, specify the name of the trigger that you want to drop after the DROP TRIGGER keywords.
● Second, specify the name of the schema to which the trigger belongs. If you skip the schema name, the statement will drop the
trigger in the current database.
● Third, use IF EXISTS option to conditionally drop the trigger if the trigger exists. The IF EXISTS clause is optional.
If you drop a trigger that does not exist without using the IF EXISTS clause, MySQL issues an error. However, if you use the IF EXISTS
clause, MySQL issues a NOTE instead.
MySQL DROP TRIGGER example

- Drop the update_items_trigger trigger:


DROP TRIGGER update_items_trigger;

- Show the triggers again to verify the removal:

SHOW TRIGGERS;
MySQL BEFORE INSERT triggers

- MySQL BEFORE INSERT triggers are automatically fired before an insert event occurs on the table.
- The following illustrates the basic syntax of creating a MySQL BEFORE INSERT trigger:

CREATE TRIGGER trigger_name

BEFORE INSERT

ON table_name FOR EACH ROW

trigger_body;

In this syntax:

First, specify the name of the trigger that you want to create in the CREATE TRIGGER clause.

Second, use BEFORE INSERT clause to specify the time to invoke the trigger.

Third, specify the name of the table that the trigger is associated with after the ON keyword.

Finally, specify the trigger body which contains one or more SQL statements that execute when the trigger is invoked.
MySQL BEFORE INSERT triggers

If you have multiple statements in the trigger_body, you have to use the BEGIN END block and change the default delimiter:

DELIMITER $$

CREATE TRIGGER trigger_name

BEFORE INSERT

ON table_name FOR EACH ROW

BEGIN

-- statements

END$$

DELIMITER ;

- Note that in a BEFORE INSERT trigger, you can access and change the NEW values. However, you cannot access the OLD values because
OLD values obviously do not exist.
MySQL BEFORE INSERT triggers
MySQL BEFORE INSERT trigger example

We will create a BEFORE INSERT trigger to maintain a summary table from another table.

Setting up a sample table

First, create a new table called WorkCenters:

DROP TABLE IF EXISTS WorkCenters;

CREATE TABLE WorkCenters (

id INT AUTO_INCREMENT PRIMARY KEY,

name VARCHAR(100) NOT NULL,

capacity INT NOT NULL

);
MySQL BEFORE INSERT trigger example

Second, create another table called WorkCenterStats that stores the summary of the capacity of the work centers:

DROP TABLE IF EXISTS WorkCenterStats;

CREATE TABLE WorkCenterStats(

totalCapacity INT NOT NULL

);
MySQL BEFORE INSERT trigger example
The following trigger updates the total capacity of the WorkCenterStats table before a new work center is inserted into the WorkCenter table:

DELIMITER $$

CREATE TRIGGER before_workcenters_insert BEFORE INSERT ON WorkCenters FOR EACH ROW

BEGIN

DECLARE rowcount INT

SELECT COUNT(*) INTO rowcount FROM WorkCenterStats

IF rowcount > 0 THEN

UPDATE WorkCenterStats SET totalCapacity = totalCapacity + new.capacity;

ELSE

INSERT INTO WorkCenterStats(totalCapacity) VALUES(new.capacity);

END IF;

END $$

DELIMITER ;
Testing the MySQL BEFORE INSERT trigger
First, insert a new row into the WorkCenter table:

INSERT INTO WorkCenters(name, capacity)

VALUES('Mold Machine',100);

Second, query data from the WorkCenterStats table:

SELECT * FROM WorkCenterStats;

Output
Testing the MySQL BEFORE INSERT trigger
Third, insert a new work center:

INSERT INTO WorkCenters(name, capacity)

VALUES('Packing',200);

Finally, query data from the WorkCenterStats:

SELECT * FROM WorkCenterStats;

Output:

The trigger has updated the total capacity from 100 to 200 as expected.

Note that to properly maintain the summary table WorkCenterStats, you should also create triggers to handle update and delete events on
the WorkCenters table.
MySQL AFTER INSERT Trigger
MySQL AFTER INSERT triggers are automatically invoked after an insert event occurs on the table.

The following shows the basic syntax of creating a MySQL AFTER INSERT trigger:

CREATE TRIGGER trigger_name

AFTER INSERT

ON table_name FOR EACH ROW

trigger_body
MySQL BEFORE UPDATE Trigger
MySQL BEFORE UPDATE triggers are invoked automatically before an update event occurs on the table associated with the triggers.

Here is the syntax for creating a MySQL BEFORE UPDATE trigger:

CREATE TRIGGER trigger_name

BEFORE UPDATE

ON table_name FOR EACH ROW

trigger_body
MySQL AFTER UPDATE Trigger
MySQL AFTER UPDATE triggers are invoked automatically after an update event occurs on the table associated with the triggers.

The following shows the syntax of creating a MySQL AFTER UPDATE trigger:

CREATE TRIGGER trigger_name

AFTER UPDATE

ON table_name FOR EACH ROW

trigger_body
MySQL BEFORE DELETE Trigger
MySQL BEFORE DELETE triggers are fired automatically before a delete event occurs in a table.

Here is the basic syntax of creating a MySQL BEFORE DELETE trigger:

CREATE TRIGGER trigger_name

BEFORE DELETE

ON table_name FOR EACH ROW

trigger_body
MySQL AFTER DELETE Trigger
MySQL AFTER DELETE triggers are automatically invoked after a delete event occurs on the table.

Here is the basic syntax of creating a MySQL AFTER DELETE trigger:

CREATE TRIGGER trigger_name

AFTER DELETE

ON table_name FOR EACH ROW

trigger_body;
Create Multiple Triggers
Before MySQL version 5.7.2, you could only create one trigger for an event in a table e.g., you could only create one trigger for the
BEFORE UPDATE or AFTER UPDATE event.

MySQL 5.7.2+ lifted this limitation and allowed you to create multiple triggers for a given table that have the same event and action
time. These triggers will activate sequentially when an event occurs.
Create Multiple Triggers
DELIMITER $$

CREATE TRIGGER trigger_name

{BEFORE|AFTER}{INSERT|UPDATE|DELETE}

ON table_name FOR EACH ROW

{FOLLOWS|PRECEDES} existing_trigger_name

BEGIN

-- statements

END$$

DELIMITER ;
How To Call a Stored Procedure From a Trigger in MySQL?

You might also like