Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
161 views22 pages

MySQL Procedures & Triggers Guide

This document discusses MySQL procedures and triggers. It explains that procedures are stored subroutines that can take parameters and execute SQL statements. Procedures help increase performance and security. The document provides step-by-step instructions for creating a simple procedure to return all department names from a database table. It also covers calling procedures, viewing procedure characteristics and source code, using variables, and different parameter modes for procedures.

Uploaded by

Hamisi Nhabayu
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)
161 views22 pages

MySQL Procedures & Triggers Guide

This document discusses MySQL procedures and triggers. It explains that procedures are stored subroutines that can take parameters and execute SQL statements. Procedures help increase performance and security. The document provides step-by-step instructions for creating a simple procedure to return all department names from a database table. It also covers calling procedures, viewing procedure characteristics and source code, using variables, and different parameter modes for procedures.

Uploaded by

Hamisi Nhabayu
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/ 22

MYSQL PROCEDURES AND TRIGGERS

A procedure (often called a stored procedure) is a subroutine like a subprogram in a regular


computing language, stored in database. A procedure has a name, a parameter list, and SQL
statement(s). All most all relational database system supports stored procedure.

Why Stored Procedures?

Typically stored procedures help increase the performance of the applications. Once
created, stored procedures are compiled and stored in the database. However, MySQL
implements the stored procedures slightly different. MySQL stored procedures are
compiled on demand. After compiling a stored procedure, MySQL puts it into a cache.
And MySQL maintains its own stored procedure cache for every single connection. If an
application uses a stored procedure multiple times in a single connection, the compiled
version is used, otherwise, the stored procedure works like a query.
Stored procedures help reduce the traffic between application and database server
because instead of sending multiple lengthy SQL statements, the application has to send
only name and parameters of the stored procedure.
Stored procedures are reusable and transparent to any applications. Stored procedures
expose the database interface to all applications so that developers don’t have to develop
functions that are already supported in stored procedures.
Stored procedures are secure. The database administrator can grant appropriate
permissions to applications that access stored procedures in the database without giving
any permissions on the underlying database tables.

Creating a Stored Procedure


A procedure is part of database object. Thus, before writing creating it, you have to open a
database using the use <database name> statement.

Let us use our university database to create a simple procedure called getAllDepartments(). The
getAllDepartments() procedure select all departments from the department table.

Pick a Delimiter
The delimiter is the character or string of characters which is used to complete an SQL statement.
By default we use semicolon (;) as a delimiter. But this causes problem in stored procedure
because a procedure can have many statements, and everyone must end with a semicolon. So for
your delimiter, pick a string which is rarely occur within statement or within procedure.

We use the command delimiter followed by the delimiter we want to set in order to change the
default delimiter. For example, to change the default delimiter to ## we could write

DELIMETER ##

NB:
The statement is terminated by a semicolon (;) because it is the current delimiter in use and there
is a space between the proposed new delimiter (## in this case) and the semicolon (current
delimiter). Failure to put the space will make MySQL wait for the statement termination (current
delimiter) as the semicolon will be counted as part of the proposed new delimiter. However to
terminate it with the current delimiter is option, you can leave it unterminated. After execution
of that command, all sql statement will be terminated by ## instead of semicolon.
SELECT deptName FROM department##

Figure 1; changing default delimiter and using the new delimiter

To switch back to semicolon as default delimiter, you need to run the delimiter command again
specifying semicolon as the new delimiter as follows:
DELIMITER ; ##

Let us now create our getAllDepartmentNames() procedure as follows:

DELIMITER //
CREATE PROCEDURE getAllDepartmentNames()
BEGIN
SELECT deptName FROM department;
END //
DELIMITER ;

Figure 2; creating getAllDepartmentNames procedure


Explanations
The first command (DELIMITER //) changes the default delimiter to two backslashes instead of
semicolon. The last command (DELIMITER ;) changes the default delimiter back to semicolon
instead of two backslashes used by the procedure. These commands are not related to our
procedure.
We use the CREATE PROCEDURE statement to create a new stored procedure. We specify the
name of stored procedure after the CREATE PROCEDURE statement. In this case, the name of
the stored procedure is getAllDepartmentNames. We put the parentheses after the name of the
stored procedure.

The section between BEGIN and END is called the body of the stored procedure. You put the
declarative SQL statements in the body to handle business logic. In this stored procedure, we use
a simple SELECT statement to query data from the department table.

Calling Stored Procedures


In order to call a stored procedure, you use the following SQL command:

CALL PROCEDURE_NAME();

For example, to call our getAllDepartmentNames procedure we could write:


CALL getAllDepartmentNames();

Figure 3; calling getAllDepartmentNames procedure

Displaying characteristics of stored procedures


Use the statement
SHOW PROCEDURE STATUS
if you want to list all procedures available in the MySQL server. That statement will list all the
properties.
Specify the name of the database using where clause in the above statement if you want to list
procedures available in a specific database. For example, if you want to list procedures available
in the university database use
SHOW PROCEDURE STATUS WHERE DB = ‘university’;

Displaying Stored Procedure’s Source Code


To display source code of a particular stored procedure, you use the SHOW CREATE
PROCEDURE followed by the name of the procedure. For example, to display the source codes
of the procedure named getAllDepartmentNames we would write:
SHOW CREATE PROCEDURE getAllDepartmentNames;

Stored Procedure Variables


A variable is a named data object whose value can change during the stored procedure execution.
We typically use the variables in stored procedures to hold the immediate results. These variables
are local to the stored procedure. You must declare a variable before you can use it.

Declaring Variables
To declare a variable inside a stored procedure, you use the DECLARE statement as follows:

DECLARE VARIABLE_NAME DATATYPE(SIZE) DEFAULT DEFAULT_VALUE;

MySQL allows you to declare two or more variables that share the same data type using a single
DECLARE statement as following:
DECLARE x, y INT DEFAULT 0;

We declared two integer variables x and y, and set their default values to zero.

Assigning Variables

Once you declared a variable, you can start using it. To assign a variable another value, you use
the SET statement, for example:

DECLARE total_department INT DEFAULT 0;


SET total_department = 9;

The value of the total_department variable is 9 after the assignment.

Besides the SET statement, you can use the SELECT INTO statement to assign the result of a
query, which returns a scalar value, to a variable. See the following example:

DECLARE total_department INT DEFAULT 0


SELECT COUNT(*) INTO total_department
FROM department
In the example above:
• First, we declare a variable named total_department and initialize its value to 0.
• Then, we used the SELECT INTO statement to assign the total_department variable the
number of products that we selected from the department table in the university database.

Variables Scope
A variable has its own scope that defines its lifetime. If you declare a variable inside a stored
procedure, it will be out of scope when the END statement of stored procedure reached.

If you declare a variable inside BEGIN END block, it will be out of scope if the END is reached.
You can declare two or more variables with the same name in different scopes because a variable
is only effective in its own scope. However, declaring variables with the same name in different
scopes is not good programming practice.

A variable that begins with the @ sign is session variable. It is available and accessible until the
session ends.

Stored Procedure Parameters


Almost stored procedures that you develop require parameters. The parameters make the stored
procedure more flexible and useful. In MySQL, a parameter has one of three modes:
IN, OUT, or INOUT.

 IN – is the default mode. When you define an IN parameter in a stored procedure, the
calling program has to pass an argument to the stored procedure. In addition, the value
of an IN parameter is protected. It means that even the value of the IN parameter is
changed inside the stored procedure, its original value is retained after the stored
procedure ends. In other words, the stored procedure only works on the copy of the IN
parameter.
 OUT – the value of an OUT parameter can be changed inside the stored procedure and
its new value is passed back to the calling program. Notice that the stored procedure
cannot access the initial value of the OUT parameter when it starts.
 INOUT – an INOUT parameter is the combination of IN and OUT parameters. It means
that the calling program may pass the argument, and the stored procedure can modify the
INOUT parameter and pass the new value back to the calling program.

The syntax of defining a parameter in the stored procedures is as follows:

MODE PARAM_NAME PARAM_TYPE(PARAM_SIZE)

The IN Parameter Example


The following example illustrates how to use the IN parameter in the getStudentsByProgram
stored procedure that select students doing a particular program.

DELIMITER ##
CREATE PROCEDURE getStudentByProgram(IN programoOfStudy VARCHAR(50))
BEGIN
SELECT studentID, fullName, gender, YoE FROM student WHERE program =
programoOfStudy;
END ##
DELIMITER ;
The program is the IN parameter of the stored procedure. Inside the stored procedure, we select
all students taking program specified by the programoOfStudy parameter.

Suppose, we want to get all students doing BCICT program, we just need to pass a value (BCICT)
to the stored procedure as follows:

CALL getStudentByProgram('BCICT');

Figure 4; calling getStudentByProgram procedure with parameter

The OUT parameter example


The following stored procedure returns the number of modules by student ID and academic year.
It has three parameters:

• registrationNumber : the IN parameter that is the registration number of the student that
we want to count his/her modules in a given academic year.
• academicYear: the IN parameter that is the academic year we want to count the student’s
modules.
• totalModule : the OUT parameter that stores the number of modules of the specified
student in the specified academic year.

DELIMITER //
CREATE PROCEDURE totalModuleYearly(
IN registrationNumber VARCHAR(25),
IN academicYear VARCHAR(12),
OUT totalModule INT)
BEGIN
SELECT COUNT(courseCode) INTO totalModule FROM enrollment WHERE
studentID = registrationNumber AND aYear = academicYear;
END //
DELIMITER ;

To get the number of enrolled modules, we call the totalModuleYearly stored procedure and
pass the studentID as registrationNumber, aYear as academicYear and also pass an argument (
@total ) to get the return value.

CALL totalModuleYearly('NIT/BCFCF/2016/2028', '2016/2017', @total);

SELECT @total;

Figure 5; calling totalModuleYearly procedure with IN and OUT parameters

It is possible to use AS keyword to rename the variable that return the output in the select
statement. For example, in the above query, we would rename the total to total modules per year
as follows:

CALL totalModuleYearly('NIT/BCFCF/2016/2028', '2016/2017', @total);

SELECT @total AS ‘Total Modules per Year’;

Figure 6; renaming the output parameter using AS keyword

The INOUT Parameter Example


The following example demonstrates how to use an INOUT parameter in the stored procedure.

DELIMITER $$
CREATE PROCEDURE set_counter(INOUT count INT(4),IN inc INT(4))
BEGIN
SET count = count + inc;
END$$
DELIMITER ;
How it works

The set_counter stored procedure accepts one INOUT parameter (count) and one IN
parameter (inc).
Inside the stored procedure, we increase the counter (count) by the value of the inc
parameter.

See how we call the set_counter stored procedure:

Stored Procedures That Return Multiple Values


MySQL stored function returns only one value. To develop stored programs that return multiple
values, you need to use stored procedures with INOUT or OUT parameters.

For example, the getTotalModulePerYearPerSemester stored procedure below accept two IN


parameters registrationNumber and academicYear and two OUT parameters semesterOne and
semeseterTwo which will return the number of modules in semester one and in semester two
respectively of a given academic year.

DELIMITER //
CREATE PROCEDURE getTotalModulePerYearPerSemester (
IN registrationNumber VARCHAR(25),
IN academicYear VARCHAR(12),
OUT semesterOne INT,
OUT semesterTwo INT)

BEGIN

/* semester one courses */


SELECT COUNT(courseCode) INTO semesterOne
FROM enrollment WHERE studentID = registrationNumber
AND aYear = academicYear and semester = 1;

/* semester two courses */


SELECT COUNT(courseCode) INTO semesterTwo
FROM enrollment WHERE studentID = registrationNumber
AND aYear = academicYear and semester = 2;

END //
DELIMITER ;
Figure 7; calling stored procedure that return multiple values

MySQL IF Statement Syntax


The following illustrates the syntax of the IF statement:

IF expression THEN
statements;
END IF;

If the expression evaluates to TRUE, then the statements will be executed, otherwise, the control
is passed to the next statement following the END IF.

MySQL IF ELSE Statement


In case you want to execute statements when the expression evaluates to FALSE, you use the IF
ELSE statement as follows:

IF expression THEN
statements;
ELSE
else-statements;
END IF;

MySQL IF ELSEIF ELSE Statement


If you want to execute statements conditionally based on multiple expressions, you use the IF
ELSEIF ELSE statement as follows:

IF expression THEN
statements;
ELSEIF elseif-expression THEN
elseif-statements;
...
ELSE
else-statements;
END IF;

If the expression evaluates to TRUE, the statements in the IF branch executes. If the expression
evaluates to FALSE, MySQL will check the elseif-expression and execute the elseif-statements
in the ELSEIF branch if the elseif_expression evaluates to TRUE.
The IF statement may have multiple ELSEIF branches to check multiple expressions. If no
expression evaluates to TRUE, the else-statements in the ELSE branch will execute.

The procedure departmentLevel below count the number of programs in a particular department
and use that number (value) to rate the department as silver department, or gold department or
platinum department depending on that number. The procedure have on IN parameter,
departmentNumber and one OUT parameter departmentLevel. Inside the procedure we declare
one variable numberOfPrograms that will store the value to be used in decision making (else –
ifelse).

DELIMITER &&
CREATE PROCEDURE departmentLevel(
IN departmentNumber VARCHAR(15),
OUT departmentLevel VARCHAR(50)
)

BEGIN

DECLARE numberOfPrograms INT;

SELECT COUNT(*) INTO numberOfPrograms FROM


program WHERE department = departmentNumber;

IF numberOfPrograms < 5 THEN


SET departmentLevel = 'SILVER DEPARTMENT';
ELSEIF numberOfPrograms < 12 THEN
SET departmentLevel = 'GOLD DEPARTMENT';
ELSE
SET departmentLevel = 'PLATNUM DEPARTMENT';
END IF;

END &&
DELIMITER ;

Figure 8; calling stored procedure that make decision using IF---ELSEIF---


MySQL CASE Statement
Besides the IF statement, MySQL provides an alternative conditional statement called CASE.
The MySQL CASE statement makes the code more readable and efficient.

There are two forms of the CASE statements: simple and searched CASE statements.

Simple CASE Statement


Let’s take a look at the syntax of the simple CASE statement:

CASE case_expression
WHEN when_expression_1 THEN commands
WHEN when_expression_2 THEN commands
...
ELSE commands
END CASE;

You use the simple CASE statement to check the value of an expression against a set of unique
values.

The case_expression can be any valid expression. We compare the value of the case_expression
with when_expression in each WHEN clause e.g., when_expression_1, when_expression_2, etc.
If the value of the case_expression and when_expression_n are equal, the commands in
the corresponding WHEN branch executes.

In case none of the when_expression in the WHEN clause matches the value of the
case_expression, the commands in the ELSE clause will execute. The ELSE clause is optional.
If you omit the ELSE clause and no match found, MySQL will raise an error.

The getStudentCountry procedure below demonstrate how we can use a simple case statement.
The procedure have one IN parameter registrationNumber and one OUT parameter
studentCountry. Inside the procedure, we use case to assign value to the OUT parameter. In case
the student’s nationality is one of the five East African Countries, we assign the name of that
country to the OUT parameter, else we set the student country as foreign.

DELIMITER //
CREATE PROCEDURE getStudentCountry (
IN registrationNumber VARCHAR(20),
OUT studentCountry VARCHAR(100)
)

BEGIN

DECLARE uraia VARCHAR(100);

SELECT nationality INTO uraia FROM student


WHERE studentID = registrationNumber;

CASE uraia
WHEN 'Tanzanian' THEN
SET studentCountry = 'Tanzania';
WHEN 'Kenyan' THEN
SET studentCountry = 'Kenya';
WHEN 'Ugandan' THEN
SET studentCountry = 'Uganda';
WHEN 'Rwandan' THEN
SET studentCountry = 'Rwanda';
WHEN 'Burundian' THEN
SET studentCountry = 'Burundi';
ELSE
SET studentCountry = 'Foreigner';
END CASE;
END //

DELIMITER ;

Figure 9; calling stored procedure that make decision using simple CASE

In the output shown in figure 9 (above), the last procedure call passed the value
NIT/BCFCF/2016/2027 as student registration number. The nationality of that student was
updated to Jamaican and that is why the output shows that the student is a foreigner.

Searched CASE Statement


The simple CASE statement only allows you match a value of an expression against a set of
distinct values. In order to perform more complex matches such as ranges, you use the searched
CASE statement. The searched CASE statement is equivalent to the IF statement, however, its
construct is much more readable.
The following illustrates the syntax of the searched CASE statement:

CASE
WHEN condition_1 THEN commands
WHEN condition_2 THEN commands
...
ELSE commands
END CASE;

In the example below, we rewrite the departmentLevel procedure whose output is in figure 8 to
allow it to use searched case in deciding whether the department is silver, gold or platinum.
Since that procedure exists in our MySQL server, we append case at the end of that name so that
they can have distinct name in the server. Thus, the name of our new procedure become
departmentLevelCase.

DELIMITER &&
CREATE PROCEDURE departmentLevelCase(
IN departmentNumber VARCHAR(15),
OUT departmentLevel VARCHAR(50)
)

BEGIN

DECLARE numberOfPrograms INT;

SELECT COUNT(*) INTO numberOfPrograms FROM


program WHERE department = departmentNumber;

CASE
WHEN numberOfPrograms < 5 THEN
SET departmentLevel = 'SILVER DEPARTMENT';
WHEN numberOfPrograms < 12 THEN
SET departmentLevel = 'GOLD DEPARTMENT';
WHEN numberOfPrograms >= 12 THEN
SET departmentLevel = 'PLATNUM DEPARTMENT';
END CASE;

END &&
DELIMITER ;
Figure 10; calling stored procedure that make decision using Searched CASE

Hints for Choosing Between IF and CASE Statements


MySQL provides both IF and CASE statements to enable you to execute a block of SQL code
based on certain conditions, which is known as flow control. So what statement should you use?
For the most developers, choosing between IF and CASE is just a matter of personal preference.
However, when you decide to use IF or CASE, you should take the following points into the
consideration:

• A simple CASE statement is more readable than the IF statement when you compare a
single expression against a range of unique values. In addition, the simple CASE
statement is more efficient than the IF statement.
• When you check complex expressions based on multiple values, the IF statement is easier
to understand.
• If you choose to use the CASE statement, you have to make sure that at least one of the
CASE condition is matched. Otherwise, you need to define an error handler to catch the
error. Recall that you don’t have to do this with the IF statement.
• In most organization, there is always something called development guidelines document
that provides developers with naming convention and guidelines on programming style.
You should refer to this document and follow the development practices.
• In some situations, mixing between IF and CASE make your stored procedure more
readable and efficient.

MySQL Loop in Stored Procedures


MySQL provides loop statements that allow you to execute a block of SQL code repeatedly
based on a condition. There are three loop statements in MySQL: WHILE, REPEAT and LOOP.

We will examine each loop statement in more detail in the following sections.
LEAVE and ITERATE Statements
There are two statements that allow you to control the loop:

The LEAVE statement allows you to exit the loop immediately without waiting for
checking the condition. The LEAVE statement works like the break statement in other
languages such as PHP, C/C++, Java, etc.
The ITERATE statement allows you to skip the entire code under it and start a new
iteration. The ITERATE statement is similar to the continue statement in PHP, C/C++,
Java, etc.

WHILE loop
The syntax of the WHILE statement is as follows:

WHILE expression DO
statements
END WHILE

The WHILE loop checks the expression at the beginning of each iteration. If the expression
evaluates to TRUE, MySQL will execute statements between WHILE and END WHILE until the
expression evaluates to FALSE. The WHILE loop is called pre-test loop because it checks the
expression before the statements execute.

Here is an example of using the WHILE loop statement in a stored procedure:

DELIMITER $$
CREATE PROCEDURE test_mysql_while_loop()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);

