You are on page 1of 18

Unit 4 and unit 5

PL/SQL

What is PL/SQL?

PL/SQL is a block structured language. The programs of PL/SQL are logical blocks that can
contain any number of nested sub-blocks. Pl/SQL stands for "Procedural Language extension
of SQL" that is used in Oracle. PL/SQL is integrated with Oracle database (since version 7). The
functionalities of PL/SQL usually extended after each release of Oracle database. Although
PL/SQL is closely integrated with SQL language, yet it adds some programming constraints that
are not available in SQL.

PL/SQL Variables

A variable is a meaningful name which facilitates a programmer to store data temporarily


during the execution of code. It helps you to manipulate data in PL/SQL programs. It is nothing
except a name given to a storage area. Each variable in the PL/SQL has a specific data type
which defines the size and layout of the variable's memory.

A variable should not exceed 30 characters. Its letter optionally followed by more letters,
dollar signs, numerals, underscore etc.

Syntax for declaring variable:

variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]

Here, variable_name is a valid identifier in PL/SQL and datatype must be valid PL/SQL data
type. A data type with size, scale or precision limit is called a constrained declaration. The
constrained declaration needs less memory than unconstrained declaration.

Example:

Radius Number := 5;

Date_of_birth date;

Declaration Restrictions:

In PL/SQL while declaring the variable some restrictions hold.


o Forward references are not allowed i.e. you must declare a constant or variable before
referencing it in another statement even if it is a declarative statement.
val number := Total - 200;
Total number := 1000;
The first declaration is illegal because the TOTAL variable must be declared before using
it in an assignment expression.

o Variables belonging to the same datatype cannot be declared in the same statement.
N1, N2, N3 Number;
It is an illegal declaration.

Naming rules for PL/SQL variables

The variable in PL/SQL must follow some naming rules like other programming languages.

o The variable_name should not exceed 30 characters.

o Variable name should not be the same as the table table's column of that block.

o The name of the variable must begin with ASCII letter. The PL/SQL is not case sensitive
so it could be either lowercase or uppercase. For example: v_data and V_DATA refer to
the same variables.

o You should make your variable easy to read and understand, after the first character, it
may be any number, underscore (_) or dollar sign ($).

o NOT NULL is an optional specification on the variable.

Initializing Variables in PL/SQL

Every time you declare a variable, PL/SQL defines a default value NULL to it. If you want to
initialize a variable with other value than NULL value, you can do so during the declaration, by
using any one of the following methods.

o The DEFAULT keyword

o The assignment operator

counter binary_integer := 0;
greetings varchar2(20) DEFAULT 'Hello JavaTpoint';
Example of initilizing variable

DECLARE

a integer := 30;

b integer := 40;

c integer;

f real;

BEGIN

c := a + b;

dbms_output.put_line('Value of c: ' || c);

f := 100.0/3.0;

dbms_output.put_line('Value of f: ' || f);

END;

After the execution, this will produce the following result:

Value of c: 70
Value of f: 33.333333333333333333

PL/SQL procedure successfully completed.

PL/SQL Constants

A constant is a value used in a PL/SQL block that remains unchanged throughout the program. It
is a user-defined literal value. It can be declared and used instead of actual values.

Syntax to declare a constant:

constant_name CONSTANT datatype := VALUE;


o Constant_name:it is the name of constant just like variable name. The constant word is a
reserved word and its value does not change.

o VALUE: it is a value which is assigned to a constant when it is declared. It can not be


assigned later.

Example of PL/SQL constant


DECLARE
pi constant number := 3.141592654;
radius number(5,2);
dia number(5,2);
circumference number(7, 2);
area number (10, 2);
BEGIN
radius := 9.5;
dia := radius * 2;
circumference := 2.0 * pi * radius;
area := pi * radius * radius;
dbms_output.put_line('Radius: ' || radius);
dbms_output.put_line('Diameter: ' || dia);
dbms_output.put_line('Circumference: ' || circumference);
dbms_output.put_line('Area: ' || area);
END;
/
Output
Radius: 9.5
Diameter: 19
Circumference: 59.69
Area: 283.53

Pl/SQL procedure successfully completed.


Operators

Operators in PL/SQL plays an important role to identify selective data from large chunks of
transactions.

Operators are inevitable in operations such as unique data retrieval, fetching of data based on its
relative existence in other tables and to stop queries from scanning the whole table.

Comparison Operators
Comparison operators are used to compare one value or expression to another.
Comparison operators are used for comparing one expression to another. The result is always
either TRUE, FALSE or NULL. All comparison operators return a boolean result.
Operator Example Usage
= IF A = B THEN The equality operator.
<> IF A <> B THEN The inequality operator.
!= IF A != B THEN Another inequality operator, synonymous with <>.
~= IF A ~= B THEN Another inequality operator, synonymous with <>.
< IF A < B THEN The less than operator.
> IF A > B THEN The greater than operator.
<= IF A <= B THEN The less than or equal to operator.
>= IF A >= B THEN The greater than or equal to operator.
LIKE IF A LIKE B THEN The pattern-matching operator.
Checks to see if a value lies within a specified range
BETWEEN IF A BETWEEN B AND C THEN
of values.
Checks to see if a value lies within a specified list of
IN IF A IN (B,C,D) THEN
values.
IS NULL IF A IS NULL THEN Checks to see if a value is null.

