Google News
logo
PL/SQL Interview Questions
PL/SQL stands for Procedural Language extension of Structured Query Language (SQL). It is a block-structured language having logical blocks which are made up of three sub-blocks i.e. a declarative part, an executable part and an exception building part. PL/SQL is integrated with Oracle and the functionalities of PL/SQL extend after each release of Oracle database.
 
It includes procedural language elements like conditions and loops and allows declaration of constants and variables, procedures and functions. It also helps the users to develop complex database applications using control structures, procedures, modules, etc. PL/SQL is not limited by any case-sensitive letters so you are free to use lower case letters or upper case letters.
Following are the features of PL/SQL :
 
* PL/SQL provides the feature of decision making, looping, and branching by making use of its procedural nature.

* Multiple queries can be processed in one block by making use of a single command using PL/SQL.

* The PL/SQL code can be reused by applications as they can be grouped and stored in databases as PL/SQL units like functions, procedures, packages, triggers, and types.

* PL/SQL supports exception handling by making use of an exception handling block.

* Along with exception handling, PL/SQL also supports error checking and validation of data before data manipulation.

* Applications developed using PL/SQL are portable across computer hardware or operating system where there is an Oracle engine.
PL/SQL tables are nothing but objects of type tables that are modeled as database tables. They are a way to provide arrays that are nothing but temporary tables in memory for faster processing.

These tables are useful for moving bulk data thereby simplifying the process.
The basic structure of PL/SQL follows the BLOCK structure. Each PL/SQL code comprises SQL and PL/SQL statement that constitutes a PL/SQL block.

Each PL/SQL block consists of 3 sections :

* The optional Declaration Section
* The mandatory Execution Section
* The optional Exception handling Section

[DECLARE]
--declaration statements (optional)
BEGIN
--execution statements
[EXCEPTION]
--exception handling statements (optional)
END;​

 

A list of some notable characteristics :
 
* PL/SQL is a block-structured language.
* It is portable to all environments that support Oracle.
* PL/SQL is integrated with the Oracle data dictionary.
* Stored procedures help better sharing of application.
There are various kinds of data types are available in PL/SQL which are :
 
Scalar data types : A scalar data type is a one-dimensional data type with no internal components. CHAR, DATE, LONG, VARCHAR2, NUMBER, BOOLEAN are some examples of scalar data types.

Composite data types : A composite data type is made up of different data types that are easy to update and have internal components that can be utilized and modified together. For instance, RECORD, TABLE, VARRAY, and so on.

Reference data types : A reference data type stores pointers, which are values that relate to other programs or data elements. REF, CURSOR is an example of a reference data type.

Large object data type : A large object data type stores locators, which define the location of large items stored out of line (such as video clips, graphic images, and so on). BLOB, BFILE, CLOB, NCLOB, and others are examples of large object data types.
* A PL/SQL cursor is nothing but a pointer to an area of memory having SQL statements and the information of statement processing. This memory area is called a context area. This special area makes use of a special feature called cursor for the purpose of retrieving and processing more than one row.
 
* In short, the cursor selects multiple rows from the database and these selected rows are individually processed within a program.

View More : PL/SQL cursors
 
We use this clause while referencing the current row from an explicit cursor. This clause allows applying updates and deletion of the row currently under consideration without explicitly referencing the row ID.

Syntax : UPDATE table_name SET field=new_value WHERE CURRENT OF cursor_name
Function : The main purpose of a PL/SQL function is generally to compute and return a single value. A function has a return type in its specification and must return a value specified in that type.
 
Procedure : A procedure does not have a return type and should not return any value but it can have a return statement that simply stops its execution and returns to the caller. A procedure is used to return multiple values otherwise it is generally similar to a function.
 
Package : A package is schema object which groups logically related PL/SQL types , items and subprograms. You can also say that it is a group of functions, procedure, variables and record type statement. It provides modularity, due to this facility it aids application development. It is used to hide information from unauthorized users.
% ROWTYPE is used when a query returns an entire row of a table or view.
 
TYPE RECORD, on the other hand, is used when a query returns column of different tables or views.


