PL/SQL Tutorial

The “PL/SQL Tutorial” is a helpful guide for anyone wanting to learn PL/SQL, which is Oracle’s way to add programming features to SQL. It explains basic concepts, control structures, data types, Cursor, Triggers, Procedures and Functions with Examples to help users create and manage database applications effectively.

What is PL/SQL

PL/SQL is a version of SQL that lets you do more than just run one command at a time. With PL/SQL, you can write scripts that handle several commands and include logic, making it easier to manage databases. It’s structured like other programming languages such as C or C++, so if you’re familiar with those, learning PL/SQL should be straightforward. Overall, PL/SQL makes working with Oracle databases more efficient and flexible.

 


 

Advantages of PL/SQL

The advantages of PL/SQL are the following.

  1. Strong Integration with SQL: PL/SQL works well with SQL, allowing you to run SQL commands in your code, making it easier to work with databases.
  2. High Performance: PL/SQL is designed to run efficiently, making it faster to handle complex tasks compared to using SQL alone.
  3. Increased Productivity: PL/SQL allows you to write more organized code that can be reused. It helps to work faster and more efficiently.
  4. Portability: PL/SQL code can be easily moved between different Oracle database systems.
  5. Scalability: PL/SQL can handle both small and large applications. It makes suitable for a wide range of database sizes.
  6. Easy Manageability: PL/SQL helps simplify the management of databases by automating tasks, reducing manual work.
  7. Support for Object-Oriented Programming: PL/SQL supports features like objects and classes, which help in modeling and organizing complex data.
  8. Web Application Development: PL/SQL allows you to build web applications within the Oracle system, working smoothly with web technologies.
  9. Server Pages Development: PL/SQL enables the creation of dynamic server-side web pages, useful for building interactive websites.

 


 

PL/SQL BLOCK

The PL/SQL block contains the following section:-

DECLARE: Used to declare variables, constants, and cursors.

BEGIN: Contains the executable SQL and PL/SQL code.

EXCEPTION: Handles errors that may occur during execution.

END: Marks the end of the block.

Example

Explanation:

In the DECLARE section, a variable stu_id and stu_name are defined.

The BEGIN section contains an SQL query to fetch the student’s name based on the student ID and print it.

The EXCEPTION section handles any errors, such as when no data is found or other issues arise.

END completes the block.

This structure allows PL/SQL to combine SQL commands with procedural logic to create efficient and flexible programs.

 


 

PL/SQL DATA-TYPE

PL/SQL provides a wide range of data types to store numbers, text, dates, and even collections of data. It also allows you to create custom types, handle entire rows, and work with large data like text documents or images. This variety helps you write efficient programs to manage databases easily.

1. Basic Data Types:

NUMBER: Used for numbers (like salaries or counts).

 

VARCHAR2: Stores text with variable length (names, descriptions).

 

CHAR: Stores fixed-length text (like single letters).

 

BOOLEAN: Stores TRUE, FALSE, or NULL.

 

DATE: Stores dates and times.

 

2. Composite Data Types:

These hold multiple values.

RECORD: Groups data together like a mini-database row (e.g., ID and name together).

 

TABLE or VARRAY: Stores a list of items (like an array).

 

3. Reference Types:

REF CURSOR: Points to a query result, so you can process each row one by one

 

4. Large Objects (LOBs):
It store big data:

CLOB: Large text (like documents).

BLOB: Large binary data (like images or files).

 

5. Row Data Types:
%ROWTYPE: Stores an entire row from a table.

 

6. Special PL/SQL Types:
PLS_INTEGER and BINARY_INTEGER: Stores whole numbers. PLS_INTEGER is faster in PL/SQL code.

 

7. User-Defined Types:
Subtypes: You can create custom data types based on existing ones.

 

8. Cursor Data Types:
CURSOR: Lets you retrieve and work with data row by row from a query.

 

9. %TYPE Attribute:
%TYPE: Lets you declare a variable with the same type as a database column. It automatically adjusts if the table changes.

 

10. NULL Values:
NULL represents missing or unknown data. It can be assigned to any variable but must be handled carefully in logic.

 


 

PL/SQL Operators

PL/SQL operators are symbols used to perform operations on data, such as arithmetic calculations, comparisons, logical tests, and string concatenation. They allow developers to manipulate values, make decisions, and control the flow of PL/SQL programs.

SQL Arithmetic Operators

Operator Description Example
+ Addselect 20 + 20;
Subtractselect 20 – 10;
* Multiplyselect 20 * 20;
/ Divideselect 30 / 10;
% Moduloselect 30 % 8;

 

SQL Comparison Operators

