PL SQL Note Full
PL SQL Note Full
PL SQL Note Full
PL/SQL is an extension of Structured Query Language (SQL) that is used in Oracle. Unlike SQL,
PL/SQL allows the programmer to write code in a procedural format. Full form of PL/SQL is
"Procedural Language extensions to SQL".
Features of PL/SQL
Advantages of PL/SQL
PL/SQL has the following advantages −
SQL is the standard database language and PL/SQL is strongly integrated with SQL. PL/SQL
supports both static and dynamic SQL. Static SQL supports DML operations and transaction
control from PL/SQL block. In Dynamic SQL, SQL allows embedding DDL statements in
PL/SQL blocks.
PL/SQL allows sending an entire block of statements to the database at one time. This reduces
network traffic and provides high performance for the applications.
PL/SQL gives high productivity to programmers as it can query, transform, and update data in a
database.
PL/SQL saves time on design and debugging by strong features, such as exception handling,
encapsulation, data hiding, and object-oriented data types.
Applications written in PL/SQL are fully portable.
PL/SQL provides high security level.
PL/SQL provides access to predefined SQL packages.
PL/SQL provides support for Object-Oriented Programming.
PL/SQL provides support for developing Web Applications and Server Pages.
1|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END;
/
PL/SQL Identifiers
PL/SQL identifiers are constants, variables, exceptions, procedures, cursors, and reserved words. The
identifiers consist of a letter optionally followed by more letters, numerals, dollar signs, underscores, and
number signs and should not exceed 30 characters.
2|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
By default, identifiers are not case-sensitive. So you can use integer or INTEGER to represent a numeric
value. You cannot use a reserved keyword as an identifier.
PL/SQL Delimiters
Delimiter Description
% Attribute indicator
. Component selector
, Item separator
= Relational operator
; Statement terminator
:= Assignment operator
|| Concatenation operator
** Exponentiation operator
3|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
PL/SQL Comments
Program comments are explanatory statements that can be included in the PL/SQL code that you write
and helps anyone reading its source code. All programming languages allow some form of comments.
The PL/SQL supports single-line and multi-line comments. All characters available inside any comment
are ignored by the PL/SQL compiler. The PL/SQL single-line comments start with the delimiter --
(double hyphen) and multi-line comments are enclosed by /* and */.
Example:
DECLARE
-- variable declaration
message varchar2(20):= 'Hello, World!';
BEGIN
/*
* PL/SQL executable statement(s)
*/
dbms_output.put_line(message);
END;
/
PL/SQL block
Function
Package
Package body
Procedure
Trigger
Type
Type body
PL/SQL - Data Types
A data type is associated with the specific storage format and range constraints. In Oracle, each value or
constant is assigned with a data type.
Basically, it defines how the data is stored, handled and treated by Oracle during the data storage and
processing.
The main difference between PL/SQL and SQL data types is, SQL data type are limited to table column
while the PL/SQL data types are used in the PL/SQL blocks.
4|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
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.
5|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
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)
5
Fixed-point or floating-point number with absolute value in range 1E-130 to (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)
6|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
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)
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
7|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
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)
The BOOLEAN data type stores logical values that are used in logical operations. The logical values are
the Boolean values TRUE and FALSE and the value NULL.
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
The DATE data type is used to store fixed-length datetimes, which include the time of day in seconds
since midnight. Valid dates range from January 1, 4712 BC to December 31, 9999 AD.
The default date format is set by the Oracle initialization parameter NLS_DATE_FORMAT. For
example, the default might be 'DD-MON-YY', which includes a two-digit number for the day of the
month, an abbreviation of the month name, and the last two digits of the year. For example, 01-OCT-12.
Each DATE includes the century, year, month, day, hour, minute, and second. The following table
shows the valid values for each field
MONTH 01 to 12 0 to 11
8|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
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.
PL/SQL – Variables
PL/SQL programming language allows defining various types of variables, such as date time data types,
records, collections.
Syntax
variable_name is a valid identifier in PL/SQL, datatype must be a valid PL/SQL data type or any user
defined data type which we already have discussed.
Example
9|Page
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Example
DECLARE
a integer := 30;
b integer := 20;
c integer;
f real;
BEGIN
c := a + b;
dbms_output.put_line('Value of c: ' || c);
f := 70.0/3.0;
dbms_output.put_line('Value of f: ' || f);
END;
/
Output
Value of c: 50
Value of f: 23.333333333333333333
Example 1
Table Created
Let us now insert some values in the table −
10 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
DECLARE
c_id customers.id%type := 1;
c_name customers.name%type;
c_addr customers.address%type;
c_sal customers.salary%type;
BEGIN
SELECT name, address, salary INTO c_name, c_addr, c_sal
FROM customers
WHERE id = c_id;
dbms_output.put_line
('Customer ' ||c_name || ' from ' || c_addr || ' earns ' || c_sal);
END;
/
Result
Customer Ramesh from Ahmedabad earns 2000
Example 2
DECLARE
EMP_NO NUMBER,
EMP_NAME VARCHAR2(150),
MANAGER NUMBER,
11 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
SALARY NUMBER
);
ex2_emp_rec emp_det;
BEGIN
ex2_emp_rec.emp_no:= 1001;
ex2_emp_rec.emp_name:='XYZ';
ex2_emp_rec.manager:= 1000;
ex2_emp_rec.salary:=10000;
dbms_output.put_line('Employee Detail');
END;
Output:
Employee Detail
A constant holds a value that once declared, does not change in the program.
12 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Declaring a Constant
Example
PL/SQL Literals
A literal is an explicit numeric, character, string, or Boolean value not represented by an identifier.
Numeric Literals
Character Literals
String Literals
BOOLEAN Literals
Date and Time Literals
The following table provides examples from all these categories of literal values.
13 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Numeric Literals
050 78 -14 0 +32767
1
6.6667 0.0 -12.0 3.14159 +7800.00
6E5 1.0E-8 3.14159e0 -1E38 -9.5e-3
Character Literals
2
'A' '%' '9' ' ' 'z' '('
String Literals
3 'Hello, world!'
'19-NOV-12'
BOOLEAN Literals
4
TRUE, FALSE, and NULL.
To embed single quotes within a string literal, place two single quotes next to each other as shown in the
following program –
Example
DECLARE
message varchar2(30):= 'Sister Nivedita University';
BEGIN
dbms_output.put_line(message);
END;
/
Result
Sister Nivedita University
PL/SQL procedure successfully completed.
PL/SQL – Operators
An operator is a symbol that tells the compiler to perform specific mathematical or logical manipulation.
PL/SQL language is rich in built-in operators and provides the following types of operators –
14 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Arithmetic operators
Relational operators
Comparison operators
Logical operators
String operators
Arithmetic operators
Following table shows all the arithmetic operators supported by PL/SQL. Let us
assume variable A holds 10 and variable B holds 5, then –
** Exponentiation operator, raises one operand to the power of other A ** B will give 100000
Relational Operators
Relational operators compare two expressions or values and return a Boolean result. Following table
shows all the relational operators supported by PL/SQL. Let us assume variable A holds 10 and variable
B holds 20, then –
Checks if the values of two operands are equal or not, if yes then condition (A = B) is not
=
becomes true. true.
!=
Checks if the values of two operands are equal or not, if values are not equal (A != B) is
<> then condition becomes true. true.
~=
Checks if the value of left operand is greater than the value of right operand, (A > B) is not
>
if yes then condition becomes true. true.
15 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Checks if the value of left operand is less than the value of right operand, if (A < B) is true.
<
yes then condition becomes true.
Checks if the value of left operand is greater than or equal to the value of right (A >= B) is not
>=
operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than or equal to the value of right (A <= B) is
<=
operand, if yes then condition becomes true. true
Comparison Operators
Comparison operators are used for comparing one expression to another. The result is always
either TRUE, FALSE or NULL.
Show Examples
The LIKE operator compares a character, string, or If 'Zara Ali' like 'Z% A_i' returns a
LIKE CLOB value to a pattern and returns TRUE if the Boolean true, whereas, 'Nuha Ali'
value matches the pattern and FALSE if it does not. like 'Z% A_i' returns a Boolean false.
Logical Operators
Following table shows the Logical operators supported by PL/SQL. All these operators work on Boolean
operands and produce Boolean results. Let us assume variable A holds true and variable B holds false,
then −
Show Examples
16 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Called the logical AND operator. If both the operands are true then condition (A and B) is
and
becomes true. false.
Called the logical OR Operator. If any of the two operands is true then (A or B) is
or
condition becomes true. true.
Called the logical NOT Operator. Used to reverse the logical state of its not (A and B)
not
operand. If a condition is true then Logical NOT operator will make it false. is true.
Operator precedence determines the grouping of terms in an expression. This affects how an expression
is evaluated. Certain operators have higher precedence than others; for example, the multiplication
operator has higher precedence than the addition operator.
For example, x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher precedence than
+, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the lowest appear at
the bottom. Within an expression, higher precedence operators will be evaluated first.
The precedence of operators goes as follows: =, <, >, <=, >=, <>, !=, ~=, ^=, IS NULL, LIKE,
BETWEEN, IN.
Show Examples
Operator Operation
** exponentiation
+, - identity, negation
*, / multiplication, division
comparison
AND conjunction
OR inclusion
17 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
PL/SQL – Conditions
IF - THEN statement
1 The IF statement associates a condition with a sequence of statements enclosed by the
keywords THEN and END IF. If the condition is true, the statements get executed and if the
condition is false or NULL then the IF statement does nothing.
IF-THEN-ELSE statement
2 IF statement adds the keyword ELSE followed by an alternative sequence of statement. If the
condition is false or NULL, then only the alternative sequence of statements get executed. It ensures
that either of the sequence of statements is executed.
IF-THEN-ELSIF statement
3
It allows you to choose between several alternatives.
Case statement
Like the IF statement, the CASE statement selects one sequence of statements to execute.
4
However, to select the sequence, the CASE statement uses a selector rather than multiple Boolean
expressions. A selector is an expression whose value is used to select one of several alternatives.
18 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
nested IF-THEN-ELSE
6 You can use one IF-THEN or IF-THEN-ELSIF statement inside another IF-THEN or IF-THEN-
ELSIF statement(s).
PL/SQL – Loops
19 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Syntax
Example
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
IF x > 50 THEN
exit;
END IF;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
20 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
40
50
After Exit x is: 60
DECLARE
x number := 10;
BEGIN
LOOP
dbms_output.put_line(x);
x := x + 10;
exit WHEN x > 50;
END LOOP;
-- after exit, control resumes here
dbms_output.put_line('After Exit x is: ' || x);
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
10
20
30
40
50
After Exit x is: 60
Syntax
Example
DECLARE
a number(2) := 10;
BEGIN
WHILE a < 20 LOOP
dbms_output.put_line('value of a: ' || a);
21 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
a := a + 1;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
Syntax
22 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
The initial_value need not be 1; however, the loop counter increment (or decrement) must be
1.
PL/SQL allows the determination of the loop range dynamically at run time.
Example
DECLARE
a number(2);
BEGIN
FOR a in 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 10
value of a: 11
value of a: 12
value of a: 13
value of a: 14
value of a: 15
value of a: 16
value of a: 17
value of a: 18
value of a: 19
value of a: 20
By default, iteration proceeds from the initial value to the final value, generally upward from the lower
bound to the higher bound. You can reverse this order by using the REVERSE keyword. In such case,
iteration proceeds the other way. After each iteration, the loop counter is decremented.
However, you must write the range bounds in ascending (not descending) order. The following program
illustrates this −
DECLARE
a number(2) ;
BEGIN
FOR a IN REVERSE 10 .. 20 LOOP
dbms_output.put_line('value of a: ' || a);
END LOOP;
END;
/
23 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
When the above code is executed at the SQL prompt, it produces the following result −
value of a: 20
value of a: 19
value of a: 18
value of a: 17
value of a: 16
value of a: 15
value of a: 14
value of a: 13
value of a: 12
value of a: 11
value of a: 10
Example
The following program uses a nested basic loop to find the prime numbers from 2 to 100 −
DECLARE
24 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
i number(3);
j number(3);
BEGIN
i := 2;
LOOP
j:= 2;
LOOP
exit WHEN ((mod(i, j) = 0) or (j = i));
j := j +1;
END LOOP;
IF (j = i ) THEN
dbms_output.put_line(i || ' is prime');
END IF;
i := i + 1;
exit WHEN i = 50;
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
2 is prime
3 is prime
5 is prime
7 is prime
11 is prime
13 is prime
17 is prime
19 is prime
23 is prime
29 is prime
31 is prime
37 is prime
41 is prime
43 is prime
47 is prime
PL/SQL – Strings
The string in PL/SQL is actually a sequence of characters with an optional size specification. The
characters could be numeric, letters, blank, special characters or a combination of all.
Fixed-length strings − In such strings, programmers specify the length while declaring the
string. The string is right-padded with spaces to the length so specified.
25 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Variable-length strings − In such strings, a maximum length up to 32,767, for the string is
specified and no padding takes place.
Character large objects (CLOBs) − These are variable-length strings that can be up to 128
terabytes.
Result
John Smith
Infotech
Hello! I'm John Smith from Infotech.
1 ASCII(x);
Returns the ASCII value of the character x.
26 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
2 CHR(x);
Returns the character with the ASCII value of x.
3 CONCAT(x, y);
Concatenates the strings x and y and returns the appended string.
4 INITCAP(x);
Converts the initial letter of each word in x to uppercase and returns that string.
6 INSTRB(x);
Returns the location of a string within another string, but returns the value in bytes.
7 LENGTH(x);
Returns the number of characters in x.
8 LENGTHB(x);
Returns the length of a character string in bytes for single byte character set.
9 LOWER(x);
Converts the letters in x to lowercase and returns that string.
11 LTRIM(x [, trim_string]);
Trims characters from the left of x.
12 NANVL(x, value);
Returns value if x matches the NaN special value (not a number), otherwise x is returned.
13 NLS_INITCAP(x);
Same as the INITCAP function except that it can use a different sort method as specified by
27 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
NLSSORT.
NLS_LOWER(x) ;
14
Same as the LOWER function except that it can use a different sort method as specified by
NLSSORT.
NLS_UPPER(x);
15
Same as the UPPER function except that it can use a different sort method as specified by
NLSSORT.
NLSSORT(x);
16
Changes the method of sorting the characters. Must be specified before any NLS function;
otherwise, the default sort will be used.
17 NVL(x, value);
Returns value if x is null; otherwise, x is returned.
21 RTRIM(x [, trim_string]);
Trims x from the right.
22 SOUNDEX(x) ;
Returns a string containing the phonetic representation of x.
24 SUBSTRB(x);
28 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Same as SUBSTR except that the parameters are expressed in bytes instead of characters for the
single-byte character systems.
26 UPPER(x);
Converts the letters in x to uppercase and returns that string.
Example 1
DECLARE
greetings varchar2(11) := 'hello world';
BEGIN
dbms_output.put_line(UPPER(greetings));
dbms_output.put_line(LOWER(greetings));
dbms_output.put_line(INITCAP(greetings));
29 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
h
d
World
ello World
2
Example 2
DECLARE
greetings varchar2(30) := '......Hello World.....';
BEGIN
dbms_output.put_line(RTRIM(greetings,'.'));
dbms_output.put_line(LTRIM(greetings, '.'));
dbms_output.put_line(TRIM( '.' from greetings));
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
......Hello World
Hello World.....
Hello World
PL/SQL – Arrays
The PL/SQL programming language provides a data structure called the VARRAY, which can store a
fixed-size sequential collection of elements of the same type. A varray is used to store an ordered
collection of data, however it is often better to think of an array as a collection of variables of the same
type. All varrays consist of contiguous memory locations. The lowest address corresponds to the first
element and the highest address to the last element.
Where
30 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Example:
CREATE Or REPLACE TYPE namearray AS VARRAY(3) OF VARCHAR2(10);
/
Type created.
Note:
In Oracle environment, the starting index for varrays is always 1.
You can initialize the varray elements using the constructor method of the varray type, which has
the same name as the varray.
Varrays are one-dimensional arrays.
A varray is automatically NULL when it is declared and must be initialized before its elements
can be referenced.
PL/SQL – Procedures
31 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
A subprogram is a program unit/module that performs a particular task. These subprograms are
combined to form larger programs. This is basically called the 'Modular design'. A subprogram
can be invoked by another subprogram or program which is called the calling program.
A subprogram can be created −
At the schema level
Inside a package
Inside a PL/SQL block
At the schema level, subprogram is a standalone subprogram. It is created with the CREATE
PROCEDURE or the CREATE FUNCTION statement. It is stored in the database and can be deleted
with the DROP PROCEDURE or DROP FUNCTION statement.
PL/SQL subprograms are named PL/SQL blocks that can be invoked with a set of parameters.
Each PL/SQL subprogram has a name, and may also have a parameter list. Like anonymous PL/SQL
blocks, the named blocks will also have the following three parts −
Declarative Part
1 It is an optional part. However, the declarative part for a subprogram does not start with the
DECLARE keyword. It contains declarations of types, cursors, constants, variables, exceptions, and
nested subprograms. These items are local to the subprogram and cease to exist when the
subprogram completes execution.
2 Executable Part
This is a mandatory part and contains statements that perform the designated action.
3 Exception-handling
This is again an optional part. It contains the code that handles run-time errors.
Creating a Procedure
A procedure is created with the CREATE OR REPLACE PROCEDURE statement.
Syntax:-
CREATE [OR REPLACE] PROCEDURE procedure_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
32 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
{IS | AS}
BEGIN
< procedure_body >
END procedure_name;
Where,
procedure-name specifies the name of the procedure.
[OR REPLACE] option allows the modification of an existing procedure.
The optional parameter list contains name, mode and types of the parameters. IN represents the
value that will be passed from outside and OUT represents the parameter that will be used to
return a value outside of the procedure.
procedure-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone procedure.
Example:
CREATE OR REPLACE PROCEDURE greetings
AS
BEGIN
dbms_output.put_line('Hello World!');
END;
/
1 IN
33 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
An IN parameter lets you pass a value to the subprogram. It is a read-only parameter. Inside the
subprogram, an IN parameter acts like a constant. It cannot be assigned a value. You can pass a
constant, literal, initialized variable, or expression as an IN parameter. You can also initialize it to a
default value; however, in that case, it is omitted from the subprogram call. It is the default mode of
parameter passing. Parameters are passed by reference.
OUT
An OUT parameter returns a value to the calling program. Inside the subprogram, an OUT parameter
2
acts like a variable. You can change its value and reference the value after assigning it. The actual
parameter must be variable and it is passed by value.
IN OUT
An IN OUT parameter passes an initial value to a subprogram and returns an updated value to the
caller. It can be assigned a value and the value can be read.
3
The actual parameter corresponding to an IN OUT formal parameter must be a variable, not a
constant or an expression. Formal parameter must be assigned a value. Actual parameter is passed by
value.
Example 1
This program finds the minimum of two values. Here, the procedure takes two numbers using the IN
mode and returns their minimum using the OUT parameters.
DECLARE
a number;
b number;
c number;
PROCEDURE findMin(x IN number, y IN number, z OUT number) IS
BEGIN
IF x < y THEN
z:= x;
ELSE
z:= y;
END IF;
END;
BEGIN
a:= 23;
b:= 45;
findMin(a, b, c);
dbms_output.put_line(' Minimum of (23, 45) : ' || c);
END;
/
Result:
Minimum of (23, 45): 23
Example 2
34 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
DECLARE
a number;
PROCEDURE squareNum(x IN OUT number) IS
BEGIN
x := x * x;
END;
BEGIN
a:= 23;
squareNum(a);
dbms_output.put_line(' Square of (23): ' || a);
END;
/
Result:
Square of (23): 529
Methods for Passing Parameters
Actual parameters can be passed in three ways −
Positional notation
Named notation
Mixed notation
Positional Notation
Named Notation
In named notation, the actual parameter is associated with the formal parameter using the arrow symbol
( => ). The procedure call will be like the following −
findMin(x => a, y => b, z => c, m => d);
Mixed Notation
In mixed notation, you can mix both notations in procedure call; however, the positional notation should
precede the named notation.
The following call is legal −
findMin(a, b, c, m => d);
However, this is not legal:
35 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
PL/SQL – Functions
A function is same as a procedure except that it returns a value.
Creating a Function
A standalone function is created using the CREATE FUNCTION statement.
Syntax:
CREATE [OR REPLACE] FUNCTION function_name
[(parameter_name [IN | OUT | IN OUT] type [, ...])]
RETURN return_datatype
{IS | AS}
BEGIN
< function_body >
END [function_name];
Where,
function-name specifies the name of the function.
[OR REPLACE] option allows the modification of an existing function.
The optional parameter list contains name, mode and types of the parameters. IN represents the
value that will be passed from outside and OUT represents the parameter that will be used to
return a value outside of the procedure.
The function must contain a return statement.
The RETURN clause specifies the data type you are going to return from the function.
function-body contains the executable part.
The AS keyword is used instead of the IS keyword for creating a standalone function.
Example:
The following example illustrates how to create and call a standalone function. This function returns the
total number of CUSTOMERS in the customers table.
Select * from customers;
36 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
RETURN total;
END;
/
Result:
Function created.
Calling a Function
While creating a function, you give a definition of what the function has to do. To use a function, you will
have to call that function to perform the defined task. When a program calls a function, the program
control is transferred to the called function.
A called function performs the defined task and when its return statement is executed or when the last
end statement is reached, it returns the program control back to the main program.
To call a function, you simply need to pass the required parameters along with the function name and if
the function returns a value, then you can store the returned value.
Example
DECLARE
c number(2);
BEGIN
c := totalCustomers();
dbms_output.put_line('Total no. of Customers: ' || c);
END;
/
Result
Total no. of Customers: 6
Example
DECLARE
a number;
b number;
c number;
FUNCTION findMax(x IN number, y IN number)
RETURN number
IS
z number;
BEGIN
IF x > y THEN
z:= x;
ELSE
Z:= y;
END IF;
RETURN z;
END;
BEGIN
a:= 23;
b:= 45;
37 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
c := findMax(a, b);
dbms_output.put_line(' Maximum of (23,45): ' || c);
END;
/
Result
Maximum of (23,45): 45
PL/SQL Recursive Functions
We have seen that a program or subprogram may call another subprogram. When a subprogram calls
itself, it is referred to as a recursive call and the process is known as recursion.
To illustrate the concept, let us calculate the factorial of a number. Factorial of a number n is defined as
−
n! = n*(n-1)!
= n*(n-1)*(n-2)!
...
= n*(n-1)*(n-2)*(n-3)... 1
The following program calculates the factorial of a given number by calling itself recursively −
DECLARE
num number;
factorial number;
BEGIN
num:= 6;
factorial := fact(num);
dbms_output.put_line(' Factorial '|| num || ' is ' || factorial);
END;
/
Result −
Factorial 6 is 720
PL/SQL – Cursors
38 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Oracle creates a memory area, known as the context area, for processing an SQL statement, which
contains all the information needed for processing the statement; for example, the number of rows
processed, etc. A cursor is a pointer to this context area. PL/SQL controls the context area through a
cursor. A cursor holds the rows (one or more) returned by a SQL statement. The set of rows the cursor
holds is referred to as the active set.
There are two types of cursors −
Implicit cursors
Explicit cursors
Implicit Cursors
Implicit cursors are automatically created by Oracle whenever an SQL statement is executed.
Programmers cannot control the implicit cursors and the information in it. Whenever a DML statement
(INSERT, UPDATE and DELETE) is issued, an implicit cursor is associated with this statement. For
INSERT operations, the cursor holds the data that needs to be inserted. For UPDATE and DELETE
operations, the cursor identifies the rows that would be affected. In PL/SQL, you can refer to the most
recent implicit cursor as the SQL cursor, which always has attributes such as %FOUND, %ISOPEN,
%NOTFOUND, and %ROWCOUNT.
%FOUND
1 Returns TRUE if an INSERT, UPDATE, or DELETE statement affected one or more rows or a
SELECT INTO statement returned one or more rows. Otherwise, it returns FALSE.
%NOTFOUND
2 The logical opposite of %FOUND. It returns TRUE if an INSERT, UPDATE, or DELETE statement
affected no rows, or a SELECT INTO statement returned no rows. Otherwise, it returns FALSE.
%ISOPEN
3 Always returns FALSE for implicit cursors, because Oracle closes the SQL cursor automatically after
executing its associated SQL statement.
%ROWCOUNT
4 Returns the number of rows affected by an INSERT, UPDATE, or DELETE statement, or returned by
a SELECT INTO statement.
39 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Example
We will be using the CUSTOMERS table.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program will update the table and increase the salary of each customer by 500 and use
the SQL%ROWCOUNT attribute to determine the number of rows affected −
DECLARE
total_rows number(2);
BEGIN
UPDATE customers
SET salary = salary + 500;
IF sql%notfound THEN
dbms_output.put_line('no customers selected');
ELSIF sql%found THEN
total_rows := sql%rowcount;
dbms_output.put_line( total_rows || ' customers selected ');
END IF;
END;
/
Result
6 customers selected
If you check the records in customers table, you will find that the rows have been updated −
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2500.00 |
| 2 | Khilan | 25 | Delhi | 2000.00 |
| 3 | kaushik | 23 | Kota | 2500.00 |
| 4 | Chaitali | 25 | Mumbai | 7000.00 |
| 5 | Hardik | 27 | Bhopal | 9000.00 |
40 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
| 6 | Komal | 22 | MP | 5000.00 |
+----+----------+-----+-----------+----------+
Explicit Cursors
Explicit cursors are programmer-defined cursors for gaining more control over the context area. An
explicit cursor should be defined in the declaration section of the PL/SQL Block.
Syntax:
CURSOR cursor_name IS select_statement;
Working with an explicit cursor includes the following steps −
Declaring the cursor defines the cursor with a name and the associated SELECT statement.
For example −
CURSOR c_customers IS
SELECT id, name, address FROM customers;
Opening the cursor allocates the memory for the cursor and makes it ready for fetching the rows returned
by the SQL statement into it. For example, we will open the above defined cursor as follows −
OPEN c_customers;
Fetching the cursor involves accessing one row at a time. For example, we will fetch rows from the
above-opened cursor as follows −
Closing the cursor means releasing the allocated memory. For example, we will close the above-opened
cursor as follows −
CLOSE c_customers;
41 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Example
DECLARE
c_id customers.id%type;
c_name customer.name%type;
c_addr customers.address%type;
CURSOR c_customers is
SELECT id, name, address FROM customers;
BEGIN
OPEN c_customers;
LOOP
FETCH c_customers into c_id, c_name, c_addr;
EXIT WHEN c_customers%notfound;
dbms_output.put_line(c_id || ' ' || c_name || ' ' || c_addr);
END LOOP;
CLOSE c_customers;
END;
/
Result
1 Ramesh Ahmedabad
2 Khilan Delhi
3 kaushik Kota
4 Chaitali Mumbai
5 Hardik Bhopal
6 Komal MP
PL/SQL procedure successfully completed.
PL/SQL – Records
A record is a data structure that can hold data items of different kinds. Records consist of
different fields, similar to a row of a database table.
For example, you want to keep track of your books in a library. You might want to track the
following attributes about each book, such as Title, Author, Subject, Book ID. A record
containing a field for each of these items allows treating a BOOK as a logical unit and allows
you to organize and represent its information in a better way.
PL/SQL can handle the following types of records −
Table-based
Cursor-based records
User-defined records
Table-Based Records
The %ROWTYPE attribute enables a programmer to create table-based and cursorbased records.
We will be using the CUSTOMERS table.
42 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
DECLARE
customer_rec customers%rowtype;
BEGIN
SELECT * into customer_rec
FROM customers
WHERE id = 5;
dbms_output.put_line('Customer ID: ' || customer_rec.id);
dbms_output.put_line('Customer Name: ' || customer_rec.name);
dbms_output.put_line('Customer Address: ' || customer_rec.address);
dbms_output.put_line('Customer Salary: ' || customer_rec.salary);
END;
/
Result
Customer ID: 5
Customer Name: Hardik
Customer Address: Bhopal
Customer Salary: 9000
Cursor-Based Records
The following example illustrates the concept of cursor-based records. We will be using the
CUSTOMERS table we had created and used in the previous chapters −
DECLARE
CURSOR customer_cur is
SELECT id, name, address
FROM customers;
customer_rec customer_cur%rowtype;
BEGIN
OPEN customer_cur;
LOOP
FETCH customer_cur into customer_rec;
EXIT WHEN customer_cur%notfound;
DBMS_OUTPUT.put_line(customer_rec.id || ' ' || customer_rec.name);
END LOOP;
END;
/
When the above code is executed at the SQL prompt, it produces the following result −
1 Ramesh
2 Khilan
3 kaushik
4 Chaitali
5 Hardik
6 Komal
User-Defined Records
43 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
PL/SQL provides a user-defined record type that allows you to define the different record structures.
These records consist of different fields. Suppose you want to keep track of your books in a library. You
might want to track the following attributes about each book −
Title
Author
Subject
Book ID
Defining a Record
DECLARE
TYPE books IS RECORD
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
Accessing Fields
To access any field of a record, we use the dot (.) operator. The member access operator is coded as a
period between the record variable name and the field that we wish to access. Following is an example to
explain the usage of record −
DECLARE
type books is record
(title varchar(50),
author varchar(50),
subject varchar(100),
book_id number);
book1 books;
book2 books;
BEGIN
-- Book 1 specification
book1.title := 'C Programming';
book1.author := 'Nuha Ali ';
book1.subject := 'C Programming Tutorial';
book1.book_id := 6495407;
-- Book 2 specification
book2.title := 'Telecom Billing';
book2.author := 'Zara Ali';
book2.subject := 'Telecom Billing Tutorial';
book2.book_id := 6495700;
44 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
PL/SQL – Exceptions
An exception is an error condition during a program execution. PL/SQL supports programmers
to catch such conditions using EXCEPTION block in the program and an appropriate action is
taken against the error condition.
There are two types of exceptions −
System-defined exceptions
User-defined exceptions
Syntax
DECLARE
<declarations section>
BEGIN
<executable command(s)>
EXCEPTION
<exception handling goes here >
WHEN exception1 THEN
exception1-handling-statements
WHEN exception2 THEN
exception2-handling-statements
45 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Example
We will be using the CUSTOMERS table.
DECLARE
c_id customers.id%type := 8;
c_name customerS.Name%type;
c_addr customers.address%type;
BEGIN
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
EXCEPTION
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
/
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 command RAISE.
Syntax for raising an exception −
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
46 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
RAISE exception_name;
END IF;
EXCEPTION
WHEN exception_name THEN
statement;
END;
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.
The syntax for declaring an exception is −
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_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
WHEN ex_invalid_id THEN
dbms_output.put_line('ID must be greater than zero!');
WHEN no_data_found THEN
dbms_output.put_line('No such customer!');
WHEN others THEN
dbms_output.put_line('Error!');
END;
47 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
/
When the above code is executed at the SQL prompt, it produces the following result −
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
Pre-defined Exceptions
PL/SQL provides many pre-defined exceptions, which are executed when any database rule is violated
by a program.
Oracle
Exception SQLCODE Description
Error
48 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
PL/SQL - Triggers
Triggers are stored programs, which are automatically executed or fired when some events occur.
Triggers are, in fact, written to be executed in response to any of the following events −
A database manipulation (DML) statement (DELETE, INSERT, or UPDATE)
49 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
Triggers can be defined on the table, view, schema, or database with which the event is associated.
Benefits of Triggers
Creating Triggers
50 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
[FOR EACH ROW] − This specifies a row-level trigger, i.e., the trigger will be executed for
each row being affected. Otherwise the trigger will execute just once when the SQL statement is
executed, which is called a table level trigger.
WHEN (condition) − This provides a condition for rows for which the trigger would fire. This
clause is valid only for row-level triggers.
Example
we will be using the CUSTOMERS table.
Select * from customers;
+----+----------+-----+-----------+----------+
| ID | NAME | AGE | ADDRESS | SALARY |
+----+----------+-----+-----------+----------+
| 1 | Ramesh | 32 | Ahmedabad | 2000.00 |
| 2 | Khilan | 25 | Delhi | 1500.00 |
| 3 | kaushik | 23 | Kota | 2000.00 |
| 4 | Chaitali | 25 | Mumbai | 6500.00 |
| 5 | Hardik | 27 | Bhopal | 8500.00 |
| 6 | Komal | 22 | MP | 4500.00 |
+----+----------+-----+-----------+----------+
The following program creates a row-level trigger for the customers table that would fire for INSERT or
UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the
salary difference between the old values and new values −
51 | P a g e
Sister Nivedita University
Department of Computer Science and Engineering
DATABASE MANAGEMENT SYSTEM LAB
If you want to query the table in the same trigger, then you should use the AFTER keyword,
because triggers can query the table or change it again only after the initial changes are applied
and the table is back in a consistent state.
The above trigger has been written in such a way that it will fire before any DELETE or INSERT
or UPDATE operation on the table, but you can write your trigger on a single or multiple
operations, for example BEFORE DELETE, which will fire whenever a record will be deleted
using the DELETE operation on the table.
Triggering a Trigger
Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement,
which will create a new record in the table −
UPDATE customers
SET salary = salary + 500
WHERE id = 2;
Result
Old salary: 1500
New salary: 2000
Salary difference: 500
52 | P a g e