Ex: . TYPE r_emp is RECORD (sno smp.smpno%type,sname smp sname %type)
 
e_rec smp %ROWTYPE

Cursor c1 is select smpno,dept from smp;
 
e_rec c1 %ROWTYPE
Cursor is a named private area in SQL from which information can be accessed. They are required to process each row individually for queries which return multiple rows.
Cursor declares %ROWTYPE as loop index implicitly. It then opens a cursor, gets rows of values from the active set in fields of the record and shuts when all records are processed.
 
Ex :
FOR smp_rec IN C1 LOOP

totalsal = totalsal + smp_recsal;

ENDLOOP;​

 

* This can be done by using Pragma called EXCEPTION_INIT.

* This gives the flexibility to the programmer to instruct the compiler to provide custom error messages based on the business logic by overriding the pre-defined messages during the compilation time.

Syntax :
DECLARE 
  exception_name EXCEPTION; 
  PRAGMA EXCEPTION_INIT (exception_name, error_code); 
BEGIN 
// PL/SQL Logic
EXCEPTION
 WHEN exception_name THEN
    // Steps to handle exception
END;
Syntax checking, binding, and P-code generation are all part of the compilation process. Syntax checking looks for compilation issues in PL/SQL code. After all mistakes have been fixed, the data holding variables are given a storage address. This process is referred to as binding. The PL/SQL engine’s P-code is a set of instructions. For named blocks, P-code is saved in the database and used the next time it is run.
COMMIT : The COMMIT command saves changes to a database permanently during the current transaction.
 
ROLLBACK : The ROLLBACK command is used at the end of a transaction to undo any modifications made since the start of the transaction.
 
SAVEPOINT : During transaction processing, the SAVEPOINT command saves the current point with a unique name.
Exception handling in PL/SQL can be adjusted. When an error occurs, the program’s error handling code is included.

There are three different sorts of exceptions :
 
* Pre-defined exceptions are frequent errors that have already been defined. NO DATA FOUND is an example.

* Undefined exceptions are errors that don’t have a name assigned to them.

* User-defined exceptions are handled by the user’s own code.
The following are some examples of predefined exceptions :
 
NO DATA FOUND : A single-row SELECT statement that returns no data.

TOO MANY ROWS : A single row SELECT statement that returns many rows.

INVALID CURSOR : An incorrect cursor operation was performed.

ZERO DIVIDE : Attempt at zero division.
The word ‘Trigger’ means to activate. In PL/SQL, the trigger is a stored procedure that defines an action taken by the database when the database-related event is performed.
 
Triggers are mainly required for the following purposes :
 
* To maintain complex integrity constraints
* Auditing table information by recording the changes
* Signaling other program actions when changes are made to the table
* Enforcing complex business rules
* Preventing invalid transactions
In PL/SQL, statements are grouped into units called Blocks. PL/SQL blocks can include constants, variables, SQL statements, loops, conditional statements, exception handling. Blocks can also build a procedure, a function or a package.
 
Broadly, PL/SQL blocks are two types :
 
(i) Anonymous blocks : PL/SQL blocks without header are known as anonymous blocks. These blocks do not form the body of a procedure, function or triggers.
 
Example :
DECLARE
num NUMBER(2);
sq NUMBER(3);
BEGIN
num:= &Number1;
sq := num*num;
DBMS_OUTPUT.PUT_LINE(‘Square:’ ||sq);
END;
 
(ii) Named blocks : PL/SQL blocks having header or labels are known as Named blocks. Named blocks can either be subprograms (procedures, functions, packages) or Triggers.
 
Example :
FUNCTION sqr (num IN NUMBER)
RETURN NUMBER is sq NUMBER(2);
BEGIN
sq:= num*num;
RETURN sq;
END;
The five types of SQL statements are :
 
DDL : The Data Definition Language(DDL) helps in the creation of a database structure or schema. CREATE, DROP, ALTER, RENAME, and TRUNCATE are the five types of DDL commands in SQL.

DML : The Data Manipulation Language (DML) allows you to insert, change, and delete data from a database instance. It’s incharge of making all kinds of changes to a database’s data. The database application and the user can insert data and information using three basic commands which are: INSERT, UPDATE, DELETE.