Operator Description Example
=       Equal toSELECT * FROM Emp WHERE Sal = 10000;
Greater thanSELECT * FROM Emp WHERE Sal > 10000;
Less thanSELECT * FROM Emp WHERE Sal < 10000;
>=Greater than or equal toSELECT * FROM Emp WHERE Sal >= 10000;
<=Less than or equal toSELECT * FROM Emp WHERE Sal <= 10000;
< >Not equal toSELECT * FROM Emp WHERE Sal < > 10000;

 

               SQL Logical Operators

OperatorDescriptionExample
ALLReturn true if all comparisons are true
ANDReturn true if both expressions are trueSELECT * FROM emp WHERE City = “Delhi” AND City = “Punjab”;
ANYReturn true if any one of the comparisons is true.
BETWEENReturn true if the operand is within a rangeSELECT * FROM emp WHERE salary BETWEEN 8000 AND 15000 order by salary;
EXISTReturn true if a subquery contains any rows
INReturn true if the operand is equal to one of the value in a listSELECT * FROM emp WHERE eid IN ( 1008,1009)  order by eid;
LIKEReturn true if the operand matches a patternSELECT * FROM emp WHERE ename LIKE ‘Am%’ ORDER BY ename;

SELECT * FROM emp WHERE ename LIKE ‘_m%’ ORDER BY ename;

NOTReverse the result of any other Boolean operator.
ORReturn true if either expression is trueSELECT * FROM emp WHERE City = “Delhi” OR City = “Punjab”;
SOMEReturn true if some of the expressions are true

 


 

How to print output in PL/SQL

DBMS_OUTPUT is a built-in PL/SQL package that allows you to display output or messages from PL/SQL programs. It’s useful for debugging and tracking the flow of execution. The output is stored in a buffer, and It can be displayed by PUT_LINE procedure.

Features:-

1. PUT_LINE: It adds a message to the buffer with a new line.

 

2. Enabling Output: In SQL*Plus, It is must to turn on SERVEROUTPUT to view the output.

 

3. Buffering: The output is not displayed immediately. It is saved in the buffer and displayed once the PL/SQL block has finished executing.

 

Know about comments. A comment can have following 2 forms in the pl/sql.

  •  To comment a single line in pl/sql use double hyphen(–), in front of line.
  •  The C style comment such as /* I am a comment */ is used for multi line comments.

 


 

PL/SQL Control Structures

Control structures in PL/SQL help control how the code runs inside a PL/SQL block or program. These structures allow you to make decisions, repeat actions (loops), and handle errors, just like in other programming languages.

Types of Control Structures in PL/SQL:

1. Conditional Control (IF-THEN-ELSE): This structure helps make decisions in the program.

IF-THEN: Executes if condition is true.

IF-THEN-ELSE: Executes ‘if’ block if true, another if false.

ELSIF: Adds multiple conditions to check.

Example:

 

2. Iterative Control (Loops): Loops are used to repeat a block of code multiple times.

LOOP: Repeats until an explicit exit condition is met.

WHILE LOOP: Repeats until given condition gets true.

FOR LOOP: A certain number of times is repeated.

Example (FOR LOOP):

 

3. Sequential Control (GOTO): GOTO transfers control to a labeled part of the code. It’s rarely used because it makes code harder to follow.

Example:

 

4. Exception Handling: This control structure manages runtime errors, allowing you to define what to do when an error occurs.

EXCEPTION: Catches errors and handles them with appropriate actions.
Example:

 


 

Programs of Control Structures in PL/SQL

Some examples of Conditional Control, Iterative Control, Sequential Control and Exception Handling are the given below.

Example 1 :- Addition of 3 numbers

Note:- Here ‘&’ is used to take user input at runtime

Output

Enter value for a:  10

Enter value for b: 20

Enter value for c: 50

Sum =  80

 

 

Example 2 :- Sum of 100 Numbers

Output

Sum between 1 to 100 is 5050

 

 

Example 3 :- Sum of Odd numbers from 1 to 100 using for loop

Output

Enter value for endvalue: 100

sum = 2500

 

 

Example 4 :- Sum of Odd numbers from 1 to 100 using While loop

Output

Enter value for endvalue: 100

Sum of odd numbers between 1 and 100 is 2500

 

 

Example 5 :- Calculation of net salary

Output

Enter value for ename: Amit Singh

Enter value for basic: 18000

Employee name : Amit Singh

Providend Fund : 1440

Net salary : 26640

 

 

Example 6 :-  pl/sql program to find greatest of three numbers

Output

Enter value for a: 25

Enter value for b: 39

Enter value for c: 12

B is Greatest

 

 

Example 7 :- Example of Loop Statement on EXIT WHEN

Output
250
300
350
400
450

 

 

Example 8 :- Simple example of For Loop

Output

11

12

13

14

15

 

 

Example 9 :- Simple example of while loop

Output

4
8
12
16
20

 

 

Example 9 :- Sequential Control  GOTO

