Advanced SQL Ofline
Advanced SQL Ofline
TABLE OF CONTENTS
Contents
TABLE OF CONTENTS .............................................................................................................. i
SORED PROCEDURES ..............................................................................................................1
Advantages of Stored Procedures .............................................................................................1
Creating a Stored Procedure ......................................................................................................1
Pick a Delimiter.........................................................................................................................1
Calling Stored Procedures .........................................................................................................3
Displaying Characteristics of Stored Procedures ......................................................................3
Displaying Stored Procedure’s Source Code ............................................................................4
Stored Procedure Variables .......................................................................................................4
Declaring Variables ...................................................................................................................4
Assigning Value to Variables ....................................................................................................4
Variables Scope .........................................................................................................................5
Stored Procedure Parameters ....................................................................................................5
The IN Parameter ......................................................................................................................5
The OUT Parameter ..................................................................................................................6
The INOUT Parameter ..............................................................................................................7
Stored Procedures that Return Multiple Values ........................................................................8
MySQL IF Statement Syntax ....................................................................................................9
MySQL IF ELSE Statement ......................................................................................................9
MySQL IF ELSEIF ELSE Statement........................................................................................9
MySQL CASE Statement .......................................................................................................11
Simple CASE Statement .........................................................................................................11
Searched CASE Statement ......................................................................................................13
Hints for Choosing Between IF and CASE Statements ..........................................................15
MYSQL TRIGGERS ..................................................................................................................16
Advantages of Using SQL Triggers ........................................................................................16
Disadvantages of Using SQL Triggers....................................................................................16
MySQL Trigger Syntax ...........................................................................................................17
MySQL Trigger Example........................................................................................................18
MySQL STORED FUNCTION ..................................................................................................21
MySQL Stored Function Syntax .............................................................................................21
MySQL Create Function Example ..........................................................................................21
Calling Stored Function ..........................................................................................................23
MySQL VIEWS ..........................................................................................................................24
Creating A View......................................................................................................................24
Displaying List of Views.........................................................................................................25
i
ADVANCED Structured Query Language | Shabani Bakari Juma
ii
ADVANCED Structured Query Language | Shabani Bakari Juma
SORED PROCEDURES
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.
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 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
1
ADVANCED Structured Query Language | Shabani Bakari Juma
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##
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 ;
DELIMITER //
CREATE PROCEDURE getAllDepartmentNames()
BEGIN
SELECT deptName FROM department;
END //
DELIMITER ;
2
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
3
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
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
4
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
▪ 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 IN Parameter
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 ;
5
ADVANCED Structured Query Language | Shabani Bakari Juma
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');
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 ;
6
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
SELECT @total;
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:
7
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
DELIMITER //
CREATE PROCEDURE getTotalModulePerYearPerSemester (
IN registrationNumber VARCHAR(25),
IN academicYear VARCHAR(12),
OUT semesterOne INT,
OUT semesterTwo INT)
BEGIN
END //
DELIMITER ;
8
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
IF expression THEN
statements;
ELSE
else-statements;
END IF;
IF expression THEN
statements;
ELSEIF elseif-expression THEN
elseif-statements;
...
ELSE
else-statements;
END IF;
9
ADVANCED Structured Query Language | Shabani Bakari Juma
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
END &&
DELIMITER ;
10
ADVANCED Structured Query Language | Shabani Bakari Juma
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
11
ADVANCED Structured Query Language | Shabani Bakari Juma
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);
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 ;
12
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
CASE
WHEN condition_1 THEN commands
WHEN condition_2 THEN commands
...
ELSE commands
END CASE;
13
ADVANCED Structured Query Language | Shabani Bakari Juma
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;
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
14
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
15
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
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.
16
ADVANCED Structured Query Language | Shabani Bakari Juma
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:
For example, before_enrollment_update is a trigger invoked before a row in the enrollment table
is updated.
17
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
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,
18
ADVANCED Structured Query Language | Shabani Bakari Juma
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.
Finally, to check if the trigger was invoked by the UPDATE statement, you can query the
student_audit table using the following query:
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.
19
ADVANCED Structured Query Language | Shabani Bakari Juma
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 ;
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:
20
ADVANCED Structured Query Language | Shabani Bakari Juma
A stored function is a special kind stored program that returns a single value. Typically, you use
stored functions to encapsulate common formulas or business rules that are reusable among SQL
statements or stored programs.
Different from a stored procedure, you can use a stored function in SQL statements wherever an
expression is used. This helps improve the readability and maintainability of the procedural code.
NOTE:
Parameter_list is a list of input parameters that will be passed during a function call
A function can be deterministic or not deterministic. A function is considered
deterministic if it always returns the same result set when it's called with the same
set of input values. A function is considered nondeterministic if it doesn't return the
same result set when it's called with the same set of input values.
If you don’t use DETERMINISTIC or NOT DETERMINISTIC, MySQL uses the NOT
DETERMINISTIC option by default.
21
ADVANCED Structured Query Language | Shabani Bakari Juma
Suppose that in the last column (credit) on figure 16 above we need to print a so-called module
status where a module with 9 credit will be rated Elective Module, the one with 12 credits will
be rated regular Core Module and the 15 credit module will be rated Super Core Module. In that
case, we will write a function and we will call it moduleStatus. The function will receive one
parameter which is the credit value. Then inside the function we will use either a switch case or
if…..else…if to assign the corresponding module rating to a variable declared inside the function
and later the variable. The function will look like:
DELIMITER ##
CREATE FUNCTION moduleStatus (idadiYaCredit int)
RETURNS varchar(100)
NOT DETERMINISTIC
BEGIN
DECLARE statusYaModule VARCHAR(100);
IF idadiYaCredit = 9 THEN
SET statusYaModule ='Fundamental Module';
ELSEIF idadiYaCredit = 12 THEN
SET statusYaModule ='Regular Core Module';
ELSE
SET statusYaModule ='Super Core Module';
END IF;
RETURN(statusYaModule);
END##
DELIMITER ;
you can view all stored functions in the current classicmodels database by using the SHOW
FUNCTION STATUS as follow:
SHOW FUNCTION STATUS WHERE db=‘databaseName’;
For example
22
ADVANCED Structured Query Language | Shabani Bakari Juma
23
ADVANCED Structured Query Language | Shabani Bakari Juma
MySQL VIEWS
A view is a named query stored in the database catalog. Normally, a view is associated with a
select statement. Once a view has been created, you can query data by referencing (selecting) the
view. A single view can select data from a single table or from multiple tables.
Next time if you want the same information from the database, you need to issue the same query.
However, if you created a view based on the above query, then you will need only to reference
the view as a table.
Creating A View
In order to create a view, u use the create view statement with the following syntax;
or simply
24
ADVANCED Structured Query Language | Shabani Bakari Juma
In the first syntax, OR REPLACE is an optional keyword that replace/drop an existing view with
the same name as the newly created view. If you attempt to create a view with the same name as
another existing view without OR REPLACE clause, the DBMS will issue error message the
new view will not be created. That is to say, within the same database, view names are distinct.
The COLUMN_LIST option allows you to create a view with explicitly columns. It is an option.
You can create a view that has no column.
Let’s now use the second syntax to create a view based on the above query. Our view will be
called viewFCTstudents.
In order to execute the view, one now need to select the view name with the ALL (*) option
(except for a view with explicit column list, you can select some columns) as follow;
25
ADVANCED Structured Query Language | Shabani Bakari Juma
From figure 20 above, you can see the last column (Table_type) shows that the last entry
(viewFCTstudents) is a view (not base table as the rest).
Alternatively, you can specify to list only view using the show full tables statement by specifying
the Table_type and using FROM or IN keyword as follow
NOTE: In a database, Base table and views share the same namespace. Hence, most of the
commands that run on a table, also run on a view. Likewise, A table and a view can not have the
same name.
Renaming a View
You can use SQL rename table statement to rename a view as they share the namespace. For
example, to rename our previous viewFCTstudents to a FCTstudentsView, we use the following
statement;
26
ADVANCED Structured Query Language | Shabani Bakari Juma
As you can see from the figure above, the fields of your view are the names displayed in your
view output while their data type are either from their original base table datatype or depending
on the output if the data is a result of applying some function(s).
Dropping a View
To remove a view from the database, use the DROP VIEW statement with the view name to be
dropped. For example, if we want to drop the above FCTstudentView, we can write
27
ADVANCED Structured Query Language | Shabani Bakari Juma
28