0% found this document useful (0 votes)
4 views35 pages

DB-PLSQL Key-1-1

The document provides a comprehensive question bank on PL/SQL, covering topics such as block structure, data types, lexical units, conditional statements, functions, and control structures. It discusses bulk operations, composite data types, and collections, detailing their characteristics and use cases. Additionally, it explains the architecture of functions, definer vs. invoker rights, and the behavior of variables within different PL/SQL blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views35 pages

DB-PLSQL Key-1-1

The document provides a comprehensive question bank on PL/SQL, covering topics such as block structure, data types, lexical units, conditional statements, functions, and control structures. It discusses bulk operations, composite data types, and collections, detailing their characteristics and use cases. Additionally, it explains the architecture of functions, definer vs. invoker rights, and the behavior of variables within different PL/SQL blocks.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 35

DATABASE PROGRAMMING WITH PL/SQL QUESTION BANK KEY R23[24-25]

1. Draw the Block Structure in PL/SQL?


ANS:

Execution Block
The execution block is the part of the PL/SQL block where the actual logic and statements to
be executed are written.
Basic Block Structure
The simplest PL/SQL block does nothing. You must have a minimum of one statement inside
any execution block, even if it’s a NULL statement.
Declaration Block
The declaration block is an optional section that is used to define and initialize variables,
constants, cursors, and subprograms required in the execution block.

2. List the Basic Scalar Data Types in PL/SQL?


ANS
Scalar Data Types:
Scalar data types are the simplest types in PL/SQL that hold a single value (e.g., a number,
string, date, or boolean).
Categories of Scalar Data Types:
1. Numeric Types
2. Character Types
3. Date/Time Types
4. Boolean Type

3. Define lexical Units in PL/SQL?


ANS
Lexical units are the smallest elements of the language that have a syntactic meaning. These
include delimiters, identifiers, literals, and comments, as they are essential for constructing
PL/SQL programs.

4.What are Conditional Statements in PL/SQL?


ANS
There are three types of conditional statements in programming languages: single-branching
statements, multiple-branching statements without fall-through, and multiple-branching
statements with fall-through. To fall through means to process all subsequent conditions after
finding a matching CASE statement.

5. What is the architecture of Functions in PL/SQL?


ANS:
Functions and procedures are named PL/SQL blocks. It also call them subroutines or
subprograms. They have headers in place of the declaration block. The header defines the
function or
procedure name, a list of formal parameters, and a return data type for functions.

6.Explain Positional Notation in PL/SQL?


ANS
Positional notation is one of the ways to pass arguments to procedures and functions. When
using positional notation, the arguments are passed in the exact order in which they are defined
in the procedure or function.

7. What is the Package Specification in PL/SQL?


Ans.
"Package Specification" is the part of a package that defines the public interface, essentially
declaring all the elements like variables, constants, cursors, procedures, and functions that are
accessible from outside the package.

8.Explain the concept of Definer vs. Invoke Rights in PL/SQL?


ANS
Definer Rights vs. Invoker Rights in PL/SQL
Definer Rights (Default): The procedure runs with the privileges of the owner (creator). The
caller inherits these privileges. Example:
CREATE OR REPLACE PROCEDURE get_emp_data AS BEGIN SELECT * FROM
employees; END;
Invoker Rights (AUTHID CURRENT_USER): The procedure runs with the privileges of
the caller. Example:
CREATE OR REPLACE PROCEDURE get_emp_data AUTHID CURRENT_USER AS
BEGIN SELECT * FROM employees; END;

9. What are Data definition Language (DDL) Triggers?


ANS
Data Definition Language (DDL) triggers are a type of database trigger that fires in response
to changes made to the structure of the database itself. Common DDL commands include:
CREATE
ALTER
DROP
RENAME
TRUNCATE

10.Explain the concept of Row-Level Triggers?


ANS
Row-level triggers are a type of trigger in Oracle that fires once for each row affected by a
DML operation (such as INSERT, UPDATE, or DELETE). These triggers allow you to
access and manipulate individual row-level data, making them useful for enforcing data
integrity, auditing, and implementing business rules at the row level.

11. Explain the behavior of variables in PL/SQL Block?


ANS:
The behavior of variables in PL/SQL depends on how they are used in anonymous blocks,
nested anonymous blocks, local named blocks, and stored named blocks.
Types of PL/SQL Blocks
PL/SQL blocks can be anonymous or named, with different scoping rules for variables.
Understanding these blocks helps in writing modular and maintainable PL/SQL programs.

1. Anonymous Blocks
An anonymous block is an unnamed PL/SQL block that is not stored in the database and
executes immediately.
Variable Behavior:
• Variables are local to the block.
• They exist only during execution and cannot be accessed outside the block.
Example:
sql
CopyEdit
BEGIN
DECLARE message VARCHAR2(50) := 'Hello, Anonymous Block!';
BEGIN
DBMS_OUTPUT.PUT_LINE(message); -- Accessible within the block
END;
-- message is not accessible here
END;

2. Nested Anonymous Blocks


A nested block is a PL/SQL block within another block.
Variable Behavior:
• Inner blocks can access outer variables unless shadowed.
• Inner variables are not accessible in the outer block.
Example:
sql
CopyEdit
BEGIN
DECLARE outer_var NUMBER := 10;
BEGIN
DECLARE inner_var NUMBER := 20;
outer_var NUMBER := 50; -- Shadows the outer variable
BEGIN
DBMS_OUTPUT.PUT_LINE('Inner outer_var: ' || outer_var); -- Outputs 50
DBMS_OUTPUT.PUT_LINE('inner_var: ' || inner_var); -- Outputs 20
END;
DBMS_OUTPUT.PUT_LINE('Outer outer_var: ' || outer_var); -- Outputs 10
-- inner_var is not accessible here
END;
END;

3. Local Named Blocks


