Unit 3 Rdbms
Unit 3 Rdbms
PL/SQL Introduction
PL/SQL is a block structured language that enables developers to combine the power of
SQL with procedural statements. All the statements of a block are passed to oracle engine
all at once which increases processing speed and decreases the traffic.
Basics of PL/SQL
Features of PL/SQL
PL/SQL has the following features −
SQL PL/SQL
PL\SQL-Introduction
PL-SQL (Procedural - SQL)
➔ Function
➔ Procedure
➔ Trigger
➔ Cursor
The sections of a PL/SQL block are:
1. The Declare section
2. The master Begin and End section that also (optionally) contains as Exception
section.
Declare
Procedural Statements;
Begin
Procedural Statements;
SQL statements;
Exceptions
SQL statements;
END;
Scalar
1 Single values with no internal components, such as a NUMBER, DATE, or
BOOLEAN.
Composite
3 Data items that have internal components that can be accessed individually.
For example, collections and records.
Reference
4 Pointers to other data items.
PL/SQL Scalar Data Types and Subtypes come under the following categories −
Numeric
1 Numeric values on which arithmetic operations are performed.
Character
2 Alphanumeric values that represent single characters or strings of characters.
Boolean
3 Logical values on which logical operations are performed.
Datetime
4 Dates and times.
PL/SQL provides subtypes of data types. For example, the data type NUMBER has a
subtype called INTEGER. You can use the subtypes in your PL/SQL program to make
the data types compatible with data types in other programs while embedding the PL/SQL
code in another program, such as a Java program.
Following table lists out the PL/SQL pre-defined numeric data types and their sub-types
PLS_INTEGER
1 Signed integer in range -2,147,483,648 through 2,147,483,647, represented
in 32 bits
BINARY_INTEGER
2 Signed integer in range -2,147,483,648 through 2,147,483,647, represented
in 32 bits
BINARY_FLOAT
3 Single-precision IEEE 754-format floating-point number
BINARY_DOUBLE
4 Double-precision IEEE 754-format floating-point number
NUMBER(prec, scale)
Fixed-point or floating-point number with absolute value in range 1E-130 to
5 (but not including) 1.0E126. A NUMBER variable can also represent 0
DEC(prec, scale)
6 ANSI specific fixed-point type with maximum precision of 38 decimal digits
DECIMAL(prec, scale)
7 IBM specific fixed-point type with maximum precision of 38 decimal digits
NUMERIC(pre, secale)
8 Floating type with maximum precision of 38 decimal digits
DOUBLE PRECISION
9 ANSI specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)
FLOAT
10 ANSI and IBM specific floating-point type with maximum precision of 126
binary digits (approximately 38 decimal digits)
INT
11 ANSI specific integer type with maximum precision of 38 decimal digits
INTEGER
12 ANSI and IBM specific integer type with maximum precision of 38 decimal
digits
SMALLINT
13 ANSI and IBM specific integer type with maximum precision of 38 decimal
digits
REAL
14 Floating-point type with maximum precision of 63 binary digits (approximately
18 decimal digits)
DECLARE
num1 INTEGER;
num2 REAL;
num3 DOUBLE PRECISION;
BEGIN
null;
END;
/
When the above code is compiled and executed, it produces the following result −
Following is the detail of PL/SQL pre-defined character data types and their sub-types −
CHAR
1 Fixed-length character string with maximum size of 32,767 bytes
VARCHAR2
2 Variable-length character string with maximum size of 32,767 bytes
RAW
3 Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL
NCHAR
4 Fixed-length national character string with maximum size of 32,767 bytes
NVARCHAR2
5 Variable-length national character string with maximum size of 32,767 bytes
LONG
6 Variable-length character string with maximum size of 32,760 bytes
LONG RAW
7 Variable-length binary or byte string with maximum size of 32,760 bytes, not
interpreted by PL/SQL
ROWID
8 Physical row identifier, the address of a row in an ordinary table
UROWID
9 Universal row identifier (physical, logical, or foreign row identifier)
However, SQL has no data type equivalent to BOOLEAN. Therefore, Boolean values
cannot be used in −
SQL statements
Built-in SQL functions (such as TO_CHAR)
PL/SQL functions invoked from SQL statements
Each DATE includes the century, year, month, day, hour, minute, and second. The
MONTH 01 to 12 0 to 11
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
Large Object (LOB) data types refer to large data items such as text, graphic images,
video clips, and sound waveforms. LOB data types allow efficient, random, piecewise
access to this data. Following are the predefined PL/SQL LOB data types −
You can define and use your own subtypes. The following program illustrates defining
and using a user-defined subtype −
DECLARE
SUBTYPE name IS char(20);
SUBTYPE message IS varchar2(100);
salutation name;
greetings message;
BEGIN
salutation := 'Reader ';
greetings := 'Welcome to the World of PL/SQL';
dbms_output.put_line('Hello ' || salutation || greetings);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
NULLs in PL/SQL
PL/SQL NULL values represent missing or unknown data and they are not an integer,
a character, or any other specific data type. Note that NULL is not the same as an empty
data string or the null character value '\0'. A null can be assigned but it cannot be equated
with anything, including itself.
Basic Syntax of PL/SQL which is a block-structured language; this means that the
PL/SQL programs are divided and written in logical blocks of code. Each block consists
of three sub-parts −
Declarations
This section starts with the keyword DECLARE. It is an optional
1
section and defines all variables, cursors, subprograms, and other
elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END
and it is a mandatory section. It consists of the executable PL/SQL
2
statements of the program. It should have at least one executable
line of code, which may be just a NULL command to indicate that
nothing should be executed.
Exception Handling
3 This section starts with the keyword EXCEPTION. This optional
section contains exception(s) that handle errors in the program.
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be
nested within other PL/SQL blocks using BEGIN and END. Following is the basic
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling>
END;
The end; line signals the end of the PL/SQL block. To run the code from the SQL
command line, you may need to type / at the beginning of the first blank line after the last
line of the code. When the above code is executed at the SQL prompt, it produces the
following result −
Hello World
Delimiter Description
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
.. Range operator
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
Hello World
Block Structure
PL/SQL block structure consists of three main sections: declarative, executable, and
exception-handling sections. The structure can be divided into:
BEGIN
-- Executable section (mandatory)
-- Code to be executed
DBMS_OUTPUT.PUT_LINE('Executable code goes here');
EXCEPTION
-- Exception-handling section (optional)
-- Code to handle errors
WHEN exception_name THEN
-- Actions to perform when the exception is raised
DBMS_OUTPUT.PUT_LINE('An error occurred: ' || SQLERRM);
DECLARE
counter NUMBER := 0;
greeting VARCHAR2(20) := 'Hello, PL/SQL!';
2. BEGIN (mandatory): The main executable code goes here. This is where the
logic and operations are performed.
BEGIN
DBMS_OUTPUT.PUT_LINE(greeting);
counter := counter + 1;
3. EXCEPTION (optional): This section is used to handle errors. PL/SQL exceptions can
be predefined or user-defined.
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No data found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An unexpected error occurred.');
When the above code is executed at the SQL prompt, it produces the following result −
In this example:
The Every Programming Language has a few Conditional statements. These Conditional
statements are also known as Decision Statements. There are a few Conditional
This is one of the first important PL / SQL Conditional Statement. In this statement only
if the condition is true, then the output is going to be shown. Else in any other cases there
is no opportunity for outputs.
Syntax :
IF <condition> then
Statement 1
Statement 2
Statement N
END IF;
Example :
SQL> DECLARE
N1 INTEGER;
BEGIN
N1 := 10;
IF N1 >= 10 THEN
END IF;
EXCEPTION
DBMS_OUTPUT.PUT_LINE('ERROR');
END;
OUTPUT:
The Value is 10
This is also one of the first important PL / SQL Conditional Statement. In this statement
only if the condition is true, then the output is going to be shown. Else in any other cases
there is opportunity for outputs to seen. If the if condition fails then the else statements
are executed.
This means if condition is true If statements are executed. If not possible else statements
are executed.
This kind of conditional statements are required for finding few real life problems like
finding odd or even number, Checking the number is divisible by two, three, etc., Finding
Largest Number, Finding Smallest Number, etc. many programs like this.
Syntax
IF >CONDITION> THEN
Statement 1
Statement 2
Statement N
ELSE
Statement 1
Statement 2
Statement N
END IF;
Example:
SQL> DECLARE
N1 INTEGER;
N2 INTEGER;
BEGIN
N1:=10;
N2:=5;
IF N1 > N2 THEN
ELSE
END IF;
END;
OUTPUT :
This is also one of the first important PL / SQL Conditional Statement. In this statement
only if the condition is true, then the output is going to be shown. Else in any other cases
there is opportunity for outputs to seen. If the if condition fails then the else if statements
with a condition are executed. Even if else if condition is False, then the else statements
are executed.
Syntax
IF <CONDITION> THEN
Statement 1
Statement 2
Statement N
Statement 1
Statement 2
Statement N
ELSE
Statement 1
Statement 2
Statement N
END IF;
Example
SQL> SET SERVEROUTPUT ON;
SQL> DECLARE
num1 INTEGER:= 7;
num2 INTEGER:= 8;
BEGIN
dbms_output.put_line('EQUAL');
ELSE
END IF;
END;
Output:
This is also one of the conditional statements used in PL / SQL. Here, we are going to
write the same if else statements. But in place of if statements we are going to write
another if condition else statements. The workings of these statements are same and
similar to the previous if else statements.
Syntax
Syntax 1
IF <CONDITION> THEN
IF <CONDITION> THEN
Statement 1
Statement 2
Statement N
ELSE
Statement 1
Statement 2
Statement N
END IF;
ELSE
Statement 1
Statement 2
Statement N
END IF;
Syntax 2:
IF <CONDITION> THEN
Statement 1
Statement 2
Statement N
ELSE
IF <CONDITION> THEN
Statement 1
Statement 2
Statement N
ELSE
Statement 1
Statement 2
Statement N
END IF;
END IF;
Example
SQL> DECLARE
num1 INTEGER;
num2 INTEGER;
num3 INTEGER;
BEGIN
num1:= 17;
num2:= 12;
num3:= 10;
END IF;
ELSE
END IF;
END;
Output:
PL/SQL Loops
There may be a situation when you need to execute a block of code several number of
times. In general, statements are executed sequentially: The first statement in a function
is executed first, followed by the second, and so on.
Programming languages provide various control structures that allow for more
complicated execution paths.
and following is the general form of a loop statement in most of the programming
languages −
PL/SQL provides the following types of loop to handle the looping requirements.
1. Basic Loop
2. While Loop
3. For Loop
We will learn about all three of them while covering the concept of nexted loops which
means loop inside a loop. So let's get started.
Basic loop or simple loop is preferred in PL/SQL code when there is no surety about how
many times the block of code is to be repeated. When we use the basic loop the code
block will be executed at least once.
● Simple loop always begins with the keyword LOOP and ends with a keyword
END LOOP.
● A basic/simple loop can be terminated at any given point by using the exit
statement or by specifying certain condition by using the statement exit when.
Syntax:
LOOP
sequence of statements
END LOOP;
Let's see the simple loop in action in the code example below.
Example
We have used the loop to print counting from 1 to 10 on the console and have used the
exit statement to break out of the loop.
SQL> DECLARE
i int;
BEGIN
i := 1;
LOOP
if i>10 then
exit;
end if;
dbms_output.put_line(i);
i := i+1;
END LOOP;
END;
Output:
10
Let's take one more example where we will be using the exit when statement to break out
of the loop.
SQL> DECLARE
i int;
BEGIN
i := 0;
LOOP
i := i+2;
dbms_output.put_line(i);
END LOOP;
END;
Output :
10
It is an entry controlled loop which means that before entering in a while loop first the
condition is tested, if the condition is TRUE the statement or a group of statements get
executed and if the condition is FALSE the control will move out of the while loop.
Syntax:
<action>
END LOOP;
Let's see the while loop in action in the code example below.
Example :
Below we have a simple program to print the odd numbers between 1 to 10 using the
while loop.
SQL> DECLARE
num int:=1;
BEGIN
dbms_output.put_line(''|| num);
num := num+2;
END LOOP;
END;
Output :
NOTE: You must write the code to increment the value of the variable that you put in the
condition otherwise the value of the variable will remain the same and the condition will
always remain true.
This loop is used when some statements in PL/SQL code block are to be repeated for a
fixed number of times.
When we use the for loop we are supposed to define a counter variable which decides
how many time the loop will be executed based on a starting and ending value provided
at the beginning of the loop.
The for loop automatically increments the value of the counter variable by 1 at the end of
each loop cycle.
The programmer need not have to write any instruction for incrementing or decrementing
value.
Syntax:
statement to be executed
END LOOP;
Example :
In the example below we have used a the for loop to print numbers from 1 to 10.
SQL> DECLARE
i number(2);
BEGIN
dbms_output.put_line(i);
END LOOP;
END;
Output:
10
Cursors
When an SQL statement is processed, Oracle creates a memory area known as context
area. A cursor is a pointer to this context area. It contains all information needed for
processing the statement. In PL/SQL, the context area is controlled by Cursor. A cursor
contains information on a select statement and the rows of data accessed by it.
A cursor is used to referred to a program to fetch and process the rows returned by the
SQL statement, one at a time. There are two types of cursors:
● Implicit Cursors
● Explicit Cursors
The implicit cursors are automatically generated by Oracle while an SQL statement is
executed, if you don't use an explicit cursor for the statement.
These are created by default to process the statements when DML statements like
INSERT, UPDATE, DELETE etc. are executed.
Oracle provides some attributes known as Implicit cursor's attributes to check the status
of DML operations. Some of them are: %FOUND, %NOTFOUND, %ROWCOUNT and
%ISOPEN.
For example: When you execute the SQL statements like INSERT, UPDATE, DELETE
then the cursor attributes tell whether any rows are affected and how many have been
affected. If you run a SELECT INTO statement in PL/SQL block, the implicit cursor
attribute can be used to find out whether any row has been returned by the SELECT
statement. It will return an error if there no data is selected.
The following table specifies the status of the cursor with each of its attribute.
Attribute Description
%FOUND Its return value is TRUE if DML statements like INSERT, DELETE
and UPDATE affect at least one row or more rows or a SELECT
INTO statement returned one or more rows. Otherwise it returns
FALSE.
%NOTFOUND Its return value is TRUE if DML statements like INSERT, DELETE
and UPDATE affect no row, or a SELECT INTO statement return no
rows. Otherwise it returns FALSE. It is a just opposite of %FOUND.
%ISOPEN It always returns FALSE for implicit cursors, because the SQL
cursor is automatically closed after executing its associated SQL
statements.
Let's execute the following program to update the table and increase salary of each
customer by 5000. Here, SQL%ROWCOUNT attribute is used to determine the number
of rows affected:
Create procedure:
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
IF sql%notfound THEN
total_rows := sql%rowcount;
END IF;
END;
Output:
6 customers updated
Now, if you check the records in customer table, you will find that the rows are updated.
The Explicit cursors are defined by the programmers to gain more control over the context
area. These cursors should be defined in the declaration section of the PL/SQL block. It
is created on a SELECT statement which returns more than one row.
Steps:
You must follow these steps while working with an explicit cursor.
It defines the cursor with a name and the associated SELECT statement.
CURSOR name IS
SELECT statement;
It is used to allocate memory for the cursor and make it easy to fetch the rows returned
by the SQL statements into it.
OPEN cursor_name;
It is used to access one row at a time. You can fetch rows from the above-opened cursor
as follows:
It is used to release the allocated memory. The following syntax is used to close the
above-opened cursors.
Close cursor_name;
Explicit cursors are defined by programmers to gain more control over the context area.
It is defined in the declaration section of the PL/SQL block. It is created on a SELECT
statement which returns more than one row.
Let's take an example to demonstrate the use of explicit cursor. In this example, we are
using the already created CUSTOMERS table.
Create procedure:
Execute the following program to retrieve the customer name and address.
DECLARE
c_id customers.id%type;
c_name customers.name%type;
c_addr customers.address%type;
CURSOR c_customers is
BEGIN
OPEN c_customers;
LOOP
END LOOP;
CLOSE c_customers;
END;
Output:
1 Ramesh Allahabad
2 Suresh Kanpur
3 Mahesh Ghaziabad
4 Chandan Noida
5 Alex Paris
6 Sunita Delhi
PL/SQL - Exceptions
What is Exception?
PL/SQL facilitates programmers to catch such conditions using exception block in the
program and an appropriate action is taken against the error condition.
● System-defined Exceptions
● User-defined Exceptions
The general syntax for exception handling is as follows. Here you can list down as many
exceptions as you can handle. The default exception will be handled using WHEN others
THEN −
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
exception1-handling-statements
exception2-handling-statements
exception3-handling-statements
........
exception3-handling-statements
END;
Example
Let us write a code to illustrate the concept. We will be using the CUSTOMERS table we
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
FROM customers
WHERE id = c_id;
EXCEPTION
dbms_output.put_line('Error!');
END;
When the above code is executed at the SQL prompt, it produces the following result −
No such customer!
The above program displays the name and address of a customer whose ID is given.
Since there is no customer with ID value 8 in our database, the program raises the run-
time exception NO_DATA_FOUND, which is captured in the EXCEPTION block.
Raising Exceptions
Exceptions are raised by the database server automatically whenever there is any internal
database error, but exceptions can be raised explicitly by the programmer by using the
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
statement;
END;
You can use the above syntax in raising the Oracle standard exception or any user-
defined exception. In the next section, we will give you an example on raising a user-
defined exception. You can raise the Oracle standard exceptions in a similar way.
User-defined Exceptions
PL/SQL allows you to define your own exceptions according to the need of your program.
A user-defined exception must be declared and then raised explicitly, using either a
RAISE statement or the procedure
DBMS_STANDARD.RAISE_APPLICATION_ERROR.
DECLARE
my-exception EXCEPTION;
Example
The following example illustrates the concept. This program asks for a customer ID, when
the user enters an invalid ID, the exception invalid_id is raised.
DECLARE
c_name customerS.Name%type;
c_addr customers.address%type;
ex_invalid_id EXCEPTION;
BEGIN
RAISE ex_invalid_id;
ELSE
FROM customers
WHERE id = c_id;
END IF;
EXCEPTION
dbms_output.put_line('Error!');
END;
When the above code is executed at the SQL prompt, it produces the following result −
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database
is raised when a SELECT INTO statement returns no rows. The following table lists few
Oracle SQLC
Exception Description
Error ODE