0% found this document useful (0 votes)
2 views

Pl SQL Notes

PL/SQL, or Procedural Language extensions to SQL, is an extension of SQL used in Oracle that allows for procedural programming with SQL's data manipulation capabilities. It consists of three main components: PL/SQL blocks, the PL/SQL engine, and the database server, and offers advantages such as better performance and tight integration with SQL. The document also covers the structure of PL/SQL blocks, data types, and the differences between SQL and PL/SQL.

Uploaded by

rojamani ganta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

Pl SQL Notes

PL/SQL, or Procedural Language extensions to SQL, is an extension of SQL used in Oracle that allows for procedural programming with SQL's data manipulation capabilities. It consists of three main components: PL/SQL blocks, the PL/SQL engine, and the database server, and offers advantages such as better performance and tight integration with SQL. The document also covers the structure of PL/SQL blocks, data types, and the differences between SQL and PL/SQL.

Uploaded by

rojamani ganta
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 59

http://plsql-tutorial.

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.

Below is the pictorial representation of Architecture of PL/SQL.

Advantage of Using PL/SQL


1. Better performance, as sql is executed in bulk rather than a single
statement
2. High Productivity
3. Tight integration with SQL
4. Full Portability
5. Tight Security
6. Support Object Oriented Programming concepts.

Basic Difference between SQL and PL/SQL


In this section, we will discuss some differences between SQL and PL/SQL
SQL PL/SQL

 SQL is a single query that is used to  PL/SQL is a block of


perform DML and DDL operations. codes that used to write
the

entire program blocks/


procedure/ function, etc.

 It is declarative, that defines what  PL/SQL is procedural


needs to be done, rather than how that defines how the
things need to be done. 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.

 Interaction with Database server.  No interaction with the


database server.

 Cannot contain PL/SQL code in it.  It is an extension of


SQL, so it can contain
SQL

inside it.

What is PL/SQL block?


PL/SQL is the procedural approach to SQL in which a direct instruction is given
to the PL/SQL engine about how to perform actions like
storing/fetching/processing data. These instruction are grouped together
called Blocks.
Blocks contain both PL/SQL as well as SQL instruction. All these instruction will
be executed as a whole rather than executing a single instruction at a time.
Block Structure
PL/SQL blocks have a pre-defined structure in which the code is to be grouped.
Below are different sections of PL/SQL blocks

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.

 This particular section is optional and can be skipped if no declarations are


needed.
 This should be the first section in a PL/SQL block, if present.
 This section starts with the keyword 'DECLARE' for triggers and
anonymous block. For other subprograms this keyword will not be present,
instead the part after the subprogram name definition marks the
declaration section.
 This section should be always followed by execution section.

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.

 This can contain both PL/SQL code and SQL code.


 This can contain one or many blocks inside it as a nested blocks.
 This section starts with the keyword 'BEGIN'.
 This section should be followed either by 'END' or Exception-Handling
section (if present)

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.

 These blocks can be called from other blocks.


 The block structure is same as an anonymous block, except it will never
start with the keyword 'DECLARE'. Instead, it will start with the keyword
'CREATE' which instruct the compiler to create it as a database object.
 These blocks can be nested within other blocks. It can also contain nested
blocks.
 Named blocks are basically of two types:
1. Procedure
2. Function

How to write a simple program using PL/SQL


In this section, we are going to write a simple program for printing "Hello World"
using "Anonymous block".

Code Explanation:

 Code line 2: Prints the message "Hello World. . ."


PL/SQL Data Types :
 CHARACTER Data type
 NUMBER Data type
 BOOLEAN Data type
 DATE Data type
 LOB Data type

CHARACTER Data type:


This data type basically stores alphanumeric characters in string format.
The literal values should always be enclosed between single quotes while
assigning them to CHARACTER data type.
This character data type is further classified as follows:

 CHAR Data type (fixed string size)


 VARCHAR2 Data type (variable string size)
 VARCHAR Data type
 NCHAR (native fixed string size)
 NVARCHAR2 (native variable string size)
 LONG and LONG RAW