A local named block is a named block defined within another PL/SQL block, improving
modularity.
Variable Behavior:
• Outer variables are accessible unless shadowed.
• Local block variables are not accessible outside.
Example:
sql
CopyEdit
DECLARE
outer_var NUMBER := 30;
BEGIN
DECLARE inner_var NUMBER := 40;
BEGIN
-- Local named block
<<local_block>>
DECLARE inner_var NUMBER := 50; -- Shadows parent block’s inner_var
BEGIN
DBMS_OUTPUT.PUT_LINE('Local Block inner_var: ' || inner_var); -- Outputs 50
DBMS_OUTPUT.PUT_LINE('Parent Block outer_var: ' || outer_var); -- Outputs 30
END local_block;

DBMS_OUTPUT.PUT_LINE('Outer inner_var: ' || inner_var); -- Outputs 40


END;
END;

4. Stored Named Blocks


A stored named block is saved in the database as a procedure, function, or package and
can be reused.
Variable Behavior:
• Variables inside procedures and functions are local to that block.
• Package variables can be global or local.
• Global package variables retain values across session calls.
Example (Procedure):
sql
CopyEdit
CREATE OR REPLACE PROCEDURE sample_proc AS
local_var NUMBER := 100; -- Local to this procedure
BEGIN
DBMS_OUTPUT.PUT_LINE('Local Variable: ' || local_var);
END sample_proc;

-- Calling the procedure


BEGIN
sample_proc;
-- local_var is not accessible here
END;

12. Discuss the different Control Structures in PL/SQL?


ANS
Control Structures in PL/SQL
PL/SQL provides control structures to control the flow of execution based on conditions,
loops, and branching. These include Conditional Statements, Loops, and Sequential
Control.

1. Conditional Statements (Decision-Making)


Conditional statements allow the execution of different code blocks based on conditions.
a) IF-THEN
Executes a block of code if the condition is TRUE.
sql
CopyEdit
DECLARE x NUMBER := 10;
BEGIN
IF x > 5 THEN
DBMS_OUTPUT.PUT_LINE('X is greater than 5');
END IF;
END;
b) IF-THEN-ELSE
Executes different blocks based on condition evaluation.
sql
CopyEdit
DECLARE x NUMBER := 3;
BEGIN
IF x > 5 THEN
DBMS_OUTPUT.PUT_LINE('X is greater than 5');
ELSE
DBMS_OUTPUT.PUT_LINE('X is 5 or less');
END IF;
END;
c) IF-THEN-ELSIF-ELSE
Checks multiple conditions sequentially.
sql
CopyEdit
DECLARE x NUMBER := 10;
BEGIN
IF x < 5 THEN
DBMS_OUTPUT.PUT_LINE('X is less than 5');
ELSIF x = 10 THEN
DBMS_OUTPUT.PUT_LINE('X is 10');
ELSE
DBMS_OUTPUT.PUT_LINE('X is greater than 10');
END IF;
END;
d) CASE Statement
Used for better readability in multiple conditions.
sql
CopyEdit
DECLARE grade CHAR := 'B';
BEGIN
CASE grade
WHEN 'A' THEN DBMS_OUTPUT.PUT_LINE('Excellent');
WHEN 'B' THEN DBMS_OUTPUT.PUT_LINE('Good');
ELSE DBMS_OUTPUT.PUT_LINE('Needs Improvement');
END CASE;
END;

2. Looping Structures (Iteration)


Loops are used to execute a block of code repeatedly.
a) Basic LOOP
Executes indefinitely until an EXIT condition is met.
sql
CopyEdit
DECLARE counter NUMBER := 1;
BEGIN
LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
EXIT WHEN counter > 5;
END LOOP;
END;
b) WHILE LOOP
Repeats as long as the condition is TRUE.
sql
CopyEdit
DECLARE counter NUMBER := 1;
BEGIN
WHILE counter <= 5 LOOP
DBMS_OUTPUT.PUT_LINE('Counter: ' || counter);
counter := counter + 1;
END LOOP;
END;
c) FOR LOOP
Repeats a fixed number of times.
sql
CopyEdit
BEGIN
FOR i IN 1..5 LOOP
DBMS_OUTPUT.PUT_LINE('Iteration: ' || i);
END LOOP;
END;

3. Sequential Control (GOTO Statement)


Transfers control to a specific label in the program (not recommended due to poor
readability).
sql
CopyEdit
DECLARE x NUMBER := 1;
BEGIN
<<jump_point>>
DBMS_OUTPUT.PUT_LINE('Jumped here!');
IF x = 1 THEN
GOTO jump_point;
END IF;
END;

13. Describe Bulk Operations in PL/SQL?


A:
Bulk Operations in PL/SQL
Bulk operations in PL/SQL improve performance by processing multiple rows at once,
rather than handling them one at a time. They are used with BULK COLLECT and
FORALL statements.

1. BULK COLLECT
• Retrieves multiple rows in a single fetch and stores them in a collection (e.g.,
VARRAY, TABLE, or RECORD).
• Reduces context switching between SQL and PL/SQL, improving performance.

Example: Using BULK COLLECT with SELECT


sql
CopyEdit
DECLARE
TYPE emp_table IS TABLE OF employees%ROWTYPE;
emp_data emp_table;
BEGIN
SELECT * BULK COLLECT INTO emp_data FROM employees WHERE department_id
= 10;
FOR i IN emp_data.FIRST .. emp_data.LAST LOOP
DBMS_OUTPUT.PUT_LINE('Employee: ' || emp_data(i).employee_name);
END LOOP;
END;

2. FORALL (Bulk DML Processing)


• Processes multiple DML (INSERT, UPDATE, DELETE) statements in bulk to
improve execution speed.
• Avoids repetitive execution of SQL statements inside loops.
Example: Using FORALL to Update Salaries
sql
CopyEdit
DECLARE
TYPE emp_ids_table IS TABLE OF employees.employee_id%TYPE;
emp_ids emp_ids_table := emp_ids_table(101, 102, 103);
BEGIN
FORALL i IN emp_ids.FIRST .. emp_ids.LAST
UPDATE employees SET salary = salary * 1.10 WHERE employee_id = emp_ids(i);
COMMIT;
END;
• Updates multiple records in one go, reducing performance overhead.

