Pl SQL Notes
Pl SQL Notes
com/
https://www.guru99.com/
What Is PL/SQL?
PL SQL basically stands for "Procedural Language extensions to SQL". This is
the extension of Structured Query Language (SQL) that is used in Oracle. Unlike
SQL, PL/SQL allows the programmer to write code in procedural format.
It combines the data manipulation power of SQL with the processing power of
procedural language to create a super powerful SQL queries.
It allows the programmers to instruct the compiler 'what to do' through SQL and
'how to do' through its procedural way.
Similar to other database languages, it gives more control to the programmers by
the use of loops, conditions and object oriented concepts.
Architecture of PL/SQL
The PL/SQL architecture mainly consists of following 3 components:
1. PL/SQL block
2. PL/SQL Engine
3. Database Server
PL/SQL block:
This is the component which has the actual PL/SQL code.
This consists of different sections to divide the code logically (declarative
section for declaring purpose, execution section for processing statements,
exception handling section for handling errors)
It also contains the SQL instruction that used to interact with the database
server.
All the PL/SQL units are treated as PL/SQL blocks, and this is the starting
stage of the architecture which serves as the primary input.
Following are the different type of PL/SQL units.
Anonymous Block
Function
Library
Procedure
Package Body
Package Specification
Trigger
Type
Type Body
PL/SQL Engine
PL/SQL engine is the component where the actual processing of the codes
takes place.
PL/SQL engine separates PL/SQL units and SQL part in the input (as
shown in the image below).
The separated PL/SQL units will be handled with the PL/SQL engine itself.
The SQL part will be sent to database server where the actual interaction
with database takes place.
It can be installed in both database server and in the application server.
Database Server:
This is the most important component of Pl/SQL unit which stores the data.
The PL/SQL engine uses the SQL from PL/SQL units to interact with the
database server.
It consists of SQL executor which actually parses the input SQL
statements and execute the same.
needs to be done.
inside it.
1. Declaration section
2. Execution section
3. Exception-Handling section
The below picture illustrates the different PL/SQL block and their section order.
Declaration Section
This is the first section of the PL/SQL blocks. This section is an optional part. This
is the section in which the declaration of variables, cursors, exceptions,
subprograms, pragma instructions and collections that are needed in the block
will be declared. Below are few more characteristics of this part.
Execution Section
Execution part is the main and mandatory part which actually executes the code
that is written inside it. Since the PL/SQL expects the executable statements from
this block this cannot be an empty block, i.e., it should have at least one valid
executable code line in it. Below are few more characteristics of this part.
Exception-Handling Section:
The exception are unavoidable in the program which occurs at run-time and to
handle this Oracle has provided an Exception-handling section in blocks. This
section can also contain PL/SQL statements. This is an optional section of the
PL/SQL blocks.
This is the section where the exception raised in the execution block is
handled.
This section is the last part of the PL/SQL block.
Control from this section can never return to the execution block.
This section starts with the keyword 'EXCEPTION'.
This section should be always followed by the keyword 'END'.
The Keyword 'END' marks the end of PL/SQL block. Below is the syntax of the
PL/SQL block structure.
Note: A block should be always followed by '/' which sends the information to the
compiler about the end of the block.
Types of PL/SQL block
PL/SQL blocks are of mainly two types.
1. Anonymous blocks
2. Named Blocks
Anonymous blocks:
Anonymous blocks are PL/SQL blocks which do not have any names assigned to
them. They need to be created and used in the same session because they will
not be stored in the server as a database objects.
Since they need not to store in the database, they need no compilation steps.
They are written and executed directly, and compilation and execution happen in
a single process.
Below are few more characteristics of Anonymous blocks.
These blocks don't have any reference name specified for them.
These blocks start with the keyword 'DECLARE' or 'BEGIN'.
Since these blocks are not having any reference name, these cannot be
stored for later purpose. They shall be created and executed in the same
session.
They can call the other named blocks, but call to anonymous block is not
possible as it is not having any reference.
It can have nested block in it which can be named or anonymous. It can
also be nested to any blocks.
These blocks can have all three sections of the block, in which execution
section is mandatory, the other two sections are optional.
Named blocks:
Named blocks are having a specific and unique name for them. They are stored
as the database objects in the server. Since they are available as database
objects, they can be referred to or used as long as it is present in the server. The
compilation process for named blocks happens separately while creating them as
a database objects.
Below are few more characteristics of Named blocks.
Code Explanation:
Oracle will be blank-padded the variable if the variable didn't occupy the
entire size that has been declared for it, hence oracle will allocate the
memory for declared size even if the variable didn't occupy it fully.
The size restriction for this data type is 1-2000 bytes.
CHAR data type is more appropriate to use where ever fixed size of data
will be handled. .
VARCHAR2 Data type:
This data type stores the string, but the length of the string is not fixed.
The size restriction for this data type is 1-4000 bytes for table column size
and 1-32767 bytes for variables.
The size is defined for each variable at the time of variable declaration.
But Oracle will allocate memory only after the variable is defined, i.e.,
Oracle will consider only the actual length of the string that is stored in a
variable for memory allocation rather than the size that have been given for
a variable in the declaration part.
It is always good to use VARCHAR2 instead of CHAR data type to
optimize the memory usage.
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.
Syntax Explanation:
So, it is always good to use LOB data type instead of LONG data type. Following
are the different LOB data types. They can store up to the size of 128 terabytes.
1. BLOB
2. CLOB and NCLOB
3. BFILE
BLOB:
This data type stores the LOB data in the binary file format up to the maximum
size of 128 TB. This doesn't store data based on the character set details, so it
can store the unstructured data such as multimedia objects, images, etc.
Syntax Explanation:
In the above, variable 'Binary_data' is declared as BLOB.
Syntax Explanation:
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.
Record Type
Record type is the complex data type which allows the programmer to create a
new data type with the desirable column structure.
Following are some of the attributes of the record type.
In the first syntax, we can see the keyword 'CREATE TYPE' this instructs
the compiler to create the record type named "type_name_db" with the
specified column as a database object.
This is given as an individual statement and not inside any block.
Syntax Explanation:
In the syntax, we are creating the record type named "type_name" only
inside the subprogram.
In both declaration method, the way of defining the column and data type is
similar.
Example 1: RECORD Type as Database Object
In this program, we are going to see how to create "Record type" as a database
object. We are going to create record type 'emp_det' with 4 columns. The
columns and their data type are as follows:
EMP_NO (NUMBER)
EMP_NAME (VARCHAR2 (150))
MANAGER (NUMBER)
SALARY (NUMBER)
Code Explanation:
Output:
Created the type 'emp_det' as record type at the database level.
Example 2: Record Type at Subprogram level- Column level access
In this example, we are going to see how to create a record type at subprogram
level and how to populate and fetch the values from it by column level.
We are going to create 'emp_det' record_type at subprogram level, and we are
going to use the same to populate and to display data from it.
Code Explanation:
Code line 2-8: Record type 'emp_det' is declared with columns emp_no,
emp_name, salary and manager of data type NUMBER, VARCHAR2,
NUMBER, NUMBER.
Code line 9: guru99_emp_rec variable is declared as 'emp_det' data type.
Now this variable can hold the value that contains all the above 4
fields/columns.
Code line 11: Populating the 'emp_no' field of 'guru99_emp_rec' with
value 1001.
Code line 12: Populating the 'emp_name' field of 'guru99_emp_rec' with
value XXX.
Code line 13: Populating the 'manager' field of 'guru99_emp_rec' with
value 1000.
Code line 14: Populating the 'salary' field of 'guru99_emp_rec' with value
10000.
Code line 15-19: Displaying the value of the 'guru99_emp_rec' in output.
Code Explanation:
Code line 2-8: Record type 'emp_det' is declared with columns emp_no,
emp_name, salary and manager of data type NUMBER, VARCHAR2,
NUMBER, NUMBER.
Code line 9: guru99_emp_rec variable is declared as 'emp_det' data type.
Now this variable can hold the value that contains all the above 4
fields/columns.
Code line 11: Populating the table emp with data 1002 as emp_no, YYY
as emp_name, 15000 as salary and 1000 as manager number.
Code line 12: Committing the above insert transaction.
Code line 13: Populating the 'guru99_emp_rec' variable as a row level
data from the select query for employee number 1002.
Code line 15-19: Displaying the value of the 'guru99_emp_rec' in output.
Output: As you can see in the above screenshot when the above code is
executed you will get the following output
Employee Detail
Employee Number: 1002
Employee Name: YYY
Employee Salary: 1000
Employee Manager Number: 15000
Note: The record type can be accessed only in column level while redirecting its
value to any output mode.
Collection
The collection is nothing but an ordered group of elements of particular data
types. It can be a collection of simple data type or complex data type (like user
defined or record types).
In the collection, each element is identified by a term called "subscript." Each
item in the collection is assigned with a unique subscript. The data in that
collection can be manipulated or fetched by referring to that unique subscript.
Collections are most useful things when a large data of the same type needs to
be processed or manipulated. Collections can be populated and manipulated as
whole using 'BULK' option in Oracle.
Collections are classified based on the structure, subscript and storage as shown
below.
At any point, data in the collection can be referred by three terms Collection
name, Subscript, Field/Column name as
"<collection_name>(<subscript>).<column_name>". You are going to learn about
these above mentioned collection categories further in the below section.
Varrays
Varray is a collection method in which the size of the array is fixed. The array size
cannot be exceeded than its fixed value. The subscript of the Varray is of a
numeric value. Following are the attributes of Varrays.
Subscript 1 2 3 4 5 6 7
Syntax Explanation:
Nested Tables
Nested table is a collection in which the size of the array is not fixed. It has the
numeric subscript type. Below are more descriptions about nested table type.
The below figure will explain the memory allocation of Nested Table (dense and
sparse) diagrammatically. The black colored element space denotes the empty
element in a collection i.e. sparse
Subscript 1 2 3 4 5 6 7
Value Xyz Dfv Sd Cxs Vbc Nh Qwe
(dense) e u
Syntax Explanation:
Index-by-table
Index-by-table is a collection in which the array size is not fixed. Unlike the other
collection types, in the index-by-table collection the subscript can be defined by
the user. Following are the attributes of index-by-table.
The below figure will explain the memory allocation of Nested Table (sparse)
diagrammatically. The black colored element space denotes the empty element
in a collection i.e. sparse
Syntax Explanation:
Collection Methods
Oracle provide many functions to manipulate and to work with the collections.
These functions are very much useful in the program to determine and to modify
the different attribute of the collections. Following table will give the different
functions and their description.
is no precedes
index value NULL
is returned
is no succeeds
index value NULL
is returned
the collection
Code line 2-8: Record type 'emp_det' is declared with columns emp_no,
emp_name, salary and manager of data type NUMBER, VARCHAR2,
NUMBER, NUMBER.
Code line 9: Creating the collection 'emp_det_tbl' of record type element
'emp_det'
Code line 10: Declaring the variable 'guru99_emp_rec' as 'emp_det_tbl'
type and initialized with null constructor.
Code line 12-15: Inserting the sample data into the 'emp' table.
Code line 16: Committing the insert transaction.
Code line 17: Fetching the records from 'emp' table and populating the
collection variable as a bulk using command "BULK COLLECT". Now the
variable 'guru99_emp_rec' contains all the record that are present in the
table 'emp'.
Code line 19-26: Setting the 'FOR' loop using to print all the records in the
collection one-by-one. The collection method FIRST and LAST is used as
lower and higher limit of the loop.
Output: As you can see in the above screenshot when the above code is
executed you will get the following output
Employee Detail
Employee Number: 1000
Employee Name: AAA
Employee Salary: 25000
Employee Manager Number: 1000
----------------------------------------------
Employee Number: 1001
Employee Name: XXX
Employee Salary: 10000
Employee Manager Number: 1000
----------------------------------------------
Employee Number: 1002
Employee Name: YYY
Employee Salary: 15000
Employee Manager Number: 1000
----------------------------------------------
Employee Number: 1003
Employee Name: ZZZ
Employee Salary: 7500
Employee Manager Number: 1000
----------------------------------------------
IF-THEN
IF-THEN-ELSE
IF-THEN-ELSIF
NESTED-IF
CASE
SEARCHED CASE
IF-THEN Statement
The IF-THEN statement is mainly used to execute a particular section of
codes only when the condition is satisfied.
The condition should yield Boolean (True/False). It is a basic conditional
statement which will allow the ORACLE to execute/skip a particular piece
of code based on the pre-defined conditions.
Syntax Explanation:
In the above syntax, keyword 'IF' will be followed by a condition which
evaluates to 'TRUE'/'FALSE'.
The control will execute the <action_block> only if the condition returns
<TRUE>.
In the case of condition evaluates to <FALSE> then, SQL will skip the
<action_block> and it will start executing the code next to 'END IF' block.
Note: Whenever condition evaluate to 'NULL', then SQL will treat 'NULL' as
'FALSE'.
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.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '10'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition, whether variable 'a' is greater than
'100.'
Code line 6: If 'a' is greater than '100', then "a is greater than 100" will be
printed. If 'a' is lesser than or equal to 100, then condition fails, so the
above printing statement ignored.
Code line 8: Printing the statement "Program completed".
Code Output:
Program started.
Program completed.
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.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'CHAR' of size '1' data type and
initializing it with value 'u'.
Code line 4: Checking the condition, whether variable 'a' is present in the
list ('A','E','I','O','U').
Value of 'a' has been converted to uppercase before comparing to make
the comparison as case-insensitive.
Code line 5: If 'a' is present in the list, then the statement "The character is
in English Vowels" will be printed. If condition failed, then this program will
not give any output, as outside the IF-THEN block we have not issued any
printing statement.
Code Output:
The character is in English Vowels
IF-THEN-ELSE Statement
The IF-THEN-ELSE statement is mainly used to select between two
alternatives based on the condition.
Below is the syntax representation of IF-THEN-ELSE statement.
Syntax Explanation:
Note: Whenever condition evaluate to 'NULL', then SQL will treat 'NULL' as
'FALSE'.
Example 1: In this example, we are going to print message whether the given
number is odd or even.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '11'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition, whether modulus of variable 'a' by '2'
is 0.
Code line 6: If '0', then "a is even number" will be printed.
Code line 7: If the modulus value is not equal to '0', then the condition
returns <FALSE>, so the message "a is odd number" will be printed.
Code line10: Printing the statement "Program completed"
Code Output:
Program started.
a is odd number
Program completed.
IF-THEN-ELSIF Statement
The IF-THEN-ELSIF statement is mainly used where one alternative
should be chosen from a set of alternatives, where each alternative has its
own condition to be satisfied.
The first condition that returns <TRUE> will be executed, and the
remaining conditions will be skipped.
The IF-THEN-ELSIF statement may contain 'ELSE' block in it. This 'ELSE'
block will be executed if none of the condition is satisfied.
Note: ELSE block is optional in this conditional statement. If there is no ELSE
block, and none of the condition satisfied, then the controller will skip all the
action block and start executing the remaining part of the code.
Syntax Explanation:
In the above syntax, the control will execute the <action_block1> only if the
condition1 returns <TRUE>.
If condition1 is not satisfied, then the controller will check for condition2.
The controller will exit from the IF-statement in the following two cases.
When the controller found any condition that returns <TRUE>. In
this case, the corresponding action_block will be executed and the
controller will exit this IF-statement block and will start executing the
remaining code.
When none of the condition satisfied, the then controller will execute
ELSE block if present, then will exit from the IF-statement.
Note: Whenever condition evaluates to 'NULL', then SQL will treat 'NULL' as
'FALSE'.
Example 1: Without ELSE block
In this example, we are going to print the grade based on the given marks without
else condition (mark >= 70 Grade A, mark >=40 and mark<70 Grade B, mark
>=35 and mark<40 Grade C).
Code Explanation:
Code line 2: Declaring the variable 'mark' as 'NUMBER' data type and
initializing it with value '55'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition1, whether 'mark' is greater or equal
70.
Code line 7: Since condition1 failed, then the condition2 '70>mark>=40' is
checked.
Code line 8: The condtition2 returns <TRUE>, hence the message 'Grade
B' will be printed.
Code line12: Printing the statement "Program completed".
In this case, the condition3 'mark < 35' will be skipped, as the controller
found one condition which returns <TRUE> before condition3.
Code Output:
Program started.
Grade B
Program completed.
Example 2: With ELSE block
In this example, we are going to print the grade based on the given marks with
else condition (mark >= 70 Grade A, mark >=40 and mark<70 Grade B, mark
>=35 and mark<40 Grade C, else 'No Grade').
Code Explanation:
Code line 2: Declaring the variable 'mark' as 'NUMBER' data type and
initializing it with value '25'.
Code line 4: Printing the statement "Program started".
Code line 5: Checking the condition 1, whether 'mark' is greater or equal
70.
Code line 7: Since condition1 failed, then the condition2 '70>mark>=40' is
checked.
Code line 8: Since condition2 failed, then the condition3 '40>mark>=35' is
checked.
Code line 11: Since all the conditions are failed, control will now check for
the presence of ELSE block, and it will print the message 'No Grade' from
ELSE block.
Code line14: Printing the statement "Program completed".
Code Output:
Program started.
No Grade
Program completed.
NESTED-IF Statement
The NESTED-IF statement is basically allows programmers to place one
or more 'IF' condition inside another 'IF' condition's <action_block> other
than normal statements.
Each 'IF' condition should have a separate 'END IF' statement which marks
the end-of-scope of that particular <action_block>.
The 'IF' statement will consider the nearest 'END IF' statement as an
endpoint for that particular condition.
The pictorial representation for NESTED-IF is shown below diagram.
Syntax Explanation:
In the above syntax, the outer IF contains one more IF statement in its
action block.
The condition1 returns <TRUE>, then control will be executing
<action_block1> and checks the condition2.
If condition2 also returns <TRUE>, then <action_block2> will also be
executed.
In case of condition2 evaluates to <FALSE> then, SQL will skip the
<action_block2>.
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '10'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and
initializing it with value '15'.
Code line 4: Declaring the variable 'c' as 'NUMBER' data type and
initializing it with value '20'.
Code line 6: Printing the statement "Program started" (line 6).
Code line 7: Checking the condition1, whether 'a' is greater than 'b' (line
7).
Code line 10: If 'a' is greater than 'b, then condition in 'nested-if 1' will
check if 'a' is greater than 'c'(line 10).
Code line 13: If still 'a' is greater, then message 'A is greatest' will be
printed (line 11). Else if condition2 fails, then 'C is greatest' will be printed
(line 13).
Code line 18: In case condition1 returns false, then condition in 'nested-if
2' will check if 'b' is greater than 'c'(line 18).
Code line 21: If 'b' is greater than 'c' , then message 'B is greatest' will be
printed (line 19), else if condition2 fails, then 'C is greatest' will be printed
(line 21).
Code line 24: Printing the statement "Program completed" (line 24).
Output of code:
Program started.
Checking Nested-IF 2
C is greatest
Program completed.
CASE Statement
CASE statement is similar to IF-THEN-ELSIF statement that selects one
alternative based on the condition from the available options.
Syntax Explanation:
In the above syntax, the expression will return a value that could be of any
type (variable, number, etc.).
Each 'WHEN' clause is treated as an alternatives which have <value> and
<action_block>.
The 'WHEN' clause which matches the value as that of the expression will
be selected, and the corresponding <action_block> will be executed.
'ELSE' block is optional which hold the <action_block_default> that needs
to be executed when none of the alternatives match the expression value.
The 'END' marks the end of CASE statement and it is a mandatory part of
CASE.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '55'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and
initializing it with value '5.'
Code line 4: Declaring the variable 'arth_operation' as 'VARCHAR2' data
type of size 20 and initializing it with value 'MULTIPLY'.
Code line 6: Printing the statement "Program started".
Code line 7: CASE checks the value of the expression. In this case, the
value of the variable 'arth_operation' is 'MULTIPLY'. This value will be
treated as a selector for this CASE statement now.
Code line 10: The WHEN clause with value 'MULTIPLY' matches with the
selector value, hence controller will select this action_block and will print
the message 'Multiplication of the numbers are: 275'.
Code line13: Marks the end of CASE statement.
Code line14: Printing the statement "Program completed".
Code Output:
Program started.
Multiplication of the numbers are: 275
Program completed.
SEARCHED CASE Statement
SEARCHED CASE statement is similar to CASE statement, rather than using the
selector to select the alternative, SEARCHED CASE will directly have the
expression defined in the WHEN clause.
The first WHEN clause that satisfies the condition will be executed, and the
controller will skip the remaining alternatives.
Syntax Explanation:
In the above syntax, each WHEN clause has the separate <expression>
and <action_block>.
The WHEN clause for which the expression returns TRUE will be
executed.
'ELSE' block is optional which hold the <action_block_default> that needs
to be executed when none of the alternatives satisfies.
The 'END' marks the end of CASE statement and it is a mandatory part of
CASE.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '55'.
Code line 3: Declaring the variable 'b' as 'NUMBER' data type and
initializing it with value '5'.
Code line 4: Declaring the variable 'arth_operation' as 'VARCHAR2' data
type of size 20 and initializing it with value 'DIVIDE.'
Code line 6: Printing the statement "Program started".
Code line 7: SEARCHED CASE statement begins. The code from line8 to
line 13 is skipped as their selector value (ADD, SUBTRACT, MULTIPLY)
doesn't match with the value of 'arth_operation'.
Code line 14: The WHEN clause expression "arth_operation = 'DIVIDE'"
satisfied and the expression returns TRUE.
Code line 15: Action_block of the WHEN clause will be executed, and
message 'Division of the numbers are: 11' will be printed.
Code line 17: Marks the end of CASE statement.
Code line 18: Printing the statement "Program completed".
Code Output:
Program started.
Division of the numbers are: 11
Program completed.
Summary
In this chapter, we have learnt the different decision making statements and their
syntax and examples. Below table gives the summary of various conditional
statements that we have discussed.
Reusability of code
Reduced code size
Easy flow of control
Reduced Complexity
Syntax Explanation:
In the above syntax, key word 'LOOP' marks beginning of the loop and
'END LOOP' marks the end of the loop.
The execution block contains all the code that needs to be executed
including the EXIT condition.
The execution part can contain any execution statement.
Note: Basic loop statement with no EXIT keyword will be an INFINITE-LOOP that
will never stop.
Example 1: In this example, we are going to print number from 1 to 5 using basic
loop statement. For that, we will execute the following code
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '1'.
Code line 4: Printing the statement "Program started".
Code line 5: Keyword 'LOOP' marks the beginning of the loop.
Code line 6: Prints the value of 'a'.
Code line 7: Increments the value of 'a' by +1.
Code line 8: Checks whether the value of 'a' is greater than 5.
Code line 9: Keyword 'END LOOP' marks the end of execution block.
The code from line 6 to line 8 will continue to execute till 'a' reaches the
value 6, as the condition will return TRUE, and the control will EXIT from
the loop.
Code line 10: Printing the statement "Program completed"
In the above syntax, keyword 'WHILE' marks beginning of the loop and
'END LOOP' marks the end of the loop.
EXIT condition is evaluated each time before the execution part is starts
executing.
The execution block contains all the code that needs to be executed.
The execution part can contain any execution statement.
Code Explanation:
Code line 2: Declaring the variable 'a' as 'NUMBER' data type and
initializing it with value '1'.
Code line 4: Printing the statement "Program started".
Code line 5: Keyword 'WHILE' marks the beginning of the loop, and it also
checks whether value of 'a' is greater than 5
Code line 7: Prints the value of 'a'.
Code line 8: Increments the value of 'a' by +1.
Code line 9: Keyword 'END LOOP' marks the end of execution block.
The code from line 7 and line 8 will continue to execute till 'a' reaches the
value 6, as the condition will returns TRUE, and the control will EXIT from
the loop.
Code line 10: Printing the statement "Program completed"
Syntax Explanation:
In the above syntax, keyword 'FOR' marks beginning of the loop and 'END
LOOP' marks the end of the loop.
Loop variable is evaluated every time before executing the execution part.
The execution block contains all the code that needs to be executed. The
execution part can contain any execution statement.
The loop_variable is declared implicitly during the execution of the entire
loop, and the scope of this loop_variable will be only inside this loop.
If the loop variable came out of the range, then control will exit from the
loop.
The loop can be made to work in the reverse order by adding the keyword
'REVERSE' before lower_limit.
Example 1: In this example, we are going to print number from 1 to 5 using FOR
loop statement. For that, we will execute the following code
Code Explanation:
Nested Loops
The loop statements can also be nested. The outer and inner loop can be of
different types. In nested loop, for every one iteration value of the outer loop, the
inner loop will be executed fully.
Syntax Explanation:
In the above syntax, the outer loop has one more loop inside it.
The loops can be of any types and execution functionality part is same.
Example 1: In this example, we are going to print number from 1 to 3 using FOR
loop statement. Each number will be printed as many times as its value. For that,
we will execute the following code
Code Explanation:
Labelling of Loops
In PL/SQL, the loops can be labeled. The label should be enclosed between "<<"
and ">>". The labeling of loops particularly in nested loop codes will give more
readability. The label can be given in EXIT command to exit from that particular
loop. Using label, the control can be made to directly exit the outer loop of the
nested loops from anyplace inside the loops, by giving the exit command followed
by outer loop label.
Syntax Explanation:
In the above syntax, the out loop has one more loop inside it.
The '<<OUTER_LOOP>>' and '<<INNER_LOOP>>' are the labels of these
loops.
Example 1: In this example, we are going to print number starting from 1 using
Basic loop statement. Each number will be printed as many times as its value.
The upper limit of the series is fixed at the program declaration part. Let us learn
how we can use the label concept to achieve this. For that, we will execute the
following code
Code Explanation:
Code line 2-3: Declaring the variable 'a' and 'b' as 'NUMBER' data type.
Code line 4: Declaring the variable 'upper_limit' as 'NUMBER' data type
with value '4'
Code line 6: Printing the statement "Program started".
Code line 7: The outer loop has been labeled as "outer_loop"
Code line 9: The value of 'a' is incremented by 1.
Code line 11: Inner loop has been labeled as "inner_loop".
Code line 13: EXIT condition that check whether the value 'a' is higher
than 'upper_limit' value. If not then it will go further, else it exits outer loop
directly.
Code line 14: Printing the value of 'b'.
Code line 15: Increments the value of 'b' by +1.
Code line 16: EXIT condition that checks whether the value of 'b' is higher
than 'a'. If so, then it will exit the control from the inner loop.
Code line 14: Printing the statement "Program completed"
Summary
In this chapter, we have learnt the loops concept, different types of loops, nested
loops and labeling of loops. Following loops summarize the types of loops and
their usage area.
Basic Exit when encounters the Good to use when exit is not based
Loop keyword 'EXIT' in the on any particular condition.
execution part
WHILE Exit when the check Good to use when the loop count is
Loop condition returns false unknown, and exit is based on some
other condition.
FOR Exit when the counter Good to use when loop count to be
Loop reaches the limit executed is known.
What is PL/SQL?
PL/SQL stands for Procedural Language extension of SQL.
PL/SQL is a combination of SQL along with the procedural features of
programming languages.
It was developed by Oracle Corporation in the early 90’s to enhance the
capabilities of SQL.
The PL/SQL Engine:
Oracle uses a PL/SQL engine to processes the PL/SQL statements. A PL/SQL
language code can be stored in the client system (client-side) or in the
database (server-side).
PL/SQL Block consists of three sections:
Declaration Section:
The Declaration section of a PL/SQL Block starts with the reserved keyword
DECLARE. This section is optional and is used to declare any placeholders like
variables, constants, records and cursors, which are used to manipulate data
in the execution section. Placeholders may be any of Variables, Constants
and Records, which stores data temporarily. Cursors are also declared in this
section.
Execution Section:
The Execution section of a PL/SQL Block starts with the reserved keyword
BEGIN and ends with END. This is a mandatory section and is the section
where the program logic is written to perform any task. The programmatic
constructs like loops, conditional statement and SQL statements form the
part of execution section.
Exception Section:
The Exception section of a PL/SQL Block starts with the reserved keyword
EXCEPTION. This section is optional. Any errors in the program can be
handled in this section, so that the PL/SQL Blocks terminates gracefully. If the
PL/SQL Block contains exceptions that cannot be handled, the Block
terminates abruptly with errors.
Every statement in the above three sections must end with a semicolon ; .
PL/SQL blocks can be nested within other PL/SQL blocks. Comments can be
used to document code.
Advantages of PL/SQL
Block Structures: PL SQL consists of blocks of code, which can be
nested within each other. Each block forms a unit of a task or a logical
module. PL/SQL Blocks can be stored in the database and reused.
Procedural Language Capability: PL SQL consists of procedural
language constructs such as conditional statements (if else
statements) and loops like (FOR loops).
Better Performance: PL SQL engine processes multiple SQL
statements simultaneously as a single block, thereby reducing network
traffic.
Error Handling: PL/SQL handles errors or exceptions effectively
during the execution of a PL/SQL program. Once an exception is
caught, specific actions can be taken depending upon the type of the
exception or it can be displayed to the user with a message.
Digits 0-9
Symbols ~!@#$%&*()_-+=|[]{}:;"'<>,.?/
Note that PL/SQL is a case-insensitive language. Uppercase letters are treated the
same way as lowercase letters except when the characters are surrounded by single
quotes (when they are literal strings) or represent the value of a character variable.
PL/SQL Variables
These are placeholders that store the values that can change through the
PL/SQL Block.
For example, if you want to store the current salary of an employee, you can
use a variable.
DECLARE
salary number (6);
When a variable is specified as NOT NULL, you must initialize the variable
when it is declared.
For example: The below example declares two variables, one of which is a
not null.
DECLARE
salary number(4);
dept varchar2(10) NOT NULL := “HR Dept”;
The value of a variable can change in the execution or exception section of
the PL/SQL Block. We can assign values to variables in the two ways given
below.
1) We can directly assign values to variables.
The General Syntax is:
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];
Example: The below program will get the salary of an employee with id '1116'
and display it on the screen.
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;
/
NOTE: The backward slash '/' in the above program indicates to
execute the above PL/SQL Block.
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.
Based on their declaration we can classify variables into two types.
For Example: In the below example we are creating two variables in the outer
block and assigning thier product to the third variable created in the inner
block. The variable 'var_mult' is declared in the inner block, so cannot be
accessed in the outer block i.e. it cannot be accessed after line 11. The
variables 'var_num1' and 'var_num2' can be accessed anywhere in the block.
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 := var_num1 *
var_num2;
11> END;
12> END;
13> /
PL/SQL Constants
As the name implies a constant is a value used in a PL/SQL Block that
remains unchanged throughout the program. A constant is a user-defined
literal value. You can declare a constant and use it instead of actual value.
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;
PL/SQL Records
What are records?
Records are another type of datatypes which oracle allows to be defined as a
placeholder. Records are composite datatypes, which means it is a
combination of different scalar datatypes like char, varchar, number etc.
Each scalar data types in the record holds a value. A record can be visualized
as a row of data. It can contain all the contents of a row.
Declaring a record:
To declare a record, you must first define a composite datatype; then
declare a record for that type.
There are different ways you can declare the datatype of the fields.
1) You can declare the field in the same way as you declare the fieds while
creating the table.
2) If a field is based on a column from database table, you can define the
field_type as follows:
col_name table_name.column_name%type;
By declaring the field datatype in the above method, the datatype of the
column is dynamically applied to the field. This method is useful when you
are altering the column specification of the table, because you do not need to
change the code again.
NOTE: You can use also %type to declare variables and constants.
The following code shows how to declare a record called employee_rec based
on a user-defined type.
DECLARE
TYPE employee_type IS RECORD
(employee_id number(5),
employee_first_name varchar2(25),
employee_last_name employee.last_name%type,
employee_dept employee.dept%type);
employee_salary employee.salary%type;
employee_rec employee_type;
If all the fields of a record are based on the columns of a table, we can
declare the record as follows:
record_name table_name%ROWTYPE;
DECLARE
employee_rec employee%ROWTYPE;
The following table consolidates the different ways in which you can define
and declare a pl/sql record.
Usage
Syntax
record_name.col_name := value;
If you used %ROWTYPE to declare a record, you can assign values as shown:
record_name.column_name := value;
If %ROWTYPE is used to declare a record then you can directly assign values
to the whole record instead of each columns separately. In this case, you
must SELECT all the columns from the table into the record as shown:
var_name := record_name.col_name;
The following table consolidates the different ways you can assign values to
and from a record:
Syntax Usage
Conditional Statements in
PL/SQL
IF THEN ELSE STATEMENT
1)
IF condition
THEN
statement 1;
ELSE
statement 2;
END IF;
2)
IF condition 1
THEN
statement 1;
statement 2;
ELSIF condtion2 THEN
statement 3;
ELSE
statement 4;
END IF
3)
IF condition 1
THEN
statement 1;
statement 2;
ELSIF condtion2 THEN
statement 3;
ELSE
statement 4;
END IF;
4)
IF condition1 THEN
ELSE
IF condition2 THEN
statement1;
END IF;
ELSIF condition3 THEN
statement2;
END IF;
Iterative Statements in PL/SQL
Iterative control Statements are used when we want to repeat the execution
of one or more statements for specified number of times.
There are three types of loops in PL/SQL:
• Simple Loop
• While Loop
• For Loop
1) Simple Loop
A Simple Loop is used when a set of statements is to be executed at least
once before the loop terminates. An EXIT condition must be specified in the
loop, otherwise the loop will get into an infinite number of iterations. When
the EXIT condition is satisfied the process exits from the loop.