CHAR Data type:


This data type stores the string value, and the size of the string is fixed at the
time of declaring the variable.

 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.

VARCHAR Data type:


This is the synonymous with the VARCHAR2 data type.

 It is always a good practice to use VARCHAR2 instead of VARCHAR to


avoid behavioral changes.

NCHAR Data type:


This data type is same as CHAR data type, but the character set will of national
character set.

 This character set can be defined for the session using


NLS_PARAMETERS.
 The character set can be either UTF16 or UTF8.
 The size restriction is 1-2000 bytes.

NVARCHAR2 Data type:


This data type is same as VARCHAR2 data type, but the character set will be of
national character set.

 This character set can be defined for the session using


NLS_PARAMETERS.
 The character set can be either UTF16 or UTF8.
 The size restriction is 1-4000 bytes.
LONG and LONGRAW Data type:
This data type is used to store large text or raw data up to the maximum size of
2GB.

 These are mainly used in the data dictionary.


 LONG data type is used to store character set data, while LONG RAW is
used to store data in binary format.
 LONG RAW data type accept media objects, images, etc. whereas LONG
works only on data that can be stored using character set.

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 these information. Values need not to enclose within quotes while
assigning for this data type.

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.

BOOLEAN Data type:


This data type stores the logical values. It represents either TRUE or FALSE and
mainly used in conditional statements. Values need not enclose within quotes
while assigning for this data type.

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.

Syntax Explanation:

 In the above, variable 'newyear' is declared as DATE data type and


assigned the value of Jan 1 , 2015 date.
st

 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.

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 LONG data type as it is more flexible than 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 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 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 much updates.

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.

CLOB and NCLOB:


CLOB data type stores the LOB data into the character set, whereas NCLOB
stores the data in the native character set. Since these data types uses character
set based storage, these 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.

Syntax Explanation:

 In the above, variable 'Charac_data' is declared as CLOB data type.

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.

Complex Data Types in PL/SQL :


Complex data types are those that include record type and collections which are
used to handle data in record format or in an array format.

In this tutorial, you will learn-


 Record Type
 Collection
 Constructor and Initialization Concept in Collections
 Collection Methods

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.

 It groups one or more column together to form a new data type


 These columns will have its own name and data type
 Record type can accept the data
 As a single record that consists of many column OR
 It can accept the value for one particular column of a record
 Record type simply means a new data type. Once the record type is
created it will be stored as a new data type in the database and the same
shall be used to declare a variable in programs.
 It will use the keyword 'TYPE' to instruct the compiler that it is creating the
new data type.
 It can be created at "database level" which can be stored as database
objects, used all-over the database or it can be created at the
"subprogram levels", which is visible only inside the subprograms.
 The database level record type can also be declared for the table columns
so that single column can hold the complex data.
 The data in these data type can be accessed by referring to their
variable_name followed by period operator (.) followed by column_name
i.e. '<record_type_variable_name>.<column_name>'

Syntax for declaration at database level:


Syntax Explanation:

 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:

 The above code will create type emp_det as a database object.


 It will have 4 column emp_no, emp_name, manager and salary as defined.
 Now 'emp_det' is a similar to other data type (like NUMBER, VARCHAR@,
etc.) And it is visible in the entire database, hence this can be used in the
entire database to declare the variable of this type.

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.

Example 3: Record Type at Subprogram level-Row level access


In this example, we are going to see how to create a record type at subprogram
level and how to populate it as a row 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 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.

 Index-by-tables (also known as Associative Array)


 Nested tables
 Varrays

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.

 Upper limit size is fixed


 Populated sequentially starting with the subscript '1'
 This collection type is always dense, i.e. we cannot delete any array
elements. Varray can be deleted as a whole, or it can be trimmed from the
end.
 Since it always be dense in nature, it has very less flexibility.
 It is more appropriate to use when the array size is known and to perform a