3. BULK COLLECT + FORALL (Best Performance)


• Combining BULK COLLECT (fetch) with FORALL (DML operations) significantly
enhances performance.
Example: Fetch and Delete Employees in Bulk
sql
CopyEdit
DECLARE
TYPE emp_ids_table IS TABLE OF employees.employee_id%TYPE;
emp_ids emp_ids_table;
BEGIN
-- Fetch all employee IDs in a department
SELECT employee_id BULK COLLECT INTO emp_ids FROM employees WHERE
department_id = 20;

-- Delete employees in bulk


FORALL i IN emp_ids.FIRST .. emp_ids.LAST
DELETE FROM employees WHERE employee_id = emp_ids(i);

COMMIT;
END;
• Minimizes SQL context switching, leading to faster execution.

Advantages of Bulk Operations


• Faster execution – Reduces repeated context switching between PL/SQL and SQL.
• Less CPU and memory usage – Processes multiple rows in one go.
• Optimized performance – Ideal for large datasets and batch processing.

14. What are the Basic Composite Data Types in PL/SQL?


ANS
1. RECORD Type
A RECORD is a group of related fields that can store different data types, similar to a row in
a table. It helps in handling multiple related values as a single unit.
Syntax:
sql
CopyEdit
DECLARE
TYPE emp_record IS RECORD (
emp_id NUMBER,
emp_name VARCHAR2(50),
salary NUMBER
);
employee emp_record; -- Declaring a record variable
BEGIN
employee.emp_id := 101;
employee.emp_name := 'John';
employee.salary := 50000;

DBMS_OUTPUT.PUT_LINE('Employee: ' || employee.emp_name || ' Salary: ' ||


employee.salary);
END;
/
Use Cases: Useful for storing and processing table row data in PL/SQL programs.
2. COLLECTIONS (ARRAY-LIKE STRUCTURES)
Collections store multiple values of the same data type. There are three types of collections in
PL/SQL:
A. Associative Arrays (Index-by Tables)
• Unbounded, dynamic arrays indexed by BINARY_INTEGER or VARCHAR2.
• Good for fast lookups in-memory.
Example:
sql
CopyEdit
DECLARE
TYPE emp_table IS TABLE OF VARCHAR2(50) INDEX BY PLS_INTEGER;
employees emp_table;
BEGIN
employees(1) := 'Alice';
employees(2) := 'Bob';

DBMS_OUTPUT.PUT_LINE('Employee 1: ' || employees(1));


END;
/

B. Nested Tables
• Can be stored in the database and used in SQL queries.
• Allows deleting and reordering elements.
Example:
sql
CopyEdit
DECLARE
TYPE num_table IS TABLE OF NUMBER;
numbers num_table := num_table(10, 20, 30);
BEGIN
DBMS_OUTPUT.PUT_LINE('First Number: ' || numbers(1));
END;
/

C. VARRAYs (Variable-Size Arrays)


• Fixed size arrays, must specify max size during declaration.
• Cannot delete individual elements, only the whole array.
Example:
sql
CopyEdit
DECLARE
TYPE grade_array IS VARRAY(3) OF NUMBER;
grades grade_array := grade_array(85, 90, 75);
BEGIN
DBMS_OUTPUT.PUT_LINE('Grade 1: ' || grades(1));
END;

Summary
Composite Type Characteristics Use Case
Holds different data types in a structured Used for processing table row
RECORD
format data
Associative Used for fast in-memory
Unbounded, indexed by numbers/strings
Array lookups
Composite Type Characteristics Use Case
Used for storing collections in
Nested Table Dynamic, stored in DB, can be sparse
tables
VARRAY Fixed size, stored in DB, dense Used for small, ordered data sets

15. Discuss the different types of Collections in PL/SQL?


Ans:
Collections in PL/SQL
Collections are data structures that store multiple elements of the same data type in a single
unit. They are similar to arrays or lists in other programming languages and are useful for
handling sets of data in PL/SQL.
Types of Collections
PL/SQL supports three types of collections:

1. Associative Arrays (Index-by Tables)


• Indexed by: BINARY_INTEGER or VARCHAR2.
• Usage: Fast in-memory lookups, cannot be stored in the database.
• Sparsity: Allows non-sequential indexes.
Example:
sql
CopyEdit
DECLARE
TYPE emp_table IS TABLE OF VARCHAR2(100) INDEX BY PLS_INTEGER;
employees emp_table;
BEGIN
employees(1) := 'John';
employees(2) := 'Jane';

DBMS_OUTPUT.PUT_LINE('Employee 1: ' || employees(1));


DBMS_OUTPUT.PUT_LINE('Employee 2: ' || employees(2));
END;
• Best for temporary data storage.

2. Nested Tables
• Usage: Can store in the database as a column, supports dynamic resizing.
• Sparsity: Can have gaps between indexes.
Example:
sql
CopyEdit
DECLARE
TYPE emp_id_table IS TABLE OF NUMBER;
emp_ids emp_id_table := emp_id_table();
BEGIN
emp_ids.EXTEND(3);
emp_ids(1) := 101;
emp_ids(2) := 102;
emp_ids(3) := 103;
FOR i IN 1..emp_ids.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('Employee ID: ' || emp_ids(i));
END LOOP;
END;
Useful for database storage and dynamic data handling.

3. VARRAYs (Variable-Size Arrays)


• Usage: Fixed maximum size, can be stored in the database.
• Sparsity: Always dense, no gaps allowed.
Example:
sql
CopyEdit
DECLARE
TYPE grade_array IS VARRAY(5) OF NUMBER(3, 1);
grades grade_array := grade_array(85.5, 90.0, 78.5);
BEGIN
FOR i IN 1..grades.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('Grade ' || i || ': ' || grades(i));
END LOOP;
END;
Best for storing a fixed number of values.