DCL : GRANT and REVOKE are commands in the DCL (Data Control Language) that can be used to grant “rights and permissions.” The database system’s parameters are controlled by other permissions.

TCL : TCL commands, or Transaction Control Language(TCL), deal with database transactions. COMMIT, ROLLBACK, SAVEPOINT are the commands of TCL.

DQL : The data is retrieved from the database using Data Query Language (DQL). It just has one command, which is SELECT
Tracing the code is a crucial technique to measure its performance during the runtime. Different methods for tracing the code includes :
 
* DBMS_APPLICATION_INFO
* DBMS_TRACE
* DBMS_SESSION and DBMS_MONITOR
* trcsess and tkprof utilities
There are three types of parameters in PL/SQL which are as follows:
 
IN : IN parameters allow you to send values to the procedure that is being called, and they can be set to default values. They behave as constants and cannot be changed.

OUT : OUT arguments must be mentioned because they return a value to the caller. These are uninitialized variables that can’t be used in expressions.

IN OUT : IN OUT parameters send starting values to a procedure and then return updated values to the caller. These parameters should be treated as initialized variables and given a value.
A PL/SQL record is a collection of values, or to put it another way, it is a collection of many pieces of information, each of which is of a simpler type and can be associated with one another as fields.
 
In PL/SQL, three types of records are supported :
 
* Records based on tables
* Records created by programmers
* Records that are based on a cursor
The variables or an expression referred to as parameters that appear in the procedure call statement is known as Actual parameters.
 
For example : raise_sal(emp_num, merit+ amount);
 
Here in the above example, emp_num and amount are the two actual parameters.


The variables that are declared in the procedure header and are referenced in the procedure body are called as Formal parameters.
 
For example :
PROCEDURE raise_sal( emp_id INTEGER) IS
curr_sal REAL:
………..
BEGIN
SELECT sal INTO cur_sal FROM emp WHERE empno = emp_id;
…….
END raise_sal;

 

Here in the above example, emp_id acts as a formal parameter.
Predefined exceptions are internally defined exceptions that occur during the execution of a program. For example, PL/SQL raises NO_DATA_FOUND when there are no rows returned upon a select operation, and if more than one row is returned using a select statement, TOO_MANY_ROWS error is generated. Some more examples :
 
* COLLECTION_IS_NULL : when a collection is null
* CURSOR_ALREADY_OPEN : When a cursor is already open
* LOGIN_DENIED : When login is incorrect or permission is not there
Merge reduces the number of table scans and performs parallel operations if required. MERGE inserts or updates data conditionally from one table to another.

For example :
MERGE INTO orders o
USING customer c
ON (o.cust_id = c.cust_id)
WHEN MATCHED THEN
UPDATE SET o.del_address = c.address
WHEN NOT MATCHED THEN
INSERT (cust_id, address)
VALUES (c.emp_id, c.address);
In this example, if a record with the matching condition is found, then the address of the same record is updated, else a new row is inserted.
SYSDATE :
* This keyword returns the current time and date on the local database server.
* The syntax is SYSDATE.
* In order to extract part of the date, we use the TO_CHAR function on SYSDATE and specify the format we need.
* Usage :
* SELECT SYSDATE FROM dual;
* SELECT id, TO_CHAR(SYSDATE, 'yyyy/mm/dd') from InterviewBitEmployeeTable where customer_id < 200;

USER :
* This keyword returns the user id of the current session.
* Usage :
* SELECT USER FROM dual;
SYS.ALL_DEPENDENCIES is used for describing all the dependencies between procedures, packages, triggers, functions that are accessible to the current user. It returns the columns like name, dependency_type, type, referenced_owner etc.
* We can use DBMS_OUTPUT and DBMS_DEBUG statements for debugging our code:
* DBMS_OUTPUT prints the output to the standard console.
* DBMS_DEBUG prints the output to the log file.
* A table that is being modified by the usage of the DML statement currently is known as a mutating table. It can also be a table that has triggers defined on it.

