pl-sql
Here’s a complete PL/SQL end-to-end revision guide you can use to brush up before interviews. It’s organized so you can skim fundamentals quickly and dive into advanced concepts as needed.
1️⃣ PL/SQL Basics
What is PL/SQL
Oracle’s procedural extension of SQL.
Combines SQL (data manipulation) with procedural features (variables, loops, conditions).
Code is grouped into blocks: anonymous blocks or named program units (procedures, functions, packages).
Block Structure
DECLARE -- optional
-- variable declarations
BEGIN
-- executable statements
EXCEPTION -- optional
-- error handling
END;Declarative Section: Define variables, constants, cursors.
Executable Section: SQL & procedural statements.
Exception Section: Handle runtime errors.
2️⃣ Data Types & Variables
Scalar: NUMBER, VARCHAR2, DATE, BOOLEAN.
Composite: RECORD, TABLE (Associative arrays).
Reference: REF CURSOR.
LOB: BLOB, CLOB.
%TYPE and %ROWTYPE: Inherit column/table structure.
Example:
3️⃣ Control Structures
Conditional: IF…THEN, CASE.
Loops:
Simple LOOP ... END LOOP;
WHILE … LOOP
FOR i IN 1..10 LOOP
4️⃣ Cursors
Used to handle multi-row query results.
Implicit Cursor: Automatically for DML (INSERT/UPDATE/DELETE/SELECT INTO).
Explicit Cursor:
Cursor FOR Loop (simpler):
Parameterised Cursor: Pass parameters at runtime.
5️⃣ Procedures & Functions
Procedure: Performs action, can return OUT parameters.
Function: Must return a value, usable in SQL expressions.
Example Procedure:
6️⃣ Packages
Group related procedures/functions, variables, cursors.
Specification: Public interface.
Body: Implementation.
Advantages: Encapsulation, reusability, better dependency management.
7️⃣ Triggers
Fired automatically on DML/DDL/events.
Types:
Row-level vs Statement-level
Before vs After
Instead Of (for views)
Example:
8️⃣ Exception Handling
Predefined Exceptions: NO_DATA_FOUND, TOO_MANY_ROWS, ZERO_DIVIDE.
User-defined:
PRAGMA EXCEPTION_INIT to map Oracle errors.
9️⃣ Collections
Associative Arrays (index-by tables)
Nested Tables
VARRAYs
Use BULK COLLECT & FORALL for bulk operations.
🔟 Performance & Optimization
Use BULK COLLECT and FORALL for large DML.
Bind variables to avoid hard parsing.
Use LIMIT in bulk fetch.
Proper indexing, EXPLAIN PLAN for query tuning.
11️⃣ Dynamic SQL
EXECUTE IMMEDIATE for DDL or dynamic queries.
Use bind variables to prevent SQL injection.
12️⃣ Advanced Topics
Autonomous Transactions: Independent commits inside a procedure/trigger.
PRAGMA AUTONOMOUS_TRANSACTION.
Ref Cursors: Strongly or weakly typed cursors returned from procedures.
Pipelined Table Functions: Return rows as they are produced.
Materialized Views & DB Links: Often come up in advanced discussions.
13️⃣ Key Oracle Built-ins
DBMS_OUTPUT: Debugging.
DBMS_SQL: Dynamic SQL.
DBMS_JOB / DBMS_SCHEDULER: Scheduling jobs.
DBMS_ALERT / DBMS_PIPE: Messaging.
14️⃣ Interview-Focused Tips
Difference SQL vs PL/SQL
SQL is declarative; PL/SQL adds procedural control.
Trigger vs Procedure
Trigger auto-fires; procedure is invoked explicitly.
Exception Propagation
Unhandled exceptions bubble up to calling block.
Transaction Control
COMMIT, ROLLBACK, SAVEPOINT—understand scope inside procedures/triggers.
15️⃣ Quick Practice Questions
Write a function to return nth highest salary.
Create a trigger to log salary changes.
Use BULK COLLECT & FORALL to insert 1M rows efficiently.
Example of parameterized cursor with dynamic filtering.
Demonstrate exception handling for DUP_VAL_ON_INDEX.
Last-Minute Checklist
✅ Understand PL/SQL block structure & scoping rules.
✅ Know common predefined exceptions & error codes.
✅ Revise differences: Procedure vs Function vs Package vs Trigger.
✅ Practice DML with cursors and collections.
✅ Review transaction behavior inside triggers.
Interview questions
Here’s a comprehensive PL/SQL Q&A set—the same 30 interview questions now paired with concise, practical answers.
You can skim key points quickly or elaborate during an interview.
🟢 Basics & Architecture
1. Explain the structure of a PL/SQL block.
Sections:
DECLARE (optional): variables, cursors, constants.
BEGIN: executable statements.
EXCEPTION (optional): error handling.
END;
Example:
2. Difference between SQL and PL/SQL.
SQL: Declarative, single statements (DML/DDL).
PL/SQL: Procedural extension of SQL; supports loops, conditions, variables, error handling.
3. Anonymous block vs Stored Procedure.
Anonymous: Not stored in DB; runs once.
Procedure: Named, compiled, stored for reuse and can have parameters.
4. Bind variables and importance.
Placeholders (:var) whose values are supplied at runtime.
Reduce parsing overhead and prevent SQL injection.
5. Scope and lifetime of variables.
Scope: Block in which variable is declared.
Lifetime: Duration of block execution. Nested blocks can shadow outer variables.
🟠 Data Types & Variables
6. %TYPE vs %ROWTYPE.
%TYPE: Inherits datatype of a column or variable.
%ROWTYPE: Represents a full row of a table or cursor.
7. Record vs Associative Array.
Record: Single row with multiple fields.
Associative array: Key-value pairs, index can be integer or string.
8. Passing collections to procedures.
Create a collection TYPE at schema level; use it as parameter:
🟡 Control Structures & Cursors
9. Implicit vs Explicit cursors.
Implicit: Automatic for single-row queries/DML.
Explicit: Declared and controlled by developer for multi-row result sets.
10. Parameterized cursor.
Call: FOR rec IN c_emp(10) LOOP … END LOOP;
11. Bulk data fetch (BULK COLLECT & FORALL).
BULK COLLECT retrieves multiple rows into collections in one go.
FORALL performs bulk DML:
12. Cursor attributes.
%FOUND, %NOTFOUND, %ROWCOUNT, %ISOPEN—return status info about cursor execution.
13. Cursor FOR loop vs explicit fetch.
FOR loop automatically opens, fetches, closes.
Explicit fetch gives fine-grained control but requires manual open/fetch/close.
🟢 Procedures, Functions & Packages
14. Procedure vs Function.
Function must return a value; can be used in SELECTs if deterministic.
Procedure may return via OUT params, cannot be used directly in SQL.
15. DML inside a function.
Allowed if function is called from PL/SQL, not directly from a SELECT (unless it’s autonomous or deterministic with pragma).
16. Returning multiple values.
OUT parameters, collections, or a record as OUT.
17. Package advantages.
Encapsulation, modularity, shared state, easier dependency mgmt.
18. Package specification vs body.
Spec: Public declarations (visible to users).
Body: Implementation (can hide private code).
19. Overloaded procedures/functions.
Multiple subprograms with same name but different parameter types or counts.
🟠 Triggers
20. BEFORE vs AFTER triggers.
BEFORE: Fires before DML; good for validation.
AFTER: Fires after DML; good for logging.
21. INSTEAD OF trigger.
Used on views to perform custom DML logic in place of normal operation.
22. Trigger chaining/recursion.
A trigger can call a procedure that fires another trigger. Recursive firing possible; control with WHEN clauses or disabling triggers.
23. Preventing mutating table errors.
Use statement-level triggers, compound triggers, or autonomous transactions to avoid querying the same table in row-level triggers.
🟡 Exception Handling
24. Predefined exceptions.
Examples: NO_DATA_FOUND, TOO_MANY_ROWS, ZERO_DIVIDE, DUP_VAL_ON_INDEX.
25. User-defined exceptions.
26. RAISE_APPLICATION_ERROR.
Used to return custom error numbers/messages to the calling environment.
Syntax: RAISE_APPLICATION_ERROR(-20001, 'Custom message');
27. RAISE vs RAISE_APPLICATION_ERROR.
RAISE: Propagates an existing or user-defined exception.
RAISE_APPLICATION_ERROR: Creates a new application-specific error with custom message.
🟢 Performance & Advanced
28. Performance tuning tips.
Use BULK COLLECT/FORALL, avoid unnecessary loops, use bind variables, keep transactions short, analyze execution plans.
29. Autonomous transactions.
Independent transaction within a block or procedure.
Declared with PRAGMA AUTONOMOUS_TRANSACTION.
Useful for logging or auditing without affecting main transaction.
30. Dynamic SQL (EXECUTE IMMEDIATE).
Allows DDL or runtime-constructed statements.
Example:
Use bind variables to avoid SQL injection.
✅ Extra Scenario Answers (Short Examples)
Nth Highest Salary:
Audit Trigger:
This set covers definitions, best practices, and code snippets—enough for most PL/SQL interviews.
Would you like me to convert this Q&A into a printable PDF cheat sheet for easier last-minute revision?
Coding questions --
Below is a complete PL/SQL coding-practice pack: the 30 questions from before, now each with a working example answer (all runnable on an Oracle database).
Each answer is deliberately concise so you can copy-paste and test.
🟢 Beginner
1. Hello PL/SQL
2. Sum/Difference/Product/Quotient
3. Odd/Even Check
4. Fibonacci (first 10)
5. SELECT INTO
🟠 Intermediate
6. Explicit Cursor
7. Parameterized Cursor
8. Factorial Function
9. Procedure – Update Salary
10. Overloaded Procedure
11. Min & Max Salary OUT Params
12. Simple Package
🟡 Collections & Bulk
13. Bulk Collect
14. FORALL Bulk Update
15. Associative Array Sum
16. Remove Duplicates from Nested Table
🟢 Triggers & Exceptions
17. Audit Trigger
18. Prevent Deletion During Business Hours
19. INSTEAD OF Trigger on View
20. Custom Exception
21. RAISE_APPLICATION_ERROR
🟠 Advanced SQL / PL/SQL
22. Nth Highest Salary
23. Palindrome Check
24. Prime Numbers Between Two Values
25. Dynamic Table Creation
26. Dynamic SELECT
🟡 Real-World Scenarios
27. Pagination Rows N to M
28. Error Logging with Autonomous Txn
29. Monthly Sales Summary
30. Employee Hierarchy Tree
Usage Notes
All examples assume common Oracle sample tables (employees, etc.).
Replace & variables or SYS.ODCINUMBERLIST with your test data when running.
Add proper exception handling or commit/rollback statements in production.
These question-answer pairs cover the spectrum—procedures, functions, triggers, collections, dynamic SQL, and performance tuning—perfect for interview preparation and practice.
Last updated