16. Explain the use of Object Types (Varry and Table Collections) in
PL/SQL.
ANS:
Use of Object Types (VARRAY and Table Collections) in PL/SQL
PL/SQL object types allow structured data storage and manipulation. VARRAYs and Table
Collections (Nested Tables) are used to store multiple values of the same data type
efficiently. They enhance performance, flexibility, and modularity in database operations.

1. VARRAY (Variable-Size Array)


• Fixed-size collection – The maximum number of elements must be defined.
• Dense structure – No gaps between elements (no deletions allowed).
• Stored in the database – Can be used in table columns.
• Efficient for small, fixed-size lists (e.g., phone numbers of an employee).
Example: Declaring and Using a VARRAY
sql
CopyEdit
DECLARE
TYPE grade_array IS VARRAY(5) OF NUMBER(3,1);
grades grade_array := grade_array(85.5, 90.0, 78.5);
BEGIN
FOR i IN 1..grades.COUNT LOOP
DBMS_OUTPUT.PUT_LINE('Grade ' || i || ': ' || grades(i));
END LOOP;
END;
Best for scenarios where the number of elements is known and fixed.

2. Table Collections (Nested Tables)


• Dynamic size – Can grow or shrink.
• Sparse structure – Elements can be deleted, creating gaps.
• Stored in the database as a column and supports indexing.
• Efficient for handling large sets of data dynamically (e.g., list of employees in a
department).
Example: Using Nested Tables
sql
CopyEdit
DECLARE
TYPE emp_table IS TABLE OF VARCHAR2(50);
emp_names emp_table := emp_table(); -- Initialize
BEGIN
emp_names.EXTEND(3);
emp_names(1) := 'John';
emp_names(2) := 'Jane';
emp_names(3) := 'Mark';

FOR i IN 1..emp_names.COUNT LOOP


DBMS_OUTPUT.PUT_LINE('Employee: ' || emp_names(i));
END LOOP;
END;
Best when working with variable-length data sets.

Key Differences: VARRAY vs. Nested Tables


Feature VARRAY Nested Table
Size Fixed Dynamic
Sparsity Always dense Can be sparse
Storage Stored as a whole Stored as separate rows
Usage Best for small, fixed-size collections Best for large, flexible data sets

17. What are Associative Arrays in PL/SQL? Discuss their features?


ANS
Associative Arrays in PL/SQL
Definition:
Associative Arrays (also called Index-by Tables) are key-value pairs in PL/SQL where each
element is identified by a unique index (PLS_INTEGER or VARCHAR2). They are used for
fast in-memory lookups and dynamic storage of data.

Features of Associative Arrays:


1. Dynamically Sized – No fixed size, elements can be added at runtime.
2. Sparse Indexing – Non-contiguous indexes are allowed (e.g., employees(1) := 'John';
employees(10) := 'Doe';).
3. Fast Lookup – Optimized for quick retrieval using key-based indexing.
4. Stored in PL/SQL Memory – Cannot be stored in a database table.
5. Supports String & Numeric Indexing – Can be indexed by PLS_INTEGER or
VARCHAR2.

Example: Associative Array with Numeric Index


DECLARE
TYPE emp_table IS TABLE OF VARCHAR2(50) INDEX BY PLS_INTEGER;
employees emp_table;
BEGIN
employees(1) := 'Alice';
employees(2) := 'Bob';
DBMS_OUTPUT.PUT_LINE('Employee 1: ' || employees(1));
DBMS_OUTPUT.PUT_LINE('Employee 2: ' || employees(2));
END;
Output:
Employee 1: Alice
Employee 2: Bob

Use Cases:
• Storing Lookup Tables (e.g., Employee ID → Name).
• Fast Data Processing in Memory.
• Session-based Data Caching for quick access.

18. Explain the Oracle Collection API?


Ans
Oracle Collection API in PL/SQL
The Oracle Collection API provides a set of built-in methods to manipulate collections like
Associative Arrays, VARRAYs, and Nested Tables in PL/SQL. These methods allow
operations such as adding, deleting, counting, and checking elements within a collection.

Key Methods of Oracle Collection API


Method Description Applicable to
Returns the number of elements in the
COUNT VARRAY, Nested Table
collection.
Checks if the nth element exists in the Associative Array,
EXISTS(n)
collection. Nested Table
Returns the maximum number of elements a
LIMIT VARRAY
VARRAY can store.
Associative Array,
FIRST / LAST Returns the index of the first and last elements.
Nested Table
PRIOR(n) / Associative Array,
Returns the previous or next index relative to n.
NEXT(n) Nested Table
Increases the size of a Nested Table by n
EXTEND(n) Nested Table
elements.
Removes n elements from the end of the
TRIM(n) Nested Table, VARRAY
collection.
Removes elements from a collection (entirely Associative Array,
DELETE
or specific index). Nested Table

Examples of Oracle Collection API Methods


1. Using COUNT, EXTEND, and TRIM
sql
CopyEdit
DECLARE
TYPE emp_list IS TABLE OF VARCHAR2(100);
employees emp_list := emp_list();
BEGIN
employees.EXTEND(3);
employees(1) := 'Alice';
employees(2) := 'Bob';
employees(3) := 'Charlie';

DBMS_OUTPUT.PUT_LINE('Total Employees: ' || employees.COUNT); -- Outputs 3

employees.TRIM(1); -- Removes last element


DBMS_OUTPUT.PUT_LINE('After TRIM, Total Employees: ' || employees.COUNT); --
Outputs 2
END;

19. What are Pass-by-Value and Pass-by-Reference Functions in PL/SQL?


Explain with examples.
ANS:
Pass-by-Value vs. Pass-by-Reference in PL/SQL
In PL/SQL, parameters can be passed to functions and procedures using two mechanisms:
Pass-by-Value (IN Mode)
Pass-by-Reference (IN OUT or OUT Mode)

1. Pass-by-Value (IN Mode)


