Introduction to PL/SQL Basics
Introduction to PL/SQL Basics
**************************************************************************
Introduction to PL/SQL: SQL v/s PL/SQL, PL/SQL Block Structure, Language
construct of PL/SQL (Variable, Basic Composite Data Type, Conditions, Looping etc.),
% TYPE and % ROWTYPE, Using Cursor (Implicit, explicit).
**************************************************************************
Several database systems support their own procedural languages, such as PL/SQL in Oracle and
TransactSQL in Microsoft SQLServer.
Oracle has two main procedural languages, PL/SQL and Java.
PL/SQL was Oracle’s original language for stored procedures and it has syntax similar to that used
in the Ada language.
Java is supported through a Java virtual machine inside the database engine. Oracle provides a
package to encapsulate related procedures, functions, and variables into single units.
Oracle supports SQLJ (SQL embedded in Java) and JDBC, and provides a tool to generate Java
class definitions corresponding to user-defined database types.
Introduction to PL/SQL:
PL/SQL stands for Procedural Language extension of SQL. It was developed by Oracle Corporation
in the late 1980s to enhance the capabilities of SQL. It is the procedural extension language for
SQL.
DECLARE
Declaration statements;
BEGIN
Execution statements;
EXCEPTION
Exception handling statements;
END;
/
Declaration section:
It is an optional section and starts with DECLARE keyword. It is used to declare the variables,
constants, records and cursors etc.
Execution section starts with BEGIN keyword and ends with END keyword. It is a mandatory
section. It is used to write the program logic code.
Note: Execution section must have one statement.
Note:
1. Every PL/SQL statement will be followed by semicolon (;).
2. PL/SQL blocks can be nested.
Advantages of PL/SQL:
Every constant, variable, and parameter has a datatype (or type), which specifies a
storage format, constraints, and valid range of values. PL/SQL provides many predefined
datatypes. For instance, you can choose from integer, floating point, character, BOOLEAN,
date, collection, reference, and large object (LOB) types. PL/SQL also lets you define your
own subtypes.
Predefined PL/SQL datatypes are grouped into composite, LOB, reference, and scalar
type categories.
1
Scalar
Single values with no internal components, such as a NUMBER,
DATE, or BOOLEAN.
2
Large Object (LOB)
Pointers to large objects that are stored separately from other data items, such as
text, graphic images, video clips, and sound waveforms.
3
Composite
Data items that have internal components that can be accessed individually. For
example, collections and records.
4
Reference
Pointers to other data items.
1
Numeric
Numeric values on which arithmetic operations are performed.
2
Character
Alphanumeric values that represent single characters or strings of characters.
3
Boolean
Logical values on which logical operations are performed.
4
Datetime
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.
1
PLS_INTEGER
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32
bits
2
BINARY_INTEGER
Signed integer in range -2,147,483,648 through 2,147,483,647, represented in 32
bits
3
BINARY_FLOAT
Single-precision IEEE 754-format floating-point number
4
BINARY_DOUBLE
Double-precision IEEE 754-format floating-point number
5
NUMBER(prec, scale)
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
6
DEC(prec, scale)
ANSI specific fixed-point type with maximum precision of 38 decimal digits
7
DECIMAL(prec, scale)
IBM specific fixed-point type with maximum precision of 38 decimal digits
8
NUMERIC(pre, secale)
Floating type with maximum precision of 38 decimal digits
9
DOUBLE PRECISION
ANSI specific floating-point type with maximum precision of 126 binary digits
(approximately 38 decimal digits)
10
FLOAT
ANSI and IBM specific floating-point type with maximum precision of 126 binary
digits (approximately 38 decimal digits)
11
INT
ANSI specific integer type with maximum precision of 38 decimal digits
12
INTEGER
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
13
SMALLINT
ANSI and IBM specific integer type with maximum precision of 38 decimal digits
14
REAL
Floating-point type with maximum precision of 63 binary digits (approximately 18
decimal digits)
1
CHAR
Fixed-length character string with maximum size of 32,767 bytes
2
VARCHAR2
Variable-length character string with maximum size of 32,767 bytes
3
RAW
Variable-length binary or byte string with maximum size of 32,767 bytes, not
interpreted by PL/SQL
4
NCHAR
Fixed-length national character string with maximum size of 32,767 bytes
5
NVARCHAR2
Variable-length national character string with maximum size of 32,767 bytes
6
LONG
Variable-length character string with maximum size of 32,760 bytes
7
LONG RAW
Variable-length binary or byte string with maximum size of 32,760 bytes, not
interpreted by PL/SQL
8
ROWID
Physical row identifier, the address of a row in an ordinary table
9
UROWID
Universal row identifier (physical, logical, or foreign row identifier)
SQL statements
Built-in SQL functions (such as TO_CHAR)
PL/SQL functions invoked from SQL statements
MONTH 01 to 12 0 to 11
HOUR 00 to 23 0 to 23
MINUTE 00 to 59 0 to 59
BLOB Used to store large binary objects in the 8 to 128 terabytes (TB)
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;
/
Output:
Hello Reader Welcome to the World of PL/SQL
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.
Syntax:
Where:
DECLARE
var1 integer := 20;
var2 integer := 40;
var3 integer;
var4 real;
BEGIN
var3 := var1 + var2;
dbms_output.put_line('Value of var3: ' || var3);
var4 := 50.0/3.0;
dbms_output.put_line('Value of var4: ' || var4);
END;
/
Output
Value of var3: 60
Value of var4: 16.66666666666666666666666666666666666667
As we discussed that PL/SQL allows the nesting of blocks i.e. blocks with
blocks.
Based on the nesting structure PL/SQL variables can be divide into following
categories:
Local variables – Those variables which are declared in an inner block and not
accessible to outer blocks are known as local variables.
Global variables – Those variables which are declared in the outer block or a
package and accessible to itself and inner blocks are known as global variables.
Example:
DECLARE
-- Global variables
num1 number := 10;
num2 number := 20;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1);
dbms_output.put_line('Outer Variable num2: ' || num2);
DECLARE
-- Local variables
num3 number := 30;
num4 number := 40;
BEGIN
dbms_output.put_line('Outer variable in inner block num1: ' || num1);
PL/SQL Constants:
A constant holds a value used in a PL/SQL block that does not change
throughout the program.
It is a user-defined literal value.
Where:
CONSTANT – is a keyword.
Example:
DECLARE
-- constant declaration
pi constant number := 3.141592654;
-- other declarations
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
-- processing
radius := 10.5;
dia := radius * 2;
circumference := 2.0 * pi * radius;
PL/SQL Literals:
DECLARE
-- variable declaration
message varchar2(20):= 'Hello World!';
BEGIN
--output
dbms_output.put_line(message);
END;
/
Output: Hello World!
PL/SQL If statement:
IF-THEN statement:
Syntax:
IF condition
THEN
//Block of statements1
END IF;
IF-THEN-ELSE statement:
Syntax:
IF condition
THEN
//Block of statements1
ELSE
//Block of statements2
END IF;
IF-THEN-ELSIF statement:
Syntax:
IF condition1
THEN
//Block of statements1
//Block of statements2
ELSE
//Block of statements3
END IF;
Example:
DECLARE
var number(3) := 50;
BEGIN
IF (var = 10) THEN
dbms_output.put_line('Value of var is 10');
ELSIF (var = 20) THEN
dbms_output.put_line('Value of var is 20');
ELSIF (var = 30) THEN
dbms_output.put_line('Value of var is 30');
ELSE
dbms_output.put_line('None of the above condition is true.');
END IF;
dbms_output.put_line('Exact value of var is: '|| var);
END;
/
Output:
None of the above condition is true.
Exact value of var is: 50
CASE [expression]
...
END
Example:
DECLARE
nameChar char(1) := 'J';
BEGIN
CASE nameChar
when 'B' then dbms_output.put_line('Bharat');
when 'R' then dbms_output.put_line('Richi');
when 'S' then dbms_output.put_line('Sahdev');
when 'V' then dbms_output.put_line('Vinod');
when 'H' then dbms_output.put_line('Harish');
when 'M' then dbms_output.put_line('Mahesh');
when 'V' then dbms_output.put_line('Vivek');
when 'A' then dbms_output.put_line('Anil');
when 'J' then dbms_output.put_line('Jai');
else dbms_output.put_line('No such name');
END CASE;
END;
/
Output: Jai
Looping Statements:
The loop repeatedly executes a block of statements until it reaches a loop exit.
The EXIT and EXIT WHEN statements are used to terminate a loop.
Where:
The for in loop repeatedly executes a block of statements for a fixed number of
times.
The loop iteration occurs between the start and end integer values.
The counter is always incremented by 1 and loop terminates when the counter
reaches the value of the end integer.
Syntax:
LOOP
//block of statements.
END LOOP;
Note:
1. The double dot (..) specifies the range operator.
2. By default iteration is from start_value to end_value but we can reverse
the iteration process by using REVERSE keyword.
3. No need to declare the counter variable explicitly because it is declared
implicitly in the declaration section.
4. The counter variable is incremented by 1 and does not need to be
incremented explicitly.
5. The EXIT and EXIT WHEN statements can be used.
The goto statement provides an unconditional jump from the GOTO to a labeled
statement in the same subprogram.
A label can be declare with the << label >> syntax.
The stored procedure is a named PL/SQL block which performs one or more
specific tasks.
A stored procedure can be divided into two parts: Header and Body part.
Header: The header part contains the name of the procedure and the
parameters passed to the procedure.
Body: The body part contains declaration section, execution section and
exception section.
EXEC procedure_name();
EXEC procedure_name;
Gajendra Chourey Page 113
Note: Execute procedure with parameters:
EXEC procedure_name(param1,param2…paramN);
BEGIN
procedure_name;
END;
/
PL SQL FUNCTION:
The function is a named PL/SQL block which performs one or more specific
tasks and must returns a value.
Syntax:
RETURN return_datatype;
IS|AS
//Declaration block
BEGIN
Return return_variable;
EXCEPTION
//Exception block
Return return_variable;
END;
return number
is
num3 number(8);
begin
num3 :=num1*num2;
return num3;
end;
In a PL/SQL Statement:
dbms_output.put_line(getMultiple(4, 5));
PL/SQL Cursor:
Context area:
When processing an SQL statement, Oracle creates a temporary work area in the
system memory which contains all the information needed for processing the
statement known as context area.
A cursor is a pointer to context area i.e. Context area is controlled by the cursor. It is
used to fetch and manipulate the data returned by the SQL statement.
Note:
1. Implicit cursors.
2. Explicit cursors.
Implicit cursors:
%FOUND
%NOTFOUND
%ISOPEN
Always returns FALSE for implicit cursors, because Oracle closes the SQL
cursor automatically after executing its associated SQL statement.
Example: SQL%ISOPEN
%ROWCOUNT
Example:
Explicit cursors:
Explicit cursors are the user defined cursors to gain more control over the
context area.
These are defined in the declaration section of the PL/SQL block.
An explicit cursor is created on a SELECT Statement which returns more than
one row.
CURSOR cur_students IS
CLOSE cur_students;
Example:
DECLARE
s_rollNo [Link]%type;
s_name [Link]%type;
s_address [Link]%type;
CURSOR cur_students is
SELECT rollNo, name, address FROM students;
BEGIN
OPEN cur_students;
LOOP
FETCH cur_students into s_rollNo, s_name, s_address;
EXIT WHEN cur_students%notfound;
dbms_output.put_line(s_rollNo || ' ' || s_name || ' ' || s_address);
END LOOP;
CLOSE cur_students;
END;
/
Output:
1 Vivek UK
2 Anil Delhi
3 Mahesh Rajasthan
4 Vishal Delhi
5 Binod UP
6 Sunil UP
BEGIN DECLARE
SELECT attr_name from table_name CURSOR cur_name IS
Exception:
PL/SQL provides a mechanism to handle such exceptions so that normal flow of the
program can be maintained.
Types of exceptions:
1. System-defined exceptions.
2. User-defined exceptions.
DECLARE
//Declaration section
BEGIN
//Exception section
EXCEPTION
END;
Example:
DECLARE
Gajendra Chourey Page 121
s_rollNo [Link]%type := 10;
s_name [Link]%type;
s_address [Link]%type;
BEGIN
EXCEPTION
dbms_output.put_line('Error!');
END;
Output:
No such student!
Database server automatically raised the exceptions in case of any internal database
error. But database exceptions can also be raised explicitly by using RAISE command.
DECLARE
exception_name EXCEPTION;
BEGIN
IF condition THEN
RAISE exception_name;
END IF;
EXCEPTION
END;
The PL/SQL provides the facility to define the custom or user-defined exceptions
according to the need of 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.
Example:
DECLARE
s_name [Link]%type;
s_address [Link]%type;
ex_invalid_rollNo EXCEPTION;
BEGIN
RAISE ex_invalid_rollNo;
ELSE
END IF;
EXCEPTION
dbms_output.put_line('Error!');
END;
Output:
Note: A trigger can be defined on the table, view, schema or database with which the
event is associated.
1. Row level trigger – An event is triggered at row level i.e. for each row updated,
inserted or deleted.
2. Statement level trigger – An event is triggered at table level i.e. for each sql
statement executed.
[OF col_name]
ON table_name
WHEN (condition)
BEGIN
END;
/
Gajendra Chourey Page 126
Where:
CREATE [OR REPLACE ] TRIGGER trigger_name – It creates a trigger with the given
name or overwrites an existing trigger with the same name.
{BEFORE | AFTER | INSTEAD OF } – It specifies the trigger get fired. i.e before or
after updating a table. INSTEAD OF is used to create a trigger on a view.
{INSERT [OR] | UPDATE [OR] | DELETE} – It specifies the triggering event. The
trigger gets fired at all the specified triggering event.
[OF col_name] – It is used with update triggers. It is used when we want to trigger
an event only when a specific column is updated.
[ON table_name] – It specifies the name of the table or view to which the trigger is
associated.
[REFERENCING OLD AS o NEW AS n] – It is used to reference the old and new values
of the data being changed. By default, you reference the values as :old.column_name
or :new.column_name. The old values cannot be referenced when inserting a record
and new values cannot be referenced when deleting a record, because they do not
exist.
[FOR EACH ROW] – It is used to specify whether a trigger must fire when each row
being affected (Row Level Trigger) or just once when the sql statement is executed
(Table level Trigger).
WHEN (condition) – It is valid only for row level triggers. The trigger is fired only
for rows that satisfy the condition specified.
Example:
Existing data:
Trigger:
DECLARE
sal_diff number;
BEGIN
END;
Note: The above trigger will execute for every INSERT, UPDATE or DELETE
operations performed on the EMPLOYEES table.
Drop a trigger:
Package Plsql
A package is a schema object that groups logically related PL/SQL types, variables
and subprograms.
Parts of a package:
1. Package specification
The package specification is the package interface which declares the types,
variables, constants, exceptions, cursors and subprograms that can be referenced
from outside the package.
Note: All objects in the package specification are known as public objects.
PROCEDURE procedure_name;
END cust_sal;
Example:
END emp_sal;
The package body or definition defines the queries for the cursors and the code for
the subprograms.
Note: All objects in the package body or definition are known as private objects.
PROCEDURE procedure_name IS
//procedure body
END procedure_name;
END package_name;
Example:
e_sal [Link]%TYPE;
BEGIN
FROM employees
WHERE id = e_id;
END find_sal;
END emp_sal;