Output

Starting the program. Value of x: 1
You are in skipped section. Value of x is still: 1

 


 

EXCEPTION HANDLING

Exception Handling in PL/SQL: Errors in PL/SQL block can be handled by error handling. It describes how we handle errors in the PL/SQL block. This is exactly the same as we do in C++ or Java programming. There are following two types of exception handling in pl/sql:

1. Predefined exceptions:

NO_DATA_FOUND == when a SELECT INTO statement returns more than one row
INVALID_CURSOR == If a cursor is not open and you are tyring to close that.
ZERO_DEVIDE == divide a number by zero.
TOO_MANY_ROWS == if more rows are returned by select statement.
OTHERS = Catches all exceptions that are not explicitly named.
CURSOR_ALREADY_OPEN == when a cursor is already opened
DUP_VAL_ON_INDEX == for duplicate entry of index
STORAGE_ERROR == if memory is damaged
PROGRAM_ERROR == internal problem in PL/SQL
LOGIN_DENIED == invalid user name or password
INVALID_NUMBER == if you are inserting a string datatype for a number datatype that is already declared

Example of Exception Handling

 

2. Handling User Defined Exceptions

 


 

CURSORS

In PL/SQL, a cursor is a pointer to the result set of a query. It allows row-by-row processing of query results. First, the cursor is declared, then opened to execute the query, followed by fetching rows into variables, and finally closed when processing is complete.

Types of cursors in In PL/SQL

1. Implicit Cursor: Automatically created by Oracle for SQL statements like SELECT INTO, INSERT, UPDATE, or DELETE. It is used when a single row is returned by the query.

2. Explicit Cursor: It is specified by the users for queries with many rows. You manually declare, open, fetch, and close these cursors to process query results row by row.

Both types help handle query result sets in PL/SQL efficiently.

 

Cursor Attributes

In PL/SQL, cursor attributes provide information about the state of cursors after query execution. The key attributes are:

%FOUND: It returns TRUE, if a row fetched successfully, otherwise FALSE.

%NOTFOUND: It returns TRUE, if no rows fetched, otherwise FALSE.

%ROWCOUNT: It returns, number of rows fetched.

%ISOPEN: Returns TRUE if the cursor is open, otherwise FALSE.

These attributes help in managing cursor operations efficiently.

 

Example 1 :- Example of SQL%FOUND (Implicit Cursor)

 

Example 2 :- Example of SQL%NOTFOUND (Implicit Cursor)

 

Example 3 :- Example of SQL%ROWCOUNT (Implicit Cursor)

 

Example 4 :- Example of SQL%ISOPEN (Implicit Cursor)

 

Example 5 :- Simple Explicit Cursor

 

Example 6 :- Explicit Cursor with Parameters

 

Example 7 :- Explicit Cursor with FOR Loop

 

Example 8 :- Display the 10 employees list who got the maximum salary

 

Example 9 :- Example of Strong Cursor

Strong Cursor: A cursor with a fixed, predefined structure (with a known return type at compile time). A strong cursor is defined with an explicit SELECT statement where the return type (columns and data types) is known.

 

Example 10 :- Example of Weak Cursor

Weak Cursor: A cursor where the structure is not fixed, meaning the return type can vary, and is determined dynamically at runtime. A weak cursor does not have a fixed structure. The query can return any number of columns and types of data.

 


 

TRIGGERS

In PL/SQL, a trigger is a stored procedure that is automatically executed in response to certain events on a particular table or view. Triggers can be used to enforce business rules, maintain audit trails, or perform validation checks automatically when DML (Data Manipulation Language) operations such as INSERT, UPDATE, or DELETE occur.

Types of Triggers

Before Trigger: Fires before the triggering DML statement (e.g., BEFORE INSERT).

After Trigger: Fires after the triggering DML statement (e.g., AFTER UPDATE).

Row-level Trigger: Fires once for each row affected by the triggering statement.

Statement-level Trigger: Fires once for the entire DML statement, regardless of the number of rows affected.

Structure of a Trigger

 

Example 1: Before Insert Trigger

This trigger ensures that, before any employee is inserted into the employees table, their salary is automatically adjusted to be at least 9000.

Note:- :NEW.salary refers to the salary of the new row being inserted.

 

Example 2: After Update Trigger

This trigger logs any changes made to the salary of employees after an UPDATE on the employees table.

Note:- :OLD.salary refers to the salary before the update, and :NEW.salary refers to the new salary after the update.

 

Example 3: Before Delete Trigger

This trigger prevents the deletion of employees from the employees table if the employee is a manager.

 

Example 4: AFTER UPDATE Trigger: Auto Update Last Modified Date

This trigger changes the last_modified column of a table whenever a record in employee table is changed.

 