The function receives a copy of the argument.
Any changes made to the parameter do not affect the original value.
Used when you only need to read the value, not modify it.
Example: Pass-by-Value
sql
CopyEdit
CREATE OR REPLACE FUNCTION square_num(n IN NUMBER) RETURN NUMBER AS
BEGIN
RETURN n * n;
END;
/
DECLARE
num NUMBER := 5;
result NUMBER;
BEGIN
result := square_num(num);
DBMS_OUTPUT.PUT_LINE('Original Value: ' || num); -- Outputs 5 (unchanged)
DBMS_OUTPUT.PUT_LINE('Square: ' || result); -- Outputs 25
END;
/
The original value remains unchanged.

2. Pass-by-Reference (IN OUT / OUT Mode)


The function receives a reference to the original variable.
Changes persist outside the function.
Used when modifications to the original variable are needed.
Example: Pass-by-Reference (IN OUT)
sql
CopyEdit
CREATE OR REPLACE PROCEDURE increment_value(n IN OUT NUMBER) AS
BEGIN
n := n + 1;
END;
/
DECLARE
num NUMBER := 5;
BEGIN
increment_value(num);
DBMS_OUTPUT.PUT_LINE('Modified Value: ' || num); -- Outputs 6 (changed)
END;
/
The original variable is modified.

Comparison Table: Pass-by-Value vs. Pass-by-Reference


Feature Pass-by-Value (IN) Pass-by-Reference (IN OUT / OUT)
Modification No effect on original value Changes original variable
Use Case Read-only operations When modification is needed
Performance Faster (uses copy) May be slower (passes reference)

20. Discuss the function model choices available in PL/SQL?


Ans:
Function Model Choices in PL/SQL (5 Marks)
PL/SQL provides different function models to ensure modularity, reusability, and efficiency
in database programming. The main function models include:
1. Standalone Functions
o Independently stored in the database.
o Can be called from SQL, PL/SQL blocks, or other programs.
o Example:
o CREATE OR REPLACE FUNCTION get_salary(emp_id NUMBER)
RETURN NUMBER IS
o salary NUMBER;
o BEGIN
o SELECT salary INTO salary FROM employees WHERE employee_id =
emp_id;
o RETURN salary;
o END;
Usage: SELECT get_salary(101) FROM dual;
2. Stored Functions in Packages
o Grouped inside a package for better organization.
o Improves security and performance.
o Example:
o CREATE OR REPLACE PACKAGE emp_pkg IS
o FUNCTION get_bonus(emp_id NUMBER) RETURN NUMBER;
o END emp_pkg;
o
o CREATE OR REPLACE PACKAGE BODY emp_pkg IS
o FUNCTION get_bonus(emp_id NUMBER) RETURN NUMBER IS
o bonus NUMBER;
o BEGIN
o SELECT salary * 0.1 INTO bonus FROM employees WHERE
employee_id = emp_id;
o RETURN bonus;
o END;
o END emp_pkg;

Usage: SELECT emp_pkg.get_bonus(101) FROM dual;


3. Inline (Local) Functions
o Defined inside a PL/SQL block and used only within it.
o Not stored in the database.
o Example:
o DECLARE
o FUNCTION square(n NUMBER) RETURN NUMBER IS
o BEGIN
o RETURN n * n;
o END;
o BEGIN
o DBMS_OUTPUT.PUT_LINE('Square of 5: ' || square(5));
o END;

4. Deterministic vs. Non-Deterministic Functions


o Deterministic: Always returns the same result for the same input (e.g., ABS,
ROUND).
o Non-Deterministic: May return different results (e.g., SYSDATE,
DBMS_RANDOM).
o Example (Deterministic Function):
o CREATE OR REPLACE FUNCTION get_fixed_value RETURN NUMBER
DETERMINISTIC IS
o BEGIN
o RETURN 100;
o END;

21. Explain the architecture of Procedures in PL/SQL?


ANS:

A PL/SQL Procedure is a named block that performs a specific task and can be executed
multiple times. It does not return a value but can take IN, OUT, or IN OUT parameters.
1. Structure of a PL/SQL Procedure
A procedure consists of four main parts:
Header – Defines the procedure name and parameters.
Declarative Section (Optional) – Declares variables, cursors, or record structures.
Execution Section (Mandatory) – Contains SQL and PL/SQL statements.
Exception Handling (Optional) – Manages errors using predefined exceptions.
Syntax:
CREATE OR REPLACE PROCEDURE procedure_name (param1 IN datatype, param2 OUT
datatype)
IS
var_name datatype;
BEGIN
-- SQL Statements and Business Logic
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error Occurred');
END procedure_name;
/
2. Example: Insert Employee Record
CREATE OR REPLACE PROCEDURE add_employee (
p_emp_id IN NUMBER,
p_name IN VARCHAR2,
p_salary IN NUMBER)
IS
BEGIN
INSERT INTO employees (emp_id, name, salary)
VALUES (p_emp_id, p_name, p_salary);
COMMIT;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
END add_employee;
/
Calling the Procedure:
EXEC add_employee(101, 'John Doe', 50000);
3. Key Features of Procedures
Modularity – Encourages reusability and better organization.
Performance – Reduces network traffic by executing as a single unit.
Security – Restricts direct table access by encapsulating logic.
Error Handling – Ensures smooth execution with exception handling.
4. Procedure vs. Function
Feature Procedure Function
Returns Value No Yes
Used in SQL Queries No Yes
Supports DML Operations Yes No (with exceptions)

22. What is the difference between Functions and Procedures in PL/SQL?


ANS
Key Differences Between Functions and Procedures

Aspect Function Procedure