* A table used for reading for the purpose of referential integrity constraint is called a constraining table.
The outcomes of the execution of the DML statement is saved in the following 4 cursor attributes :

SQL%FOUND : This returns TRUE if at least one row has been processed.

SQL%NOTFOUND : This returns TRUE if no rows were processed.

SQL%ISOPEN : This checks whether the cursor is open or not and returns TRUE if open.

SQL%ROWCOUNT : This returns the number of rows processed by the DML statement.
A list of predefined exceptions in PL/SQL :
 
* DUP_VAL_ON_INDEX
* ZERO_DIVIDE
* NO_DATA_FOUND
* TOO_MANY_ROWS
* CURSOR_ALREADY_OPEN
* INVALID_NUMBER
* INVALID_CURSOR
* PROGRAM_ERROR
* TIMEOUT _ON_RESOURCE
* STORAGE_ERROR
* LOGON_DENIED
* VALUE_ERROR
   etc.
DBMS_ series of packages, such as, DBMS_PIPE, DBMS_DDL, DBMS_LOCK, DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_SQL, DBMS_TRANSACTION, UTL_FILE.
PL/SQL packages have the following two parts :
 
Specification part : It specifies the part where the interface to the application is defined.
 
Body part : This part specifies where the implementation of the specification is defined.
There are two way to execute a stored procedure.
 
From the SQL prompt, write EXECUTE or EXEC followed by procedure_name.
 
EXECUTE or [EXEC] procedure_name;

Simply use the procedure name
 
procedure_name; 
Database links are used to establish communication across multiple databases or environments such as test, development, and production. Other information can be accessed using the database links, which are read-only.
When the name of the same procedure is repeated with parameters of different datatypes and parameters in different places then that is referred to as procedure overloading.
An expression is made up of a series of literals and variables separated by operators. Operators are used in PL/SQL to manipulate, compare, and calculate data. An expression is made up of two parts : operators and operands.

Operands : These are an argument to the operators. Operands can be a variable, function call or constant.

Operators : These specify the actions to be performed on operators. Example: ‘+’, ‘*’, etc.
When the OPEN cursor command is used to open a cursor, it performs the following operations:
 
* A processing memory region has been set aside.
* The statement SELECT is parsed.
* The memory addresses are used to assign values to the input variables.
* The active set of rows that meet the criteria for selection are recognized.
* The pointer is placed exactly before the active set’s first row.
Stored procedures have various advantages to help you design sophisticated database systems, as listed below : 
 
* Ease of Use
* Advance Security
* Better Performance
* Higher Productivity
* Interoperability
* Replication
* Increased Scalability.
* High Maintainability.
SET SERVER OUTPUT ON
DECLARE
BEGIN
FOR i IN REVERSE 1..99
LOOP
IF Mod(i,3) = 0 THEN
DBMS_OUTPUT.PUT_LINE(i);
END IF;
END LOOP;
END;
/
Comments are the text which is included with the code to enhance readability and for the understanding of the reader. These codes are never executed.
 
There are two ways to comment in PL/SQL :
 
* Single line comment : This comment starts with double .
 
Example :
DECLARE
num NUMBER(2);        — it is a local variable.
BEGIN
 
* Multi-line comment : This comment starts with /* and ends with */.
 
Example :
BEGIN
num := &p_num;         /* This is a host variable used in program body */
……….
END
PL/SQL block consists of three sections : declaration, executable and exception-handling sections. The executable section is mandatory. There are two types of blocks: named and anonymous.
 
Named blocks are functions and procedures which are stored in the database server and can be reused. Anonymous blocks are for one time use and are not stored in the server. Example :

 

DECLARE

 message VARCHAR2(255):= 'Welcome to PL/SQL';
 byzero NUMBER;

BEGIN

   DBMS_OUTPUT.put_line (message);
   byzero := 1/0;

   EXCEPTION

  WHEN ZERO_DIVIDE THEN
 DBMS_OUTPUT.PUT_LINE(SQLERRM);
END;
SQLCODE and SQLERRM are used to trace exceptions that are not explicitly handled in the program. These are globally defined variables. SQLCODE returns the error code while SQLERRM returns the corresponding error message.
Yes, it is possible. Use ACCEPT keyword to take inputs from the user. Example –
 