similar activities on all the array elements.
 The subscript and sequence always remain stable, i.e. the subscript and
count of the collection is always same.
 They needs to be initialized before using them in programs. Any operation
(except EXISTS operation) on uninitialized collection will throw an error.
 It can be created as a database object, which is visible throughout the
database or inside the subprogram, which can be used only in that
subprogram.
The below figure will explain the memory allocation of Varray (dense)
diagrammatically.

Subscript 1 2 3 4 5 6 7

Value Xy Dfv Sde Cx Vbc Nhu Qwe


z s

Syntax Explanation:

 In the above syntax, type_name is declared as VARRAY of the type


'DATA_TYPE' for the given size limit. The data type can be either simple or
complex type.

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 Nested table has no upper size limit.


 Since the upper size limit is not fixed, the collection memory needs to be
extended each time before we actually use it. We can extend the collection
using 'EXTEND' keyword.
 Populated sequentially starting with the subscript '1'.
 This collection type can be of both dense and sparse, i.e. we can create
the collection as a dense, and we can also delete the individual array
element randomly, which make it as sparse.
 It gives more flexibility in terms of deleting the array element.
 It is stored in the system generated database table and can be used in the
select query to fetch the values.
 The subscript and sequence are not stable, i.e. the subscript and the count
of the array element can vary.
 They need to be initialized before using them in programs. Any operation
(except EXISTS operation) on the uninitialized collection will throw an
error.
 It can be created as a database object, which is visible throughout the
database or inside the subprogram, which can be used only in that
subprogram.

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

Value(sparse Qwe Asd Afg Asd Wer


)

Syntax Explanation:

 In the above syntax, type_name is declared as Nested table collection of


the type 'DATA_TYPE'. The data type can be either simple or complex
type.

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 subscript can of integer or strings. At the time of creating the


collection, the subscript type should be mentioned.
 These collections are not stored sequentially.
 They are always sparse in nature.
 The array size is not fixed.
 They cannot be stored in the database column. They shall be created and
used in any program in that particular session.
 They give more flexibility in terms of maintaining subscript.
 The subscripts can be of negative subscript sequence also.
 They are more appropriate to use for relatively smaller collective values in
which the collection can be initialized and used within the same
subprograms.
 They need not to be initialized before start using them.
 It cannot be created as a database object. It can only be created inside the
subprogram, which can be used only in that subprogram.
 BULK COLLECT cannot be used in this collection type as the subscript
should be given explicitly for each record in the collection.

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

Subscript FIRS SECON THIR FOURT FIFT SIXT SEVENT


(varchar) T D D H H H H

Value(spars Qwe Asd Afg Asd Wer


e)

Syntax Explanation:

 In the above syntax, type_name is declared as an index-by-table collection


of the type 'DATA_TYPE'. The data type can be either simple or complex
type. The subsciprt/index variable is given as VARCHAR2 type with
maximum size as 10.

Constructor and Initialization Concept in Collections


Constructors are the in-built function provided by the oracle that has the same
name as of the object or collections. They are executed first whenever object or
collections are getting referred for the first time in a session. Below are the
important details of constructor in collection context:

 For collections, these constructors should be called explicitly to initialize it.


 Both Varray and Nested tables need to be initialized through these
constructors before getting referred into the program.
 Constructor implicitly extends the memory allocation for a collection
(except Varray), hence constructor can also assign the variables to the
collections.
 Assigning values to the collection through constructors will never make the
collection sparse.

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.

Method Description SYNTAX

EXISTS This method will <collection_name>.EXISTS(element_position)


(n) return Boolean
results. It will return
'TRUE' if the
n element exists in
th

that collection, else


it will return
FALSE. Only
EXISTS functions
can be used in
uninitialized
collection

COUNT Gives the total <collection_name>.COUNT


count of the
elements present
in a collection

LIMIT It returns the <collection_name>.LIMIT