Definition A subprogram that computes andA subprogram that performs an action or
returns a single value. task, but does not necessarily return a value.
Return Value Must return a value using theDoes not return a value directly. Data can be
RETURN statement. passed back using OUT or IN OUT
parameters.
Invocation Can be called from SQL queriesCannot be called from SQL queries. Must be
(if the function meets purityinvoked in PL/SQL blocks or programs.
rules).
Used for computations andUsed for tasks like performing DML
Usage transformations that return aoperations (INSERT, UPDATE, DELETE)
single value. or complex
logic.
Parameter Accepts IN parameters by default. Supports IN, OUT, and IN OUT parameters.
Modes
SQL Can be used in SELECT,Cannot be used in SQL statements directly.
Statement WHERE, or other SQL clauses.
Side Effects Should ideally have no sideCan have side effects (e.g., modifying
effects, though they can exist. database state).
Compilation Created with the CREATECreated with the CREATE PROCEDURE
Unit FUNCTION statement. statement.

23. Explain the structure and components of a PL/SQL Packages?


ANS:
Structure and Components of PL/SQL Packages
A PL/SQL Package is a collection of related procedures, functions, variables, and other
elements stored together as a single unit. Packages provide modularity, reusability, and
better performance in PL/SQL programs.

1. Structure of a PL/SQL Package


A package consists of two parts:
1. Package Specification (Interface)
Declares procedures, functions, cursors, and global variables.
Acts as the public interface of the package.
2. Package Body (Implementation)
Defines the logic for procedures and functions declared in the specification.
May contain private functions and procedures not accessible outside the package.
2. Components of a PL/SQL Package
A. Package Specification
Declares procedures, functions, variables, and cursors.
Does not contain logic (only declarations).
Syntax:
CREATE OR REPLACE PACKAGE package_name AS
PROCEDURE proc_name;
FUNCTION func_name RETURN NUMBER;
VAR_NAME NUMBER; -- Global variable
END package_name;

B. Package Body
Implements the logic for procedures and functions.
Can have private components that are not accessible outside the package.
Syntax:
CREATE OR REPLACE PACKAGE BODY package_name AS
PROCEDURE proc_name IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Procedure Executed');
END proc_name;

FUNCTION func_name RETURN NUMBER IS


BEGIN
RETURN 100;
END func_name;
END package_name;

3. Example: Employee Management Package


Package Specification:
CREATE OR REPLACE PACKAGE emp_pkg AS
PROCEDURE add_employee(p_id NUMBER, p_name VARCHAR2, p_salary NUMBER);
FUNCTION get_salary(p_id NUMBER) RETURN NUMBER;
END emp_pkg;

Package Body:
CREATE OR REPLACE PACKAGE BODY emp_pkg AS
PROCEDURE add_employee(p_id NUMBER, p_name VARCHAR2, p_salary NUMBER)
IS
BEGIN
INSERT INTO employees(emp_id, name, salary) VALUES (p_id, p_name, p_salary);
COMMIT;
END add_employee;

FUNCTION get_salary(p_id NUMBER) RETURN NUMBER IS


emp_salary NUMBER;
BEGIN
SELECT salary INTO emp_salary FROM employees WHERE emp_id = p_id;
RETURN emp_salary;
END get_salary;
END emp_pkg;

Calling the Package Procedures and Functions:


BEGIN
emp_pkg.add_employee(101, 'John Doe', 50000);
DBMS_OUTPUT.PUT_LINE('Salary: ' || emp_pkg.get_salary(101));
END;
/
4. Benefits of PL/SQL Packages
• Encapsulation – Hides implementation details, exposing only necessary components.
• Reusability – Procedures and functions in packages can be reused in multiple
programs.
• Improved Performance – Reduces disk I/O and enhances execution speed.
• Modularity – Groups related procedures and functions logically.

24. Describe how to manage packages in the database catalog?


A:
Managing Packages in the Database Catalog
A package in a database is a collection of related procedures, functions, variables, and
cursors stored together for modular programming. Managing packages in the database
catalog involves creating, modifying, compiling, and dropping packages.

Viewing Package Information


The database catalog contains metadata about packages, which can be retrieved using system
views:
Query Purpose
SELECT * FROM USER_OBJECTS WHERE
Lists all packages owned by the user.
OBJECT_TYPE = 'PACKAGE';
SELECT * FROM ALL_OBJECTS WHERE
Lists packages accessible to the user.
OBJECT_TYPE = 'PACKAGE';
SELECT * FROM DBA_OBJECTS WHERE Lists all packages in the database
OBJECT_TYPE = 'PACKAGE'; (requires DBA privileges).
SELECT * FROM USER_SOURCE WHERE NAME Retrieves the stored PL/SQL code for
= 'EMPLOYEE_PKG'; a package.
Viewing Existing Packages
Use the following query to check all packages in the database:
sql
CopyEdit
SELECT OBJECT_NAME, STATUS
FROM USER_OBJECTS
WHERE OBJECT_TYPE = 'PACKAGE';
Checks the status of all packages (VALID or INVALID).
2. Checking Package Source Code
View the package specification and body using:
sql
CopyEdit
SELECT TEXT FROM USER_SOURCE WHERE NAME = 'EMPLOYEE_PKG';
Retrieves stored PL/SQL package code.
3. Recompiling a Package
If a package becomes INVALID, recompile it:
sql
CopyEdit
ALTER PACKAGE employee_pkg COMPILE;
ALTER PACKAGE employee_pkg COMPILE BODY;
Ensures the package is valid and usable.
4. Dropping a Package
If a package is no longer needed:
sql
CopyEdit
DROP PACKAGE employee_pkg;
Removes the package from the catalog permanently.

25. Discuss the importance of Prototype Features in PL/SQL Packages?


Ans:
Importance of Prototype Features in PL/SQL Packages
Prototype features in PL/SQL packages refer to declaring procedures and functions in the
package specification before implementing them in the package body. This separation
improves modularity, reusability, and security.

1. Key Benefits of Prototypes in PL/SQL Packages