SET x = 1;
SET str = '';

WHILE x <= 5 DO
SET str = CONCAT(str,x,',');
SET x = x + 1;
END WHILE;

SELECT str;
END$$
DELIMITER ;

In the test_mysql_while_loop stored procedure above:

First, we build str string repeatedly until the value of the x variable is greater than 5.
Then, we display the final string using the SELECT statement.

Notice that if we don’t initialize the x variable, its default value is NULL. Therefore, the condition
in the WHILE loop statement is always TRUE and you will have an indefinite loop, which is not
expected.
Let’s test the test_mysql_while_loop stored procedure:

Figure 11; WHILE loop in a stored procedure

REPEAT Loop

The syntax of the REPEAT loop statement is as follows:

REPEAT
statements;
UNTIL expression
END REPEAT

First, MySQL executes the statements, and then it evaluates the expression. If the
expression evaluates to FALSE, MySQL executes the statements repeatedly until the
expression evaluates to TRUE.

Because the REPEAT loop statement checks the expression after the execution of
statements therefore the REPEAT loop statement is also known as the post-test loop.

We can rewrite the test_mysql_while_loop stored procedure that uses WHILE loop statement
above using the REPEAT loop statement:

DELIMITER $$
DROP PROCEDURE IF EXISTS mysql_test_repeat_loop $$
CREATE PROCEDURE mysql_test_repeat_loop()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);