maximum size of
the collection. For
Varray, it will return
the fixed size that
has been defined.
For Nested table
and Index-by-table,
it gives NULL

FIRST Returns the value <collection_name>.FIRST


of the first index
variable(subscript)
of the collections

LAST Returns the value <collection_name>.LAST


of the last index
variable(subscript)
of the collections

PRIOR Returns precedes <collection_name>.PRIOR(n)


(n) index variable in a
collection of the
n element. If there
th

is no precedes
index value NULL
is returned

NEXT Returns succeeds <collection_name>.NEXT(n)


(n) index variable in a
collection of the
n element. If there
th

is no succeeds
index value NULL
is returned

EXTEND Extends one <collection_name>.EXTEND


element in a
collection at the
end

EXTEND Extends n <collection_name>.EXTEND(n)


(n) elements at the
end of a collection

EXTEND Extends n copies <collection_name>.EXTEND(n,i)


(n,i) of the i element at
th

the end of the


collection

TRIM Removes one <collection_name>.TRIM


element from the
end of the
collection

TRIM (n) Removes n <collection_name>.TRIM (n)


elements from the
end of collection

DELETE Deletes all the <collection_name>.DELETE


elements from the
collection. Makes
the collection
empty

DELETE Deletes the nth <collection_name>.DELETE(n)


(n) element from the
collection. If the
n element is NULL,
th

then this will do


nothing

DELETE Deletes the <collection_name>.DELETE(m,n)


(m,n) element in the
range m to n in
th th

the collection

Example1: Record Type at Subprogram level


In this example, we are going to see how to populate the collection using 'BULK
COLLECT' and how to refer the collection data.
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: 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
----------------------------------------------

PL/SQL Decision Making Statements


Decision making statements are important to write any complex programs. These
statements will decide the control flow at run time based on pre-defined
conditions.

 Introduction to Decision Making Statements


 IF-THEN Statement
 IF-THEN-ELSE Statement
 IF-THEN-ELSIF Statement
 NESTED-IF Statement
 CASE Statement
 SEARCHED CASE Statement

Introduction to Decision Making Statements


Decision making statements are those which will decide the flow-control
of SQL statements based on the conditions. It gives the programmer a better
control like preventing a particular code from executing (diagram 1) or choosing a
desired code based on the condition (diagram 2). Below is the pictorial
representation of the "Decision Making Statement".
Types of Decision Making Statements:
Oracle provides the following types of decision making statements.

 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:

 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 block will be executed.

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>.

Here we are going to see an example of Nested If –


Example of Nested- If Statement: Greatest of three number
In this example, we are going to print the greatest of three numbers by using
Nested-If statement. The numbers will be assigned in the declare part, as you
can see in the code below, i.e Number= 10,15 and 20 and the maximum number
will be fetched using nested-if statements.
Code Explanation:

 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.

 CASE statement uses "selector" rather than a Boolean expression to


choose the sequence.
 The value of the expression in the CASE statement will be treated as a
selector.
 The expression could be of any type (arithmetic, variables, etc.)
 Each alternative is assigned with a certain pre-defined value (selector) and
the alternative with selector value that matches the conditional expression
value will get executed.
 Unlike IF-THEN-ELSIF, the CASE statement can also be used in SQL
statements.
 ELSE block in CASE statement holds the sequence that needs to be
executed when none of the alternatives got selected.

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.

Example 1: Arithmetic Calculation using Case


In this example, we are going to do arithmetic calculation between two numbers
55 and 5.

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.

Example 1: Arithmatic Calculation using Searched Case


In this example, we are going to do arithmetic calculation between two numbers
55 and 5.

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.

TYPE DESCRIPTION USAGE

IF-THEN Checks for a Boolean condition, if TRUE To skip,/execute a


code in 'THEN' block will be executed particular code
based on the
condition.

IF-THEN- Checks for a Boolean condition, if TRUE Most appropriate


