Lesson_11__Stored_Procedures_and_Triggers_in_MySQL
Lesson_11__Stored_Procedures_and_Triggers_in_MySQL
Learning Objectives
Parameter List
SQL
Name
Statements
The explanation of each parameter in the stored procedure syntax is given below:
Increased Scalability
Working with Stored Procedures
Changing the Default Delimiter
MySQL Workbench uses the delimiter (;) to separate statements and execute each
statement distinctly.
SYNTAX
CREATE PROCEDURE procedure_name(parameter_list)
BEGIN
statements;
END
In MySQL, code is written between the BEGIN and END keywords. The delimiter character is placed
after END to conclude the procedure statement.
Executing Stored Procedures
To execute the stored procedure, you can use the following syntax with the CALL keyword:
SYNTAX
If the procedure has parameters, then the parameter values must be specified in
the parenthesis.
Removing Stored Procedures
SYNTAX
• If you drop a procedure that does not exist without using the IF EXISTS option, MySQL
shows an error.
• If you use the IF EXISTS option for the same condition, then MySQL shows a warning.
Stored Procedures: Example
Problem Statement: You are a junior DB administrator in your company. Your manager has
asked you to retrieve data on employees with more than five years of experience, using a
single command.
Step 1: You have a table on employees with details, such as employee ID, first name, last
name, gender, role name, department, experience, country, and continent.
• If you drop a procedure that does not exist without using the IF EXISTS option, MySQL
shows an error.
• If you use the IF EXISTS option for the same condition, then MySQL shows a warning.
Stored Procedures: Example
Step 2: Create a stored procedure that displays the employees with more than five years of
experience using the following command.
QUERY
DELIMITER &&
CREATE PROCEDURE get_mid_experience()
BEGIN
SELECT * FROM Emp_Table WHERE experience > 5;
END &&
• If you drop a procedure that does not exist without using the IF EXISTS option, MySQL
shows an error.
• If you use the IF EXISTS option for the same condition, then MySQL shows a warning.
Stored Procedures: Example
Step 3: Call for the stored procedure to return the results based on the specified condition.
QUERY
CALL get_mid_experience();
Output:
Using Variables in Stored Procedures
Variable is a named data object whose value can be changed during stored procedure execution.
They are used to store immediate results and are local to the stored procedure.
Declaring and Assigning Variables
DECLARE and SET keywords are used to declare and set variables.
Problem statement: You are a junior DB administrator, and your manager has asked you to
identify the total number of employees in the employee table created earlier.
Objectives: Use the stored procedure to view the number of employees anytime and also
declare a variable for total employees.
Declaring and Assigning Variables: Example
Step 1: Using the same employee table as earlier, create a stored procedure and declare a
default variable 0.
QUERY
DELIMITER &&
CREATE PROCEDURE get_total_employees()
BEGIN
DECLARE totalemployee INT DEFAULT 0;
SELECT COUNT (*)
INTO totalemployee
FROM Emp_Table;
SELECT totalemployee;
END &&
DELIMITER ;
Declaring and Assigning Variables: Example
Step 2: Use the CALL function to view the stored procedure results.
QUERY
CALL get_total_employees()
Output:
Scope of Variables
A variable declared
A variable declared Two or more variables
inside the stored
inside the block with the same name
procedure will be out
BEGIN END will be out can be declared in
of scope when it
of scope at END. MySQL.
reaches END.
Note: A variable that begins with @ is called a session variable. It is accessible until the
session ends.
Stored Procedures That Return Multiple Values
IN OUT INOUT
Generally, MySQL stored functions return a single value. To obtain multiple values, use
stored procedures with INOUT or OUT parameters.
Stored Procedures That Return Multiple Values (IN)
This is the default mode, and parameter is the input here. The calling program must pass an
argument to the stored procedure when it is defined.
Problem Statement: You are a junior DB administrator in your organization. Your manager
has asked you to list the employee names in the automotive department.
Step 1: Create a procedure named employee of auto. Keep the department as the IN parameter.
QUERY
QUERY
CALL Emp_of_Auto("Automotive");
Output:
Stored Procedures That Return Multiple Values (OUT)
This parameter is used to pass a parameter as an output. Its value can be changed inside
the stored procedure.
OUT
The initial value of the OUT parameter cannot be accessed by the stored procedure
when it starts.
Stored Procedures That Return Multiple Values: Example (OUT)
Problem Statement: You are a junior DB administrator in your organization. Your manager
has asked you to count the employees in the retail department.
Objective: Create a stored procedure with an OUT parameter and extract the required result.
Stored Procedures That Return Multiple Values: Example (OUT)
Step 1: Create a procedure called employee count in retail with the OUT parameter to count the
employees in the retail department.
QUERY
DELIMITER &&
CREATE PROCEDURE Emp_Count_in_Retail ( OUT total_Emp INT)
BEGIN
SELECT count(Emp_ID) INTO total_Emp FROM Emp_Table WHERE Dept
= "Retail";
END &&
Stored Procedures That Return Multiple Values: Example (OUT)
Step 2: Call the created procedure to store the returned value. Pass a session variable named
@Retail_Employees. Select values from these in a separate value called employee retail.
QUERY
Output:
INOUT
This specifies that the calling program can pass the argument and the stored procedure can
modify the INOUT parameter.
Stored Procedures That Return Multiple Values (IN OUT)
Problem Statement: You are a junior DB administrator in your organization. Your manager
wants to track total number of changes made each time when there is a new addition to an
existing database.
Objective: Create a stored procedure with an IN OUT parameter to display the required
count.
Stored Procedures That Return Multiple Values (IN OUT)
Step 1: Create a procedure iteration with count as the IN OUT parameter and increment as the
IN parameter.
QUERY
CREATE PROCEDURE
Iterations (INOUT count int, IN increment int)
BEGIN
SET count = count + increment;
END
Stored Procedures That Return Multiple Values (IN OUT)
Step 2: Set Iterations to zero. Call the procedure with the variable when there is one change;
repeat the process when there are five changes.
QUERY
Output:
SET @Iterations = 0;
CALL Increment_Counter (@Iterations, 1);
select @Iterations;
CALL Increment_Counter (@Iterations, 5);
select @Iterations;
Stored Procedures with One and Multiple Parameters
Stored procedures can have one or more parameters, and these parameters are separated
by commas.
Stored Procedures with One Parameter: Example
Problem Statement: You are a junior DB administrator in your organization. Your manager
wants to identify an employee’s experience based on just the employee ID and decide
whether to give them a hike or not.
Step 1: Create a stored procedure with the relevant employee details and keep employee
ID as the parameter.
QUERY
DELIMITER $$
CREATE PROCEDURE GetEmpExp(eid int)
BEGIN
SELECT Emp_ID, Emp_Name
Role_name, Dept, Experience
FROM Emp_Table
WHERE Emp_ID = eid;
END $$
Stored Procedures with One Parameter: Example
QUERY
CALL GetEmpExp(620);
Output:
Stored Procedures with Two Parameter: Example
Problem Statement: You are a junior DB administrator in your organization. Your manager
wants to identify employees with less than 3 years of experience and salaries less than 30000.
Objective: Create a stored procedure that takes the employee experience and salary as
parameters.
Stored Procedures with Two Parameter: Example
Step 1: Create a stored procedure with the relevant employee details and keep employee
experience and employee salary as the parameters.
QUERY
DELIMITER $$
CREATE PROCEDURE GetEmpHike(exp int, sal int)
BEGIN
SELECT *
FROM Emp_Table
WHERE Experience <= exp
AND Salary <= sal;
END $$
Stored Procedures with Two Parameter: Example
QUERY
CALL GetEmpHike(3,30000);
Output:
Listing Stored Procedures
SHOW PROCEDURE STATUS statement displays all the characteristics of stored procedures.
Problem Statement: You work as a junior analyst at your organization. You must assist the
HR department with the development of an employee information table in one of the
databases so that the HR can track and retrieve their data anytime they need it.
Objective: Build the appropriate database and table for storing the HR specific data.
The HR department has provided a detailed description of the required table given below.
Step 1: Create a database named HR_DB with the CREATE DATABASE statement.
SQL Query
Step 2: Set HR_DB as the default database in MySQL with the USE statement.
SQL Query
USE HR_DB;
Use Case: Employee Data Analysis by HR
Step 3: Set INNODB as the default storage engine for HR_DB database in MySQL
with the SET statement.
SQL Query
SET default_storage_engine =
INNODB;
Use Case: Employee Data Analysis by HR
Step 4: Create the required EMP_RECORDS table in the HR_DB database with the CREATE TABLE
statement as given below.
SQL Query
CREATE TABLE IF NOT EXISTS HR_DB.EMP_RECORDS (
) ENGINE=INNODB;
Use Case: Employee Data Analysis by HR
Step 5: Analyze the structure of the EMP_RECORDS table with the DESCRIBE statement.
Output:
SQL Query
DESCRIBE HR_DB.EMP_RECORDS;
Use Case: Employee Data Analysis by HR
Step 6: Insert the required data from the downloaded HR_EMP_TABLE.csv file into the
EMP_RECORDS table as shown below.
SQL Query
INSERT INTO
HR_DB.EMP_RECORDS(EMP_ID,FIRST_NAME,LAST_NAME,GENDER,ROLE,DEPT,EXP,COUNTRY,CONTIN
ENT,SALARY,EMP_RATING,MANAGER_ID)
VALUES
("E083","Patrick","Voltz","M","MANAGER","HEALTHCARE",15,"USA","NORTH
AMERICA","9500",5,"E002"),
...
...
Step 7: Analyze the data entered into the EMP_RECORDS table with the SELECT statement.
SQL Query
Output:
Compound Statement
Compound Statement
Syntax
[begin_label:] BEGIN
[statement_list]
END [end_label]
Compound Statement: Example
Problem Statement: The HR department wants to extract the manager’s details along with
the number of employees reporting to the manager by using the manager’s employee ID.
Objective: Create a stored procedure that takes the manager's employee ID as input and
returns the manager's basic information as well as the number of employees reporting to
the manager.
Compound Statement: Example
Step 2: Execute this stored procedure with the EMP_ID of the manager and check the output.
SQL Query
CALL GetEmpCount("E083");
Output:
Conditional Statements
Conditional Statements
IF CASE
Conditional
Statement
IF Statement
It is a type of control-flow
In the IF condition, a block
statement that determines
whether to execute a block of
IF of SQL code is specified
STATEMENT between the IF and END
SQL code based on a specified
IF keywords.
condition.
Types of IF Statements
IF
IF-THEN IF-THEN-ELSEIF-
ELSE
IF-THEN-ELSE
IF-THEN Statement
The IF-THEN statement executes a set of SQL statements based on a specified condition.
Syntax
IF condition THEN
statement_list;
END IF;
IF-THEN Statement: Example
Problem Statement: The HR department wants to identify the employees who have a rating
below three and are not performing well.
DELIMITER $$
Step 2: Use the EMP_ID and a temporary global variable @performance to run this stored
procedure, and then use this variable to examine the result.
CALL getEmpScore1("E505",
SELECT @performance;
@performance);
Output:
IF-THEN-ELSE Statement
The IF-THEN-ELSE statement executes another set of SQL statements when the
condition in the IF branch does not evaluate to TRUE.
Syntax
IF condition THEN
statement_list;
ELSE
statement_list;
END IF;
IF-THEN-ELSE Statement
Problem Statement: The HR department needs to know the employees who have a rating below
three and are not doing well as well as the ones with a rating of three or more and are
performing well.
DELIMITER $$
IF score < 3 THEN
CREATE PROCEDURE getEmpScore2(
SET performance = "BAD";
IN eid VARCHAR(4), OUT performance VARCHAR(50))
ELSE
BEGIN
SET performance = "GOOD";
DECLARE score INT DEFAULT 1;
END IF;
SELECT EMP_RATING INTO score
END$$
FROM EMP_RECORDS
Step 2: Use the EMP_ID and a temporary global variable @performance to run this stored
procedure, and then use this variable to examine the result.
CALL getEmpScore2("E005",
SELECT @performance;
@performance);
Output:
IF-THEN-ELSEIF-ELSE Statement
Syntax
IF condition THEN
statement_list;
statement_list;
...
ELSE
statement_list;
END IF;
Problem Statement: The HR department needs to know how each employee is performing
by categorizing them based on their ratings, which vary from one to five. They want to grade
each employee's performance as Overachiever, Excellent Performance, Meeting
Expectations, Below Expectations, and Not Achieving Any Goals.
Step 2: Use the EMP_ID and a temporary global variable @performance to run this stored
procedure, and then use this variable to examine the result.
CALL getEmpScore3("E005",
SELECT @performance;
@performance);
Output:
CASE Statement
CASE
Statement
It is a type of control-flow
statement used in stored It extends the
procedures to create functionality of the IF
conditional statements statement.
that make the code more
readable and efficient.
Types of CASE Statements
Syntax
CASE case_value
WHEN when_value1 THEN statements
WHEN when_value2 THEN statements
ELSE
[ELSE else_statements]
Or,
BEGIN
END;
END CASE;
MySQL raises an error in absence of the ELSE clause if no conditions are satisfied.
Error
The ELSE clause utilizes an empty BEGIN...END block to prevent any errors.
Simple CASE Statement: Example
Problem Statement: The HR department needs to know how each employee is performing
by categorizing them based on their ratings, which vary from one to five. They want to grade
each employee's performance as Overachiever, Excellent Performance, Meeting
Expectations, Below Expectations, and Not Achieving Any Goals.
WHEN 1 THEN
ELSE
BEGIN
END;
END CASE;
END$$
Simple CASE Statement: Example
Step 2: Use the EMP_ID and a temporary global variable @performance to run this stored
procedure, and then use this variable to examine the result.
CALL getEmpScore4("E005",
SELECT @performance;
@performance);
Output:
Searched CASE Statement
Syntax
CASE
WHEN search_condition1 THEN statements
WHEN search_condition1 THEN statements
...
[ELSE else_statements]
Or,
BEGIN
END;
END CASE;
MySQL raises an error in absence of the ELSE clause if no condition evaluates to TRUE.
Error
Problem Statement: The HR department needs to know how each employee is performing
by categorizing them based on their ratings, which vary from one to five. They want to grade
each employee's performance as Overachiever, Excellent Performance, Meeting
Expectations, Below Expectations, and Not Achieving Any Goals.
ELSE
BEGIN
END;
END CASE;
END$$
Searched CASE Statement: Example
Step 2: Use the EMP_ID and a temporary global variable @performance to run this stored
procedure, and then use this variable to examine the result.
CALL getEmpScore5("E005",
SELECT @performance;
@performance);
Output:
Loops in Stored Procedures
Loops in Stored Procedures
DEFINITION FUNCTIONALITY
Syntax Flowchart
[begin_label]: LOOP
statement_list START
STATEMENT
LOOP Statement: Example
Problem Statement: Your manager expects you to write a simple infinite loop in MySQL that
counts even integers and adds them one after the other in a string separated by a comma.
Objective: Create a stored procedure with a simple infinite loop in MySQL that counts even
integers from 1 and adds them one after the other in a string separated by a comma.
LOOP Statement: Example
loop_label: LOOP
DROP PROCEDURE InfiniteEvenLoop;
SET num = num + 1;
Step 2: Execute this stored procedure with the CALL statement, and analyze the warning produced
by MySQL as the loop is infinite.
SQL Query
CALL InfiniteEvenLoop();
Output:
WHILE Loop
DEFINITION FUNCTIONALITY
Flowchart
START
Syntax
[begin_label]: LOOP
statement_list
SEARCH
END LOOP [end_label]; CONDITION
TRUE
STATEMENT FALSE
START
WHILE Loop: Example
Problem Statement: Your manager expects you to write a loop in MySQL that counts
integers till 10 and adds them one after the other in a string separated by a comma.
Objective: Create a stored procedure with a while loop in MySQL that counts integers till 10
and adds them one after the other in a string separated by a comma.
WHILE Loop: Example
Step 2: Execute this stored procedure with CALL statement and check the output.
SQL Query
CALL EvenWhileLoop();
Output:
REPEAT Loop
DEFINITION FUNCTIONALITY
Flowchart
START
Syntax
[begin_label]: LOOP
statement_list
STATEMENT
END LOOP [end_label];
FALSE
SEARCH
CONDITION
TRUE
START
REPEAT Loop: Example
Problem Statement: Your manager expects you to write a loop in MySQL that counts integers
till 10 and adds them one after the other in a string separated by a comma.
Objective: Create a stored procedure with a repeat loop in MySQL that counts integers till
10 and adds them one after the other in a string separated by a comma.
REPEAT Loop: Example
Step 2: Execute this stored procedure with CALL statement and check the output.
SQL Query
CALL EvenRepeatLoop();
Output:
Terminating Stored Procedures and Loops
LEAVE Statement
Syntax
LEAVE label;
Using LEAVE With Stored Procedure
Syntax
DELIMITER //
CREATE PROCEDURE
procedure_name(parameter_list)
[label]: BEGIN
statement_list;
...
IF condition THEN
LEAVE [label];
END IF;
...
-- other statements
END //
DELIMITER;
Using LEAVE With Stored Procedure: Example
Problem Statement: The HR department wants to find the employees with a rating above 3
along with their basic information.
Objective: Create a stored procedure for the basic information of an employee only if the
rating is above 3.
Using LEAVE With Stored Procedure: Example
LEAVE sp;
Delimiter $$
END IF;
CREATE PROCEDURE GoodEmployeeRecord(eid VARCHAR(4))
SELECT EMP_ID, FIRST_NAME, LAST_NAME, DEPT,
sp: BEGIN
SALARY
DECLARE rating INT DEFAULT 0;
FROM EMP_RECORDS WHERE EMP_ID = eid;
SELECT EMP_RATING INTO rating
END$$
FROM EMP_RECORDS WHERE EMP_ID = eid;
Using LEAVE With Stored Procedure: Example
Step 2: Execute this stored procedure with the EMP_ID of the employee and check the output.
SQL Query
CALL GoodEmployeeRecord("E083");
Output:
Using LEAVE With LOOP Statement
Syntax
[label]: LOOP
statement_list
...
-- terminate the loop
IF condition THEN
LEAVE [label];
END IF;
...
-- other statements
END LOOP [label];
Using LEAVE With LOOP Statement: Example
Problem Statement: Your manager expects you to write a simple infinite loop in MySQL that
counts even integers to add them one after the other in a string separated by a comma and
terminate when the integer exceeds 10.
Objective: Create a stored procedure with a simple infinite LOOP in MySQL that counts even
integers till 10 and adds them one after the other in a string separated by a comma,
terminating the loop when the integer count exceeds 10.
Using LEAVE With LOOP Statement: Example
ELSE
END IF;
SELECT msg;
END$$
Using LEAVE With LOOP Statement: Example
Step 2: Execute this stored procedure with the CALL statement, and analyze the warning
produced by MySQL as the loop is infinite.
SQL Query
CALL EvenLoop();
Output:
Using LEAVE With WHILE Loop
Syntax
[label:] WHILE search_condition DO
statement_list
...
-- terminate the loop
IF condition THEN
LEAVE [label];
END IF;
...
-- other statements
END WHILE [label];
Using LEAVE With WHILE Loop: Example
Problem Statement: Your manager expects you to write a loop in MySQL that produces the
sum of first 20 even integers.
Objective: Create a stored procedure with a WHILE Loop in MySQL that counts first 20
even integers and adds them one by one, terminating the loop when the integer count
exceeds the 20th even integer and return the sum.
Using LEAVE With WHILE Loop: Example
Step 2: Execute this stored procedure with CALL statement and check the output.
SQL Query
CALL LeaveWhileLoop();
Output:
Using LEAVE With REPEAT Loop
Syntax
[label:] REPEAT
statement_list
...
-- terminate the loop
IF condition THEN
LEAVE [label];
END IF;
...
-- other statements
UNTIL search_condition
END REPEAT [label];
Using LEAVE With WHILE Loop: Example
Problem Statement: Your manager expects you to write a loop in MySQL that produces the
sum of first 20 even integers.
Objective: Create a stored procedure with a REPEAT Loop in MySQL that counts first 20
even integers and adds them one by one, terminating the loop when the integer count
exceeds the 20th even integer and return the sum.
Using LEAVE With REPEAT Loop: Example
END$$
Using LEAVE With REPEAT Loop: Example
Step 2: Execute this stored procedure with CALL statement and check the output.
SQL Query
CALL LeaveRepeatLoop();
Output:
Stored Functions in Stored Procedures
Stored Functions in Stored Procedures
Parameters Description
fun_name The name of the stored function that the user wants to create
Example:
EMP_ID Fname Lname Start_Date
DELIMITER //
Output:
1 Ravi Kumar 21
2 Slim Shady 16
3 Michael Scott 19
4 Travis Baker 17
Stored Functions in Stored Procedures
Problem Scenario: You are a junior database administrator. Your manager has asked you to perform
different operations using stored function on the emp_details table with the schema named as sys.
Objective: You are required to extract the first and last names, department, and designation based on
the experience of the employees.
Solution
DELIMITER $$
drop function sys.Customer_details1;
CREATE FUNCTION Customer_details1(experience int)
RETURNS VARCHAR(2255) DETERMINISTIC
BEGIN DECLARE customer_details1 VARCHAR(2255);
IF experience <= 2 THEN SET customer_details1 = 'JUNIOR DATA SCIENTIST';
ELSEIF experience <= 5 THEN SET customer_details1 = 'ASSOCIATE DATA SCIENTIST';
ELSEIF experience <= 10 THEN SET customer_details1 = 'SENIOR DATA SCIENTIST';
ELSEIF experience <= 12 THEN SET customer_details1 = 'LEAD DATA SCIENTIST';
ELSEIF experience > 12 THEN SET customer_details1 = 'MANAGER'
END IF; RETURN (customer_details1); END$$ DELIMITER $$;
SELECT first_name, last_name, department, Customer_details1(experience) as designation FROM
sys.emp_details ORDER BY experience;
Output
Problem Scenario: You are a junior database administrator. Your manager has asked you to perform
different operations using stored function on the emp_details table with the schema named as sys.
Objective: You are required to extract the names and status of the projects using stored procedure
with stored functions.
Solution
DELIMITER $$
CREATE FUNCTION Customer_details1(project_id VARCHAR(225))
RETURNS VARCHAR(2255) DETERMINISTIC
BEGIN DECLARE customer_details1 VARCHAR(2255);
IF project_id = 'P103' THEN SET customer_details1 = 'Drug Discovery';
ELSEIF project_id = 'P105' THEN SET customer_details1 = 'Fraud Detection';
ELSEIF project_id = 'P109' THEN SET customer_details1 = 'Market Basket Analysis';
ELSEIF project_id = 'P201' THEN SET customer_details1 = 'Self Driving Cars';
ELSEIF project_id = 'P204' THEN SET customer_details1 = 'Supply Chain Management';
ELSEIF project_id = 'P208' THEN SET customer_details1 = 'Algorithmic Trading';
ELSEIF project_id = 'P302' THEN SET customer_details1 = 'Early Detection of Lung Cancer';
ELSEIF project_id = 'P406' THEN SET customer_details1 = 'Customer Sentiment Analysis';
END IF; RETURN (customer_details1); END$$
DELIMITER $$;
Solution
DELIMITER $$
CREATE PROCEDURE GetCustomerDetail() BEGIN
SELECT project_id, status , Customer_details1(project_id) as
project_name FROM sys.project_details ORDER BY project_id;
END$$ DELIMITER ; call GetCustomerDetail();
Output
After executing the query, the list of project_id, project_name, and status are
shown as the following output:
Difference Between Stored Functions and Stored Procedures
• A function has a return type and returns a • A procedure does not have a return type.
value. It returns values using the OUT
parameters.
• Functions cannot be used with data
manipulation queries. Only select queries • DML queries such as insert, update, and
are allowed in functions. select can be used with procedures.
• A function does not allow output • A procedure allows both input and output
parameters. parameters.
• Stored procedures cannot be called from a • Functions can be called from a stored
function. procedure.
Assisted Practice: Stored Procedures
Duration: 20 mins
Problem statement: You are working for a company that deals with geographical data. Most of the SQL
work done here is via stored procedures. You are an analyst and have been asked to create a stored
procedure to pull all North American countries using the COUNTRY table.
Assisted Practice: Stored Procedures
Steps to be performed:
Step 01: Create a view containing the columns COUNTRY_ID, COUNTRY_NAME, and CONTINENT_ID
and name it "COUNTRY“
SQL Query
Output:
Assisted Practice: Stored Procedures
SQL Query
INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (1, 'Ukraine', 3, 'Europe');
INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (2, 'France', 3, 'Europe'); INSERT
COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (3, 'Germany', 3, 'Europe'); INSERT
COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (4, 'Italy', 3, 'Europe'); INSERT COUNTRY
(COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (5, 'United States', 2, 'North America'); INSERT
COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (6, 'Bosnia and Herzegovina', 3,
'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (7, 'United Kingdom',
3, 'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (8, 'Japan', 1,
'Asia'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (9, 'Indonesia', 1,
'Asia'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (10, 'Vietnam', 1,
'Asia'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (11, 'Russia', 3,
'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (12, 'Switzerland', 3,
'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (13, 'Cuba', 2, 'North
America');
Assisted Practice: Stored Procedures
Output:
Assisted Practice: Stored Procedures
SQL Query
SELECT * FROM COUNTRY
Assisted Practice: Stored Procedures
Output:
Assisted Practice: Stored Procedures
Step 04: Write a query to create a stored procedure and name it "SP_COUNTRIES_NA"
SQL Query
DELIMITER &&
CREATE PROCEDURE SP_COUNTRIES_NA()
BEGIN
SELECT COUNTRY_NAME FROM COUNTRY WHERE CONTINENT_NAME="North America";
END &&
CALL SP_COUNTRIES_NA();
Assisted Practice: Stored Procedures
Output:
Assisted Practice: Stored Procedures with One
Parameter
Duration: 20 mins
Problem statement: You are working for a company that deals with geographical data. Most of the
SQL work done here is via stored procedures. You are an analyst and have been asked to create a
stored procedure to pull the count of distinct countries in a continent, passed in the procedure
argument, using the COUNTRY table.
Assisted Practice: Stored Procedures with One
Parameter
Steps to be performed:
Step 01: Create a view containing the columns COUNTRY_ID, COUNTRY_NAME, and CONTINENT_ID
and name it "COUNTRY“
SQL Query
DROP TABLE IF EXISTS COUNTRY;
CREATE TABLE COUNTRY (
COUNTRY_ID INT,
COUNTRY_NAME TEXT,
CONTINENT_ID INT,
CONTINENT_NAME TEXT);
Assisted Practice: Stored Procedures with One
Parameter
Output:
Assisted Practice: Stored Procedures with One
Parameter
SQL Query
INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (1, 'Ukraine', 3, 'Europe');
INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (2, 'France', 3, 'Europe'); INSERT
COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (3, 'Germany', 3, 'Europe'); INSERT
COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (4, 'Italy', 3, 'Europe'); INSERT COUNTRY
(COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (5, 'United States', 2, 'North America'); INSERT
COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (6, 'Bosnia and Herzegovina', 3,
'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (7, 'United Kingdom',
3, 'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (8, 'Japan', 1,
'Asia'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (9, 'Indonesia', 1,
'Asia'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (10, 'Vietnam', 1,
'Asia'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (11, 'Russia', 3,
'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (12, 'Switzerland', 3,
'Europe'); INSERT COUNTRY (COUNTRY_ID, COUNTRY_NAME, CONTINENT_ID, CONTINENT_NAME) VALUES (13, 'Cuba', 2, 'North
America');
Assisted Practice: Stored Procedures with One
Parameter
Output:
Assisted Practice: Stored Procedures with One
Parameter
SQL Query
SELECT * FROM COUNTRY
Assisted Practice: Stored Procedures with One
Parameter
Output:
Assisted Practice: Stored Procedures with One
Parameter
Step 04: Write a query to create a stored procedure and name it "SP_COUNTRIES_OF_CONTINENT"
SQL Query
DELIMITER &&
CREATE PROCEDURE SP_COUNTRIES_OF_CONTINENT(IN CONT_NAME TEXT)
BEGIN
SELECT COUNT(DISTINCT COUNTRY_NAME) FROM COUNTRY WHERE CONTINENT_NAME=CONT_NAME;
END &&
CALL SP_COUNTRIES_OF_CONTINENT('Asia');
Output:
Assisted Practice: Stored Procedures with Multiple
Values
Duration: 20 mins
Problem statement: You work for an ed-tech startup that curates and delivers courses for experienced
professionals. You have been asked to create a procedure that classifies the courses into three
categories:
• StudentCount less than or equal to 1000
• StudentCount greater than 1000 and StudentCount less than or equal to 5000
• StudentCount greater than 5000
Assisted Practice: Stored Procedures with Multiple
Values
Steps to be performed:
Step 01: Create a view with the columns CourseID, CourseName, and StudentCount and name it
"Course"
CREATE
CREATE TABLE Course (
CourseID INT,
CourseName TEXT,
StudentCount INT);
Assisted Practice: Stored Procedures with Multiple
Values
Output:
Assisted Practice: Stored Procedures with Multiple
Values
Query
INSERT INTO Course(CourseID, CourseName, StudentCount) VALUES(1,'Data
Science',100034),
(2,'PMP',2500),
(3,'Agile',4003),
(4,'ITIL',387),
(5,'Blockchain',7876);
Assisted Practice: Stored Procedures with Multiple
Values
Output:
Assisted Practice: Stored Procedures with Multiple
Values
Query
SELECT * FROM Course;
Assisted Practice: Stored Procedures with Multiple
Values
Output:
Assisted Practice: Stored Procedures with Multiple
Values
Step 04: Write a query to create a stored procedure and name it "CLASSIFY_COURSE"
Query
DELIMITER &&
CREATE PROCEDURE CLASSIFY_COURSE(IN id INT, OUT CATEGORY TEXT)
BEGIN DECLARE C INT DEFAULT 1;
SELECT StudentCount INTO C FROM Course WHERE CourseID=id;
IF C<=1000 THEN
SET CATEGORY = "Low Demand";
ELSEIF C>1000 AND C<=5000 THEN
SET CATEGORY = "Mid Demand";
ELSE SET CATEGORY = "High Demand";
END IF; END &&
CALL CLASSIFY_COURSE(1, @CATEGORY);
SELECT @CATEGORY;
Assisted Practice: Stored Procedures with Multiple
Values
Output:
Assisted Practice: Stored Procedures with Multiple
Values
Test Case 01
DELIMITER &&
CREATE PROCEDURE CLASSIFY_COURSE(IN id INT, OUT CATEGORY TEXT)
BEGIN DECLARE C INT DEFAULT 1;
SELECT StudentCount INTO C FROM Course WHERE CourseID=id;
IF C<=1000 THEN
SET CATEGORY = "Low Demand";
ELSEIF C>1000 AND C<=5000 THEN
SET CATEGORY = "Mid Demand";
ELSE SET CATEGORY = "High Demand";
END IF; END &&
CALL CLASSIFY_COURSE(3, @CATEGORY);
SELECT @CATEGORY;
Assisted Practice: Stored Procedures with Multiple
Values
Output:
Knowledge Check
Knowledge
Check
Which of the following defines a stored procedure in SQL?
1
A. Block of functions
C. Collection of views
A. Block of functions
C. Collection of views
A stored procedure is a logical unit in a database that groups one or more precompiled SQL
statements contained within the BEGIN and END keywords in the stored procedure's body.
Knowledge
Check
What is the purpose of the SQL CASE statement?
2
The CASE expression evaluates conditions sequentially and yields a value upon the first met condition, resembling
an if-then-else statement. Therefore, once a condition becomes true, the evaluation halts, and the corresponding
result is returned.
Knowledge
Check
Which of the following is an escape character in SQL?
3
A. Period
B. Comma
C. Colon
D. Backslash
Knowledge
Check
Which of the following is an escape character in SQL?
3
A. Period
B. Comma
C. Colon
D. Backslash
A. DECLARE PROCEDURE
B. SET PROCEDURE
C. CREATE PROCEDURE
D. ASSIGN PROCEDURE
Knowledge
Check
What is the keyword used to create a stored procedure?
4
A. DECLARE PROCEDURE
B. SET PROCEDURE
C. CREATE PROCEDURE
D. ASSIGN PROCEDURE
A. Loops
B. Control structures
C. Repeat statement
D. Stored procedures
Knowledge
Check Which of the following repeats a set of instructions until a specific condition is
5 reached?
A. Loops
B. Control structures
C. Repeat statement
D. Stored procedures
Repeat statements are used to repeat a set of instructions until a specific condition is met.
Knowledge
Check Which characteristics are used to control the privileges of execution of a stored object?
6 Select all that apply.
A. DEFINER
B. SET
C. SQL SECURITY
D. DECLARE
Knowledge
Check Which characteristics are used to control the privileges of execution of a stored object?
6 Select all that apply.
A. DEFINER
B. SET
C. SQL SECURITY
D. DECLARE
DEFINER and SQL SECURITY characteristics are used to control the privileges of execution of a stored
object.
Lesson-End Project: Payroll Calculation
Problem statement:
You are a part of the HR department in a company, and you have been asked
to calculate the monthly payout for each employee based on their experience
and performance.
Objective:
The objective is to design a database to retrieve the detailed salary divisions
of each employee in the organization.
Tasks to be performed:
Tasks to be performed:
Note: Download the solution document from the Course Resources section
and follow the steps given in the document
Key Takeaways
IF and CASE are the two types of conditional statements that govern
the execution of a SQL query.