SET x = 1;
SET str = '';

REPEAT
SET str = CONCAT(str,x,',');
SET x = x + 1;
UNTIL x > 5
END REPEAT;

SELECT str;
END$$
DELIMITER ;

NB: There is no semicolon (;) in the UNTIL expression.


Let’s test the mysql_test_repeat_loop stored procedure:

Figure 12; REPEAT loop in a stored procedure

MySQL LOOP
MySQL also gives you a LOOP statement that executes a block of code repeatedly with an
additional flexibility of using a loop label.

The following is an example of using the LOOP loop statement.

DELIMITER &&
CREATE PROCEDURE test_mysql_loop()
BEGIN
DECLARE x INT;
DECLARE str VARCHAR(255);
SET x = 1;
SET str = ' ';
loop_label: LOOP
IF x > 10 THEN
LEAVE loop_label;
END IF;
SET x = x + 1;
IF (x mod 2) THEN
ITERATE loop_label;
ELSE
SET str = CONCAT(str, x, ',');
END IF;
END LOOP;
SELECT str;
END &&
DELIMITER ;

Figure 13; LOOP loop in a stored procedure

The stored procedure only constructs a string with even numbers e.g., 2, 4, 6, etc.
We put a loop_label loop label before the LOOP statement.
If the value of x is greater than 10, the loop is terminated because of the LEAVE statement.
If the value of the x is an odd number, the ITERATE statement ignores everything below
it and starts a new iteration.
If the value of the x is an even number, the block in the ELSE statement will build the
string with even numbers.