Logical Operators in PL/SQL

AND Query will execute only if all the conditions in AND clause are true

NOT is a negate operator. It reverses the meaning of an operator with which it is


NOT
used. (NOT EXISTS, NOT IN etc.)
OR Query will execute if any of the conditions in OR clause are true.

IS NULL IS NULL compares a column value with a NULL value.

UNIQUE The UNIQUE operator searches rows of a specified table for unique values.

Arithmetic Operators in PL/SQL

+ Addition Operator

– Subtraction Operator

* Multiplication Operator

/ Division Operator

Concatenation Operators in PL/SQL

|| We can concatenate character strings using || operators

Set Operators in PL/SQL

UNION Returns distinct records from all the queries with which it is connected

UNION ALL All records from queries with which it is connected are returned

Returns only those records from the first query which are not in common with
MINUS
the second query
INTERSECT Common records from queries with which it is connected are returned

What is PL/SQL Data types?


Data Types in PL/SQL are used to define how the data will be stored, handled, and treated by
Oracle during the data storage and processing. Data types are associated with the specific storage
format and range constraints. In Oracle, each value or constant is assigned with a data type.
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.

• PL/SQL CHARACTER Data Type


• PL/SQL NUMBER Data Type
• PL/SQL BOOLEAN Data Type
• PL/SQL DATE Data Type
• PL/SQL LOB Data Type

PL/SQL CHARACTER Data Type


This data type basically stores alphanumeric characters in string format.The literal values should
always be enclosed in 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

Data Type Description Syntax

CHAR This data type stores the string grade CHAR;


value, and the size of the string manager CHAR (10):=
is fixed at the time of declaring 'guru99';
the variable.
VARCHAR2 This data type stores the string, manager
but the length VARCHAR2(10) := ‘guru99';
manager
VARCHAR2(10) := ‘guru99';
of the string is not fixed.

VARCHAR This is synonymous with the manager VARCHAR(10) :=


VARCHAR2 data type. ‘guru99';
• It is always a good
practice to use
VARCHAR2 instead
of VARCHAR to avoid
behavioral changes.
NCHAR This data type is same as native NCHAR(10);
CHAR data type, but the
character set will of the
national character set.
NVARCHAR2 This data type is same as Native var
NVARCHAR2(10):='guru99';
VARCHAR2 data type, but
the character set will be of the
national character set.
LONG and LONGRAW This data type is used to store Large_text LONG;
Large_raw LONG RAW;
large text or raw data up to the
maximum size of 2GB.

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

A NUMBER(8,2);
B NUMBER(8);
C NUMBER;

PL/SQL BOOLEAN Data Type


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

Var1 BOOLEAN;

In the above, variable ‘Var1’ is declared as BOOLEAN data type. The output of the code will
be either true or false based on the condition set.
PL/SQL 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.

newyear DATE:='01-JAN-2015';
current_date DATE:=SYSDATE;

PL/SQL 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 a LONG data type as it is more
flexible than the 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 a 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 the LONG column is 2GB, whereas LOB can store up to 128 TB.
• Oracle is constantly improving the LOB data type in each of their releases according to
the modern requirement, whereas LONG data type is constant and not getting many
updates.

So, it is always good to use LOB data type instead of the 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

Conditional and iterative control

PL/SQL supports programming language features like conditional statements, iterative


statements. Pl/SQL control structure allows you to control the behaviour of the block as it runs.
You can change the logical flow of statements within the PL/SQL block with a number of
control statements.

Condition control

Structure of the PL?SQL IF statements is similar to the structure of IF statements in other


procedural languages. It allows PL?SQL to perform actions selectively based on conditions.
There are three forms of IF statement :

(a) IFTHENEND IF Syntax :

IF condition THEN

statements;

END IF;

EXAMPLE :-
DECLARE

A NUMBER;

B NUMBER;

BEGIN

A:=10;

B:=5;

IF A>B THEN

dbms_Output.Put_Line(‘A is BIGGER THAN B’);

END IF;

END;

/
(b) IF-THEN-ELSE-END IF

Syntax :-

IF condition THEN

Statements;
ELSE

Statements;

END IF;

Example :-

DECLARE

A NUMBER;

B NUMBER;

BEGIN

A:=22;

B:=33;

IF A>B THEN

dbms_output.put_line(‘A is bigger than b’);

ELSE

dbms_output.put_line(‘B is bigger than A’);

END IF;

END;

c) IF-THEN-ELSEIF-END IF

Syntax :-

IF condition THEN

Statements;

[ELSEIF condition THEN

Statements;]

[ELSE
Statements;]

