1. Database Management System (DBMS)
Sanjivani Rural Education Society’s
Sanjivani College of Engineering, Kopargaon-423603
(An Autonomous Institute Affiliated to Savitribai Phule Pune University, Pune)
NACC ‘A’ Grade Accredited, ISO 9001:2015 Certified
Department of Information Technology
(NBAAccredited)
Mr. R. N. Kankrale
Assistant Professor
SY IT
2. Introduction to PL/SQL
• PL/SQL is Procedural Language for SQL. It is designed by Oracle
Corporation in the early 90's to enhance SQL. It is combination of SQL
along with the procedural features wherein it is easy to both read and
write. PL/SQL is high performing transaction-processing language,
which is completely portable. It dispenses a built-in, interpreted and
OS independent programming environment. User can directly call to
database from external programming language calls. PL/SQL
incoporates procedural language elements such as loops and
conditions. It can manage run-time error and allows declaration of
constants and variables, procedures and functions, types and
variables. In this, all the statements of a block are moved to oracle
engine at once which decreases the traffic and increases processing
speed.
DBMS – Unit-III PL/SQL Department of Information Technology
3. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL in MySQL – Explanation and Alternative Approach
Does MySQL Support PL/SQL?
No, PL/SQL (Procedural Language/SQL) is specifically used in Oracle Database.
MySQL does not support PL/SQL, but it has a similar feature called Procedural
SQL (PSM - Persistent Stored Modules), which includes:
✅ Stored Procedures
✅ Functions
✅ Triggers
✅ Cursors
✅ Exception Handling
In MySQL, we use stored procedures and begin-end blocks to implement
procedural programming, similar to PL/SQL.
4. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL (Oracle) MySQL Equivalent
BEGIN ... END; BEGIN ... END;
EXCEPTION DECLARE HANDLER
LOOP LOOP ... END LOOP;
CURSOR CURSOR
IF-THEN-ELSE IF-THEN-ELSE
RAISE SIGNAL SQLSTATE
7. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
SQL PL/SQL
SQL is a single query that is used to perform DML
and DDL operations.
PL/SQL is a block of codes that used to write the
entire program blocks/ procedure/ function, etc.
It is declarative, that defines what needs to be
done, rather than how things need to be done.
PL/SQL is procedural that defines how the things
needs to be done.
Execute as a single statement. Execute as a whole block.
Mainly used to manipulate data. Mainly used to create an application.
Cannot contain PL/SQL code in it.
It is an extension of SQL, so it can contain SQL
inside it.
8. Structure of PL/SQL Block
• Structure of PL/SQL Block: PL/SQL extends SQL by adding constructs found in
procedural languages, resulting in a structural language that is more powerful
than SQL. The basic unit in PL/SQL is a block. All PL/SQL programs are made up
of blocks, which can be nested within each other.
DBMS – Unit-III PL/SQL Department of Information Technology
9. Introduction to PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
DECLARE
declaration statements;
BEGIN
executable statements
EXCEPTIONS
exception handling statements
END;
10. Structure of PL/SQL Block
• DECLARE
• declaration statements;
• BEGIN
• executable statements
• EXCEPTIONS
• exception handling statements
• END;
DBMS – Unit-III PL/SQL Department of Information Technology
11. Structure of PL/SQL Block
• Declare section starts with DECLARE keyword in which variables, constants,
records as cursors can be declared which stores data temporarily. It basically
consists definition of PL/SQL identifiers. This part of the code is optional.
• Execution section starts with BEGIN and ends with END keyword. This is a
mandatory section and here the program logic is written to perform any task like
loops and conditional statements. It supports all DML commands, DDL
commands and SQL*PLUS built-in functions as well.
• Exception section starts with EXCEPTION keyword. This section is optional which
contains statements that are executed when a run-time error occurs. Any
exceptions can be handled in this section.
DBMS – Unit-III PL/SQL Department of Information Technology
12. PL/SQL Variables
• Following is the syntax for declaring variable:
• variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
• Here, variable_name is a valid identifier in PL/SQL and datatype must be valid
PL/SQL data type. A data type with size, scale or precision limit is called a
constrained declaration. The constrained declaration needs less memory than
unconstrained declaration.
• Example:
• Radius Number := 5;
• Date_of_birth date;
DBMS – Unit-III PL/SQL Department of Information Technology
13. PL/SQL Variables
• SQL> SET SERVEROUTPUT ON;
• SQL> DECLARE
• var1 INTEGER;
• var2 REAL;
• var3 varchar2(20) ;
• BEGIN
• null;
• END;
• /
• Output:
• PL/SQL procedure successfully completed.
DBMS – Unit-III PL/SQL Department of Information Technology
14. PL/SQL Variables
• Displaying Output: The outputs are displayed by using DBMS_OUTPUT which is a built-in package
that enables the user to display output, debugging information, and send messages from PL/SQL
blocks, subprograms, packages, and triggers. Let us see an example to see how to display a
message using PL/SQL :
• SQL> SET SERVEROUTPUT ON;
• SQL> DECLARE
• var varchar2(40) := 'GeeksForGeeks' ;
• BEGIN
• dbms_output.put_line(var);
• END;
• /
• Output:
• GeeksForGeeks
• PL/SQL procedure successfully completed.
DBMS – Unit-III PL/SQL Department of Information Technology
15. PL/SQL Variables
• --PL/SQL code to print sum of two numbers taken from the user.
• SQL> SET SERVEROUTPUT ON;
• SQL> DECLARE
• -- taking input for variable a
• a integer := &a ;
• -- taking input for variable b
• b integer := &b ;
• c integer ;
• BEGIN
• c := a + b ;
• dbms_output.put_line('Sum of '||a||' and '||b||' is = '||c);
• END;
• /
DBMS – Unit-III PL/SQL Department of Information Technology
16. PL/SQL Variables
• Enter value for a: 2
• Enter value for b: 3
• Sum of 2 and 3 is = 5
• PL/SQL procedure successfully completed.
DBMS – Unit-III PL/SQL Department of Information Technology
17. Decision Making in PL/SQL
• (if-then , if-then-else, Nested if-then, if-then-elsif-then-else )
Improve
• declare
• -- declare the values here
• begin
• if condition then
• dbms_output.put_line('output');
• end if;
• dbms_output.put_line('output2');
• end;
DBMS – Unit-III PL/SQL Department of Information Technology
18. Decision Making in PL/SQL
-- pl/sql program to illustrate If statement
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 > num2 then
dbms_output.put_line('num1 small');
end if;
dbms_output.put_line('I am Not in if');
end;
DBMS – Unit-III PL/SQL Department of Information Technology
19. Decision Making in PL/SQL
-- pl/sql program to illustrate If else statement
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 < num2 then
dbms_output.put_line('i am in if block');
ELSE
dbms_output.put_line('i am in else Block');
end if;
dbms_output.put_line('i am not in if or else Block');
end;
DBMS – Unit-III PL/SQL Department of Information Technology
20. Decision Making in PL/SQL
Output:-
i'm in if Block
i'm not in if and not in else Block
DBMS – Unit-III PL/SQL Department of Information Technology
21. Decision Making in PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
22. DBMS – Unit-III PL/SQL Department of Information Technology
-- pl/sql program to illustrate nested If statement
declare
num1 number:= 10;
num2 number:= 20;
num3 number:= 20;
begin
if num1 < num2 then
dbms_output.put_line('num1 small num2');
if num1 < num3 then
dbms_output.put_line('num1 small num3 also');
end if;
end if;
dbms_output.put_line('after end if');
end;
Decision Making in PL/SQL
23. Decision Making in PL/SQL
DBMS – Unit-III PL/SQL Department of Information Technology
if-then-
elsif-
then-
else
ladder
24. DBMS – Unit-III PL/SQL Department of Information Technology
if-then-elsif-then-else ladder
-- pl/sql program to illustrate if-then-elif-then-else ladder
declare
num1 number:= 10;
num2 number:= 20;
begin
if num1 < num2 then
dbms_output.put_line('num1 small');
ELSEIF num1 = num2 then
dbms_output.put_line('both equal');
ELSE
dbms_output.put_line('num2 greater');
end if;
dbms_output.put_line('after end if');
end;
25. PL/SQL Case Statement
DBMS – Unit-III PL/SQL Department of Information Technology
• The PL/SQL CASE statement facilitates you to execute a sequence of statements
based on a selector. A selector can be anything such as variable, function or an
expression that the CASE statement checks to a boolean value.
• The CASE statement works like the IF statement, only using the keyword WHEN. A
CASE statement is evaluated from top to bottom. If it get the condition TRUE, then
the corresponding THEN clause is executed and the execution goes to the END CASE
clause.
26. PL/SQL Case Statement
DBMS – Unit-III PL/SQL Department of Information Technology
Syntax for the CASE Statement:
1.CASE [ expression ]
2.WHEN condition_1 THEN result_1
3. WHEN condition_2 THEN result_2
4. ...
5. WHEN condition_n THEN result_n
6. ELSE result
7.END
27. Example of PL/SQL case statement
DBMS – Unit-III PL/SQL Department of Information Technology
1.DECLARE
2. grade char(1) := 'A';
3.BEGIN
4. CASE grade
5. when 'A' then dbms_output.put_line('Excellent');
6. when 'B' then dbms_output.put_line('Very good');
7. when 'C' then dbms_output.put_line('Good');
8. when 'D' then dbms_output.put_line('Average');
9. when 'F' then dbms_output.put_line('Passed with Grace')
;
10. else dbms_output.put_line('Failed');
11. END CASE;
12.END;
28. Example of PL/SQL case statement
DBMS – Unit-III PL/SQL Department of Information Technology
1.After the execution of above code, you will get the
following result:
Excellent
PL/SQL procedure successfully completed.
29. PL/SQL Loop
DBMS – Unit-III PL/SQL Department of Information Technology
1.The PL/SQL loops are used to repeat the execution of one or more statements for
specified number of times. These are also known as iterative control statements.
Syntax for a basic loop:
2.LOOP
3. Sequence of statements;
4.END LOOP;
Types of PL/SQL Loops
There are 4 types of PL/SQL Loops.
5.Basic Loop / Exit Loop
6.While Loop
7.For Loop
8.Cursor For Loop
30. PL/SQL Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL Exit Loop (Basic Loop)
PL/SQL exit loop is used when a set of statements is to be executed at least
once before the termination of the loop. There must be an EXIT condition
specified in the loop, otherwise the loop will get into an infinite number of
iterations. After the occurrence of EXIT condition, the process exits the loop.
Syntax of basic loop:
1.LOOP
2. Sequence of statements;
3.END LOOP;
31. PL/SQL Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Syntax of exit loop:
1.LOOP
2. statements;
3. EXIT;
4. {or EXIT WHEN condition;}
5.END LOOP;
32. Example of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
1.DECLARE
2.i NUMBER := 1;
3.BEGIN
4.LOOP
5.EXIT WHEN i>10;
6.DBMS_OUTPUT.PUT_LINE(i);
7.i := i+1;
8.END LOOP;
9.END;
33. Example of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
After the execution of the above code, you will get the following result:
1
2
3
4
5
6
7
8
9
10
34. Example of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Note: You must follow these steps while using PL/SQL Exit Loop.
• Initialize a variable before the loop body
• Increment the variable in the loop.
• You should use EXIT WHEN statement to exit from the Loop.
Otherwise the EXIT statement without WHEN condition, the
statements in the Loop is executed only once.
35. Example 2 of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
1.DECLARE
2.VAR1 NUMBER;
3.VAR2 NUMBER;
4.BEGIN
5.VAR1:=100;
6.VAR2:=1;
7.LOOP
8.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
9.IF (VAR2=10) THEN
10.EXIT;
11.END IF;
12.VAR2:=VAR2+1;
13.END LOOP;
14.END;
36. Example 2 of PL/SQL EXIT Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Output:
100
200
300
400
500
600
700
800
900
1000
37. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL while loop is used when a set of statements has to be executed as long as a
condition is true, the While loop is used. The condition is decided at the beginning of
each iteration and continues until the condition becomes false.
Syntax of while loop:
1.WHILE <condition>
2. LOOP statements;
3.END LOOP;
38. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Example of PL/SQL While Loop
Let's see a simple example of PL/SQL WHILE loop.
1.DECLARE
2.i INTEGER := 1;
3.BEGIN
4.WHILE i <= 10 LOOP
5.DBMS_OUTPUT.PUT_LINE(i);
6.i := i+1;
7.END LOOP;
8.END;
39. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
After the execution of the above code, you will get the following
result:
1
2
3
4
5
6
7
8
9
10
40. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL WHILE Loop Example 2
1.DECLARE
2.VAR1 NUMBER;
3.VAR2 NUMBER;
4.BEGIN
5.VAR1:=200;
6.VAR2:=1;
7.WHILE (VAR2<=10)
8.LOOP
9.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
10.VAR2:=VAR2+1;
11.END LOOP;
12.END;
41. PL/SQL While Loop
DBMS – Unit-III PL/SQL Department of Information Technology
Output:
200
400
600
800
1000
1200
1400
1600
1800
2000
42. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL FOR Loop
PL/SQL for loop is used when you want to execute a set of
statements for a predetermined number of times. The loop is
iterated between the start and end integer values. The counter is
always incremented by 1 and once the counter reaches the value
of end integer, the loop ends.
Syntax of for loop:
1.FOR counter IN initial_value .. final_value LOOP
2. LOOP statements;
3.END LOOP;
43. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL For Loop Example 1
Let's see a simple example of PL/SQL FOR loop.
1.BEGIN
2.FOR k IN 1..10 LOOP
3.-- note that k was not declared
4.DBMS_OUTPUT.PUT_LINE(k);
5.END LOOP;
6.END;
44. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL For Loop Example 2
1.DECLARE
2.VAR1 NUMBER;
3.BEGIN
4.VAR1:=10;
5.FOR VAR2 IN 1..10
6.LOOP
7.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8.END LOOP;
9.END;
45. PL/SQL FOR Loop
DBMS – Unit-III PL/SQL Department of Information Technology
PL/SQL For Loop REVERSE Example 3
Let's see an example of PL/SQL for loop where we are using REVERSE
keyword.
1.DECLARE
2.VAR1 NUMBER;
3.BEGIN
4.VAR1:=10;
5.FOR VAR2 IN REVERSE 10..1
6.LOOP
7.DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
8.END LOOP;
9.END;
46. PL/SQL Procedure
DBMS – Unit-III PL/SQL Department of Information Technology
The PL/SQL stored procedure or simply a procedure is a PL/SQL
block which performs one or more specific tasks. It is just like
procedures in other programming languages.
The procedure contains a header and a body.
• Header: The header contains the name of the procedure and
the parameters or variables passed to the procedure.
• Body: The body contains a declaration section, execution
section and exception section similar to a general PL/SQL block.
47. PL/SQL Procedure
DBMS – Unit-III PL/SQL Department of Information Technology
DELIMITER $$
CREATE PROCEDURE GetCustomers()
BEGIN
SELECT
customerName,
city,
state,
postalCode,
country
FROM
customers
ORDER BY customerName;
END$$
DELIMITER ;
48. PL/SQL Procedure
DBMS – Unit-III PL/SQL Department of Information Technology
After saving the stored procedure, you can invoke it by using the CALL
statement:
CALL GetCustomers();
49. MySQL stored procedure parameters
DBMS – Unit-III PL/SQL Department of Information Technology
A parameter in a stored procedure has one of three modes: IN, OUT, or INOUT.
IN parameters
IN is the default mode. When defining an IN parameter in a stored procedure, the calling
program must pass an argument to the stored procedure.
Additionally, the value of an IN parameter is protected. This means that even if you
change the value of the IN parameter inside the stored procedure, its original value
remains unchanged after the stored procedure ends. In other words, the stored procedure
works only on the copy of the IN parameter.
50. MySQL stored procedure parameters
DBMS – Unit-III PL/SQL Department of Information Technology
OUT parameters
The value of an OUT parameter can be modified within the stored
procedure, and its updated value is then passed back to the calling
program.
INOUT parameters
An INOUT parameter is a combination of IN and OUT parameters. This
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.
Defining a parameter
Here is the basic syntax for defining a parameter in stored procedures:
[IN | OUT | INOUT] parameter_name datatype[(length)]
51. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The IN parameter example
The following example creates a stored procedure that finds all offices that are located in a country
specified by the input parameter countryName:
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(255))
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //
DELIMITER ;
52. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
office_id office_name city country phone
1 Head Office New York USA +1-212-555-1234
2 Branch Office Los Angeles USA +1-310-555-5678
3 European HQ London UK +44-20-555-7890
4 Asia Pacific Office Tokyo Japan +81-3-555-6789
5 South America Office São Paulo Brazil +55-11-555-4321
offices
53. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The IN parameter example
The following example creates a stored procedure that finds all offices that are located in a country
specified by the input parameter countryName:
DELIMITER //
CREATE PROCEDURE GetOfficeByCountry(IN countryName VARCHAR(255))
BEGIN
SELECT *
FROM offices
WHERE country = countryName;
END //
DELIMITER ;
CALL GetOfficeByCountry('France’);
CALL GetOfficeByCountry('USA');
54. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The IN parameter example
Because the countryName is the IN parameter, you must pass an argument. If you don’t do so, you’ll get an
error:
CALL GetOfficeByCountry();
Error Code: 1318. Incorrect number of arguments for PROCEDURE
classicmodels.GetOfficeByCountry; expected 1, got 0
55. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The OUT-parameter example
The following defines a stored procedure that returns the number of orders based on their order status.
DELIMITER $$
CREATE PROCEDURE GetOrderCountByStatus (IN orderStatus VARCHAR(25),OUT total INT)
BEGIN
SELECT COUNT(orderNumber)
INTO total
FROM orders
WHERE status = orderStatus;
END$$
DELIMITER ;
56. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The stored procedure GetOrderCountByStatus() has two parameters:
The orderStatus is the IN parameter specifies the status of orders to return.
The total is the OUT parameter that stores the number of orders in a specific status.
To find the number of orders that already shipped, you call GetOrderCountByStatus and pass the order status
as of Shipped, and also pass a session variable ( @total ) to receive the return value.
CALL GetOrderCountByStatus('Shipped',@total);
SELECT @total;
+--------+
| @total |
+--------+
| 303 |
+--------+
1 row in set (0.00 sec)
57. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
CALL GetOrderCountByStatus('In Process',@total);
SELECT @total AS total_in_process;
+------------------+
| total_in_process |
+------------------+
| 6 |
+------------------+
1 row in set (0.00 sec)
58. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The INOUT parameter example
The following example demonstrates how to use an INOUT parameter in a stored
procedure:
DELIMITER $$
CREATE PROCEDURE SetCounter(INOUT counter INT,IN inc INT)
BEGIN
SET counter = counter + inc;
END$$
DELIMITER ;
In this example, the stored procedure SetCounter() accepts one INOUT
parameter ( counter ) and one IN parameter ( inc ). It increases the counter
( counter ) by the value specified by the inc parameter.
59. MySQL stored procedure parameter examples
DBMS – Unit-III PL/SQL Department of Information Technology
The INOUT parameter example
These statements illustrate how to call the SetSounter stored procedure:
SET @counter = 1;
CALL SetCounter(@counter,1); -- 2
CALL SetCounter(@counter,1); -- 3
CALL SetCounter(@counter,5); -- 8
SELECT @counter; -- 8
Code language: SQL (Structured Query Language) (sql)
Here is the output:
61. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
In MySQL, a cursor is a database object used for iterating the result of a SELECT
statement.
Typically, you use cursors within stored procedures, triggers, and functions where you
need to process individual rows returned by a query one at a time.
Here’s the basic syntax of a cursor:
-- declare a cursor
DECLARE cursor_name CURSOR FOR
SELECT column1, column2
FROM your_table
WHERE your_condition;
62. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- open the cursor
OPEN cursor_name;
FETCH cursor_name INTO variable1, variable2;
-- process the data
-- close the cursor
CLOSE cursor_name;
63. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
When working with MySQL cursor, you must also declare a NOT FOUND handler to
manage the situation when the cursor cannot find any row.
Each time you call the FETCH statement; the cursor attempts to read the next row
in the result set. When the cursor reaches the end of the result set, it will not be
able to retrieve the data, and a condition is raised. The handler is used to handle
this condition.
To declare a NOT FOUND handler, you use the following syntax:
DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;
The finished is a variable to indicate that the cursor has reached the end of the
result set.
Notice that the handler declaration must appear after the variable and cursor
declarations within the stored procedures.
64. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
MySQL Cursor Example
We’ll develop a stored procedure that creates an email list of all employees in the
employees table in the sample database:
65. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
DELIMITER $$
CREATE PROCEDURE create_email_list (INOUT email_list TEXT)
BEGIN
DECLARE done BOOL DEFAULT false;
DECLARE email_address VARCHAR(100) DEFAULT "";
-- declare cursor for employee email
DECLARE cur CURSOR FOR SELECT email FROM employees;
66. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;
-- open the cursor
OPEN cur;
67. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
SET email_list = ‘ ';
process_email: LOOP
FETCH cur INTO email_address;
IF done = true THEN
LEAVE process_email;
END IF;
SET email_list = CONCAT(email_address,";",email_list);
END LOOP;
CLOSE cur;
END$$
DELIMITER ;
68. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
Example: Using a Cursor in MySQL
• We will create a stored procedure that loops through employees and calculates a
bonus for each employee.
• Step 1: Create an employees Table
• CREATE TABLE employees ( emp_id INT PRIMARY KEY, emp_name
VARCHAR(100), salary DECIMAL(10,2));
• INSERT INTO employees (emp_id, emp_name, salary) VALUES
• (1, 'John Doe', 5000.00),
• (2, 'Jane Smith', 6000.00),
• (3, 'Robert Brown', 4500.00);
69. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
DELIMITER //
CREATE PROCEDURE CalculateBonus()
BEGIN
-- Declare variables
DECLARE done INT DEFAULT 0;
DECLARE empId INT;
DECLARE empName VARCHAR(100);
DECLARE empSalary DECIMAL(10,2);
DECLARE empBonus DECIMAL(10,2);
--
70. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- Declare a cursor to fetch employee records
DECLARE emp_cursor CURSOR FOR
SELECT emp_id, emp_name, salary FROM employees;
-- Declare a handler for end of cursor
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
-- Open the cursor
OPEN emp_cursor;
71. DBMS – Unit-III PL/SQL Department of Information Technology
-- Loop through the records
read_loop: LOOP
FETCH emp_cursor INTO empId, empName, empSalary;
-- Exit loop if no more records
IF done THEN
LEAVE read_loop;
END IF;
-- Calculate a 10% bonus
SET empBonus = empSalary * 0.10;
72. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
-- Print employee bonus (in real case, we can insert into another table)
SELECT CONCAT(empName, ' gets a bonus of $', empBonus) AS BonusInfo;
END LOOP;
-- Close the cursor
CLOSE emp_cursor;
END //
DELIMITER ;
73. MySQL Cursor
DBMS – Unit-III PL/SQL Department of Information Technology
Step 4: Call the Procedure
CALL CalculateBonus();
Expected Output:
BonusInfo
--------------------------
John Doe gets a bonus of $500.00
Jane Smith gets a bonus of $600.00
Robert Brown gets a bonus of $450.00
74. MySQL Triggers
DBMS – Unit-III PL/SQL Department of Information Technology
In MySQL, a trigger is a stored program invoked automatically in response to
an event such as insert, update, or delete that occurs in the associated table.
For example, you can define a trigger that is invoked automatically before a
new row is inserted into a table.
75. MySQL Triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• The SQL standard defines two types of triggers: row-level triggers and
statement-level triggers.
• A row-level trigger is activated for each row that is inserted, updated, or
deleted. For example, if a table has 100 rows inserted, updated, or deleted, the
trigger is automatically invoked 100 times for the 100 rows affected.
• A statement-level trigger is executed once for each transaction regardless of
how many rows are inserted, updated, or deleted.
76. MySQL Triggers
DBMS – Unit-III PL/SQL Department of Information Technology
MySQL supports only row-level triggers. It doesn’t support statement-
level triggers.
77. Advantages of triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• Triggers provide another way to check the integrity of data.
• Triggers handle errors from the database layer.
• Triggers give an alternative way to run scheduled tasks. By using triggers, you
don’t have to wait for the scheduled events to run because the triggers are
invoked automatically before or after a change is made to the data in a table.
• Triggers can be useful for auditing the data changes in tables.
78. Disadvantages of triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• Triggers can only provide extended validations, not all validations. For simple
validations, you can use the NOT NULL, UNIQUE, CHECK and FOREIGN KEY
constraints.
• Triggers can be difficult to troubleshoot because they execute automatically in the
database, which may not be visible to the client applications.
• Triggers may increase the overhead of the MySQL server.
79. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
• Introduction to MySQL SHOW TRIGGER statement
• The SHOW TRIGGERS statement list triggers defined for tables in the current database.
The following illustrates the basic syntax of the SHOW TRIGGERS statement:
SHOW TRIGGERS
[{FROM | IN} database_name]
[LIKE 'pattern' | WHERE search_condition];
80. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
In this syntax, if you don’t use the last two clauses, the SHOW TRIGGERS returns all
triggers in all databases:
SHOW TRIGGERS;
To show all triggers in a specific database, you specify the database name after
the FROM or IN keyword like this:
SHOW TRIGGERS
FROM database_name;
or
SHOW TRIGGERS
IN database_name;
81. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
To list triggers according to a pattern, you use the LIKE clause:
SHOW TRIGGERS
LIKE 'pattern';
Code language: SQL (Structured Query Language) (sql)
or
SHOW TRIGGERS
FROM database_name
LIKE 'pattern';
82. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
To find triggers that match a condition, you use the WHERE clause:
SHOW TRIGGERS
WHERE search_condition;
Code language: SQL (Structured Query Language) (sql)
or
SHOW TRIGGERS
FROM database_name
WHERE search_condition;
83. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
The SHOW TRIGGERS statement returns a result set that includes the following columns:
trigger: the name of the trigger
event: the event that invokes the trigger e.g., INSERT, UPDATE, or DELETE.
table: the table to which the trigger belongs.
statement: the body of the trigger.
timing: the activation time of the trigger, either BEFORE or AFTER.
created: the created time of the trigger.
sql_mode: the SQL_MODE when the trigger executes.
definer: the user account that created the trigger.
character_set_client
collation_connection
database collation
84. Managing MySQL triggers
DBMS – Unit-III PL/SQL Department of Information Technology
MySQL SHOW TRIGGER statement examples
SHOW TRIGGERS;
Code language: SQL (Structured Query Language) (sql)
The following example shows all triggers in the classicmodels database:
SHOW TRIGGERS
FROM classicmodels;
Code language: SQL (Structured Query Language) (sql)
The following statement list all the triggers associated with the employees table:
SHOW TRIGGERS
FROM classicmodels
WHERE table = 'employees';
85. Introduction to MySQL CREATE TRIGGER statement
DBMS – Unit-III PL/SQL Department of Information Technology
The CREATE TRIGGER statement allows you to create a new trigger
associated with a table.
CREATE TRIGGER trigger_name
{BEFORE | AFTER} {INSERT | UPDATE | DELETE}
ON table_name
FOR EACH ROW
BEGIN
-- Trigger body (SQL statements)
END;
86. Introduction to MySQL CREATE TRIGGER statement
DBMS – Unit-III PL/SQL Department of Information Technology
In this syntax:
• trigger_name: Name of the trigger.
• BEFORE or AFTER: Specifies when the trigger should be executed.
• INSERT, UPDATE, or DELETE: Specifies the type of operation that activates the
trigger.
• table_name: Name of the table on which the trigger is defined.
• FOR EACH ROW: Indicates that the trigger should be executed once for each
row affected by the triggering event.
• BEGIN and END: Delimit the trigger body, where you define the SQL statements
to be executed.
87. Introduction to MySQL CREATE TRIGGER statement
DBMS – Unit-III PL/SQL Department of Information Technology
The trigger body can access the values of the column being affected by the operation.
To distinguish between the value of the columns BEFORE and AFTER the event has fired,
you use the NEW and OLD modifiers. For example, if you update the value in the
description column, in the trigger body, you can access the value of the description column
before the update OLD.description and the new value NEW.description.
The following table illustrates the availability of the OLD and NEW modifiers:
Trigger Event OLD NEW
INSERT No Yes
UPDATE Yes Yes
DELETE Yes No
88. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
First, create a new table called items:
CREATE TABLE items (
id INT PRIMARY KEY,
name VARCHAR(255) NOT NULL,
price DECIMAL(10, 2) NOT NULL
);
Second, insert a row into the items table:
INSERT INTO items(id, name, price)
VALUES (1, 'Item', 50.00);
89. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
Third, create the item_changes table to store the changes made to the data in the
items table:
CREATE TABLE item_changes (
change_id INT PRIMARY KEY AUTO_INCREMENT,
item_id INT,
change_type VARCHAR(10),
change_timestamp TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (item_id) REFERENCES items(id)
);
90. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
Fourth, create a trigger called update_items_trigger associated with the items table:
DELIMITER //
CREATE TRIGGER update_items_trigger
AFTER UPDATE
ON items
FOR EACH ROW
BEGIN
INSERT INTO item_changes (item_id, change_type)
VALUES (NEW.id, 'UPDATE');
END;
//
DELIMITER ;
91. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
In this example:
The trigger is named update_items_trigger.
It is set to execute AFTER UPDATE on the items table.
The trigger body inserts a record into the item_changes table with the item_id and
change_type.
Now, whenever you update a row in the items table, the trigger will run to add the
corresponding record to the item_changes table.
Fifth, update a row in the items table:
UPDATE items
SET price = 60.00
WHERE id = 1;
92. MySQL trigger example
DBMS – Unit-III PL/SQL Department of Information Technology
Finally, retrieve data from the item_changes table to see the logged changes:
SELECT * FROM item_changes;
Output:
+-----------+---------+-------------+---------------------+
| change_id | item_id | change_type | change_timestamp |
+-----------+---------+-------------+---------------------+
| 1 | 1 | UPDATE | 2023-12-27 18:21:43 |
+-----------+---------+-------------+---------------------+
1 row in set (0.01 sec)