MySQL Triggers
The database trigger is powerful tool for protecting the integrity of the data in your MySQL
databases. In addition, it is useful to automate some database operations such as logging,
auditing, etc.

A SQL trigger is a set of SQL statements stored in the database catalog. A SQL trigger is
executed or fired whenever an event associated with a table occurs e.g., insert, update or delete.

A SQL trigger is a special type of stored procedure. It is special because it is not called directly
like a stored procedure. The main difference between a trigger and a stored procedure is that a
trigger is called automatically when a data modification event is made against a table whereas a
stored procedure must be called explicitly.

It is important to understand SQL trigger’s advantages and disadvantages so that you can use it
appropriately. In the following sections, we will discuss the advantages and disadvantages of
using SQL triggers.

Advantages of Using SQL triggers

SQL triggers provide an alternative way to check the integrity of data.


SQL triggers can catch errors in business logic in the database layer.
SQL triggers provide an alternative way to run scheduled tasks. By using SQL triggers,
you don’t have to wait to run the scheduled tasks because the triggers are invoked
automatically before or after a change is made to the data in the tables.
SQL triggers are very useful to audit the changes of data in tables.

Disadvantages of Using SQL triggers

SQL triggers only can provide an extended validation and they cannot replace all the
validations. Some simple validations have to be done in the application layer. For
example, you can validate user’s inputs in the client side by using JavaScript or in the
server side using server-side scripting languages such as JSP, PHP, ASP.NET, Perl, etc.
SQL triggers are invoked and executed invisible from the client applications, therefore,
it is difficult to figure out what happen in the database layer.
SQL triggers may increase the overhead of the database server.

