PLSQL
PLSQL
What is PL/SQL
PL/SQL, in simple terms, is a programming language used for managing
data in databases. It combines SQL for data manipulation and
procedural features for building applications. It's like a toolkit that lets
you efficiently interact with and control your Oracle database.
Features of PL/SQL :
The various features of PL/SQL are given below –
PL/SQL runs on various operating systems such as windows, Linux
etc.
PL/SQL have an error-checking facility and displays user-friendly
messages when an error occurs in a program.
It offers logging and debugging capabilities, including the capacity to
use exception messages.
SQL can be executed dynamically.
When certain data events, such as INSERT, UPDATE, or DELETE
actions on a table, occur, triggers are specialized forms of stored
processes that are automatically invoked.
Multi-row queries are handled using cursors.
The declaration of variables and constants to store data values is
supported.
Disadvantages of PL/SQL :
PL/SQL requires high memory.
Lacks of functionality debugging in stored procedures.
Blocks in PL/SQL
In PL/SQL, All statements are classified into units that is called Blocks.
PL/SQL blocks can include variables, SQL statements, loops, constants,
conditional statements and exception handling. Blocks can also build a
function or a procedure or a package.
Broadly, PL/SQL blocks are two types : Anonymous blocks and Named
blocks are as follows:
1. Anonymous blocks: In PL/SQL, That’s blocks which is not having
header are known as anonymous blocks. These blocks do not form the
body of a function or triggers or procedure. Example: Here a code
example of find greatest number with Anonymous blocks.
SQL
DECLARE
-- declare variable a, b and c
-- and these three variables datatype are integer
a number;
b number;
c number;
BEGIN
a:= 10;
b:= 100;
--find largest number
--take it in c variable
IF a > b THEN
c:= a;
ELSE
c:= b;
END IF;
dbms_output.put_line(' Maximum number in 10 and 100: ' || c);
END;
/
-- Program End
Output:
Maximum number in 10 and 100: 100
SQL
DECLARE
PL/SQL Constants
Variables:
Let's understand each method one be one along with the Examples.
1. Using Declare Variables in PL/SQL
To declare a variable in PL/SQL, use the DECLARE keyword followed
by the variable name and its data type. Optionally, you can also assign
an initial value to the variable using the ':=' operator.
Syntax:
DECLARE
variable_name datatype := initial_value;
here,
variable_name: It is the name of the variable.
datatype: It is the data type of the variable.
:= initial_value: It is an optional assignment of an initial value to the
variable.
Example:
DECLARE
name VARCHAR2(20) := 'GeeksForGeeks';BEGIN
DBMS_OUTPUT.PUT_LINE(name);END;
Output:
Output
You can also assign a value to a variable later in the code using the :=
operator.
Syntax:
DECLARE
my_variable NUMBER;BEGIN
my_variable := value;END;
Example:
DECLARE
num1 NUMBER;
num2 NUMBER;
result NUMBER;BEGIN
num1 := 5;
num2 := 3;
result := num1 + num2;
DBMS_OUTPUT.PUT_LINE('Sum: ' || result);END;
Output:
Example:
DECLARE
global_var NUMBER; -- global variableBEGIN
-- PL/SQL code using global_var
DECLARE
local_var NUMBER; -- local variable
BEGIN
-- PL/SQL code using local_var and global_var
END;
-- Here you can't access local_var END;
DECLARE
salary_var employees.salary%TYPE;BEGIN
-- Assign a value to the variable
salary_var := 70000;
Output:
Explanation: In the above Query, We have declares a
variable salary_var with the same data type as the salary column in
the employees table, assigns a value of 70000 to it, and then prints the
assigned salary using DBMS_OUTPUT.PUT_LINE.
DECLARE
employee_record employees%ROWTYPE;BEGIN
-- Fetch data from the table into the record variable
SELECT * INTO employee_record FROM employees WHERE
employee_id = 2;
Output:
Scalar data types are basic types that store only one value at a time.like
numbers, characters, or even logical values each representing an
individual value. The scalar data types are categorized into:
Numeric Types: It Stores any integer value along with a fractional
entity whatever large it is or as per the requirement of the program.
Character Types: Nodes represent strings of text and These act as
structures of text whereby an individual string is represented by a
node.
Boolean Types: It Contains ‘true’ or ‘false’ values.
Datetime Types: It is Used to represent date and time values which
are of typical usage in computer systems.
Subtypes are defined based on the base scalar types and are formed by
placing additional constraints upon values that can be assigned.
1. IF THEN
Example:-
-- pl/sql program to illustrate If else statementdeclarenum1 number:=
10;num2 number:= 20;
begin
if num1 < num2 thendbms_output.put_line('i am in if block');
ELSEdbms_output.put_line('i am in else Block');end if;
dbms_output.put_line('i am not in if or else Block');end;
Output:-
i'm in if Block
i'm not in if and not in else Block
The block of code following the else statement is executed as the
condition present in the if statement is false after calling the statement
which is not in block(without spaces).
3. NESTED-IF-THEN
Here, a user can decide among multiple options. The if then statements
are executed from the top down. As soon as one of the conditions
controlling the if is true, the statement associated with that if is
executed, and the rest of the ladder is bypassed. If none of the conditions
is true, then the final else statement will be executed. Syntax:-
if (condition) then
--statement
elsif (condition) then
--statement
.
.
else
--statement
endif
Flow Chart:-
Example:-
-- pl/sql program to illustrate if-then-elif-then-else ladderdeclarenum1
number:= 10;num2 number:= 20;
begin
if num1 < num2 thendbms_output.put_line('num1 small');
ELSEIF num1 = num2 thendbms_output.put_line('both equal');
ELSEdbms_output.put_line('num2 greater');end if;
dbms_output.put_line('after end if');end;
Output:-
num1 small
after end i
PL SQL Triggers:
PL/SQL triggers are stored programs that run automatically when a specific event
occurs in the database. They are created using the CREATE TRIGGER statement and can
be enabled or disabled. Triggers are defined on tables, views, schemas, or the
database and respond to DML, DDL, or system events. The two timing points are
BEFORE and AFTER the triggering event. They only affect new or changed data,
not existing data.
PL/SQL Trigger
A trigger is something that automatically runs (or “fires”) when a specific event
happens in the database.
“Think of it like a security alarm: When someone opens a door (event), the alarm
goes off (trigger action).”
1.
We want: Every time an employee is deleted, the database should automatically add
their info to the employee_log table.
Code Example:
CREATE OR REPLACE TRIGGER trg_employee_delete
BEFORE DELETE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_log(emp_id, emp_name, deleted_on)
VALUES (:OLD.emp_id, :OLD.emp_name, SYSDATE);
END;
Explanation:
BEFORE DELETE ON employees: This trigger runs before a delete happens on the
employees table.
:OLD is used to access the data before it gets deleted.
SYSDATE adds the current date and time.
So, when someone deletes a row from employees, this trigger automatically
copies that data into employee_log.
What is a Cursor?
In PL/SQL, a cursor is like a pointer that helps you go through rows of data one by
one from a query.
Think of it like:
You have a list of names. A cursor is your finger pointing at one name at a time as
you read them one by one.
Types of Cursors:
Implicit Cursor – Automatically used by PL/SQL when you write simple SQL
statements.
Explicit Cursor – You define it yourself when you want more control over how rows
are processed.
Example:
DECLARE
v_name students.name%TYPE;
BEGIN
OPEN c;
CLOSE c;
END;
Exception handling is used to catch and manage errors so that your program doesn't
crash when something goes wrong. It helps make your code more reliable, safe, and
user-friendly.
Think of it like:
“If something goes wrong, don’t panic — just do this instead.”
Example:
BEGIN
DECLARE
a NUMBER := 10;
b NUMBER := 0;
c NUMBER;
BEGIN
EXCEPTION
END;
END;
What’s happening:
We’re trying to divide 10 by 0, which is not allowed.
That causes a ZERO_DIVIDE error.
Instead of crashing, the program catches the error and shows a friendly
message:
Error: Cannot divide by zero!