RDBMS Unit4
RDBMS Unit4
PL/SQL
Unit 4
Prepared by Shimi 1
Biju
Introduction
Prepared by Shimi 2
Biju
Disadvantages of SQL
Prepared by Shimi 3
Biju
Advantages of PL/SQL
PL/SQL is development tool that not only supports sql data manipulation but also provides
facilities of conditional checking, branching and looping.
Pl/SQL sends an entire block of sql statements to the oracle engine all in one go
It also permits dealing with the errors as required, and facilitates displaying user friendly
messages
It allows declaration and use of variables in blocks of code, which can store intermediate results
of query or to calculate values.
All sorts of calculations can be done quickly and efficiently without the use of oracle engine.
Application written in PL/SQL are portable to any computer hardware and operating system
where oracle is operational
Prepared by Shimi 4
Biju
PL/SQL Block
Prepared by Shimi 5
Biju
PL/SQL Block
Prepared by Shimi 6
Biju
Declare section
Prepared by Shimi 7
Biju
Begin Section
Prepared by Shimi 8
Biju
The Exception
section
This section deals with handling of errors that arise during
execution of the data manipulation statements which make up the
PL/SQL code block
Errors can arise due to syntax, logic and/or validation rule violation
Prepared by Shimi 9
Biju
End Section
Prepared by Shimi 10
Biju
PL/SQL - Basic Syntax
DECLARE
Declarations of memory variables, constants, cursors etc in PL/SQL
BEGIN
SQL executable statements
PL/SQL executable statements
EXCEPTION
SQL or PL/SQL code to handle errors that may arise during the execution of
the code block between Begin and Exception section
END;
Prepared by Shimi 11
Biju
PL/SQL Environment
Prepared by Shimi 12
Biju
PL/SQL Environment
Prepared by Shimi 13
Biju
PL/SQL The character set:
Prepared by Shimi 14
Biju
Literals
A literal is a numeric value or a character string used to represent itself
Numeric Literal
These can be either integers or floats
Eg. 25,6.34
String Literal
These are represented by one or more legal characters and must be enclosed
within single quotes.
Eg, ‘Hello World’
Character Literal
These are string literals consisting of single characters
Eg, ‘A’
Logical Literal
These are predetermined constants.
Eg, TRUE, FALSE, NULL
Prepared by Shimi 15
Biju
PL/SQL Data Types
number, char and date data types can have NULL values.
Prepared by Shimi 16
Biju
The %TYPE attribute
Prepared by Shimi 17
Biju
NOT NULL
Prepared by Shimi 18
Biju
Variables:
Prepared by Shimi 19
Biju
Assigning values to
variables
Using the assignment operator :=
Selecting or fetching table data values into variables
Prepared by Shimi 20
Biju
Constants:
Prepared by Shimi 21
Biju
Displaying user Message on the Screen
BEGIN
dbms_output.put_line(‘Welcome to Pl/SQL');
END;
Prepared by Shimi 22
Biju
Displaying user Messages on the Screen:
Prepared by Shimi 23
Biju
Comments:
Prepared by Shimi 24
Biju
PL/SQL Variables
DECLARE
a number := 10;
b number;
c char :='A';
str char(10) :='welcome';
pi constant number :=3.14;
BEGIN
dbms_output.put_line('Value of a is '||a);
b := 20;
dbms_output.put_line('Value of b is '||b);
dbms_output.put_line('Value of c is '||c);
dbms_output.put_line('Value of str is '||str);
dbms_output.put_line('Value of constant pi is '||pi);
END;
Prepared by Shimi 25
Biju
We can assign values to variables in the two ways
variable_name:= value;
2)We can assign values to variables directly from the database columns by
using a SELECT.. INTO statement. The General Syntax is:
SELECT column_name
INTO variable_name
FROM table_name
[WHERE condition];
Prepared by Shimi 26
Biju
DECLARE
var_salary number(6);
var_emp_id number(6) = 1116;
BEGIN
SELECT salary
INTO var_salary
FROM employee
WHERE emp_id = var_emp_id;
dbms_output.put_line(var_salary);
dbms_output.put_line('The employee ' || var_emp_id || ' has salary ' ||
var_salary);
END;
Prepared by Shimi 27
Biju
Scope of PS/SQL Variables
PL/SQL allows the nesting of Blocks within Blocks i.e, the Execution
section of an outer block can contain inner blocks.
Therefore, a variable which is accessible to an outer Block is also
accessible to all nested inner Blocks.
The variables declared in the inner blocks are not accessible to outer
blocks.
1> DECLARE
2> var_num1 number;
3> var_num2 number;
4>BEGIN
5> var_num1 := 100;
6> var_num2 := 200;
7> DECLARE
8> var_mult number;
9> BEGIN
10> var_mult :=
11> var_num1 *
var_num2;
12> END;
END;
Prepared by Shimi 29
Biju
General Syntax to declare a constant is:
constant_name CONSTANT datatype := VALUE;
constant_name is the name of the constant i.e. similar to a variable
name.
The word CONSTANT is a reserved word and ensures that the
value does not change.
VALUE - It is a value which must be assigned to a constant when it
is declared. You cannot assign a value later.
Prepared by Shimi 30
Biju
For example, to declare salary_increase, you can write code as follows:
DECLARE
salary_increase CONSTANT number (3) := 10;
You must assign a value to a constant at the time you declare it. If you do not assign a value to a
constant while declaring it and try to assign a value in the execution section, you will get a
error. If you execute the below Pl/SQL block you will get error.
DECLARE
salary_increase CONSTANT number(3);
BEGIN
salary_increase:= 100;
dbms_output.put_line (salary_increase);
END;
Prepared by Shimi 31
Biju
PL/SQL Datatypes
Prepared by Shimi 32
Biju
Different Data Types in PL/SQL
Prepared by Shimi 33
Biju
Numeric Data Types and Subtypes
Prepared by Shimi 34
Biju
Prepared by Shimi 35
Biju
NUMBER Data Type:
This data type stores fixed or floating point numbers up to 38 digits of precision.
This data type is used to work with fields which will contain only number data.
The variable can be declared either with precision and decimal digit details or
without this information.
Values need not enclose within quotes while assigning for this data type.
A NUMBER(8,2);
B NUMBER(8);
C NUMBER;
Syntax Explanation:
In the above, the first declaration declares the variable 'A' is of number data type
with total precision 8 and decimal digits 2.
The second declaration declares the variable 'B' is of number data type with total
precision 8 and no decimal digits.
The third declaration is the most generic, declares variable 'C' is of number data
type with no restriction in precision or decimal places. It can take up to a
maximum of 38 digits.
Prepared by Shimi Biju
36
CHARACTER Data Type:
Prepared by Shimi 37
Biju
CHAR
Prepared by Shimi 38
Biju
VARCHAR
2
Data Type Description Syntax
VARCHAR2 This data type stores the string, but manager VARCHAR2(10) : = ‘ o r a c l e ' ;
the length of the string is not fixed. Syntax Explanation:
Prepared by Shimi 40
Biju
NCHAR
Data Type Description Syntax
Prepared by Shimi 41
Biju
NVARCHAR2
Data Type Description Syntax
Prepared by Shimi 42
Biju
LONG and LONGRAW
Data Type Description Syntax
LONG and
This data type is used to store large Lar ge_text LONG;
LONGRAW
Large_raw LONG RAW;
text or raw data up to the maximum
Syntax Explanation:
size of 2GB.
These are mainly used in the data
dictionary. The above declaration
statement declares the
LONG data type is used to store
variable 'Large_text' of
character set data, while LONG LONG data type and
RAW is used to store data in binary 'Large_raw' of LONG RAW
should
Prepared by Shimi Biju
whereas LONG works only on data
BOOLEAN Data Type:
Var1 BOOLEAN;
Syntax Explanation:
In the above, variable 'Var1' is declared as BOOLEAN data type.
The output of the code will be either true or false based on the
condition set
Prepared by Shimi 44
Biju
DATE Data Type:
This data type stores the values in date format, as date, month, and year.
Whenever a variable is defined with DATE data type along with the date it can
hold time information and by default time information is set to 12:00:00 if not
specified. Values need to enclose within quotes while assigning for this data
type.
The standard Oracle time format for input and output is 'DD-MON-YY' and it is
again set at NLS_PARAMETERS (NLS_DATE_FORMAT) at the session level.
newyear DATE:='01-JAN-2015';
current_date DATE:=SYSDATE;
Syntax Explanation:
In the above, variable 'newyear' is declared as DATE data type and assigned the
value of Jan 1st, 2015 date.
The second declaration declares the variable current_date as DATE data type
and assigned the value with current system date.
Both these variable holds the time information.
Prepared by Shimi Biju
LOB Data Type:
This data type is mainly used to store and manipulate large blocks of unstructured
data's like images, multimedia files, etc.
Oracle prefers LOB instead of the a LONG data type as it is more flexible than the
LONG data type.
The below are the few main advantage of LOB over LONG data type.
The number of column in a table with LONG data type is limited to 1, whereas
a table has no restriction on a number of columns with LOB data type.
The data interface tool accepts LOB data type of the table during data
replication, but it omits LONG column of the table. These LONG columns need
to be replicated manually.
The size of the LONG column is 2GB, whereas LOB can store up to 128 TB.
Oracle is constantly improvising the LOB data type in each of their releases
according to the modern requirement, whereas LONG data type is constant and
not getting many updates.
Prepared by Shimi 46
Biju
Different LOB data types
Data Type Description Syntax
Binary_data BLOB;
BLOB This data type stores the LOB data in the binary file format up to Syntax Explanation:
the maximum size of 128 TB. This doesn't store data based on
the character set details, so that it can store the unstructured data In the above, variable 'Binary_data' is
such as multimedia objects, images, etc. declared as a BLOB.
Charac_data CLOB;
CLOB and CLOB data type stores the LOB data into the character set, Syntax Explanation:
NCLOB whereas NCLOB stores the data in the native character set. In the above, variable 'Charac_data' is
Since these data types use character set based storage, these declared as CLOB data type.
cannot store the data like multimedia, images, etc. that cannot be
put into a character string. The maximum size of these data
types is 128 TB.
BFILE BFILE are the data types that stored the unstructured binary
format data outside the database as an operating-system
file.
The size of BFILE is to a limited operating system, and they
are read-only files and can't be modified.
Prepared by Shimi 48
Biju
Arithmetic Operators
Following table shows all the arithmetic operators supported by
PL/SQL. Let us assume variable A holds 10 and variable B holds
5, then −
Operator Description Example
Checks if the values of two operands are equal or not, if (A = B) is not true.
=
yes then condition becomes true.
!=
Checks if the values of two operands are equal or not, if
<> (A != B) is true.
values
~= are not equal then condition becomes true.
Checks if the value of left operand is greater than the (A > B) is not true.
>
value of right operand, if yes then condition becomes
true.
Checks if the value of left operand is less than the (A < B) is true.
<
value of right operand, if yes then condition becomes
true.
Checks if the value of left operand is greater than or equal (A >= B) is not true.
>=
to the value of right operand, if yes then condition
becomes true.
Prepare Checks if the value of left operand is less than or equal to (A <= B) is true
d by Shimi<B =iju the value of right operand, if yes then condition 50
Exampl
DECLARE
e a number (2) := 21;
Prepared by Shimi 52
Biju
Comparison Operators
Comparison operators are used for comparing one expression to
another. The result is always either TRUE, FALSE or NULL.
Operator Description Example
The LIKE operator compares a character, string, or If 'Zara Ali' like 'Z% A_i' returns a
LIKE CLOB value to a pattern and returns TRUE if the Boolean true, whereas, 'Nuha Ali'
value matches the pattern and FALSE if it does like 'Z% A_i' returns a Boolean
not. false.
expression
A character expression such as a column or field.
pattern
A character expression that contains pattern matching. The patterns that you can
choose from are:
Prepared by Shimi 54
Biju
Wildcard Explanation
Allows you to match any string of
%
any length (including zero length)
Allows you to match on a
_
single character
escape_character
• Optional.
• It allows you to test for literal instances of a wildcard character such as % or _.
Prepared by Shimi 55
Biju
Example - Using % wildcard (percent sign
wildcard)
to find all of the customers whose last_name begins with 'Ap'.
SELECT last_name
FROM customers
WHERE last_name
LIKE 'Ap%';
SELECT last_name
Pr epar wFROM
ed bhy Sohim si eBijulast_name contains the
customers 56
Example - Using _ wildcard (underscore wildcard)
_ wildcard is looking for only one character.
Example
SELECT supplier_name
FROM suppliers
WHERE supplier_name
LIKE 'Sm_th';
This Oracle LIKE condition example would return all suppliers whose
supplier_name is 5 characters long, where the first two characters is 'Sm' and the last
two characters is 'th'. For example, it could return suppliers whose supplier_name is
'Smith', 'Smyth', 'Smath', 'Smeth', etc.
SELECT *
FROM suppliers
WHERE account_number
LIKE '92314_';
You might find that you are looking for an account number, but you only have 5 of
Using NOT Operator
For example:
SELECT supplier_name
FROM suppliers
WHERE supplier_name
NOT LIKE ‘T%';
By placing the NOT Operator in front of the Oracle LIKE condition, you
are able to retrieve all suppliers whose supplier_name does not start
with 'W'.
Prepared by Shimi 58
Biju
Using Escape Characters
Please note that you can only define an escape character as a single
character (length of 1).
Prepared by Shimi 59
Biju
example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'Water!%' ESCAPE '!';
This Oracle LIKE condition example identifies the ! character as an escape
character. This statement will return all suppliers whose name is Water%.
Here is another more complicated example using escape characters in the Oracle
LIKE condition.
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!%' ESCAPE '!';
This Oracle LIKE condition example returns all suppliers whose name starts
with H and ends in %. For example, it would return a value such as 'Hello%'.
Prepared by Shimi 60
Biju
The escape character with the _ character in the Oracle LIKE
condition.
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!_' ESCAPE '!';
This Oracle LIKE condition example returns all suppliers whose
name starts with H and ends in _. For example, it would return a
value such as 'Hello_'.
Prepared by Shimi 61
Biju
BETWEEN Operator
Prepared by Shimi 62
Biju
IN and IS NULL Operators
DECLARE
letter varchar2(1) := 'm';
BEGIN
IF (letter in ('a', 'b', 'c')) THEN
dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;
END
Prepared by Shimi 63
Biju
DECLARE
letter varchar2(1) := 'm';
BEGIN
IF (letter is null) THEN
dbms_output.put_line('True');
ELSE
dbms_output.put_line('False');
END IF;
END;
Prepared by Shimi 64
Biju
Logical Operators
Following table shows the Logical operators supported by PL/SQL.
All these operators work on Boolean operands and produce
Boolean results. Let us assume variable A holds true and variable
B holds false, then −
Operator Description Examples
Prepared by Shimi 67
Biju
Types of decision making statements
IF-THEN
IF-THEN-ELSE
IF-THEN-ELSIF
NESTED-IF
CASE
SEARCHED CASE
Prepared by Shimi 68
Biju
IF-THEN Statement
Prepared by Shimi 69
Biju
Syntax for IF THEN Statements:
Prepared by Shimi 70
Biju
Example 1: In this example, we are going to print a message when the number
is greater than 100. For that, we will execute the following code
To print a message when a number has value more than 100, we execute the
following code.
DECLARE
a NUMBER :=10;
BEGIN
dbms_output.put_line(‘Program started.' );
IF( a > 100 ) THEN
dbms_output.put_line('a is greater than 100');
END IF;
dbms_output.put_line(‘Program completed.');
END;
Prepared by Shimi 71
Biju
Example 2: In this example, we are going to print a message if a given
alphabet is present in English vowels (A, E, I, O, U).
To print a message when the given character is Vowel, we execute the
following code.
DECLARE
a CHAR(1) :=’u’;
BEGIN
IF UPPER(a) in ('A’,'E','I','0','U' ) THEN
dbms_output.put_line(‘The character is in English Vowels');
END IF;
END;
Prepared by Shimi 72
Biju
IF-THEN-ELSE Statement
Prepared by Shimi 73
Biju
In the above syntax, keyword 'IF' will be followed by a condition
which evaluates to 'TRUE'/'FALSE'.
The control will execute the <action_block1> only if the condition
returns <TRUE>.
In case of condition evaluates to <FALSE> then, SQL will execute
<action_block2>.
In any case, one of the two action blocks will be executed.
Prepared by Shimi 74
Biju
Example 1: In this example, we are going to print message whether the given
number is odd or even.
DECLARE
a NUMBER:=11;
BEGIN
dbms_outpu
t.put_line
(‘Program
started');
IF( mod(a,2)
=0) THEN
dbms_output.put_line('a is even number' );
ELSE
dbms_output.put_line('a is odd
number1);
END IF;
Prepared by Shimi 75
Biju
IF-THEN-ELSIF Statement
The IF-THEN-ELSIF statement allows you to choose between several alternatives. An IF-
THEN statement can be followed by an optional ELSIF...ELSEstatement. The ELSIF clause
lets you add additional conditions.
Syntax
The syntax of an IF-THEN-ELSIF Statement in PL/SQL programming language is −
IF(boolean_expression 1)THEN
S1; -- Executes when the boolean expression 1 is true
ELSIF( boolean_expression 2) THEN
S2; -- Executes when the boolean expression 2 is true
ELSIF( boolean_expression 3) THEN
S3; -- Executes when the boolean expression 3 is
true
ELSE
S4; -- executes when the none of the above condition is true
END IF;
Prepared by Shimi 76
Biju
Exampl
e
DECLARE
a number(3) := 100;
BEGIN
IF ( a = 10 )
THEN
dbms_output.pu
t_line('Value of a
is 10' );
ELSIF ( a = 20 )
THEN
dbms_output.pu
t_line('Value of a
is 20' );
ELSIF ( a = 30 )
THEN
dbms_output.put_line('Value of a is 30' ); 77
Nested IF-THEN-ELSE Statements
Prepared by Shimi 78
Biju
Exampl
e
DECLARE
a number(3) := 100;
b number(3) := 200;
BEGIN
-- check the boolean condition
IF( a = 100 ) THEN
-- if condition is true then check the following
IF( b = 200 ) THEN
-- if condition is true then print the following
dbms_output.put_line('Value of a is 100 and b is 200' );
END IF;
END IF;
dbms_output.put_line('Exact value of a is : ' || a );
dbms_output.put_line('Exact value of b is : ' || b );
END;
Prepared by Shimi 79
Biju
CASE Statement
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN
S3;
...
ELSE Sn; -- default case
END CASE;
Prepared by Shimi 80
Biju
Exampl
e
DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then
dbms_output.put_line('Excellent'); when 'B' then
dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well
done'); when 'D' then dbms_output.put_line('You
passed');
when 'F' then dbms_output.put_line('Better try
again'); else dbms_output.put_line('No such grade');
END CASE;
END;
Prepared by Shimi 81
Biju
Searched CASE Statement
The searched CASE statement has no selector and the WHEN clauses
of the statement contain search conditions that give Boolean values.
Syntax
The syntax for the searched case statement in PL/SQL is −
CASE
WHEN selector = 'value1' THEN S1;
WHEN selector = 'value2' THEN S2;
WHEN selector = 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;
Prepared by Shimi 82
Biju
Exampl
e
DECLARE
grade char(1) := 'B';
BEGIN
case
when grade = 'A' then
dbms_output.put_line('Excellent'); when grade = 'B' then
dbms_output.put_line('Very good');
when grade = 'C' then dbms_output.put_line('Well
done'); when grade = 'D' then dbms_output.put_line('You
passed');
when grade = 'F' then dbms_output.put_line('Better try
again'); else dbms_output.put_line('No such grade');
end case;
END;
Prepared by Shimi 83
Biju
Loops
A loop statement allows us to execute a statement or group of
statements multiple times
S.No Loop Type & Description
PL/SQL Basic LOOP
1 In this loop structure, sequence of statements is enclosed between the LOOP and
the END LOOP statements. At each iteration, the sequence of statements is
executed and then control resumes at the top of the loop.
Prepared by Shimi 84
Biju
Simple Loop
Prepared by Shimi 85
Biju
These are the important steps to be followed while using Simple
Loop.
1) Initialise a variable before the loop body.
2) Increment the variable in the loop.
3) Use a EXIT WHEN statement to exit from the Loop.
If you use a EXIT statement without WHEN condition, the
statements in the loop is executed only once.
Prepared by Shimi 86
Biju
Example of PL/SQL EXIT Loop
DECLARE
VAR1 NUMBER;
VAR2 NUMBER;
BEGIN
VAR1:=100;
VAR2:=1
; LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
IF (VAR2=10) THEN
EXIT;
END IF;
VAR2:=VAR2+
1;
END LOOP;
END; 88
While Loop
DECLARE
i INTEGER := 1;
BEGIN
WHILE i <= 10 LOOP
DBMS_OUTPUT.PUT_LINE(i);
i := i+1;
END LOOP;
END;
Prepared by Shimi 90
Biju
PL/SQL WHILE Loop Example 2
DECLARE
VAR1 NUMBER;
VAR2 NUMBER;
BEGIN
VAR1:=200;
VAR2:=1;
WHILE (VAR2<=10)
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
VAR2:=VAR2+1;
END LOOP;
END;
Prepared by Shimi 91
Biju
FOR Loop
Prepared by Shimi 93
Biju
PL/SQL For Loop Example 1
BEGIN
FOR k IN 1..10 LOOP
-- note that k was not declared
DBMS_OUTPUT.PUT_LINE(k)
; END LOOP;
END;
Prepared by Shimi 94
Biju
PL/SQL For Loop Example 2
DECLARE
VAR1 NUMBER;
BEGIN
VAR1:=10;
FOR VAR2 IN 1..10
LOOP
DBMS_OUTPUT.PUT_LINE (VAR1*VAR2);
END LOOP;
END;
Prepared by Shimi 95
Biju
PL/SQL For Loop REVERSE Example 3
Let's see an example of PL/SQL for loop where we are using REVERSE
keyword.
DECLARE
VAR1 NUMBER;
BEGIN
VAR1:=10;
FOR VAR2 IN
REVERSE 1..10
LOOP
DBMS_OUTPUT.
PUT_LINE
(VAR1*VAR2);
END LOOP;
Prepared by Shimi 96
END;
Biju
The Loop Control Statements
Prepared by Shimi 97
Biju
Loop Control Statements
S.No Control Statement & Description
EXIT statement
1
The Exit statement completes the loop and control passes to
the statement immediately after the END LOOP.
CONTINUE statement
GOTO statement
Prepared by Shimi 98
Biju
Sequential control
GOTO label;
..
..
<< label >>
statement;
Prepared by Shimi 99
Biju
Exampl
e
DECLARE
a number(2) := 10;
BEGIN
<<loopstart>>
-- while loop execution
WHILE a < 20 LOOP
dbms_output.put_line ('value of a: ' || a);
a := a + 1;
IF a = 15 THEN
a := a + 1;
GOTO loopstart;
END IF;
END LOOP;
END;