END IF;

EXAMPLE:-

DECLARE

A NUMBER;

B NUMBER;

C NUMBER;

BEGIN

A:=10;

B:=20;

C:=30;

IF A>B THEN

IF A>C THEN

DBMS_OUTPUT.PUT_LINE(A||’ is biggest’);

ELSE

DBMS_OUTPUT.PUT_LINE(C|| ‘ IS BIGGEST’);

END IF;

ELSEIF B>C THEN

dbms_output.put_line(B||’ is biggest’);

ELSE

dbms_output.put_line(C||’ is biggest’);

END IF;

END;

/
CASE EXPRESSIONS

Like the IF statement, the CASE statement selects one sequence of statements to execute.
However, to select the sequence, the CASE statement uses a selector rather than multiple
Boolean expressions. A selector is an expression, the value of which is used to select one of
several alternatives.

Syntax
The syntax for the case statement in PL/SQL is −
CASE selector
WHEN 'value1' THEN S1;
WHEN 'value2' THEN S2;
WHEN 'value3' THEN S3;
...
ELSE Sn; -- default case
END CASE;

DECLARE
grade char(1) := 'A';
BEGIN
CASE grade
when 'A' then dbms_output.put_line('Excellent');
when 'B' then dbms_output.put_line('Very good');
when 'C' then dbms_output.put_line('Well done');
when 'D' then dbms_output.put_line('You passed');
when 'F' then dbms_output.put_line('Better try again');
else dbms_output.put_line('No such grade');
END CASE;
END;
/

Iterative control

LOOP CONTROL STRUCTURES Iterative control statements or LOOP control structures are
used when we want to repeat the execution of one or more statements for specified number of
times. PL/SQL provides the following types of loops:

(1) Basic loop/Simple loop

(2) WHILe loop

(3) FOR loop

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

DECLARE
a NUMBER:=1;
BEGIN
dbms_output.put_line('Program started.');
LOOP
dbms_output.put_line(a);
a:=a+1;
EXIT WHEN a>5;
END LOOP;
dbms_output.put_line('Program completed');
END:
/
(2) WHILe loop

You can use the WHILE loop to repeat a sequence of statements until the controlling condition is
TRUE. The condition is evaluated at the start of each iteration. The loop terminates when
condition is FALSE. If the condition is FALSE at the start of the loop, then no further iterations
are performed.

syntax

WHILE condition LOOP

Statement1;

Statement2;

……..

END LOOP;

Example :-

DECLARE

N number;

F number;

I number;

BEGIN

F:=1;

I:=1;

N:=&Number;

While (I<=N)

LOOP

F:= F*I;
I:=I+1;

END LOOP;

Dbms_Output.put_line ( ' Factorial of ' || N || ' IS : ' || F);

END;

/
3) FOR LOOP

FOR loops have the same general structure as the basic loop. In addition, they have a control
statement before the LOOP keyword to determine the number of iterations the PL/SQL performs.

Syntax :-

FOR counter IN [REVERSE]

<lower_bound>..<super_bound> LOOP

Statement1;

Statement2;

…….

END LOOP

In the syntax :-

(a) counter :- is an implicitly declared integer whose value automatically increases or

decreases by 1 on each iteration of the loop until the upper or lower bound is reached.

(b) REVERSE :- causes the counter to decrement with each iteration from the upper

bound to lower bound.

© lower_bound :- specifies the lower bound for the range of counter values.

(d) upper_bound:- specifies the upper bound for the range of counter values.
Example :-

DECLARE

N NUMBER;

F NUMBER;

BEGIN

F:=1;

N:= &NUMBER;

FOR I IN 1..N

LOOP

F:=F*I;

END LOOP;

dbms_output.Put_line (' Factorial of '||N||' is: ' ||F);

END;

SEQUENTIAL CONTROL

By default, all PL/SQL blocks are executed in a top down sequential process. The process begins
with a BEGIN statement and terminates with an END statement. So, to change the sequence of
execution of statements, you can use, following unconditional statements:

1. GOTO Statement The PL/SQL GOTO statement is a sequence control structure available in
oracle. The GOTO statement immediately transfers program control(called branching)
unconditionally to a named statement label or block label. The statement or label name must be
unique in the block.

Syntax:

GOTO << LABEL_NAME>>;

Where LABLE_NAME is the name of the label identifying the target statements.
Example :-

BEGIN

dbms_output.Put_Line (' This is the first line.');

GOTO FOUR;

Dbms_Output.Put_Line (' This is the Second Line.');

dbms_output.Put_Line (' this is the Third Line.');

<<FOUR>>

Dbms_Output.Put_Line (' this is the FOURTH LINE.');

END;

2. NULL Statement

The NULL statement is a no-op (no operation); it passes control to the next statement without
doing anything. Simply passes the control to the next statement.

Syntax:

NULL;

Example:
IF salary < 9000 THEN
compute_appraisal(emp_id);
ELSE
NULL;
END IF;

You might also like