ELSE code in 'THEN' block will be executed, if in 'THIS-OR-THAT'
false code in 'ELSE' block is executed. condition.

IF-THEN- Checks for a Boolean condition in a Used to choose


ELSIF sequential order. The first block in the from more than 2
sequence which returns TRUE condition alternative mostly.
will be executed. If none of the conditions
in sequence is TRUE, then code in 'ELSE'
block is executed

NESTED-IF Allows one or more IF-THEN or IF-THEN- Mainly used in


ELSIF statement inside another IF-THEN nested condition
or IF-THEN-ELSIF statement(s). situation.

CASE Similar to IF-THEN-ELSIF statement. A Used to select


'SELECTOR' is used to choose the from several
alternatives instead of Boolean alternatives using
expression. 'SELECTOR'

SEARCHED CASE statement with no actual Used to choose


CASE 'SELECTOR'. Instead it contains the from more than 2
actual condition (which evaluates to alternative mostly.
TRUE/FALSE) that will select the
alternatives

Loop Control Statements :


 Types of Loop in PL/SQL
 Basic Loop Statement
 WHILE Loop Statement
 FOR Loop Statement
 Nested Loops
 Labelling of Loops

Introduction to Loops Concept


Loops concept basically allows a certain part of the code in a program to get
executed for the desired number of types.
Loops concept provides the following advantage in coding

 Reusability of code
 Reduced code size
 Easy flow of control
 Reduced Complexity

The below diagram shows the looping concept in a pictorial manner