Triggers or stored procedures? It is recommended that if you have no way to get the work done
with stored procedure, think about SQL 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. Before MySQL version
5.7.2, you can to define maximum six triggers for each table.
i. BEFORE INSERT – activated before data is inserted into the table.
ii. AFTER INSERT – activated after data is inserted into the table.
iii. BEFORE UPDATE – activated before data in the table is updated.
iv. AFTER UPDATE – activated after data in the table is updated.
v. BEFORE DELETE – activated before data is removed from the table.
vi. AFTER DELETE – activated after data is removed from the table.

However, from MySQL version 5.7.2+, you can define multiple triggers for the same trigger
event and action time.

When you 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.

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. However, you can have the
same trigger name defined for different tables though it is not a good practice.

You should name the triggers using the following naming convention:

(BEFORE | AFTER)_tableName_(INSERT| UPDATE | DELETE)

For example, before_enrollment_update is a trigger invoked before a row in the enrollment table
is updated.

The following naming convention is as good as the one above.

tablename_(BEFORE | AFTER)_(INSERT| UPDATE | DELETE)

For example, enrollment_before_update is the same as before_enrollment_update trigger above.

MySQL Trigger Syntax


In order to create a new trigger, you use the CREATE TRIGGER statement. The following
illustrates the syntax of the CREATE TRIGGER statement:

CREATE TRIGGER trigger_name trigger_time trigger_event


ON table_name
FOR EACH ROW
BEGIN
……..
END;

Let’s examine the syntax above in more detail.

You put the trigger name after the CREATE TRIGGER statement. The trigger name
should follow the naming convention [trigger time]_[table name]_[trigger event], for
example before_employees_update.
Trigger activation time can be BEFORE or AFTER. You must specify the activation time
when you define a trigger. 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.
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.

MySQL Trigger Example


Let’s start creating a trigger in MySQL to log the changes of the student table in our university
database. Before updating student table, the trigger will copy the data of the row to be updated
into the student_audit table. First of all, let us create the student_audit table.

create table student_audit


(
ID INT AUTO_INCREMENT PRIMARY KEY,
studentID VARCHAR(100) NOT NULL,
fullname text NOT NULL,
dob DATE NOT NULL,
nationality VARCHAR(100),
maritualStatus VARCHAR(100),
program VARCHAR(100),
YoE INT(4) not null,
changeTime DATETIME NOT NULL,
action VARCHAR(100)NOT NULL
)engine=innoDB;

Then, we create the trigger called before_student_update as follows:

DELIMITER ??
CREATE TRIGGER before_student_update
BEFORE UPDATE ON student
FOR EACH ROW
BEGIN
INSERT INTO student_audit
SET action = 'update',
studentID =OLD.studentID,
fullname = OLD.fullname,
dob =OLD.dob,
nationality = OLD.nationality,
maritualStatus = OLD.maritualStatus,
program = OLD.program,
YoE = OLD.YoE,
changeTime = NOW();
END ??
DELIMITER ;
Inside the body of the trigger, we used the OLD keyword to access stdudentID, fullname, dob,
nationality, maritualStatus, program and YoE column of the row affected by the trigger.

Notice that in a trigger defined for INSERT, you can use NEW keyword only. You cannot use
the OLD keyword. However, in the trigger defined for DELETE, there is no new row so you can
use the OLD keyword only. In the UPDATE trigger, OLD refers to the row before it is updated
and NEW refers to the row after it is updated.

Then, to view all triggers in the current database, you use SHOW TRIGGERS statement.

To delete a particular trigger in the current database we use the DROPTRIGGER statement. For
example, to drop the above trigger, we could write:

DROP TRIGGER IF EXISTS before_student_update;

After that, update the employees table to check whether the trigger is invoked.

UPDATE student SET fullname='Prosper Magayane', nationality='Kenyan',


maritualStatus='Married' WHERE studentID='NIT/BCLTM/2016/1472';

Finally, to check if the trigger was invoked by the UPDATE statement, you can query the
student_audit table using the following query:

SELECT * FROM student_audit;

Figure 14; Checking if after update trigger was activated

Now let us check example of after insert trigger. Assuming that once we insert a student in a
student table, then we have to create login information of that student in the userLogin table. Let
say, by default the username of that student will be his/her student ID, and the password will be
his/her date of birth encrypted using message digest five (MD5) algorithm.

Let us first create the userLogin table.

CREATE TABLE userLogin


(
userID VARCHAR(100) NOT NULL PRIMARY KEY,
password TEXT NOT NULL,
active ENUM('yes','no')NOT NULL DEFAULT 'yes'
)engine=innoDB;

Then, let us create the after_student_insert trigger.

DELIMITER $$
CREATE TRIGGER after_student_insert
AFTER INSERT ON student
FOR EACH ROW
BEGIN
INSERT INTO userLogin
SET
userID =NEW.studentID,
password = MD5(NEW.dob);
END $$
DELIMITER ;

Then, let us insert a new student into student table.

INSERT INTO student (studentID, fullname, gender, dob, nationality, maritualStatus, program,
YoE, active, status) VALUES ('NIT/BCFCF/2016/2073', 'Isihakha Muya', 'male', '1995-09-08',
'Tanzanian', 'Single', 'BCICT', 2016, 'yes', 'continuing');

Then

Finally, to check if the trigger was invoked by the INSERT statement, you can query the
userLogin table using the following query:

SELECT * FROM userLogin;

Figure 15; Checking if after insert trigger was activated

You might also like