ACCEPT age number prompt ‘Enter your age :
Example :
CREATE PROCEDURE get_customer_details @age nvarchar(30), @city nvarchar(10)
AS

BEGIN
SELECT * FROM customers WHERE age = @age AND city = @city;
END;
General functions are of the following types :
 
NVL : Converts a null value to an actual value. NVL (exp1, exp2) .If exp1 is null then the NVL function returns the value of exp2.
 
NVL2 : If exp1 is not null, nvl2 returns exp2, if exp1 is null, nvl2 returns exp3. The argument exp1 can have any data type. NVL2 (exp1, exp2, exp3)
 
NULLIF : Compares two expressions and returns null if they are equal or the first expression if they are not equal. NULLIF (exp1, exp2)
 
COALESCE : Returns the first non-null expression in the expression list. COALESCE (exp1, exp2… expn). The advantage of the COALESCE function over the NVL function is that the COALESCE function can take multiple alternative values.
 
Conditional Expressions : Provide the use of IF-THEN-ELSE logic within a SQL statement. Example: CASE Expression and DECODE Function. 
COUNT (*) : Returns a number of rows in a table including duplicates rows and rows containing null values in any of the columns.

COUNT (EXP) : Returns the number of non-null values in the column identified by expression.

COUNT (DISTINCT EXP) : Returns the number of unique, non-null values in the column identified by expression.
A subquery is a SELECT statement that is embedded in a clause of another SELECT statement. A subquery can be placed in WHERE HAVING and FROM clause.
 
Guidelines for using subqueries :
 
* Enclose sub queries within parenthesis
* Place subqueries on the right side of the comparison condition.
* Use Single-row operators with single-row subqueries and Multiple-row operators with multiple-row subqueries.


Types of subqueries :
 
* Single-Row Subquery : Queries that return only one row from the inner select statement. Single-row comparison operators are: =, >, >=, <, <=, <>

* Multiple-Row Subquery : Queries that return more than one row from the inner Select statement. There are also multiple-column subqueries that return more than one column from the inner select statement. Operators include: IN, ANY, ALL.
ANY Operator compares value to each value returned by the subquery. ANY operator has a synonym SOME operator.
 
* > ANY means more than the minimum.
* < ANY means less than the maximum
* = ANY is equivalent to IN operator.

ALL Operator compares value to every value returned by the subquery.
 
* > ALL means more than the maximum
* < ALL means less than the minimum
* <> ALL is equivalent to NOT IN condition.
This procedure can be used to send user-defined error messages from stored subprograms. You can prevent returning unhandled exceptions by reporting failures to your application.

It appears in two places : the executable section and the exceptional section.
DECODE and CASE statements are very similar, but CASE is extended version of DECODE. DECODE does not allow Decision making statements in its place.
 
select decode(totalsal=12000,’high’,10000,’medium’) as decode_tesr from smp where smpno in (10,12,14,16);
 
This statement returns an error :
 
CASE is directly used in PL SQL, but DECODE is used in PL/SQL through SQL only.
Polymorphism is a feature of OOP. It is the ability to create a variable, an object or function with multiple forms. PL/SQL supports Polymorphism in the form of program unit overloading inside a member function or package..Unambiguous logic must be avoided whilst overloading is being done.
* Create database objects—tables, synonyms, sequences, etc.
* To implement business rules, create procedures, functions, etc.
* To impose business rules, create constraints, triggers, etc.
* For data manipulation, create cursors
The pragma_exception_init command in PL/SQL instructs the compiler to associate an exception name with an Oracle error number. This enables you to refer to any internal exception by name and create a custom handler for it.
The PL/SQL output is shown on the screen using the DMS_OUTPUT package. get_line, put_Line, new_line, and many more are found in DBMS_OUTPUT. The put_line procedure, which is a part of the DBMS_OUPUT package, is used to display the information in the line.
It provides several benefits like
 
Enforced Information Hiding : It offers the liberty to choose whether to keep data private or public

Top-down design : You can design the interface to the code hidden in the package before you actually implemented the modules themselves