In the above diagram, the loop condition will be checked, and as long as the loop
condition is satisfied, the execution block will be executed.
In each iteration, the loop counter variable that actually decides the loop condition
should modify to make the control exit from the loop. In some cases, this loop
counter variable is increment/decrement operator for a predefined count and in
some case it is a search condition that keep on executing the block till it satisfies
it.
Loop Control Statements
Before learning the loops concept, it is mandatory to learn about loop control
statements. Loop control statements are those that actually controls the flow of
execution inside the loop. Below is the detailed description about the loop control
statements.
CONTINUE
This keyword sends an instruction to the PL/SQL engine that whenever PL/SQL
engine encounters this keyword inside the loop, then it will skip the remaining
code in the execution block of the code, and next iteration will start immediately.
This will be mainly used if the code inside the loop wants to be skipped for certain
iteration values.
EXIT / EXIT WHEN
This keyword sends an instruction to the PL/SQL engine that whenever PL/SQL
engine encounters this keyword, then it will immediately exit from the current
loop. If the PL/SQL engine encounters the EXIT in nested loops, then it will come
out of the loop in which it has been defined, i.e. in a nested loops, giving EXIT in
the inner loop will only exit the control from inner loop but not from the outer loop.
'EXIT WHEN' is followed by an expression which gives Boolean result. If the
result is TRUE, then the control will EXIT.
GOTO
This statement will transfer the control to the labeled statement ("GOTO
<label> ;"). This has the following restrictions

 Transfer of control can be done only within the subprograms.


 Transfer of control cannot be done from exception handling part to the
execution part
Usage of this statement is not recommended unless there are no other
alternatives, as the code-control traceability will be very difficult in the program
due to the transfer of control from one part to another part.
Types of Loop in PL/SQL
PL/SQL provides following three types of loops

 Basic loop statement


 For loop statement
 While loop statement

Basic Loop Statement


This loop statement is the simplest loop structure in PL/SQL. The execution block
starts with keyword 'LOOP' and ends with the keyword 'END LOOP'.
The exit condition should be given inside this execution block so that control exit
from the loop.
It needs EXIT keyword to be given explicitly in the execution part to exit from the
loop.

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"

WHILE Loop Statement


WHILE loop statement works similar to the Basic loop statement except the EXIT
condition is at the very beginning of the loop.
It works like entry-check loop in which execution block will not even be executed
once if the condition is not satisfied, as the exit condition is checking before
execution part. It does not require keyword 'EXIT' explicitly to exit from the loop
since it is validating the condition implicitly each time of the loop.
Syntax Explanation:

 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.

Example 1: In this example, we are going to print number from 1 to 5 using


WHILE 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 '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"

FOR Loop Statement


"FOR LOOP" statement is best suitable when you want to execute a code for
known number of times rather than based on some other conditions.
In this loop, the lower limit and the higher limit will be specified and as long as the
loop variable is in between these range the loop will be executed.
The loop variable is self-incremental, so no explicit increment operation is needed
in this loop. The loop variable need not to be declared, as it is declared implicitly.

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:

 Code line 2: Printing the statement "Program started".


 Code line 3: Keyword 'FOR' marks the beginning of the loop and
loop_variable 'a' is declared. It now will have the value starting from 1 to 5
 Code line 5: Prints the value of 'a'.
 Code line 6: Keyword 'END LOOP' marks the end of execution block.
 The code from line 5 will continue to execute till 'a' reaches the value 6, as
the condition will fail, and the control will EXIT from the loop.
 Code line 7: Printing the statement "Program completed"

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:

 Code line 2: Declaring the variable 'b' as 'NUMBER' data type.


 Code line 4: Printing the statement "Program started".
 Code line 5: Keyword 'FOR' marks the beginning of the loop and
loop_variable 'a' is declared. It now will have the value starting from 1 to 3
 Code line 7: Resetting the value of 'b' to '1' each time.
 Code line 8: Inner while loop checks for the condition a>=b.
 Code line 10: Prints the value of 'a' as long as the above condition is
satisfied.
 Code line 14: Printing the statement "Program completed"

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.

Loop EXIT Criteria Usage

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:

 The Declaration section (optional).


 The Execution section (mandatory).
 The Exception Handling (or Error) section (optional).

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.

How a Sample PL/SQL Block Looks


DECLARE
Variable
declaration
BEGIN
Program
Execution
EXCEPTION
Exception
handling
END;

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.

The PL/SQL Character Set


A PL/SQL program consists of a sequence of statements, each of which is made up
of one or more lines of text. Text is made up of combinations of the characters
shown in Table 2.1 .

Table 2.1: PL/SQL Character Set


Type Characters

Letters A-Z, a-z

Digits 0-9

Symbols ~!@#$%&*()_-+=|[]{}:;"'<>,.?/

Whitespac Tab, space, carriage return


e

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.

Define PL/SQL Placeholders


Depending on the kind of data you want to store, you can define
placeholders with a name and a datatype. Few of the datatypes used to
define placeholders are as given below.
Number (n,m) , Char (n) , Varchar2 (n) , Date , Long , Long raw, Raw, Blob,
Clob, Nclob, Bfile

PL/SQL Variables
These are placeholders that store the values that can change through the
PL/SQL Block.

General Syntax to declare a variable is


variable_name datatype [NOT NULL := value ];

 variable_name is the name of the variable.


 datatype is a valid PL/SQL datatype.
 NOT NULL is an optional specification on the variable.
 value or DEFAULT valueis also an optional specification, where you can
initialize a variable.
 Each variable declaration is a separate statement and must be
terminated by a semicolon.

For example, if you want to store the current salary of an employee, you can
use a variable.

DECLARE
salary number (6);

* “salary” is a variable of datatype number and of length 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.

 Local variables - These are declared in a inner block and cannot be


referenced by outside Blocks.
 Global variables - These are declared in a outer block and can be
referenced by its itself and by its inner blocks.

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.

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.

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;

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.

The General Syntax to define a composite datatype is:

TYPE record_type_name IS RECORD


(first_col_name column_datatype,
second_col_name column_datatype, ...);

 record_type_name – it is the name of the composite type you want to


define.
 first_col_name, second_col_name, etc.,- it is the names the
fields/columns within the record.
 column_datatype defines the scalar datatype of the fields.

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 General Syntax to declare a record of a uer-defined datatype is:


record_name record_type_name;

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;

For example, the above declaration of employee_rec can as follows:

DECLARE
employee_rec employee%ROWTYPE;

The advantages of declaring the record as a ROWTYPE are:


1) You do not need to explicitly declare variables for all the columns in a
table.
2) If you alter the column specification in the database table, you do not need
to update the code.
The disadvantage of declaring the record as a ROWTYPE is:
1) When u create a record as a ROWTYPE, fields will be created for all the
columns in the table and memory will be used to create the datatype for all
the fields. So use ROWTYPE only when you are using all the columns of the
table in the program.
NOTE: When you are creating a record, you are just creating a datatype,
similar to creating a variable. You need to assign values to the record to use
them.

