Final PLSQL
Final PLSQL
PL/SQL Block
Structure
PL/SQL (Procedural Language/Structured Query Language) is Oracle’s procedural extension to
SQL. It combines SQL capabilities with procedural programming features such as loops,
conditions, and exception handling. Every PL/SQL program is written in the form of blocks,
which are the fundamental units of execution.
Example:
v_salary NUMBER(10,2);
Features
Supports nested blocks.
Provides modular programming.
Improves security and performance.
Integrates tightly with SQL.
Thus, PL/SQL block structure ensures structured programming, better error handling, and
efficient database interaction.
2. Behavior of
Variables in Blocks
Variables in PL/SQL are used to store temporary data during execution. They follow specific
scope and lifetime rules.
Declaration Syntax
variable_name datatype [NOT NULL] [:= initial_value];
Example:
1. Scope
2. Lifetime
3. Initialization
Declared using:
5. Anchored Declarations
Example:
v_empname [Link]%TYPE;
1. Numeric Types
NUMBER(p,s)
PLS_INTEGER
BINARY_INTEGER
2. Character Types
VARCHAR2(size)
CHAR(size)
LONG
Attributes
%TYPE
%ROWTYPE
Scalar data types are essential for data manipulation, condition checking, and arithmetic
operations.
4. Composite Data
Types
Composite types store multiple related values.
1. Records
Advantages:
2. %ROWTYPE
emp_rec emp%ROWTYPE;
3. Collections
Collections store multiple elements.
Types:
1. Associative Arrays
2. Nested Tables
3. VARRAYs
Used for:
Bulk operations
Temporary storage
Data manipulation
5. Control Structures
Control structures determine execution flow.
1. Conditional Statements
IF Statement
IF condition THEN
statements;
END IF;
IF-ELSE
IF condition THEN
statements;
ELSE
statements;
END IF;
CASE Statement
2. Iterative Statements
LOOP
FOR LOOP
6. Exceptions
Exceptions are runtime errors that occur during execution.
Types of Exceptions
1. Predefined Exceptions
NO_DATA_FOUND
TOO_MANY_ROWS
ZERO_DIVIDE
VALUE_ERROR
2. User-Defined Exceptions
Declared explicitly.
invalid_salary EXCEPTION;
3. Non-Predefined Exceptions
Linked using:
Benefits:
1. BULK COLLECT
FORALL i IN 1..emp_tab.COUNT
INSERT INTO emp VALUES emp_tab(i);
Advantages:
8. Functions
A function is a named PL/SQL block that returns a single value.
Syntax
CREATE OR REPLACE FUNCTION calc_bonus
RETURN NUMBER IS
BEGIN
RETURN 1000;
END;
Characteristics
9. Procedures
A procedure is a named PL/SQL block that performs an action.
Syntax
CREATE OR REPLACE PROCEDURE update_salary IS
BEGIN
UPDATE emp SET salary = salary + 1000;
END;
Features
Procedures are mainly used for business logic and database operations.
10. Packages
A package is a schema object that groups logically related PL/SQL elements.
Components
Package Specification
Package Body
Contains implementation.
Advantages:
Encapsulation
Better performance
Improved security
Code reusability
Overloading support
11. Transaction
Scope
A transaction is a logical unit of work.
Transaction Control Statements
COMMIT
ROLLBACK
SAVEPOINT
Properties (ACID)
Atomicity
Consistency
Isolation
Durability
Transaction in PL/SQL
1. Lexical Units in
PL/SQL
Lexical units are the smallest meaningful elements of a PL/SQL program. They form the basic
building blocks of the PL/SQL language. A PL/SQL program is composed of various lexical
units arranged according to syntax rules.
1. Identifiers
Identifiers are names given to PL/SQL elements such as variables, constants, cursors,
procedures, functions, triggers, packages, and labels.
v_total_salary NUMBER;
Identifiers improve readability and allow programmers to reference data and program elements
easily.
2. Delimiters
Examples:
Arithmetic Operators: +, -, *, /
Relational Operators: =, <, >, <=, >=, <>
Logical Operators: AND, OR, NOT
Assignment Operator: :=
Statement Terminator: ;
Concatenation Operator: ||
3. Literals
Types:
4. Comments
Single-line:
-- This is a comment
Multi-line:
/* This is
a multi-line comment */
Declaration Syntax:
variable_name datatype [NOT NULL] [:= initial_value];
Example:
NUMBER
VARCHAR2
CHAR
DATE
BOOLEAN
TIMESTAMP
Scalar types are used for arithmetic operations and string manipulation.
Records
Collections
Used for structured data handling.
REF CURSOR
Object types
Anchored Declarations
%TYPE
v_empname [Link]%TYPE;
%ROWTYPE
emp_record emp%ROWTYPE;
3. Conditional
Statements
Conditional statements control program flow based on logical conditions.
1. IF Statement
IF condition THEN
statements;
END IF;
2. IF-ELSE Statement
IF condition THEN
statements;
ELSE
statements;
END IF;
3. IF-ELSIF-ELSE
IF condition1 THEN
statements;
ELSIF condition2 THEN
statements;
ELSE
statements;
END IF;
4. CASE Statement
Simple CASE
CASE variable
WHEN value1 THEN statements;
WHEN value2 THEN statements;
END CASE;
Searched CASE
CASE
WHEN condition1 THEN statements;
WHEN condition2 THEN statements;
END CASE;
Advantages:
Improves readability.
Avoids complex nested IF statements.
Enhances logical clarity.
4. Iterative
Statements
Iterative statements allow repeated execution of code.
1. Basic LOOP
LOOP
statements;
EXIT WHEN condition;
END LOOP;
2. WHILE LOOP
3. FOR LOOP
5. Cursor Structures
A cursor is a pointer to the result set of a SQL query.
Types of Cursors
1. Implicit Cursor
Attributes:
SQL%FOUND
SQL%NOTFOUND
SQL%ROWCOUNT
SQL%ISOPEN
2. Explicit Cursor
Steps:
1. Declare
2. Open
3. Fetch
4. Close
Example:
OPEN emp_cur;
FETCH emp_cur INTO v_empno, v_ename;
CLOSE emp_cur;
Cursor FOR LOOP
6. Bulk Statements
Bulk statements improve performance by reducing context switching between SQL and PL/SQL
engines.
BULK COLLECT
FORALL
FORALL i IN 1..emp_ids.COUNT
DELETE FROM emp WHERE empno = emp_ids(i);
Advantages:
High performance
Efficient large data processing
Reduces network overhead
7. Introduction to
Collections
Collections are PL/SQL data types used to store multiple values of the same datatype.
Types:
1. VARRAY
2. Nested Table
3. Associative Array
8. Object Types:
VARRAY and Table
Collections
VARRAY
Fixed maximum size.
Ordered collection.
Stored inline with table.
Advantages:
Maintains order.
Suitable for small fixed-size lists.
Nested Table
No fixed size.
Stored separately.
Can grow dynamically.
Advantages:
Flexible size.
Efficient for large datasets.
9. Associative Arrays
Also called Index-by tables.
Important Methods
COUNT
FIRST
LAST
NEXT
PRIOR
EXTEND
DELETE
EXISTS
TRIM
Example:
[Link];
[Link](2);
⃣ Function and
Procedure
Architecture (10
Marks)
Introduction
Functions and Procedures are PL/SQL subprograms used to modularize application logic. They
help in reusability, maintainability, security, and structured programming.
Function Architecture
Syntax
CREATE OR REPLACE FUNCTION calc_bonus
(p_salary IN NUMBER)
RETURN NUMBER
IS
v_bonus NUMBER;
BEGIN
v_bonus := p_salary * 0.10;
RETURN v_bonus;
EXCEPTION
WHEN OTHERS THEN
RETURN 0;
END calc_bonus;
/
Calling Function
DECLARE
v_result NUMBER;
BEGIN
v_result := calc_bonus(50000);
DBMS_OUTPUT.PUT_LINE('Bonus: ' || v_result);
END;
/
Procedure Architecture
Syntax
CREATE OR REPLACE PROCEDURE update_salary
(p_empid IN NUMBER, p_increment IN NUMBER)
IS
BEGIN
UPDATE emp
SET salary = salary + p_increment
WHERE empno = p_empid;
COMMIT;
EXCEPTION
WHEN OTHERS THEN
ROLLBACK;
END update_salary;
/
Calling Procedure
BEGIN
update_salary(101, 2000);
END;
/
Key Difference
Function Procedure
Must return value No compulsory return
Used in SQL Cannot be used in SQL
Used for calculations Used for operations
⃣ Transaction
Scope (10 Marks)
Definition
COMMIT
ROLLBACK
Example
BEGIN
UPDATE emp SET salary = salary + 1000 WHERE empno = 101;
SAVEPOINT before_delete;
ROLLBACK TO before_delete;
COMMIT;
END;
/
Autonomous Transaction
CREATE OR REPLACE PROCEDURE log_action
IS
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO log_table VALUES('Updated record');
COMMIT;
END;
/
Important Points
⃣ Calling
Subroutines (10
Marks)
Subroutines can be called from:
Anonymous blocks
Other procedures
Functions
SQL statements (functions only)
Example
CREATE OR REPLACE PROCEDURE greet_user
(p_name VARCHAR2)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Hello ' || p_name);
END;
/
Calling:
BEGIN
greet_user('Oracle');
END;
/
⃣ Positional
Notation (10 Marks)
Parameters passed in the same order as declared.
Calling:
BEGIN
add_employee(101, 'John');
END;
/
⃣ Named Notation
(10 Marks)
Parameters passed using parameter names.
BEGIN
add_employee(p_name => 'John',
p_id => 101);
END;
/
⃣ Mixed Notation
(10 Marks)
Combination of positional and named.
BEGIN
add_employee(101,
p_name => 'John');
END;
/
Rule:
⃣ Exclusionary
Notation (10 Marks)
Used when parameters have default values.
Calling:
BEGIN
display_info(101);
END;
/
✔ Optional parameters
✔ Flexible procedure calls
⃣ SQL Call
Notation (10 Marks)
Functions can be used inside SQL queries.
SELECT empno,
double_salary(salary)
FROM emp;
Restrictions:
⃣ Function Model
Choices (10 Marks)
1. Standalone Function
CREATE FUNCTION simple_func
RETURN NUMBER
IS
BEGIN
RETURN 1;
END;
/
2. Package Function
CREATE PACKAGE math_pkg AS
FUNCTION square(p NUMBER) RETURN NUMBER;
END;
/
3. Deterministic Function
CREATE FUNCTION square_det(p NUMBER)
RETURN NUMBER DETERMINISTIC
IS
BEGIN
RETURN p*p;
END;
/
Creation Options
(10 Marks)
Common options:
OR REPLACE
AUTHID CURRENT_USER
DETERMINISTIC
PARALLEL_ENABLE
Example:
⃣ ⃣ Pass-by-Value
Functions (10 Marks)
Default behavior for IN parameters.
⃣ ⃣ Pass-by-
Reference Functions
(10 Marks)
Using IN OUT.
⃣ ⃣ Procedures
(Pass-by-Value &
Reference) (10
Marks)
Pass-by-Value (IN)
CREATE PROCEDURE test_value
(p_num IN NUMBER)
IS
BEGIN
DBMS_OUTPUT.PUT_LINE(p_num);
END;
/
Calling:
DECLARE
v_num NUMBER := 10;
BEGIN
test_reference(v_num);
DBMS_OUTPUT.PUT_LINE(v_num);
END;
/
⃣ ⃣ Supporting
Scripts (10 Marks)
Supporting scripts help in maintenance.
Drop Script
DROP FUNCTION calc_bonus;
DROP PROCEDURE update_salary;
Grant Script
GRANT EXECUTE ON calc_bonus TO user1;
Testing Script
BEGIN
DBMS_OUTPUT.PUT_LINE(calc_bonus(50000));
END;
/
Packages in PL/SQL
(10 Marks – With
Explanation + Code)
1. Package Architecture
A Package is a schema object that groups related procedures, functions, variables, cursors, and
types into a single unit.
Advantages:
Modularity
Encapsulation
Better performance
Easier maintenance
Security control
2. Package Specification
Example:
CREATE OR REPLACE PACKAGE emp_pkg AS
-- Public variable
bonus_rate NUMBER := 0.10;
-- Public procedure
PROCEDURE raise_salary(p_empid NUMBER, p_amount NUMBER);
-- Public function
FUNCTION get_salary(p_empid NUMBER) RETURN NUMBER;
END emp_pkg;
/
Explanation:
3. Package Body
RETURN v_salary;
END get_salary;
END emp_pkg;
/
4. Prototype Features
Example:
FUNCTION calculate_bonus(p_salary NUMBER) RETURN NUMBER;
Syntax:
CREATE OR REPLACE PACKAGE large_pkg
IS
PRAGMA SERIALLY_REUSABLE;
...
END;
/
Purpose:
Procedure Example:
PROCEDURE add_employee(p_name VARCHAR2, p_salary NUMBER) IS
BEGIN
INSERT INTO employees(name, salary)
VALUES (p_name, p_salary);
END;
Function Example:
FUNCTION total_employees RETURN NUMBER IS
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM employees;
RETURN v_count;
END;
Invoker Rights
Difference:
Compile Package
ALTER PACKAGE emp_pkg COMPILE;
Drop Package
DROP PACKAGE emp_pkg;
Describe Package
DESC emp_pkg;
Check Errors
SHOW ERRORS;
Validate Package
ALTER PACKAGE emp_pkg COMPILE BODY;
SELECT *
FROM user_dependencies
WHERE name = 'EMP_PKG';
Shows:
Tables used
Other procedures/functions used
1. Timestamp Method
2. Signature Method
Timestamp Signature
Based on time Based on structure
Less accurate More accurate
Faster Safer
Conclusion
PL/SQL Packages provide:
Modular programming
Encapsulation
Performance improvement
Better security through Definer/Invoker rights
Efficient dependency management
⃣ Package
Architecture
Concept
A Package is a schema object that encapsulates logically related PL/SQL elements (procedures,
functions, variables, types, cursors).
Structure:
Architecture View
Client → Package Specification → Package Body → Database Objects
Features:
Encapsulation
Session persistence
Performance (Loaded once per session)
Security control
⃣ Package
Specification
Definition
Code Example
CREATE OR REPLACE PACKAGE finance_pkg AS
-- Public variable
tax_rate NUMBER := 0.18;
-- Public type
TYPE emp_rec IS RECORD(
emp_id NUMBER,
emp_salary NUMBER
);
-- Procedure prototype
PROCEDURE update_salary(p_id NUMBER, p_amt NUMBER);
-- Function prototype
FUNCTION calculate_tax(p_salary NUMBER) RETURN NUMBER;
END finance_pkg;
/
Key Points:
Only declarations
No implementation
Acts as interface
⃣ Prototype
Features
Concept
Enables:
Forward referencing
Overloading
Better modularity
Example
Specification:
Body:
⃣ Serially Reusable
Precompiler
Directive
Concept
Syntax
CREATE OR REPLACE PACKAGE temp_pkg
IS
PRAGMA SERIALLY_REUSABLE;
PROCEDURE display;
END;
/
Body:
CREATE OR REPLACE PACKAGE BODY temp_pkg
IS
PRAGMA SERIALLY_REUSABLE;
PROCEDURE display IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Temporary execution');
END;
END;
/
Use Case:
High-concurrency environments
Large global variables
⃣ Variables in
Packages
Public Variable
v_counter NUMBER := 0;
Persistent Nature:
⃣ Types in Packages
Packages allow creation of reusable types.
Record Type
TYPE dept_rec IS RECORD(
dept_id NUMBER,
dept_name VARCHAR2(50)
);
Collection Type
TYPE emp_list IS TABLE OF NUMBER;
⃣ Components:
Functions and
Procedures
Procedure Example
PROCEDURE insert_emp(p_id NUMBER, p_name VARCHAR2) IS
BEGIN
INSERT INTO employees(employee_id, first_name)
VALUES (p_id, p_name);
END;
Function Example
FUNCTION total_emp RETURN NUMBER IS
v_count NUMBER;
BEGIN
SELECT COUNT(*) INTO v_count FROM employees;
RETURN v_count;
END;
⃣ Package Body
Definition
Example
CREATE OR REPLACE PACKAGE BODY finance_pkg AS
END finance_pkg;
/
Key Features:
⃣ Definer vs
Invoker Rights
Mechanics
Definer Rights (Default)
Difference Table:
Managing
Packages in Database
Catalog
View Packages
SELECT object_name, status
FROM user_objects
WHERE object_type = 'PACKAGE';
Recompile
ALTER PACKAGE finance_pkg COMPILE;
Drop
DROP PACKAGE finance_pkg;
⃣ Finding,
Validating &
Describing Packages
Describe Package
DESC finance_pkg;
Show Errors
SHOW ERRORS PACKAGE finance_pkg;
Validate
ALTER PACKAGE finance_pkg COMPILE BODY;
⃣ Checking
Dependencies
Concept
Query
SELECT name, type, referenced_name
FROM user_dependencies
WHERE name = 'FINANCE_PKG';
Purpose:
⃣ Timestamp vs
Signature Validation
Oracle invalidates packages when dependent objects change.
Timestamp Method
Checks last modified time
If changed → invalid
Limitation:
Signature Method
Comparison Table
Timestamp Signature
Based on time Based on structure
Less accurate Highly accurate
More recompilations Fewer recompilations
Conclusion (For 10
Marks Ending)
PL/SQL Packages provide modular, secure, and high-performance database programming.
They support:
Encapsulation
Persistent variables
Reusable types
Controlled access via Definer/Invoker rights
Dependency tracking and validation
⃣ Introduction to
Triggers
Information
A Trigger is a stored PL/SQL block that automatically executes when a specified event occurs
in the database.
Triggering Events:
Basic Syntax
CREATE OR REPLACE TRIGGER trigger_name
BEFORE | AFTER | INSTEAD OF
INSERT OR UPDATE OR DELETE
ON table_name
[FOR EACH ROW]
BEGIN
-- Trigger logic
END;
/
⃣ Database Trigger
Architecture
Information
User SQL → SQL Engine → Trigger Fired → PL/SQL Engine → Execution → Database
Updated
Components:
Trigger Event
Timing (BEFORE/AFTER)
Target Object
Trigger Body
⃣ DDL Triggers
Information
CREATE
ALTER
DROP
TRUNCATE
⃣ Event Attribute
Functions
Used inside DDL triggers.
Function Purpose
ORA_SYSEVENT Returns event name
ORA_DICT_OBJ_NAME Object name
ORA_DICT_OBJ_TYPE Object type
ORA_LOGIN_USER User name
Example
BEGIN
DBMS_OUTPUT.PUT_LINE('Event: ' || ORA_SYSEVENT);
END;
⃣ Building DDL
Triggers
Example: Restrict Table Drop
CREATE OR REPLACE TRIGGER restrict_drop
BEFORE DROP ON SCHEMA
BEGIN
IF ORA_DICT_OBJ_TYPE = 'TABLE' THEN
RAISE_APPLICATION_ERROR(-20001, 'Dropping tables not allowed');
END IF;
END;
/
⃣ DML Triggers
Information
INSERT
UPDATE
DELETE
⃣ Statement-Level
Triggers
Information
Example
CREATE OR REPLACE TRIGGER stmt_trigger
AFTER INSERT ON employees
BEGIN
INSERT INTO audit_log(action_date, action_type)
VALUES (SYSDATE, 'INSERT STATEMENT');
END;
/
⃣ Row-Level
Triggers
Information
Executes once per affected row
Uses :NEW and :OLD
Example
CREATE OR REPLACE TRIGGER row_trigger
BEFORE UPDATE ON employees
FOR EACH ROW
BEGIN
IF :[Link] < :[Link] THEN
RAISE_APPLICATION_ERROR(-20002, 'Salary cannot be reduced');
END IF;
END;
/
⃣ Compound
Triggers
Information
Example
CREATE OR REPLACE TRIGGER compound_trigger
FOR UPDATE ON employees
COMPOUND TRIGGER
BEFORE STATEMENT IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Before update statement');
END BEFORE STATEMENT;
AFTER STATEMENT IS
BEGIN
DBMS_OUTPUT.PUT_LINE('After update statement');
END AFTER STATEMENT;
END compound_trigger;
/
INSTEAD OF
Triggers
Information
⃣ ⃣ System &
Database Event
Triggers
Information
LOGON
LOGOFF
STARTUP
SHUTDOWN
Example
CREATE OR REPLACE TRIGGER logon_trigger
AFTER LOGON ON DATABASE
BEGIN
INSERT INTO login_audit(user_name, login_time)
VALUES (USER, SYSDATE);
END;
/
⃣ ⃣ Trigger
Restrictions
Key Restrictions:
Example (Invalid)
COMMIT; -- Not allowed inside trigger
⃣ ⃣ Maximum
Trigger Size
Maximum size: 32 KB
For large logic → Call stored procedure
Example
CREATE OR REPLACE TRIGGER call_proc
AFTER INSERT ON employees
BEGIN
audit_procedure;
END;
/
⃣ ⃣ SQL
Statements in
Triggers
Allowed:
SELECT INTO
INSERT
UPDATE
DELETE
Example:
Not Allowed:
⃣ ⃣ LONG and
LONG RAW Data
Types
Restrictions:
Cannot reference LONG directly in trigger
Cannot compare LONG values
Solution:
Final Conclusion
([Link] Level)
Triggers provide:
However: