Chapter 2_Overview to PLSQL
Chapter 2_Overview to PLSQL
Overview of PL/SQL
PL/SQL, the Oracle procedural extension of SQL, is a portable, high-performance transaction-
processing language.
The PL/SQL programming language was developed by Oracle Corporation in the late 1980s as
procedural extension language for SQL and the Oracle relational database.
Features of PL/SQL
To run PL/SQL programs, you should have the Oracle RDBMS Server installed in your machine. This
will take care of the execution of the SQL commands. The most recent version of Oracle RDBMS is
11g. You can download a trial version of Oracle 11g from the following link −
https://www.oracle.com/technetwork/database/enterprise-edition/downloads/index.html
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
DECLARE
<declarations
section>
BEGIN
<executable
command(s)>
EXCEPTION
<exception
handling> END;
The 'Hello World' Example
DECLARE
message varchar2(20):= 'Hello, World!';
BEGIN
dbms_output.put_line(message);
END; /
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
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);
After the execution, this will produce the following result:
END;
Value of c: 70
Value of f: 33.333333333333333333
END;
END;
/
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL Scalar Data Types
Date Type & Description
Numeric
Numeric values on which arithmetic operations are performed.
Character
Alphanumeric values that represent single characters or strings of characters.
Boolean
Logical values on which logical operations are performed.
Datetime
Dates and times.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL Character Data
S.No Data Type & Description
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)
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL Numeric Data Types
S.No Data Type & Description
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)
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Variable Declaration in PL/SQL
You must declare the PL/SQL variable in the declaration section or in a package as a global variable.
After the declaration, PL/SQL allocates memory for the variable's value and the storage location is
identified by the variable name.
Syntax for declaring variable:
variable_name [CONSTANT] datatype [NOT NULL] [:= | DEFAULT initial_value]
Example:
Radius Number := 5;
Date_of_birth date;
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.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL - Conditions
Decision making statements are those statements which are in charge of executing a statement
out of multiple given statements based on some condition. The condition will return either true or
false. Based on what the condition returns, the associated statement is executed.
For example, if someone says, If I get 40 marks, I will pass the exam, else I will fail. In this case
condition is getting 40 marks, if its true then the person will pass else he/she will fail.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
The decision making statements in PL/SQL are of two types:
1.If Else statements
2.Case statement
PL/SQL: if Statement
The if statement, or the if...then statement can be used when there is only a single condition to be tested. If the result of the
condition is TRUE then certain specified action will be performed otherwise if it is FALSE then no action is taken and the
control of program will just move out of the if code block.
Syntax:
if <test_condition> then
body of action
end if;
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
This example initializes a variable x with the value 10. The IF statement checks if x is greater than 15. If the condition is true, it
prints 'X is greater than 15'; otherwise, it prints 'X is not greater than 15'.
DECLARE
x NUMBER := 10;
BEGIN
IF x > 15 THEN
DBMS_OUTPUT.PUT_LINE('X is greater than 15');
ELSE
DBMS_OUTPUT.PUT_LINE('X is not greater than 15');
END IF;
END;
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL IF THEN ELSIF statement
IF condition_1 THEN
statements_1
ELSIF condition_2 THEN
statements_2
[ ELSIF condition_3 THEN
statements_3
]
...
[ ELSE
else_statements
]
END IF;
In this structure, the condition between IF and THEN, which is the first condition, is always evaluated. Each other condition
between ELSEIF and THEN is evaluated only if the preceding condition is FALSE. For example, the condition_2 is evaluated
only if the condition_1 is false, the condition_3 is evaluated only if the condition_2 is false, and so on.
If a condition is true, other subsequent conditions are not evaluated. If no condition is true, the else_statements between
the ELSE and ENDIF execute. In case you skip the ELSE clause and no condition is TRUE, then the IF THEN ELSIF does nothing
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
DECLARE
score NUMBER := 75;
BEGIN
IF score >= 90 THEN
DBMS_OUTPUT.PUT_LINE('Excellent!');
ELSIF score >= 80 THEN
DBMS_OUTPUT.PUT_LINE('Very good!');
ELSIF score >= 70 THEN
DBMS_OUTPUT.PUT_LINE('Good job!');
ELSIF score >= 60 THEN
DBMS_OUTPUT.PUT_LINE('Satisfactory.');
ELSE
DBMS_OUTPUT.PUT_LINE('Needs
improvement.');
END IF;
END;
In this example, there's a variable score set to 75. The IF...THEN...ELSIF construct checks the value of score against different
ranges. Depending on the value of score, it prints different messages. If the score is 75, it falls into the 'Good job!' category
and will output 'Good job!' to the console.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL: Case Statement
The CASE statement chooses one sequence of statements to execute out of many possible sequences.
The CASE statement has two types: simple CASE statement and searched CASE statement. Both types of CASE statements
support an optional ELSE clause.
The simple CASE statement has the following structure:
CASE selector
WHEN selector_value_1 THEN
statements_1
WHEN selector_value_1 THEN
statement_2
...
ELSE
else_statements
END CASE;
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
--The following example compares single value (c_grade) with many possible values ‘A’,
‘B’,’C’,’D’, and ‘F’:
DECLARE
c_grade CHAR( 1 );
c_rank VARCHAR2( 20 );
BEGIN
c_grade := 'B';
CASE c_grade
WHEN 'A' THEN
c_rank := 'Excellent' ;
WHEN 'B' THEN
c_rank := 'Very Good' ;
WHEN 'C' THEN
c_rank := 'Good' ;
WHEN 'D' THEN
c_rank := 'Fair' ;
WHEN 'F' THEN
c_rank := 'Poor' ;
ELSE
c_rank := 'No such grade' ;
END CASE;
DBMS_OUTPUT.PUT_LINE( c_rank );
END;
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL Loops
Loops in PL/SQL provides a way of repeating a particular part of any program or any code statement
as many times as required.
In PL/SQL we have three different loop options to choose from when we want to execute a
statement repeatedly in our code block. They are:
1.Basic Loop
2.While Loop
3.For Loop
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.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Syntax:
LOOP
sequence of statements
END LOOP;
Example :
DECLARE
counter NUMBER := 1;
BEGIN
-- Basic Loop
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
EXIT WHEN counter > 5; -- Exit the loop when counter is greater than 5
END LOOP;
END;
In this example, there's a counter variable initialized to 1. The loop continues indefinitely unless the counter becomes
greater than 5. Inside the loop, it prints the current value of the counter using DBMS_OUTPUT.PUT_LINE, increments the
counter by 1, and checks whether the counter has reached a value greater than 5 using the EXIT WHEN statement to break
out of the loop.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL: While Loop
PL/SQL WHILE loop is a control structure that repeatedly executes a code block as
long as a specific condition remains true.
WHILE condition
LOOP
statements;
END LOOP;
In this syntax, the condition is a boolean expression that evaluates to TRUE, FALSE or NULL.
The WHILE loop statement continues to execute the statements between the LOOP and END LOOP as long as the condition
evaluates to TRUE.
PL/SQL evaluates the condition in the WHILE clause before each loop iteration. If the condition is TRUE, then the loop body
executes. If the condition is FALSE or NULL, the loop terminates.
If the condition is FALSE before entering the loop, the WHILE loop does not execute at all. This behavior is different from the
LOOP statement whose loop body always executes once.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
DECLARE
n_counter NUMBER := 1;
BEGIN
WHILE n_counter <= 7
LOOP
DBMS_OUTPUT.PUT_LINE( 'Counter : ' || n_counter );
n_counter := n_counter + 1;
END LOOP;
END;
In this example:
• First, initialize the counter to one.
• Second, the condition in the WHILE clause was evaluated before each loop iteration.
• Third, inside the loop body, the counter was increased by one in each loop iteration. After five iterations, the condition
was FALSE that caused the loop to terminate.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
PL/SQL: For Loop
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.
PL/SQL FOR LOOP executes a sequence of statements a specified number of times. The
PL/SQL FOR LOOP statement has the following structure:
The index is an implicit variable. It is local to the FOR LOOP statement. In other
words, you cannot reference it outside the loop.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Simple PL/SQL FOR LOOP example
In this example, the loop index is l_counter, lower_bound is one, and upper_bound is five. The loop shows a list of integers
from 1 to 5.
BEGIN
FOR l_counter IN 1..5
LOOP
DBMS_OUTPUT.PUT_LINE( l_counter );
END LOOP;
END;
DECLARE
l_counter PLS_INTEGER := 10;
BEGIN
FOR l_counter IN 1.. 5 loop
DBMS_OUTPUT.PUT_LINE (l_counter);
end loop;
-- after the loop
DBMS_OUTPUT.PUT_LINE (l_counter);
END;
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
DECLARE
TYPE NameList IS TABLE OF VARCHAR2(50);
names NameList := NameList('Alice', 'Bob', 'Charlie', 'David');
i NUMBER;
BEGIN
-- Loop through the collection
FOR i IN 1..names.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('Name ' || i || ': ' || names(i));
END LOOP;
END;
In this example:
num is the number for which we want to calculate the factorial (here, it's set to 5).
factorial is initialized to 1.
The FOR loop runs from 1 to num and multiplies each value from 1 to num to calculate the factorial.
Finally, it outputs the factorial of the given number using DBMS_OUTPUT.PUT_LINE.
For num = 5, the factorial would be calculated as 1 * 2 * 3 * 4 * 5 = 120.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Q4: Write PL/SQL program that calculates the factorial of a given number.