Object persistence : Objects declared in a package specification behaves like a global data for all PL/SQL objects in the application. You can modify the package in one module and then reference those changes to another module

Object oriented design : The package gives developers strong hold over how the modules and data structures inside the package can be used

Guaranteeing transaction integrity : It provides a level of transaction integrity

Performance improvement : The RDBMS automatically tracks the validity of all program objects stored in the database and enhance the performance of packages.
The PLV msg enables you to
 
* It retrieves the message text by number
*
Assign individual text message to specified row in the PL/SQL table
* It substitutes automatically your own messages for standard Oracle error messages with restrict toggle
* Batch load message numbers and text from a database table directly PLV msg PL/SQL table
* Null substitution value
* Set of assertion routines
* Miscellaneous utilities
* Pre-defined datatypes
* Set of constants used throughout PL vision
PLVprs : It is an extension for string parsing for PL/SQL, and it is the lowest level of string parsing functionality

PLVprsps : It is the highest level package to parse PL/SQL source code into separate atomics. It relies on other parsing packages to get work done.
With a single program call :fcopy procedure”, you can copy the complete contents of one file into another file. While to copy the contents of a file directly into a PL/SQL table, you can use the program “file2pstab”.
The PL/SQL table are the closest to arrays in PL/SQL, and in order to access this table you have to first declare a table type, and then you have to declare PL/SQL table itself. But by using PLVtab, you can avoid defining your own PL/SQL table type and make PL/SQL data-table access easy.
PLVtab enables you to do following things when you show the contents of PL/SQL tables
 
* Display or suppress a header for the table
* Display or suppress the row numbers for the table values
* Show a prefix before each row of the table
PL/Vision offers two packages that help you manage transaction processing in PL/SQL application. It is PLVcmt and PLVrb.
 
PLVcmt : PLVcmt package wraps logic and complexity for dealing with commit processing

PLVrb : It provides a programmatic interface to roll-back activity in PL/SQL
USER TABLES : This is a collection of tables created and maintained by the user. Contain USER information.

DATA DICTIONARY : This is a collection of tables created and maintained by the Oracle Server. It contains database information. All data dictionary tables are owned by the SYS user.
Data Types is a specific storage format used to store column values. Few data types used in SQL are :
 
VARCHAR2(size) : Minimum size is ‘1’ and Maximum size is ‘4000
CHAR(size) : Minimum size is ‘1’and Maximum size is ‘2000
NUMBER(P,S) : " Precision" can range from 1 to 38 and the “Scale” can range from -84 to 127.
DATE
LONG : 2GB
CLOB : 4GB
RAW (size) : Maximum size is 2000
LONG RAW : 2GB
BLOB : 4GB
BFILE : 4GB
ROWID : A 64 base number system representing the unique address of a row in the table.
ON DELETE CASCADE Indicates that when the row in the parent table is deleted, the dependent rows in the child table will also be deleted. ON DELETE SET NULL Covert foreign key values to null when the parent value is removed. Without the ON DELETE CASCADE or the ON DELETE SET NULL options, the row in the parent table cannot be deleted if it is referenced in the child table.
Simple View :
Derives data from only one table.
Contains no functions or group of data
Can perform DML operations through the view.

Complex View :
* Derives data from many tables.  Contain functions or groups of data.
* Derives data from many tables.  Contain functions or groups of data.
* Does not always allow DML operations through the view
* Into a row-level trigger based on a table, the trigger body cannot read data from the same table and also we cannot perform DML operation on the same table.

* If we are trying this oracle server returns mutating error oracle-4091: table is mutating.

* This error is called a mutating error, and this trigger is called a mutating trigger, and the table is called a mutating table.

* Mutating errors are not occurred in statement-level trigger because through this statement-level trigger when we are performing DML operations automatically data committed into the database, whereas in the row-level trigger when we are performing transaction data is not committed and also again we are reading this data from the same table then only mutating errors is occurred.
If we want to perform multiple operations in different tables then we must use triggering events within the trigger body. These are inserting, updating, deleting clauses. These clauses are used in the statement, row-level triggers. These triggers are also called trigger predicate clauses.