• Encapsulation & Modularity – Keeps the interface (specification) separate from
implementation (body), allowing updates without affecting dependent applications.
• Code Reusability – Functions and procedures can be reused across applications,
promoting standardization.
• Security & Access Control – Private functions stay hidden in the package body,
restricting unauthorized access.
• Performance Optimization – Packages load into memory as a whole, reducing
repeated parsing and improving execution speed.
• Dependency Management – Modifications in the package body don’t require
recompiling dependent objects, simplifying maintenance.
• Function Overloading – Allows multiple functions with the same name but
different parameters for flexible usage.

2. Example of Prototyping in a Package


Package Specification (Prototype Declaration)
sql
CopyEdit
CREATE OR REPLACE PACKAGE employee_pkg AS
FUNCTION get_salary(emp_id NUMBER) RETURN NUMBER;
PROCEDURE update_salary(emp_id NUMBER, new_salary NUMBER);
END employee_pkg;
Package Body (Implementation)
sql
CopyEdit
CREATE OR REPLACE PACKAGE BODY employee_pkg AS
FUNCTION get_salary(emp_id NUMBER) RETURN NUMBER IS
salary NUMBER;
BEGIN
SELECT salary INTO salary FROM employees WHERE emp_id = emp_id;
RETURN salary;
END get_salary;
PROCEDURE update_salary(emp_id NUMBER, new_salary NUMBER) IS
BEGIN
UPDATE employees SET salary = new_salary WHERE emp_id = emp_id;
COMMIT;
END update_salary;
END employee_pkg;
This structure ensures flexibility and better code organization.

26. Compare Validation Methods: Timestamp vs. signature in PL/SQL?


ANS
validation is important to ensure that objects are correctly compiled and up-to-date. When an
object is invalidated (e.g., due to a change in a dependent object), it needs to be recompiled.

Let's compare these two methods in terms of how they work and when they are useful.
Timestamp-based Validation
Timestamp-based validation relies on comparing the timestamp (last modification time) of
the dependent object and the objects it relies on (such as tables, views, or other packages). If
the dependent object has a later timestamp than the object it depends on, the object is
considered out of date or invalid and requires recompilation.

Example:
You can view the last compiled time of an object with a query like this: SELECT
object_name, last_ddl_time
FROM user_objects
WHERE object_type IN ('PACKAGE', 'FUNCTION', 'PROCEDURE')
AND object_name = 'MY_PACKAGE';

Signature-based Validation
Signature-based validation involves comparing the signature of a PL/SQL object to see if it
matches its previous version. The signature includes the interface of the object, such as the
procedure's name, parameters, return type, and the names of functions. Essentially, the
signature represents the “contract” of the object, and any change to this contract (such as
changing the number or types of parameters in a function) would invalidate the object.

Example:
Suppose you have a function:
CREATE OR REPLACE FUNCTION calculate_tax (p_salary NUMBER) RETURN
NUMBER IS BEGIN
RETURN p_salary * 0.1; END calculate_tax;
If you change the parameter (e.g., rename p_salary to p_income), the signature of the function
changes, and Oracle will mark the function as invalid even if the timestamp remains
unchanged.
You can view the signature of an object by querying the USER_PROCEDURES or
USER_FUNCTIONS views, and checking for changes in the parameters:
SELECT object_name, procedure_name, parameter_name FROM user_procedures
WHERE object_name = 'MY_PACKAGE';

Comparing Timestamp and Signature Validation

Feature Timestamp-based Validation Signature-based Validation


Granularity Tracks changes based on modificationTracks changes in the structure of
times. the object (interface changes).
Automatic vs Typically requires manual
Manual Automatically done by Oracle. recompilation or custom validation
tools.
Precision Less precise, as it only detects changesMore precise, detects changes in
in modification time. the object’s interface or structure.
Performance Efficient for detecting time-basedMore resource-intensive due to its
changes. focus on the object’s structure.
Use Case Suitable for detecting timestamp-basedSuitable for ensuring that the
changes, such as table modifications. object’s interface remains
consistent.
When BestWhen dealing with objects that changeWhen needing to track changes in
Used infrequently. object structure, parameters, etc.

27. Explain the architecture of Database Triggers in PL/SQL?


ANS

Architecture of Database Triggers in PL/SQL


The architecture of Database Triggers in PL/SQL consists of several key components that
define when and how a trigger executes. These components ensure triggers effectively
automate tasks, enforce business rules, and maintain data integrity.

1. Components of PL/SQL Trigger Architecture


Trigger Event – Specifies the DML operation that activates the trigger (INSERT, UPDATE,
DELETE).
Trigger Timing – Determines when the trigger fires (BEFORE, AFTER, INSTEAD OF).
Trigger Type – Defines whether it applies to individual rows (ROW-LEVEL) or the entire
statement (STATEMENT-LEVEL).
Trigger Body – Contains the PL/SQL block that executes when the trigger fires.
2. Execution Flow of a PL/SQL Trigger
A DML operation occurs on a table.
The trigger detects the operation and checks its condition.
If conditions are met, the trigger executes the PL/SQL block.
The transaction continues based on the trigger’s effect.

3. Example: Trigger for Auditing Data Changes


sql
CopyEdit
CREATE OR REPLACE TRIGGER audit_employee_changes
AFTER UPDATE ON employees
FOR EACH ROW
BEGIN
INSERT INTO employee_audit (emp_id, old_salary, new_salary, change_date)
VALUES (:OLD.emp_id, :OLD.salary, :NEW.salary, SYSDATE);
END;
Purpose: Tracks salary updates in an audit table.

4. Conclusion
The PL/SQL trigger architecture ensures automatic execution when specific events occur,
helping maintain data consistency, security, and automation in database systems.

28. Discuss the different types of DML Triggers and their use cases?
Ans
Types of DML Triggers and Their Use Cases

DML (Data Manipulation Language) triggers are special procedures that automatically
execute when a DML operation (INSERT, UPDATE, DELETE) occurs on a table in a
database. They help enforce business rules, maintain data integrity, and automate processes.
1. AFTER Triggers (Post-Trigger)
Executed after a DML operation is completed.
Used for logging changes or auditing data modifications.
Use Case:

Keeping a log of deleted records in an audit table.


Sending notifications after an update.
Example:

CREATE TRIGGER after_employee_update


AFTER UPDATE ON employees
FOR EACH ROW
INSERT INTO audit_log (emp_id, action)
VALUES (OLD.emp_id, 'Updated');
2. INSTEAD OF Triggers
Used instead of a DML operation (INSERT, UPDATE, DELETE).
Useful for views that don’t allow direct modification.
Use Case:
Updating data in complex views that include multiple tables.
Example:
CREATE TRIGGER instead_of_update_view
INSTEAD OF UPDATE ON employee_view
FOR EACH ROW
BEGIN
UPDATE employees SET name = :NEW.name WHERE emp_id = :OLD.emp_id;
END;
3. BEFORE Triggers (Pre-Trigger)
Executed before a DML operation.
Used to validate or modify data before insertion/updating.
Use Case:
Prevent negative values in salary columns.
Example:
CREATE TRIGGER before_salary_insert
BEFORE INSERT ON employees
FOR EACH ROW
BEGIN
IF :NEW.salary < 0 THEN
RAISE_APPLICATION_ERROR(-20001, 'Salary cannot be negative');
END IF;
END;

29.Describe INSTEAD OF Triggers in PL/SQL and their applications.


ANS:
INSTEAD OF TRIGGERS

An INSTEAD OF trigger is a special type of trigger in Oracle that allows you to replace the default
DML action (such as INSERT, UPDATE, or DELETE) with custom logic. These triggers are
commonly used with views to perform DML operations on underlying base tables when users interact
with the view, essentially providing a mechanism to perform actions on a virtual layer rather than
directly on the physical data structure.

Syntax for INSTEAD OF Triggers

The basic syntax for an INSTEAD OF trigger is as follows:

CREATE OR REPLACE TRIGGER trigger_name INSTEAD OF {INSERT | UPDATE | DELETE}


ON view_name [FOR EACH ROW] DECLARE
-- Optional variable declarations BEGIN
-- Trigger body: custom logic for INSERT, UPDATE, or DELETE END;

Example 1: Using INSTEAD OF Trigger for INSERT on a View

Let's say you have a view that combines data from two tables: employees and departments. You want to
allow users to insert data into the view, but when they do, the trigger should insert data into the correct
base tables.

Step 1: Create the Base Tables

CREATE TABLE employees (


employee_id NUMBER PRIMARY KEY, employee_name VARCHAR2(100), department_id
NUMBER
);

CREATE TABLE departments ( department_id NUMBER PRIMARY KEY, department_name


VARCHAR2(100)
);

Step 2: Create a View


You create a view that combines data from both the employees and departments tables: CREATE
VIEW employee_view AS
SELECT e.employee_id, e.employee_name, d.department_name FROM employees e
JOIN departments d
ON e.department_id = d.department_id;

Step 3: Create the INSTEAD OF Trigger for INSERT

Now, you create an INSTEAD OF trigger that redirects INSERT operations on the employee_view to
the underlying employees and departments tables.

CREATE OR REPLACE TRIGGER employee_view_insert INSTEAD OF INSERT ON


employee_view
FOR EACH ROW BEGIN
-- Insert into the departments table if the department doesn't already exist DECLARE
v_department_id NUMBER;

BEGIN
SELECT department_id INTO v_department_id FROM departments
WHERE department_name = :NEW.department_name;
EXCEPTION
WHEN NO_DATA_FOUND THEN
-- If department doesn't exist, insert a new department INSERT INTO departments
(department_name) VALUES (:NEW.department_name);
-- Get the new department_id SELECT department_id INTO v_department_id FROM
departments
WHERE department_name = :NEW.department_name; END;

-- Insert into the employees table


INSERT INTO employees (employee_name, department_id) VALUES
(:NEW.employee_name, v_department_id);
END;

Step 4: Test the Trigger

You can now test inserting data into the view:

-- Insert a new employee into the view


INSERT INTO employee_view (employee_name, department_name) VALUES ('John Doe',
'HR');
-- Check the data in the tables SELECT * FROM employees; SELECT * FROM departments;

The trigger will handle the INSERT operation by adding data to both the employees and
departments tables as needed.

30. What are the restrictions on PL/SQL Triggers?


ANS
These restrictions ensure the proper functioning of the database and help prevent unexpected
behavior, such as infinite loops or performance degradation.

Here’s a breakdown of the most common restrictions associated with triggers:

Mutating Table Error

One of the most common errors encountered with triggers is the mutating table error. This
occurs when a trigger attempts to modify the same table that fired the trigger.
Mutating Table

A mutating table refers to a table that is in the process of being modified by a DML operation
(such as INSERT, UPDATE, or DELETE). If a trigger attempts to query or modify the same
table during this operation, Oracle cannot guarantee that the data will be consistent.

Example of Mutating Table Error:

Consider a scenario where you have a trigger that fires AFTER UPDATE on the employees
table and attempts to query the employees table to check the old and new values of certain
columns.

CREATE OR REPLACE TRIGGER check_salary_update AFTER UPDATE ON employees


BEGIN
-- Mutating table error: trying to query the same table during an update SELECT COUNT(*)
INTO v_count FROM employees
WHERE department_id = :NEW.department_id; END;

This will raise a mutating table error because the trigger tries to query the employees table
while an UPDATE operation is already happening on it.

Solution:a

To avoid this error, you can:

Use a BEFORE trigger or AFTER statement-level trigger to work with the entire table
rather than specific rows.
Use a temporary table or collection to store values during the trigger and access them later.

Example of Multiple Rows Affected by a Trigger:

When performing an UPDATE on multiple rows in a table, a row-level trigger will fire for each row
affected by the UPDATE.

CREATE OR REPLACE TRIGGER update_employee_salary BEFORE UPDATE ON employees


FOR EACH ROW BEGIN
-- Trigger logic will be applied for each row individually
:NEW.salary := :OLD.salary + 1000; END;

You might also like