0% found this document useful (0 votes)
9 views

Chapter 2_Overview to PLSQL

PL/SQL is Oracle's procedural extension of SQL, designed for high-performance transaction processing and tightly integrated with SQL. It offers features such as extensive error checking, support for object-oriented programming, and the ability to develop web applications. The document outlines the advantages, syntax, data types, and control structures of PL/SQL, providing examples of variable declaration, conditional statements, and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

Chapter 2_Overview to PLSQL

PL/SQL is Oracle's procedural extension of SQL, designed for high-performance transaction processing and tightly integrated with SQL. It offers features such as extensive error checking, support for object-oriented programming, and the ability to develop web applications. The document outlines the advantages, syntax, data types, and control structures of PL/SQL, providing examples of variable declaration, conditional statements, and loops.
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Advance Database using PL/SQL

Unit 2 : Overview to PL/SQL

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

•PL/SQL is tightly integrated with SQL.


•It offers extensive error checking.
•It offers numerous data types.
•It offers a variety of programming structures.
•It supports structured programming through functions and procedures.
•It supports object-oriented programming.
•It supports the development of web applications and server pages.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Advantages of PL/SQL
PL/SQL offers several advantages over other programming languages.

PL/SQL has these advantages:


•Tight Integration with SQL
•High Performance
•High Productivity
•Portability
•Scalability
•Manageability
•Support for Object-Oriented Programming
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Advantages of PL/SQL
1. 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.
2. 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.
3. PL/SQL gives high productivity to programmers as it can query, transform, and
update data in a database.
4. PL/SQL saves time on design and debugging by strong features, such as
exception handling, encapsulation, data hiding, and object-oriented data types.
5. Applications written in PL/SQL are fully portable.
6. PL/SQL provides high security level.
7. PL/SQL provides access to predefined SQL packages.
8. PL/SQL provides support for Object-Oriented Programming.
9. PL/SQL provides support for developing Web Applications and Server Pages.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL

PL/SQL - Environment Setup

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

PL/SQL - Basic Syntax


PL/SQL programs are divided and written in logical blocks of code. Each block consists of three sub-
parts −
Sections & Description
Declarations
This section starts with the keyword DECLARE. It is an optional section and defines all
variables, cursors, subprograms, and other elements to be used in the program.
Executable Commands
This section is enclosed between the keywords BEGIN and END and it is a mandatory section.
It consists of the executable PL/SQL statements of the program. It should have at least one
executable line of code, which may be just a NULL command to indicate that nothing should
be executed.
Exception Handling
This section starts with the keyword EXCEPTION. This optional section
contains exception(s) that handle errors in the program
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Every PL/SQL statement ends with a semicolon (;). PL/SQL blocks can be nested within other PL/SQL
blocks using BEGIN and END. Following is the basic structure of a PL/SQL block −

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

PL/SQL Block Syntax


Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL

Let's take a simple example

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

PL/SQL procedure successfully completed.


Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
Example of Local and Global variables
DECLARE
-- Global variables
num1 number := 95;
num2 number := 85;
BEGIN
dbms_output.put_line('Outer Variable num1: ' || num1); Outer Variable num1: 95
dbms_output.put_line('Outer Variable num2: ' || num2); Outer Variable num2: 85
DECLARE Inner Variable num1: 195
-- Local variables Inner Variable num2: 185
num1 number := 195;
num2 number := 185; PL/SQL procedure
BEGIN successfully completed.
dbms_output.put_line('Inner Variable num1: ' || num1);

dbms_output.put_line('Inner Variable num2: ' || num2);

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;

sales number(10, 2);


pi CONSTANT double precision := 3.1415;
name varchar2(25);
address varchar2(100);
Advance Database using PL/SQL
Unit 2 : Overview to 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.
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

PL/SQL IF THEN statement example


--In the following example, the statements between THEN and END IF execute because
the sales revenue is greater than 100,000.

DECLARE n_sales NUMBER := 2000000;


BEGIN
IF n_sales > 100000 THEN
DBMS_OUTPUT.PUT_LINE( 'Sales revenue is greater than 100K ' );
END IF;
END;
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL

PL/SQL: if...then...else statement


If the condition evaluates to TRUE, then the statements between THEN and ELSE execute. In case the condition evaluates to
FALSE or NULL, the else_statements between ELSE and END IF executes.
Syntax:
if <test_condition> then
IF condition THEN
statement 1/set of statements 1
statements;
else
ELSE
statement 2/set of statements 2
else_statements;
end if;
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.

While using it, following two things must be considered:

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.

Here’s the syntax for the WHILE loop statement:

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:

FOR index IN lower_bound .. upper_bound


LOOP
statements;
END LOOP;

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

Other Example on 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:

NameList is a user-defined collection type of strings (VARCHAR2(50)).


names is an instance of the NameList collection initialized with some names.
The FOR loop iterates from index 1 to the COUNT of elements in the names collection.
Within the loop, it prints each name along with its index.
This loop iterates through the names collection and prints each name along with its index using DBMS_OUTPUT.PUT_LINE.
Advance Database using PL/SQL
Unit 2 : Overview to PL/SQL
DECLARE
num NUMBER := 5;
factorial NUMBER := 1;
BEGIN
-- Calculate factorial of a number using a loop
FOR i IN 1..num LOOP
factorial := factorial * i;
END LOOP;

DBMS_OUTPUT.PUT_LINE('Factorial of ' || num || ' is ' || factorial);


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

Frequently Asked Questions


Q1: Write some Advantages of PL/SQL.

Q2: Describe decision making statements in


PL/SQL.
Q3: What are the PL/SQL Loops describe with example.

Q4: Write PL/SQL program that calculates the factorial of a given number.

You might also like