CS2202_MySQL_Trigger
CS2202_MySQL_Trigger
CS2202
1
Trigger
• In MySQL, a trigger is a set of SQL statements that is invoked automatically when a
change is made to the data on the associated table.
• A trigger can be defined to be invoked either before or after the data is changed by
INSERT, UPDATE or DELETE statement.
2
Trigger Types
• BEFORE INSERT - activated before data is inserted into the table.
• AFTER INSERT - activated after data is inserted into the table.
• BEFORE UPDATE - activated before data in the table is updated.
• AFTER UPDATE - activated after data in the table is updated.
• BEFORE DELETE - activated before data is removed from the table.
• AFTER DELETE - activated after data is removed from the table.
3
• When we use a statement that does not use INSERT, DELETE or UPDATE statement
to change data in a table, the triggers associated with the table are not invoked.
– For example, the TRUNCATE statement removes all data of a table but does
not invoke the trigger associated with that table.
– Truncate operations drop and re-create the table
– Syntax: mysql:>truncate table table_name;
– If there is any FOREIGN KEY constraints from other tables which reference the
table that you truncate, the TRUNCATE TABLE statement will fail.
4
• There are some statements that use the INSERT statement behind the scenes such
as REPLACE statement or LOAD DATA statement.
• If you use these statements, the corresponding triggers associated with the table
are invoked.
• You must use a unique name for each trigger associated with a table.
5
Replace statement
• Replace statement works as below-
• Step 1. Insert a new row into the table, if a duplicate key error occurs.
• Step 2. If the insertion fails due to a duplicate-key error occurs:
– Delete the conflicting row that causes the duplicate key error from the table.
– Insert the new row into the table again.
6
Replace to insert
• Using MySQL REPLACE to insert a new row
• Syntax
– mysql:> REPLACE [INTO] table_name(column_list)
VALUES(value_list);
Let’s create a table Let’s insert some records
CREATE TABLE cities ( REPLACE INTO cities(name,population)
id INT AUTO_INCREMENT PRIMARY KEY, VALUES('New York',8008278),
name VARCHAR(50), ('Los Angeles',3694825),
population INT NOT NULL ('San Diego',1223405);
);
7
Replace
Use the REPLACE statement to update the population of the Los
Angeles city to 3696820.
id name population
1 New York 8008278
2 null 3696820
3 San Diego 1223405
8
Replace to update
• Using MySQL REPLACE statement to update a row
– Syntax
– mysql:> REPLACE INTO table
SET column1 = value1,
column2 = value2;
No where clause
9
Replace to update
REPLACE INTO cities
SET id = 4,
name = 'Phoenix',
population = 1768980;
10
MySQL Trigger Synatx
Syntax :
Trigger name convention: after the CREATE
CREATE TRIGGER trigger_name
TRIGGER statement, the trigger name should
trigger_time trigger_event
follow the naming convention
ON table_name
[trigger time]_[table name]_[trigger event], for
FOR EACH ROW
example before_employees_update.
BEGIN
.........
END;
Reference: www.mysqltutorial.org
11
Activation time and trigger event
• One must specify the activation time when a trigger is defined.
– You use the BEFORE keyword if you want to process action prior to the change
is made on the table and AFTER if you need to process action after the change
is made.
• The trigger event can be INSERT, UPDATE or DELETE.
– This event causes the trigger to be invoked. A trigger only can be invoked by
one event. To define a trigger that is invoked by multiple events, you have to
define multiple triggers, one for each event.
12
Trigger
• A trigger must be associated with a specific table. Without a table trigger would
not exist therefore you have to specify the table name after the ON keyword.
• You place the SQL statements between BEGIN and END block. This is where you
define the logic for the trigger.
• To view all triggers in the current database, you use SHOW TRIGGERS statement as
follows:
– mysql:>SHOW TRIGGERS;
13
Trigger example
Let’s create a table Let’s create another table
DROP TABLE IF EXISTS WorkCenters; DROP TABLE IF EXISTS WorkCenterStats;
15
Another example
Let’s create members table create another table
DROP TABLE IF EXISTS members; called reminders that stores reminder
messages to members
CREATE TABLE members ( DROP TABLE IF EXISTS reminders;
id INT AUTO_INCREMENT,
name VARCHAR(100) NOT NULL, CREATE TABLE reminders (
email VARCHAR(255), id INT AUTO_INCREMENT,
birthDate DATE, memberId INT,
PRIMARY KEY (id) message VARCHAR(255) NOT NULL,
); PRIMARY KEY (id , memberId)
);
members reminders
id name email birthDate id memberId message
16
After insert trigger
members
DELIMITER $$ id name email birthDate
18
Example
DROP TABLE IF EXISTS sales;
21
Advantages of Trigger
• 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.
22
Disadvantages
• 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.
23
Cursor
• A cursor is a database object that enables the end-user to retrieve, process, and
scroll through rows of the result set one at a time.
• While standard SQL queries usually operate on data sets, cursors perform
operations on one row at a time
• This can be very useful for complicated data manipulations and procedural logic.
• It enables the user to fetch and process each row individually, allowing for detailed
manipulation and analysis of data.
• By using cursors, developers can precisely control the flow of data processing, such
as updating or analyzing specific rows based on custom criteria.
24
Declare a cursor
• A cursor is declared within a stored procedure or function using
a CURSOR statement. This binds the cursor to a specified SQL query.
25
Cursor: Open, Fetch and Close
• You need to open the cursor before you fetch rows from it. You do this with the
OPEN statement.
OPEN cursor_name;
• The FETCH statement retrieves the data from the cursor and moves the cursor to
the next line in the result set; it loads the data into variables
FETCH cursor_name INTO variable1, variable2, ...;
• variable1, variable2, … : Variables in which the fetched data has to be stored.
• Finally, you would close the cursor after you have processed all the data, so that
the resources that are allocated for it will be released.
CLOSE cursor_name;
26
sp sno pno qty dos
Use of Cursor … … … …
CREATE TABLE IF NOT EXISTS
• Create a Log Table: low_supply_log (
low_supply_log to store records
where qty < 600. log_id INT AUTO_INCREMENT
PRIMARY KEY,
• Create a Stored Procedure:
– Declare a cursor to iterate over the
sno VARCHAR(10),
sp table. pno VARCHAR(10),
– Process each record and check the qty SMALLINT,
quantity.
dos DATE,
– If qty is below 600, insert the
record into low_supply_log. log_time TIMESTAMP DEFAULT
CURRENT_TIMESTAMP
);
id sno pno qty dos log_time
… … … … … … 27
sp Log_supply_log
sno pno qty dos id sno pno qty dos log_time
… … … … … … … … … …
-- Start processing each row
DELIMITER //
read_loop: LOOP
CREATE PROCEDURE procSupplyData()
BEGIN -- Fetch the current row data
FETCH sp_cursor INTO v_sno, v_pno, v_qty, v_dos;
DECLARE done INT DEFAULT FALSE;
-- Exit if no more records
DECLARE v_sno VARCHAR(10);
IF done THEN
DECLARE v_pno VARCHAR(10);
LEAVE read_loop;
DECLARE v_qty SMALLINT;
END IF;
DECLARE v_dos DATE;
-- If quantity is below threshold, insert into log
-- Declare cursor
IF v_qty < 600 THEN
DECLARE sp_cursor CURSOR FOR
INSERT INTO low_supply_log (sno, pno, qty, dos)
SELECT sno, pno, qty, dos FROM sp;
VALUES (v_sno, v_pno, v_qty, v_dos);
-- Declare exit handler
END IF;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done =
TRUE; END LOOP;
-- Open the cursor -- Close the cursor
OPEN sp_cursor; CLOSE sp_cursor;
END // 28
DELIMITER ;