Example 5: BEFORE INSERT Trigger: Assigning Default Values

This trigger assigns a default value to the job_title if it is not provided during an insert.

 


 

PROCEDURES AND FUNCTIONS

A procedure is a small program made up of SQL statements, designed to perform a particular task. It is similar to a function. Procedures and functions combine SQL and PL/SQL statements to complete a specified purpose. A stored procedure or function is a named block of PL/SQL code that is saved in the database and can be reused whenever necessary.

 

Difference between Procedures and Functions

Below is explaining the difference between procedures and functions in PL/SQL:

FeaturesProcedureFunction
Return ValueDoes not have to return a value.Must return a single value.
Use in SQLCannot be called directly in SQL queries.Can be called and used in SQL queries.
PurposePerform actions or tasks, like updating data.Used for calculations or to return result.
Call MethodCalled as a standalone statement.Called as part of an expression.
Multiple OutputsCan return multiple outputs via parameters.Return only one value.
SyntaxEXEC procedure_name;SELECT function_name(…) from dual;

 

Syntax for Creating a Stored Procedure

A stored procedure in PL/SQL is a block of code that performs some specific task. It can accept parameters, perform operations, and return results (if needed). The basic syntax for creating a stored procedure in PL/SQL is following:

Explanation:

  • CREATE [OR REPLACE] PROCEDURE: Used to create new or update an existing procedure.
  • procedure_name: Name of the procedure.
  • parameter1, parameter2, …: The parameters that the procedure accepts. You can specify the direction of the parameters using:
    • IN: Input parameter (read-only).
    • OUT: Output parameter (write-only).
    • IN OUT: Both input and output (read and write).
  • IS/AS: Keyword that begins the declaration of the procedure’s body.
  • BEGIN: Marks the start of the executable part of the procedure.
  • EXCEPTION: This section is optional and used for handling exceptions (errors).
  • END procedure_name: Ends of procedure.

 

Example of a Simple Procedure

Here, the procedure update_employee_salary accepts two parameters: emp_id (employee ID) and salary_grow (Amount to increase salary). It updates the salary of an employee in the employees table and handles any exceptions.

 

Syntax for creating a function

In PL/SQL, a function is created using the CREATE OR REPLACE FUNCTION statement. The basic syntax for creating a function is the following:

Explanation

  • CREATE OR REPLACE FUNCTION: Creates a new function or replaces an existing one.
  • function_name: The name of the function.
  • parameter_name1, parameter_name2: Input parameters with their data types.
  • RETURN: return data type of the function.
  • IS: Introduces the declaration section.
  • BEGIN: Begins the executable section.
  • RETURN value: Specifies the value the function returns.
  • EXCEPTION: An optional section for exception handling.
  • END function_name: Ends of function.

 

Example of a function

Here, the function get_employee_salary takes an employee ID as input and returns the salary of that employee. If no data is found, it returns 0.

 

Other Examples

Stored Procedure with IF-ELSE Logic : This procedure checks whether a number is even or odd.

Use

 


 

Stored Procedure to Calculate Factorial: This procedure calculates the factorial of a given number.

Use:

 


 

Stored Procedure with Multiple OUT Parameters: This procedure accepts two numbers and returns their sum, subtraction, and multiply.

Use:

 


 

PACKAGE

A package is an Oracle object that contains other objects within it. It is a schema object that groups logically related PL/SQL types, variables, procedures, and functions.

 

Types of Packages

Packages have two following parts:

Package Specification: This is the interface to the package, declaring all the public elements (procedures, functions, variables, types) that can be accessed by the calling programs.

Package Body: This contains the implementation of the procedures and functions defined in the specification, along with any private variables, types, or procedures.

 

Advantages of PL/SQL Packages

Modularity: Code can be logically grouped.

Encapsulation: You can hide implementation details in the package body.

Reusability: Packages include procedures and functions that are reusable in several applications.

Performance: When a packaged procedure is called, the entire package is loaded into memory, resulting in quicker access for subsequent calls to its elements.

 

Example of a PL/SQL Package

1. Package Specification : This part defines the interface (what’s accessible to the outside).

 

2. Package Body  : This part provides the implementation of the procedures and functions declared in the specification.

 

Usage of Package

Once the package is created, you can use its procedures and functions like this:

Example 1: Get Employee Name

 

Example 2: Update Employee Salary

 

Example 3: Calculate Employee Bonus

 

 

Overloading in PL/SQL

PL/SQL supports overloading, meaning you can define multiple procedures or functions with the same name, as long as they have different numbers or types of parameters (or both). This is a feature called overloading, which allows you to reuse the same function or procedure name for different purposes based on the input parameters.

 

Example of Overloading in PL/SQL

Overloaded Procedures:

 

Package Body:

 

Use:

 

 

The End

 

 

Scroll to Top