The following table consolidates the different ways in which you can define
and declare a pl/sql record.

Usage
Syntax

TYPE record_type_name IS RECORD Define a composite datatype,


(column_name1 datatype, column_name2 where each field is scalar.
datatype, ...);

col_name table_name.column_name Dynamically define the datatype


%type; of a column based on a database
column.

record_name record_type_name; Declare a record based on a user-


defined type.

record_name table_name%ROWTYPE; Dynamically declare a record


based on an entire row of a table.
Each column in the table
corresponds to a field in the
record.
Passing Values To and From a Record
When you assign values to a record, you actually assign values to the fields
within it.
The General Syntax to assign a value to a column within a record direclty is:

record_name.col_name := value;

If you used %ROWTYPE to declare a record, you can assign values as shown:

record_name.column_name := value;

We can assign values to records using SELECT Statements as shown:

SELECT col1, col2


INTO record_name.col_name1, record_name.col_name2
FROM table_name
[WHERE clause];

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:

SELECT * INTO record_name


FROM table_name
[WHERE clause];

Lets see how we can get values from a record.


The General Syntax to retrieve a value from a specific field into another
variable is:

var_name := record_name.col_name;

The following table consolidates the different ways you can assign values to
and from a record:

Syntax Usage

record_name.col_name := value; To directly assign a value to a


specific column of a record.

record_name.column_name := value; To directly assign a value to a


specific column of a record, if
the record is declared using
%ROWTYPE.

SELECT col1, col2 INTO To assign values to each field of


record_name.col_name1, a record from the database
record_name.col_name2 FROM table_name table.
[WHERE clause];

SELECT * INTO record_name FROM To assign a value to all fields in


table_name [WHERE clause]; the record from a database
table.

variable_name := record_name.col_name; To get a value from a record


column and assigning it to a
variable.

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.

General Syntax to write a Simple Loop is


:
LOOP
statements;
EXIT;
{or EXIT WHEN condition;}
END LOOP;
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.
2) While Loop
A WHILE LOOP is used when a set of statements has to be executed as long
as a condition is true. The condition is evaluated at the beginning of each
iteration. The iteration continues until the condition becomes false.
The General Syntax to write a WHILE LOOP is:
WHILE <condition>
LOOP statements;
END LOOP;
Important steps to follow when executing a while loop:

1) Initialise a variable before the loop body.


2) Increment the variable in the loop.
3) EXIT WHEN statement and EXIT statements can be used in while loops but
it's not done oftenly.
3) FOR Loop
A FOR LOOP is used to execute a set of statements for a predetermined
number of times. Iteration occurs between the start and end integer values
given. The counter is always incremented by 1. The loop exits when the
counter reachs the value of the end integer.
The General Syntax to write a FOR LOOP is:
FOR counter IN val1..val2
LOOP statements;
END LOOP;

 val1 - Start integer value.


 val2 - End integer value.

Important steps to follow when executing a while loop:

1) The counter variable is implicitly declared in the declaration section, so it's


not necessary to declare it explicity.
2) The counter variable is incremented by 1 and does not need to be
incremented explicitly.
3) EXIT WHEN statement and EXIT statements can be used in FOR loops but
it's not done oftenly.

You might also like