0% found this document useful (0 votes)
14 views109 pages

plsqlinterviewquestions(1) (1)

Uploaded by

kapil Jadhav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views109 pages

plsqlinterviewquestions(1) (1)

Uploaded by

kapil Jadhav
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 109

PL/SQL

Interview Question
Bank

PL/SQL Interview Questions Page 1


Question:

What are the different methods for passing parameters to a procedure?

Methods of passing parameters –


 Positional : Lists the actual parameter values in the order in
which the formal parameters are declared.

 Named: Lists the actual values in random order and uses the
association operator to associate each actual parameter with its
formal parameter by name The PL/SQL association operator is =>.

 Combination: Lists the first parameter values by their position


and the remainder by using the special syntax of the named
method.

Example:

create or replace procedure add_dept(dname


departments.department_name%type, mgrid number, locid number)
is
begin
insert into deptcopy values(seq1.nextval,dname,mgrid,locid);
end add_dept;
/

--passing by positional notation:


execute add_dept('Training',103,1800);

--passing by named notation:


execute add_dept(locid=>1900,dname=>'Sports',mgrid=>108);

--passing by combination
execute add_dept('Transport',locid=>1700,mgrid=>100)

PL/SQL Interview Questions Page 2


Question:

Write a program to pass parameters to a cursor and print the result.

Example:

create or replace procedure proc1(did number)


is
cursor c1(deptid number) is select *
from employees
where department_id=deptid;
r1 c1%rowtype;
begin
open c1(did);
loop
fetch c1 into r1;
exit when c1%notfound;
dbms_output.put_line(r1.employee_id||' '||r1.last_name
||' '||r1.salary||' '||r1.department_id);
end loop;
close c1;
end;
/

exec proc1(90);

PL/SQL Interview Questions Page 3


Question:

Can BOOLEAN datatype be used in functions that are called from SQL
statements?

No, functions called from SQL statements can only use valid SQL
datatypes, such as NUMBER, VARCHAR2, and DATE.
However, they cannot use PL/SQL datatypes such as BOOLEAN,
RECORD, and TYPE.

Example:
create or replace function fun1(n number)
return boolean
is
r number;
begin
r:=mod(n,2);
if r=0 then
return true;
else
return false;
end if;
end;
/
Function created.

SQL> select fun1(56) from dual;


select fun1(56) from dual
*
ERROR at line 1:
ORA-06552: PL/SQL: Statement ignored
ORA-06553: PLS-382: expression is of wrong type

PL/SQL Interview Questions Page 4


Question:

Is it possible to copy contents of one record to another?

Yes, it is.
But make sure that both records same structure(number of fields
and their datatypes).

Example1:

declare
r1 employees%rowtype;
r2 employees%rowtype;
begin
select * into r1 from employees where employee_id=100;
dbms_output.put_line(r1.employee_id||' '||r1.salary);
r2:=r1;
dbms_output.put_line(r2.employee_id||' '||r2.salary);
end;
/
output
100 24000
100 24000

PL/SQL Interview Questions Page 5


Example2:

declare
type r1 is record (eid number, ename varchar2(20));
type r2 is record (empid number, empname varchar2(20));
rec1 r1;
rec2 r2;
begin
select employee_id, last_name into rec1
from employees
where employee_id=100;
dbms_output.put_line(rec1.eid||' '||rec1.ename);
rec2.empid:=rec1.eid;
rec2.empname:=rec1.ename;
dbms_output.put_line(rec2.empid||' '||rec2.empname);
end;
/

output

100 King
100 King

PL/SQL Interview Questions Page 6


Question:

What is the use of the USER_ERRORS data dictionary view?

The USER_ERRORS data dictionary view is used to view the


compilation errors of the subprograms that are owned by the
current user.

create or replace procedure proc1(id number)


is
begin
select department_name into dname
from departments
where department_id=10;
dbms_output.put_line(dname);
end;

SQL> /
Warning: Procedure created with compilation errors.
SQL> select name, type, text from user_errors where
name='PROC1';

NAME TYPE TEXT


--------------- ---------- ------------------------------
PROC1 PROCEDURE PLS-00201: identifier 'DNAME'
must be declared
PROC1 PROCEDURE PL/SQL: ORA-00904: : invalid
identifier
PROC1 PROCEDURE PL/SQL: SQL Statement ignored
PROC1 PROCEDURE PLS-00201: identifier 'DNAME'
must be declared
PROC1 PROCEDURE PL/SQL: Statement ignored

PL/SQL Interview Questions Page 7


Question:

What is an identifier?

Identifiers are names of variables.


Variables are storage locations of data. Data is stored in
memory.
Variables point to this memory location where data can be read
and modified.
Identifiers are used to name PL/SQL objects(such as variables,
types, cursors and subprograms).

PL/SQL Interview Questions Page 8


Question:

What are schema-level triggers?

A trigger defined at the schema or table level fires only when


the triggering event involves that schema or table.

PL/SQL Interview Questions Page 9


Question:

Can there be multiple RETURN statements within a function?

You can have more than on Return Statement.


But you can return only one value at a time.
If you like to return more values then use OUT variables to
achieve that.

Example:

create or replace function fun12(id number)


return varchar2
is
begin
if id<>0 then
return 'none zero';
else
return 'zero';
end if;
end;
/

PL/SQL Interview Questions Page 10


Question:

Can a variable be assigned a value from database? If yes, then how?

Yes a variable can assigned a value from database using into


clause in select statement.

Example:

declare
lname varchar2(20);
begin
select last_name into lname
from employees
where employee_id=102;
dbms_output.put_line(lname);
end;
/

In the above example we have assigned last name of employee 102


to variable lname.

PL/SQL Interview Questions Page 11


Question:

Does a USER_OBJECTS view have an entry for a trigger?

Yes, USER_OBJECTS view have an entry for a trigger.


You can get list of triggers in your schema using below query:

select object_name, object_type from user_objects where


object_type='TRIGGER';

Example:
create or replace trigger trg1
before insert on departments
begin
raise_application_error(-20124,’Can not insert into
departments’);
end;
/
select object_name, object_type
from user_objects
where object_type='TRIGGER' and object_name=’TRG1’;

PL/SQL Interview Questions Page 12


Question:

Write the SQL query to view all the procedures within a schema.

select object_name, object_type from user_procedures where


object_type='PROCEDURE';

PL/SQL Interview Questions Page 13


Question:

What is SELECT FOR UPDATE and how can it be used in a cursor?

If there are multiple sessions for a single database,


there is the possibility that the rows of a particular table were
updated after you opened your cursor.
You see the updated data only when you reopen the cursor.
Therefore, it is better to have locks on the rows before you
update or delete rows.
You can lock the rows with the FOR UPDATE clause in the cursor
query. Check the example on next page.

PL/SQL Interview Questions Page 14


Example:
declare
cursor c1 is select *
from empcopy
where department_id = 20 for update of salary nowait;
rec_c1 c1%rowtype;
l_new_sal number;
begin
dbms_output.put_line(rpad('Employee',15)|| rpad('Old Salary',15)||
rpad('New Salary',15));
open c1;
loop
fetch c1 into rec_c1;
exit when c1%notfound;
if rec_c1.salary < 7000 then
l_new_sal:= rec_c1.salary * 1.25;
update empcopy
set salary = l_new_sal
where employee_id = rec_c1.employee_id;
else
l_new_sal := rec_c1.salary * 1.15;
update empcopy
set salary = l_new_sal
where employee_id = rec_c1.employee_id;
end if;
dbms_output.put_line(rpad(rec_c1.last_name,15)||
rpad(rec_c1.salary,15)|| rpad(l_new_sal,15));
end loop;
close c1;
end;
/

PL/SQL Interview Questions Page 15


Question:

How can you force FOR-LOOP to end unconditionally?

You can use EXIT statement to terminate the loop unconditionally.


Whenever the exit statement gets execute inside loop, the loops
get terminate and control passes to the next statement after the
END LOOP statement.

Example:
begin
for i in 1..10 loop
if i>=6 then
exit;
end if;
dbms_output.put_line(i);
end loop;
end;
SQL> /
1
2
3
4
5

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 16


Question:

What are the system privileges that are required by a schema owner
(user) to create a trigger on a table?

To create a trigger in your own schema on a table in your own


schema or on your own schema (SCHEMA), you must have the CREATE
TRIGGER system privilege.
To create a trigger in any schema on a table in any schema, or on
another user's schema, you must have the CREATE ANY TRIGGER
system privilege.
In addition to the preceding privileges, to create a trigger on
DATABASE, you must have the ADMINISTER DATABASE TRIGGER system
privilege.

PL/SQL Interview Questions Page 17


Question:

What is the difference between formal and actual parameters in a


subprogram specification?

 Formal parameters are local variables that are declared in the


parameter list of subprogram specification(heading).
 Actual parameters can be literal values, variables and
expressions that are provided in the parameter list of a called
subprogram.
 The formal and actual parameters should be of compatible data
types.

Example:

create or replace procedure p12(a number, b number) --formal


--parameters
is
c number;
begin
c:=a+b;
dbms_output.put_line('Sum:='||c);
end;
SQL> /
Procedure created.
SQL> begin
2 p12(5,8); -- actual parameters
3 end;
4 /
Sum:=13
PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 18


Question:

What are the advantages of using packages?

Advantages of using Packages

 Modularity and ease of maintenance: You encapsulate


logically related programming structures in named module.
Each package is easy to understand and the interface between
packages is simple, clear and well defined.

 Hiding information: You decide which constructs are public


(visible and accessible) and which are private(hidden and
inaccessible). Declarations in the package specification are
visible and accessible to applications. The package body
hides the definition of private constructs.

 Better performance: When you call a packaged subprogram the


first time, the entire package is loaded into memory. Later
calls to related subprograms in the package therefore
require no further disk I/O.

 Overloading: With packages, you can overload procedures and


functions, which means you can create multiple subprograms
with the same name in the same package, each taking
parameters of different number or data type.

PL/SQL Interview Questions Page 19


Question:

Is it possible to have more than one OTHERS clause?

No, only one OTHERS clause can be use in exception section and
OTHERS handler must be last among the exception handlers of a
block.

PL/SQL Interview Questions Page 20


Question:

When should a procedure and a function be used?

Procedures and functions are also known as subprograms.


These subprograms are compiled and stored in the database.
Because they are named and stored you can invoke them whenever
you want.

A procedure is a named PL/SQL block that can accept parameters.


Generally, you use a procedure to perform an action.

A function is named PL/SQL block that can accept parameters, be


invoked and return a value.
In general, you use a function to compute a value.

PL/SQL Interview Questions Page 21


Question:

Does a NOT NULL constraint of a database column apply to %TYPE


variables?

No, a NOT NULL constraint does not apply to variables declared


using the %TYPE attribute.

PL/SQL Interview Questions Page 22


Question:

What is the difference between implicit cursor and explicit cursor?

Implicit cursor: Implicit cursors are created and managed by the


Oracle server. You do not have access to them. The oracle server
creates such a cursor when it has to execute a SQL statement.

Explicit cursor: Explicit cursors are declared and managed by


programmers are called explicit cursor. As a programmer you may
want to retrieve multiple rows from a database table, have a
pointer to each row that is retrieved, and work on the rows one
at a time. In such cases, you can declare cursors explicitly
depending on your business requirements.

PL/SQL Interview Questions Page 23


Question:

What is forward declaration and how can it be achieved within a


package?

A subprogram must be declared before you can call it.


Coding standards often require that subprograms be kept in
alphabetical sequence to make them easy to find.
The solution in this case is to use forward declarations provided
in PL/SQL.
A forward declaration enables you to declare the heading of a
subprogram that is the subprogram specification terminated by a
semicolon.

When creating a forward declaration:


 The formal parameters must appear in both the forward
declaration and the subprogram body.
 The subprogram body can appear anywhere after the forward
declaration, but both must appear in the same program unit.

Example is given on the next page.

PL/SQL Interview Questions Page 24


Example:
Create or replace package calculation
is
procedure addition(a number, b number);
procedure subtraction(a number, b number);
end calculation;
/

Package created.

create or replace package body calculation


is
procedure print(str varchar2); --forward declaration

procedure addition(a number, b number)


is
begin
print('the addition:='||(a+b));
end addition;

procedure subtraction(a number, b number)


is
begin
print('the subtraction:='||(a-b));
end subtraction;

procedure print(str varchar2)


is
begin
dbms_output.put_line(str);
end print;
end calculation;
/

PL/SQL Interview Questions Page 25


Question:

What is the difference between SQL and PL/SQL?

 SQL :- Structured Query language is a non procedural language


that interacts with the database. It is used for data
manipulation using DDL, DML, TCL commands.

 PL/SQL :- PL/SQL is a procedural programming language. PL/SQL


statements are compiled and processed as a block. It has
conditional construct , looping construct etc.

 PL/SQL is a language that has programming features that serve as


an extension to SQL.

 SQL, which is a nonprocedural language, is made procedural with


PL/SQL programming constructs.

 PL/SQL has the following advantages-

 Integration with database — PL/SQL supports SQL statements,


thus enabling integration between procedural language
capabilities and the database technology.

 Better performance — SQL statements are grouped within a


PL/SQL block and sent together to database for parsing
therefore, it reduces the network traffic and increases the
performance.

PL/SQL Interview Questions Page 26


Question:

What is a subprogram? What are its advantages?

Procedures and functions are named PL/SQL blocks. They are also
known as subprograms.
These subprograms are compiled and stored in the database.
Because they are named and stored you can invoke them whenever
you want.

PL/SQL Interview Questions Page 27


Question:

Can a complete package be called?

No, complete package cannot be called, only the member of the


package can be called.

PL/SQL Interview Questions Page 28


Question:

When is an exception propagated to the outside environment?

When a sub block (nested) handles an exception, it terminates


normally. Control resumes in the enclosing (outer) block
immediately after the sub block’s END statement.
However, if a PL/SQL raises an exception and the current block
does not have a handler for the exception, the exception
propagates (passes) to an enclosing(outer) until it finds a
handler.
When the exception propagates to an enclosing block, the
remaining executable actions in that block are bypassed.

begin
declare
empid number;
begin
select employee_id into empid
from employees
where department_id=89;
dbms_output.put_line(empid);
end;
dbms_output.put_line('Hi this vivek');
exception
when no_data_found then
dbms_output.put_line('no data found exception raised');
end;
/
no data found exception raised

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 29


Question:

Why SQL%ISOPEN does always returns the FALSE value?

SQL is the name of the implicit cursor, which is always opened


when the database executes the SQL statement.
SQL%ISOPEN always evaluates to FALSE as ORACLE closes the
implicit cursor as soon as it executes the query.

Example:

declare
sal number;
begin
select salary into sal from employees where employee_id=101;
dbms_output.put_line('salary of employee 101 is :'||sal);
if sql%isopen then
dbms_output.put_line('implicit cursor is open');
else
dbms_output.put_line('implicit cursor is closed');
end if;
end;
SQL> /
salary of employee 101 is :17000
implicit cursor is closed

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 30


Question:

Can a procedure be declared and defined within a PL/SQL block?

Local subprogram reduce the size of a module by removing


redundant code. This is one of the main reasons for creating a
local subprogram. If a module needs the same routine several
times, but only this module needs the routine, then define it as
a local subprogram.

You can define a named PL/SQL block in the declarative section of


any PL/SQL program that it is declared at the end of the
declaration section.

Local subprograms have the following characteristics:


They are only accessible to the block in which they are defined.
They are compiled as part of their enclosing blocks.

Example:
declare
procedure p1(str varchar2) – Local subprogram
is
begin
dbms_output.put_line(str);
end;
begin
p1('If you wanna be the best you need to take out the best');
end;
/
output: If you wanna be the best you need to take out the best

PL/SQL Interview Questions Page 31


Question:

What are the advantages of PL/SQL?

Benefits of PL/SQL

1) Integration of procedural constructs with SQL

The most important advantage of PL/SQL is the integration of


procedural constructs with SQL. SQL is a nonprocedural language.
When you issue a SQL command, your command tells the database server
what to do. However, you cannot specify how to do it. PL/SQL
integrates control statements and conditional statements with SQL,
giving you better control of your SQL statements and their
execution.

2) Improved performance

Without PL/SQL, you would not be able to logically combine SQL


statements as one unit. If you have designed an application
containing forms, you may have many different forms with fields in
each form. When a form submits the data, you may have to execute a
number of SQL statements. SQL statements are sent to the database
one at a time. This result in many network trips and one call to the
database for each SQL statement, thereby increasing network traffic
and reducing performance (especially in a client/server model). With
PL/SQL, you can combine all these SQL statements into a single
program unit. The application can send the entire block to the
database instead of sending the SQL statements one at a time. This
significantly reduces the number of database calls. As the slide
illustrates, if the application is SQL intensive, you can use PL/SQL
blocks to group SQL statements before sending them to the Oracle
Database server for execution.

PL/SQL Interview Questions Page 32


3) Modularized program development

a. A basic unit in all PL/SQL programs is the block.


b. Blocks can be nested in other blocks.
c. Modularized program development has the following
advantages:

 You can group logically related statements within


blocks.
 You can nest blocks inside larger blocks to build
powerful programs.
 You can break your application into smaller modules.
If you are designing a complex application, PL/SQL
allows you to break down the application into smaller,
manageable, and logically related modules.
 You can easily maintain and debug the code.

PL/SQL Interview Questions Page 33


Question:

What is the difference between CREATE OR REPLACE FUNCTION and DROP


FUNCTION commands?

Specify OR REPLACE to re-create the procedure if it already


exists.
Use this clause to change the definition of an existing procedure
without dropping, re-creating.

If the CREATE fails after a DROP, you are left with nothing, not
even the old procedure.
If the CREATE OR REPLACE fails (e.g. a syntax or semantics error
in the code), the previous version is still available and usable.

REPLACE is an optional keyword used in object definitions (DDL)


to override the older objet definition with a new one.
It retains the access privileges of the object during the
definition modification process. If the object is dropped and
recreated, however, its privileges are lost.

PL/SQL Interview Questions Page 34


Question:

What is a bind variable and how is it used?

Bind variables

Bind variables are variables that you create in a host


environment. For this reason, they are sometimes called host
variables.

Use of Bind variables

Bind variables are created in the environment and not in the


declarative section of a PL/SQL block. Variables declared in a
PL/SQL block are available only when you execute the block. After
the block is executed, the memory used by the variable is freed.
However, bind variables are accessible even after the block is
executed. When created, therefore, bind variables can be used and
manipulated by multiple subprograms. They can be used in SQL
statements and PL/SQL block just like any other variable.

Creating bind variables

To create a bind variables in SQL*PLUS use the VARIABLE command.

for example,

VARIABLE sal number;

You can reference a bind variable in a PL/SQL program by


preceding the variable with a colon(:).

The example is given on the next page.

PL/SQL Interview Questions Page 35


Example:
SQL> variable deptid number;
SQL> begin
2 select department_id into :deptid
3 from departments
4 where department_name='Administration';
5 end;
6 /

PL/SQL procedure successfully completed.

SQL> print deptid;

DEPTID
----------
10

SQL> declare
2 lname varchar2(20);
3 begin
4 select last_name into lname
5 from employees
6 where department_id=:deptid;
7 dbms_output.put_line(lname);
8 end;
9 /

Whalen

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 36


Question:

What is a procedure? Can it be stored in the database?

Procedures are compiled and stored in the database. Because they


are named and stored you can invoke them whenever you want.
A procedure is a named PL/SQL block that can accept parameters.
Generally, you use a procedure to perform an action.

PL/SQL Interview Questions Page 37


Question:

Is it possible to write a package specification without a package


body?

Yes, a package specification can exist without a package body-


that is, when the package specification does not declare
subprograms, a body is not required.
However, a package body cannot exist without a package
specification.

PL/SQL Interview Questions Page 38


Question:

What is the significance of AUTHID property while creating a


procedure?

The AUTHID property affects the name resolution and privilege


checking of SQL statements at runtime; however, it does not
affect the compilation.

Any procedure may be created with its AUTHID property set to


either the DEFINER or the INVOKER rights.
If a procedure is created with the DEFINER rights, then the user
executing the procedure need not have an access to database
objects, which the procedure is accessing.
However, if a procedure is created with the INVOKER rights, then
the user must have access rights to all the objects that the
procedure is accessing.

PL/SQL Interview Questions Page 39


Question:

Can an IN parameter be assigned a value within a procedure?

No, a formal parameter of IN mode cannot be assigned a value and


cannot be modified in the body of the procedure.

PL/SQL Interview Questions Page 40


Question:

What is the meaning of PRAGMA keyword?

In Oracle PL/SQL, PRAGMA refers to a compiler directive or "hint"


it is used to provide an instruction to the compiler.
Pragma directives are processed at compile time where they pass
necessary information to the compiler; they are not processed at
runtime.

PL/SQL Interview Questions Page 41


Question:

What does the REPLACE option indicates in the procedure definition?

Specify OR REPLACE to re-create the procedure if it already


exists.
Use this clause to change the definition of an existing procedure
without dropping, re-creating.

PL/SQL Interview Questions Page 42


Question:

Suppose a procedure, a_proc, is defined with a number parameter as


input within a package called a_package in the a_user schema.
Write the statement to invoke the a_proc procedure on the SQL prompt
from the user, b_user.

Note: Make sure that user b_user has execute privilege


on a package a_package.

syntax:
execute schema_name.package_name.procedure_name(parametervalue);
example:
execute a_user.a_package.a_proc(5);

PL/SQL Interview Questions Page 43


Question:

Describe the OTHERS exception handler.

The exception-handling section traps only those exceptions that


are specified; any other exceptions are not trapped unless you
use the OTHERS exception handler.
The WHEN OTHERS clause is used to trap all remaining exceptions
that have not been handled by your predefined Exceptions and
Named Programmer-Defined Exceptions.
If you have use OTHERS exception handler then it must be the last
exception handler that is defined in the exception section.

PL/SQL Interview Questions Page 44


Question:

What is a SAVEPOINT command?

In Oracle SAVEPOINT is a TCL (Transaction Control Language)


statement.

The SAVEPOINT statement names and marks the current point in the
processing of a transaction.
With the ROLLBACK TO statement, savepoints undo parts of a
transaction instead of the whole transaction.

A SAVEPOINT is a marker within a transaction that allows for a


partial rollback.
As changes are made in a transaction, we can create SAVEPOINTs to
mark different points within the transaction.

PL/SQL Interview Questions Page 45


Example:

SQL> INSERT INTO AUTHOR


2 VALUES ('A11l', 'john',
3 'garmany', '123-345-4567',
4 '1234 here st', 'denver',
5 'CO','90204', '9999');

1 row created.

SQL> savepoint in_author;

Savepoint created.

SQL> INSERT INTO BOOK_AUTHOR VALUES ('A111', 'B130', .20);


1 row created.

SQL> savepoint in_book_author;

Savepoint created.

SQL> INSERT INTO BOOK


2 VALUES ('B130', 'P002', 'easy oracle sql',
3 'miscellaneous', 9.95, 1000, 15, 0, '',
4 to_date ('02-20-2005','MM-DD-YYYY'));
1 row created.

SQL> rollback to in_author;

Rollback complete.

In the example above, I inserted a row into the AUTHOR


table and created a SAVEPOINT called in_author.
Next, I inserted a row into the book_author table and
created another SAVEPOINT called in_book_author.
Finally, I inserted a row in the BOOK table. I then issued
a ROLLBACK to in_author.

PL/SQL Interview Questions Page 46


Question:

Which data dictionary views have the information on the triggers that
are available in the database?

Use USER_TRIGGERS data dictionary to view the information of


triggers owned by the user.

Following are the columns in USER_TRIGGERS:

TRIGGER_NAME Name of the trigger


Type of the trigger (when it fires) -
TRIGGER_TYPE
BEFORE/AFTER and STATEMENT/ROW
Statement that will fire the trigger -
TRIGGERING_EVENT
INSERT,UPDATE and/or DELETE
Owner of the table that this trigger is
TABLE_OWNER
associated with
Name of the table that this trigger is
TABLE_NAME
associated with
The name of the column on which the trigger is
COLUMN_NAME
defined over
WHEN clause must evaluate to true in order for
WHEN_CLAUSE
triggering body to execute
STATUS If DISABLED then trigger will not fire

TRIGGER_BODY Action taken by this trigger when it fires

PL/SQL Interview Questions Page 47


Question:

How can you display data from a PL/SQL block?

To display results to the user we use a procedure called


dbms_output.put_line to place the results in a buffer that
SQL*Plus will retrieve and display.
SQL*Plus must be told to retrieve data from this buffer in order
to display the results.
The SQL*Plus command set serveroutput on causes SQL*Plus to
retrieve and display the buffer.
The DBMS_OUTPUT is a built-in package that enables you to display
output.

Example:
SQL> set serveroutput on
SQL>begin
2 dbms_output.put_line('Hello World');
3 end;
/

Hello World

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 48


Question:

What is a cursor FOR loop and how does it differ from an explicit
cursor?

Cursor for loop is the way by which you can reduce the size of
code.
It opens the cursor automatically, fetches the new record for
each iteration and closes the cursor automatically when it
doesn't find any record to fetch.
It reduces few steps from standard implementation of explicit
cursor.

Note : Do not declare the record that controls the loop; it is


declared implicitly.

Example:

declare
cursor c1 is select * from departments;
begin
for r1 in c1 loop
dbms_output.put_line(r1.department_id||’ ’
||r1.department_name);
end loop;
end;
/

PL/SQL Interview Questions Page 49


Question:

What are the different types of exceptions?

Following are the types of exceptions:

1) Predefined exceptions(Named System Exceptions):

System exceptions are automatically raised by Oracle, when a


program violates a RDBMS rule.
There are some system exceptions which are raised frequently,
so they are pre-defined and given a name in Oracle which are
known as Named System Exceptions.
For example: NO_DATA_FOUND and ZERO_DIVIDE are called Named
System exceptions.

2) Non-predefined exceptions(Unnamed System Exceptions):

Those system exception for which oracle does not provide a


name is known as unnamed system exception. These exception do
not occur frequently.
These Exceptions have a code and an associated message.
 There are two ways to handle unnamed system exceptions:
 By using the WHEN OTHERS exception handler, or
 By associating the exception code to a name and using
it as a named exception.

PL/SQL Interview Questions Page 50


3) User-defined exceptions:

Apart from system exceptions we can explicitly define


exceptions based on business rules. These are known as user-
defined exceptions.
Steps to be followed to use user-defined exceptions:
a. They should be explicitly declared in the declaration
section.
b. They should be explicitly raised in the Execution
Section.
c. They should be handled by referencing the user-defined
exception name in the exception section.

Note: Predefined exceptions and Non-predefined exceptions are


implicitly raised by oracle server however User-defined
exceptions are explicitly raised by user with RAISE statement.

PL/SQL Interview Questions Page 51


Question:

Which privileges are required to execute a subprogram owned by another


user?

To call procedure, function or package of other users you must


have EXECUTE privilege on it.

Example:

SQL> set serveroutput on


SQL> show user
USER is "SAURABHG"
SQL> create or replace procedure proc456
2 is
3 begin
4 dbms_output.put_line('This is procedure proc456');
5 end;
6 /

Procedure created.

SQL> exec proc456;

PL/SQL procedure successfully completed.

SQL> exec proc456;


This is procedure proc456

PL/SQL procedure successfully completed.

SQL> grant execute on proc456 to vivek; --granting execute

Grant succeeded.

SQL> conn vivek/vivek


Connected.
SQL> set serveroutput on
SQL> exec saurabhg.proc456;

PL/SQL procedure successfully completed.

SQL> exec saurabhg.proc456;


This is procedure proc456

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 52


Question:

What are the mandatory keywords in a PL/SQL program block?

The PL/SQL block is divided into three different sections


declaration section, executable section and exception section.
Among these sections declaration section and exception section is
optional however the executable section is mandatory.

Executable section- The executable section begins with the


keyword BEGIN and ends with END. It contains SQL statements to
retrieve data from the database and PL/SQL statements to
manipulate data in the block.
So the BEGIN and END keywords are mandatory for any PL/SQL block.

PL/SQL Interview Questions Page 53


Question:

Explain how the %NOTFOUND attribute can be used to exit from a loop.

Opening cursor- The OPEN statement executes the query associated


with the cursor, identifies the active set.

Fetching data from the cursor- The FETCH statement retrieves the
rows from the cursor one at a time.

You can use the %NOTFOUND attribute to determine whether the


entire active set has been retrieved. %NOTFOUND is Boolean
attribute evaluates to TRUE if the most recent fetch does not
returns a row.

Example:
declare
cursor c1 is select * from departments;
r1 c1%rowtype;
begin
open c1;
loop
fetch c1 into r1;
exit when c1%notfound;
dbms_output.put_line(r1.department_id||’ ’
||r1.department_name);
end loop;
close c1;
end;
/

PL/SQL Interview Questions Page 54


Question:

What will be the value of %NOTF0UND attribute after a cursor is opened


but before a FETCH statement is executed?

The value of %NOTFOUND attribute will be null.

Example:

declare
cursor c1 is select * from departments;
r1 c1%rowtype;
begin
open c1;
if c1%notfound then
dbms_output.put_line('true');
elsif c1%notfound is null then
dbms_output.put_line('null');
else
dbms_output.put_line('false');
end if;
close c1;
end;
/
output: null

PL/SQL Interview Questions Page 55


Question:

Can DDL commands be used within a procedure? If so, then how?

DDL commands, such as create, alter, revoke, and grant, cannot be


used directly within the procedural language block.
They can only be called using Native Dynamic SQL which allows the
execution of the DDL statements at runtime.

Example:

create or replace procedure create_table(table_name varchar2,


col_specs varchar2)
is
begin
EXECUTE IMMEDIATE ‘create table ‘
||table_name||’(‘||col_specs||’)’;
end;
/

call example:

begin
create_table('employee_details',
'id number primary key, name varchar2(10)');
end;
/

PL/SQL Interview Questions Page 56


Question:

Give a few pre-defined Oracle errors.

NO_DATA_FOUND Single row select statement returned no data

TOO_MANY_ROWS Single row select statement returned more


than one row.
ZERO_DIVIDE Attempted to divide by zero.
INVALID_CURSOR Illegal cursor operation occurred.
DUP_VAL_ON_INDEX Attempted to insert duplicate value
CURSOR_ALREADY_OPEN Attempted to open an already open cursor

PL/SQL Interview Questions Page 57


Question:

Can stand-alone programs be overloaded?

No, however the subprograms which are member of the package can
be overloaded.

Example:

CREATE OR REPLACE PACKAGE emp_actions


AS
PROCEDURE hire_fire_employee (ename VARCHAR2, job VARCHAR2,
esal NUMBER, comm NUMBER);
PROCEDURE hire_fire_employee (emp_id NUMBER);
END emp_actions;
/

CREATE OR REPLACE PACKAGE BODY emp_actions


AS

PROCEDURE hire_fire_employee(ename VARCHAR2,job VARCHAR2,


esal NUMBER, comm NUMBER)
IS
new_empno NUMBER;
BEGIN
SELECT empno_seq.NEXTVAL INTO new_empno FROM dual;
INSERT INTO emp VALUES (new_empno, ename, job,SYSDATE,
esal, comm);
DBMS_OUTPUT.PUT_LINE('employee inserted successfully');
END hire_fire_employee;

PROCEDURE hire_fire_employee(emp_id NUMBER)


IS
BEGIN
DELETE FROM emp WHERE empno = emp_id;
IF SQL%FOUND THEN
DBMS_OUTPUT.PUT_LINE('employee '||emp_id||
' deleted successfully');
ELSE
DBMS_OUTPUT.PUT_LINE('invalid employee');
END IF;
END hire_fire_employee;

END emp_actions;
/

PL/SQL Interview Questions Page 58


Question:

Can SQL group functions be used within the procedural statements?

The SQL group functions, such as AVG, MIN, MAX, COUNT and SUM
cannot be directly used within PL/SQL.
However, they can be embedded within SQL statements and then can
be utilized in the procedural statements.

Example:

SQL> declare
2 maxdeptid number;
3 begin
4 select max(department_id) into maxdeptid
5 from departments;
6 dbms_output.put_line('The maximum department_id is:'
||maxdeptid);
7 end;
8 /
The maximum department_id is:270
PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 59


Question:

Explain the DECODE function? Can it be used in the procedural


statements?

The DECODE function compares its first argument to one or more


search expressions that are paired with result expressions. Any
of the search or result expression can be null. If a search is
successful, the corresponding result is returned.
The DECODE function cannot be used within the procedural
statements. It can only be used within the SQL statements.

Example:

declare
Var_bonus number;
begin
SELECT DECODE(emprating, 'D', 1500,
'C', 4000,
'B', 6000,
'A', 8000)
INTO var_bonus FROM empcopy WHERE employee_id = 115;
dbms_output.put_line(var_bonus);
end;
/

PL/SQL Interview Questions Page 60


Question:

What is the use of NVL function?

NVL function is used to replace the NULL values with an actual


value or expression.

Example:

declare
v_salary number;
v_bonus number;
v_total_salary number;
begin
select salary, bonus into v_salary, v_bonus
from employees
where employee_id=115;
v_total_salary := NVL(v_salary,0) + NVL(v_bonus,0);
dbms_output.put_line(v_total_salary);
end;
/

PL/SQL Interview Questions Page 61


Question:

What are INSTEAD OF triggers?

A view cannot be modified by normal DML statements if the view


query contains set operators, group functions, clauses such as
GROUP BY, DISTICNT operator or joins.

INSTEAD OF triggers provide a transparent way of modifying views


that cannot be modified directly through DML statements (INSERT,
UPDATE, and DELETE).
These triggers are called INSTEAD OF triggers because, unlike
other types of triggers, Oracle fires the trigger instead of
executing the triggering statement.

Example:

create or replace view empdeptname(empid,dname)


as select employee_id, department_name
from emp123 join dept123
using(department_id);

SQL> create trigger trgempdeptname


2 instead of update
3 on empdeptname
4 for each row
5 begin
6 update emp123 set department_id=(select department_id
7 from dept123 where department_name=:new.dname)
8 where employee_id=:old.empid;
9 end;
10 /
Trigger created.

SQL> update empdeptname


2 set department_name='Human Resources'
3 where department_name='IT';

5 rows updated.

PL/SQL Interview Questions Page 62


Question:

What is the function of OPEN cursor command?

The OPEN statement is included in the executable section of the


PL/SQL block.
The OPEN statement executes the query associated with the cursor,
identifies the active set and positions the cursor pointer at the
first row.

PL/SQL Interview Questions Page 63


Question:

What is the meaning of disabling a trigger?

A disabled trigger does not execute its trigger body, even if a


triggering statement is entered.

PL/SQL Interview Questions Page 64


Question:

What are the restrictions on functions that are called within SQL
statements?

They cannot modify any database table.


They can only take the IN parameter modes. The OUT and IN OUT
parameter modes are not allowed in a function.
They can only use valid SQL datatypes, such as NUMBER, VARCHAR2,
and DATE. However, they cannot use PL/SQL datatypes, such as
BOOLEAN, RECORD, and TYPE.
They return type of a function should be of SQL datatype.
They cannot have the COMMIT and ROLLBACK statements.

PL/SQL Interview Questions Page 65


Question:

What is the maximum length of an identifier that can be used?

The maximum length of an identifier in a PL/SQL block is 30.

PL/SQL Interview Questions Page 66


Question:

What are the different forms of conditional IF construct?

1) IF ....... THEN
......
......
END IF;

2) IF ....... THEN
......
......
ELSE
......
......
END IF;

3) IF ....... THEN
......
......
ELSIF ...... THEN
......
......
END IF;

4) IF ....... THEN
......
......
ELSIF ...... THEN
......
ELSE
......
......
END IF;

PL/SQL Interview Questions Page 67


Question:

What are the different ways to determine the status of a cursor?

The status of a cursor can be determined by checking the


attributes of that cursor.

Following are the attributes of a cursor:

Boolean attribute evaluates to TRUE if the


%ISOPEN
cursor is open
Boolean attribute evaluates to TRUE if the
%FOUND
most recent fetch returns a row.
Boolean attribute evaluates to TRUE if the
%NOTFOUND
most recent fetch does not returns a row.
An integer value that represents number of row
%ROWCOUNT
returned so far.

PL/SQL Interview Questions Page 68


Question:

What is the equivalent of DECODE function in the procedural


statements?

The if...then...else statement is the equivalent of DECODE


function within the procedural statements.

PL/SQL Interview Questions Page 69


Question:

What is the difference between private package construct and public


package construct?

 Public constructs:
All constructs placed in the specification of the package are
called public constructs.
Public constructs can be accessed from outside of the package
that is from any oracle server environment that is external to
the package.

 Private constructs:
Any subprogram not in the package specification but coded in the
package body is called a private constructs.
Private constructs are placed in the package body and can be
referenced only by other constructs within the same package body.

PL/SQL Interview Questions Page 70


Question:

What causes the INVALID_CURSOR exception?

If you attempt to fetch data from a cursor after it has been


closed, then an INVALID_CURSOR exception will be raised.

Example:

1 declare
2 cursor c1 is select * from departments;
3 r1 c1%rowtype;
4 begin
5 fetch c1 into r1;
6 end;
SQL> /
declare
*
ERROR at line 1:
ORA-01001: invalid cursor
ORA-06512: at line 5

PL/SQL Interview Questions Page 71


Question:

What is the difference between EXIT and EXIT-WHEN statements?

The EXIT statement terminates a loop unconditionally and


transfers control to the next statement after the END LOOP
statement.
The EXIT WHEN statement terminates a loop when the condition in
it’s WHEN clause is true and transfers control to next statement
after the END LOOP statement.

Example:(EXIT statement)

begin
for i in 1..10 loop
if i>5 then
exit;
end if;
dbms_output.put_line(i);
end loop;
end;
/

Example: (EXIT when statement)

begin
for i in 1..10 loop
exit when i>5;
dbms_output.put_line(i);
end loop;
end;
/

PL/SQL Interview Questions Page 72


PL/SQL Interview Questions Page 73
Question:

Can triggers stop a DML statement from executing on a table?

The RAISE_APPLICATION_ERROR is a server-side built in procedure


that returns an error to the user and causes the trigger to fail.
When a trigger fails, the triggering statement is automatically
rolled back by oracle server.

Example:

create or replace trigger securedept


before INSERT OR UPDATE OR DELETE
on departments
begin
raise_application_error(-20500,'You may DML operation on
departments table during business hours');
end;
/

PL/SQL Interview Questions Page 74


Question:

What is the advantage of using the %ROWTYPE datatype?

Advantages of using %ROWTYPE

 The %ROWTYPE attribute is useful when retrieving a row with


the select * statement.
 The number and data types of the underlying database columns
need not be known and in fact might change at run time.
 Using %ROWTYPE ensures that the data types of the variables
declared with this attribute change dynamically when
underlying table is altered.
 In the absence of this attribute, you would be forced to
declare a variable for each of the columns retrieved by the
select statement.

Example:

declare
r1 departments%rowtype;
begin
select * into r1 from departments where department_id=10;
dbms_output.put_line(r1.department_id||''||r1.department_name
||' '||r1.manager_id||' '||r1.location_id);
end;
SQL> /
10 Administration 200 1700

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 75


Question:

How can you check if an UPDATE statement in PL/SQL is successfully


executed?

PL/SQL does not return an error if a DML statement does not


affect rows in the underlying table.
Using implicit cursor attributes, you can test the outcome of
your dml statements.
SQL%FOUND is Boolean attribute evaluates to TRUE if the most
recent SQL statement returned at least one row.

Example:

begin
update departments
set manager_id=125
where location_id=1800;
if sql%found then
dbms_output.put_line(' table departments is updated
successfully');
else
dbms_output.put_line(' table departments is not udpated');
end if;
end;
SQL> /
table departments is updated successfully

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 76


Question:

How can triggers be used for the table auditing?

Oracle provides DDL triggers to audit all schema changes and can
report the exact change, when it was made, and by which user.
Using the Data Definition Language (DDL) triggers, the Oracle DBA
can automatically track all changes to the database,
including changes to tables. The data from this trigger is
especially useful for change control for the Oracle DBA.

Syntax:

CREATE [ OR REPLACE ] TRIGGER trigger_name


Timing
[ ddl_event1 [ OR ddl_event2 OR ...] ]
ON DATABASE | SCHEMA
trigger_body

PL/SQL Interview Questions Page 77


in the above syntax:

 ddl_event1 can be:

 CREATE causes the oracle server to fire the trigger


whenever a CREATE statement adds a new database object
to the dictionary.
 ALTER causes the oracle server to fire the trigger
whenever an ALTER statement modifies a database object
in the data dictionary.
 DROP causes the oracle server to fire the trigger
whenever a DROP statement removes a database object in
the data dictionary.

 ON DATABASE | SCHEMA

 You can create trigger for above events on DATABASE or


SCHEMA.
 A trigger defined at the database level fires for all
users, and a trigger defined at the schema or table
level fires only when the triggering event involves that
schema or table.

PL/SQL Interview Questions Page 78


Example:

create table ddltrack(uname varchar2(20),


objname varchar2(30),
objtype varchar2(20),
ddlevent varchar2(10),
datetime timestamp);

create or replace trigger trgddltrack


before create or alter or drop
on database
begin
dbms_output.put_line('ddl event occure');
insert into ddltrack values(user, ora_dict_obj_name,
ora_dict_obj_type, ora_sysevent, systimestamp);
end;
/

In the above example

USER function returns the user_id from the current Oracle session.

ORA_DICT_OBJ_NAME returns an object name as a VARCHAR2 datatype.

ORA_DICT_OBJ_TYPE returns the datatype of the dictionary object


changed by the event as a VARCHAR2 datatype.

ORA_SYSEVENT function returns the system event that was responsible


for firing the trigger as a VARCHAR2 datatype.

PL/SQL Interview Questions Page 79


Question:

What is the difference between database trigger and stored procedure?

Difference between Procedure and Trigger

Procedure Trigger
Defined with CREATE PROCEDURE Defined with CREATE TRIGGER
Procedure accept parameters Trigger does not accept
parameter
Invoked explicitly Invoked implicitly
COMMIT, ROLLBACK and SAVEPOINT COMMIT, ROLLBACK and SAVEPOINT
are allowed are not allowed

PL/SQL Interview Questions Page 80


Question:

What is an anonymous block and how is it executed?

Anonymous blocks are unnamed executable PL/SQL blocks.


They are declared at the point in an application where they are
to be executed and are compiled each time the application is
executed.
These blocks are not stored in the database.
They are passed to PL/SQL engine for execution at runtime.
If you want to execute the same block again, you have to rewrite
the block.
You are unable to invoke or call the block that you wrote earlier
because blocks are anonymous and do not exist after they are
executed.

Example:

declare
deptname varchar2(40);
begin
select department_name into deptname
from departments
where department_id=(select department_id from employees
where employee_id=100);
dbms_output.put_line('employee 100 works in '||deptname||'
department');
end;
SQL> /
employee 100 works in Executive department

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 81


Question:

How can the text of a procedure or function specification be viewed?

The source code for PL/SQL subprograms (PROCEDURE, PACKAGE,


PACKAGE BODY, TRIGGER and FUNCTION) is stored in the data
dictionary tables.

To view the PL/SQL source code stored in the data dictionary,


execute a SELECT statement on the following tables:

 The USER_SOURCE table to display PL/SQL code that you own.


 The ALL_SOURCE table to display PL/SQL code to which you have
been granted the EXECUTE privilege by the owner of that
subprogram code.

Example:

SELECT text
FROM user_source
WHERE name='RAISE_SALARY' and type='FUNCTION';

PL/SQL Interview Questions Page 82


Question:

What are the different parameter modes, which can be used in the
function specification?

All parameter modes IN, OUT and IN OUT can be used in the
function specification.

Parameters modes

Parameters are assign to one of the three parameter passing


modes: IN, OUT or IN OUT.

 IN - An IN parameter passes a constant value from the


calling environment into the procedure. The IN mode is the
default if no mode is specified. IN parameters are passed as
read-only values from the calling environment into the
procedure. Attempts to change the value of an IN parameter
in called subprogram result in compile-time error.

 OUT - The OUT parameter passes a value from procedure to the


calling environment. The OUT parameter can be assigned
values only in the body of the procedure in which they are
declared. Make sure that the data type for the actual
parameter variables used to retrieve values from OUT
parameters has a size sufficient to hold the data values
being returned.

 IN OUT - An IN OUT parameter passes a value from the calling


environment to the procedure and a possibly different value
from the procedure back to the calling environment using the
same parameter.

PL/SQL Interview Questions Page 83


Question:

Is DROP PACKAGE command used to drop the package specification or the


package body?

To remove whole package(specification and body) use following


syntax:

DROP PACKAGE package_name;

You can remove only package body and retain the package
specification using following syntax:

DROP PACKAGE BODY package_name;

PL/SQL Interview Questions Page 84


Question:

What is a RECORD datatype?

Variables of scalar data type can hold only one value, whereas a
variable of composite data type can hold multiple values of
scalar data type.

PL/SQL records is of composite data type.

PL/SQL records: Records are used to treat related but dissimilar


data as a logical unit. A PL/SQL record can have variables of
different types.

For example, you can define a record to hold employee details.


This involves storing an employee number as NUMBER, a first name
and last name as VARCHAR2 and so on.
By creating a record to store employee details, you create a
logical collective unit.
This makes data access and manipulation easier.

It is good to have single bag for all your laptop components


rather than a separate bag for each component.

Use PL/SQL records when you want to store values of different


data types that are logically related.

Use PL/SQL records when you want to store values of different


data types but only one occurrence at a time.

Example is given on the next page.

PL/SQL Interview Questions Page 85


Example:

declare
type rec is record(empid number(3), fname varchar2(30),
lname varchar2(30));
r1 rec;
begin
select employee_id, first_name, last_name into r1
from employees
where department_id=10;
dbms_output.put_line(r1.empid||' '||r1.fname||' '||r1.lname);
end;
/
200 Jennifer Whalen

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 86


Question:

What is the value of SQL%FOUND attribute after and before an INSERT


statement is executed?

SQL%FOUND is Boolean attribute evaluates to TRUE if the most


recent SQL statement returned at least one row.

Before INSERT statement the value of SQL%FOUND attribute will be


NULL and after INSERT statement it will be TRUE.

Example:

begin
if SQL%FOUND is null then
dbms_output.put_line('null');
end if;
insert into departments values(300,'sports',null,null);
if SQL%FOUND then
dbms_output.put_line('new department inserted successfully');
end if;
end;
/

output:
null
new department inserted successfully

PL/SQL Interview Questions Page 87


Question:

Can a function be defined without a RETURN statement?

No, a function must return a value to the calling environment, so


it must contain RETURN statement in the executable section.

PL/SQL Interview Questions Page 88


Question:

How can the parameter list for a function or procedure be displayed?

You can the parameter list for a function or procedure using


below command:

desc <procedurename|functionname>;

PL/SQL Interview Questions Page 89


Question:

What is the meaning of the following error statement: ORA-06575:


Package or function func_test is in an invalid state?

This error occurs when you tried to execute a SQL statement that
referenced a PLSQL function that is in an invalid state. This
happens when the function is compiled with errors

 Cause: A SQL statement references a PL/SQL function that is in


an invalid state. Oracle attempted to compile the function,
but detected errors.

 Action: Check the SQL statement and the PL/SQL function for
syntax errors or incorrectly assigned, or missing, privileges
for a referenced object.

PL/SQL Interview Questions Page 90


Question:

Is it possible to drop the package body without dropping the package


specification?

Yes, you can remove only package body and retain the package
specification using following syntax:

DROP PACKAGE BODY package_name;

PL/SQL Interview Questions Page 91


Question:

Describe the SQLCODE and SQLERRM functions.

When an exception occurs, you can identify the associated error


code or error message by using below functions.
Based on the values of the code or the message, you can decide
which subsequent actions to take.

 SQLCODE - Returns the numeric value for error code (You can
assign it to a NUMBER variable).
 SQLERRM - Returns the character data containing the message
associated with the error number.

Example:
declare
insert_excep EXCEPTION; -- declare the name of exception
PRAGMA EXCEPTION_INIT(insert_excep,-01400); -- associate
begin
insert into departments(department_id, department_name)
values(280,null);
exception
when insert_excep then -– handling exception
dbms_output.put_line('Insert operation failed');
dbms_output.put_line(SQLERRM);
end;
/
Insert operation failed

ORA-01400: cannot insert NULL


into("VIVEK"."DEPARTMENTS"."DEPARTMENT_NAME")

PL/SQL Interview Questions Page 92


Question:

What is the basic structure of a Procedural Language/Structured Query


Language (PL/SQL) block?

PL/SQL block structure:

 DECLARE(optional)
Variables, cursors, user-defined exceptions
 BEGIN(mandatory)
SQL statements
PL/SQL statements
 EXCEPTION(optional)
Actions to perform when error occur
 END;(mandatory)

Declaration section- The declarative section begins with the


keyword DECLARE and ends when executable section starts. It
contains declarations of all variables, constants, cursors and
user-defined exceptions that are referenced in the executable and
exception section.

Executable section- The executable section begins with the


keyword BEGIN and ends with END. It contains SQL statements to
retrieve data from the database and PL/SQL statements to
manipulate data in the block.

Exception handling section- The exception section is nested


within the executable section. This section begins with keyword
EXCEPTION. This specifies the actions to perform when errors and
abnormal conditions arise in the executable section.

PL/SQL Interview Questions Page 93


Question:

Can functions be stored within a database as database objects?

Yes, procedures and functions are named PL/SQL blocks. They are
also known as subprograms.
These subprograms are compiled and stored in the database.
Because they are named and stored you can invoke them whenever
you want.

PL/SQL Interview Questions Page 94


Question:

What is an exception?

An exception is an error in PL/SQL that is raised during the


execution of a block.
A block always terminates when PL/SQL raises an exception, but
you can specify and exception handler to perform final actions
before the block ends.

PL/SQL Interview Questions Page 95


Question:

Can default values be assigned to IN OUT parameters in a procedure?

No, an OUT or IN OUT parameters cannot be assigned default


values; however it can be assigned to IN parameters.

When default values are assigned to formal parameters, you can


call the procedure without supplying an actual parameter value
for the parameter. Thus you can pass different number of actual
parameters to a subprogram, either by accepting or by overriding
the default values as required.

NOTE- You cannot assign default values to OUT and IN OUT


parameters.
There are two ways of assigning a default value to an IN
parameter:
1) The assignment operator(:=)
2) The DEFAULT option.

Example:
create procedure add_dept1(dname varchar2:='Unknown',
locid number default 1800)
is
begin
insert into deptcopy values(seq1.nextval,dname,null,locid);
end add_dept1;
/
execute add_dept1;
execute add_dept1('Testing',1700);
execute add_dept1(locid=>1900);

PL/SQL Interview Questions Page 96


Question:

How the concept of overloading is implemented within a package?

The overloading feature in PL/SQL:


- Enables you to create two or more subprograms with same name
- Requires that the subprograms’ formal parameters differ in
number, order or data type family.

Note- Overloading can be done with package subprograms but not


with standalone subprograms.

Example:

CREATE OR REPLACE PACKAGE emp_actions


AS
PROCEDURE hire_fire_employee (ename VARCHAR2, job VARCHAR2,
esal NUMBER, comm NUMBER);
PROCEDURE hire_fire_employee (emp_id NUMBER);
END emp_actions;
/

PL/SQL Interview Questions Page 97


Question:

What is RAISE_APPLICATION_ERROR?

RAISE_APPLICATION_ERROR is a built-in procedure in oracle which


is used to display the user-defined error messages along with the
error number whose range is in between -20000 and -20999.

Whenever a message is displayed using RAISE_APPLICATION_ERROR,


all previous transactions which are not committed within the
PL/SQL Block are rolled back automatically (i.e. change due to
INSERT, UPDATE, or DELETE statements).

The General Syntax to use this procedure is:

RAISE_APPLICATION_ERROR (error_number, error_message);

• The error_number must be between -20000 and -20999


• The error_message is the message you want to display when the
error occurs.

PL/SQL Interview Questions Page 98


Question:

When is the CURSOR_ALREADY_OPEN exception raised?

The CURSOR_ALREADY_OPEN exception (ORA-06511) occurs when a


program attempts to open an already open cursor. A cursor must be
closed before it can be reopened.

Example:

declare
cursor c1 is select * from departments;
r1 c1%rowtype;
begin
open c1;
loop
fetch c1 into r1;
exit when c1%notfound;
open c1;
end loop;
close c1;
end;
SQL> /
declare
*
ERROR at line 1:
ORA-06511: PL/SQL: cursor already open
ORA-06512: at line 2
ORA-06512: at line 9

PL/SQL Interview Questions Page 99


Question:

Can a parameter use a sequence generator for the assignment of default


value to a parameter?

Yes, a parameter uses a sequence generator for the assignment of


default value to an in parameter.

Example:

SQL> create sequence seq123 start with 1 increment by 1


maxvalue 10;

Sequence created.

SQL> create or replace procedure proc1(srno number default


seq123.nextval)
2 is
3 begin
4 dbms_output.put_line(srno);
5 end;
6 /

Procedure created.

SQL> set serveroutput on


SQL> exec proc1
1

PL/SQL Interview Questions Page 100


Question:

Can an IF-THEN-ELSIF block have infinite number of ELSE clauses?

No, ELSIF and ELSE are optional in an IF statement. You can have
any number of ELSIF keywords but only one ELSE keyword in your IF
statement.

PL/SQL Interview Questions Page 101


Question:

What will be the consequence if the upper bound of the FOR-LOOP


counter gets a smaller value than the lower bound?

If the upper bound of a loop range evaluates to a smaller integer


value than the lower bound, the loop body is not executed and
control passes to the next statement after the END LOOP
statement.

Example:

SQL> begin
2 for i in 10..2 loop
3 dbms_output.put_line(i);
4 end loop;
5 dbms_output.put_line('loop is skipped');
6 end;
7 /
loop is skipped

PL/SQL procedure successfully completed.

PL/SQL Interview Questions Page 102


Question:

What is the difference between PROCEDURE and FUNCTION?

Procedure Function
Procedure may or may not return Function is mainly used in the
a value or may return more than case where it must return a
one value using the OUT value.
parameter.
Can not contain RETURN clause Must contain RETURN clause in
in the header the header
We cannot call procedure in We can call functions in select
select statement statement in select statement

PL/SQL Interview Questions Page 103


Question:

Explain statement level and row level triggers.

 A statement trigger:
 Executes once for the triggering event
 Is the default type of trigger
 Fires once even if no rows are affected at all

 A row trigger:
 Executes once for each row affected by the triggering event.
 Is not executed if the trigging event does not affect any
rows.
 Is indicated by specifying the FOR EACH ROW clause.

PL/SQL Interview Questions Page 104


Question:

What is the error in the following code?

begin

select emp_age from t_employee where emp_code=212;

end;

The select query has been written without the into clause, which
is mandatory for a select statement in a pl/sql block. As a
result, the select query cannot get execute without assigning its
output to variable.

PL/SQL Interview Questions Page 105


Question:

What is the difference in usage of SELECT INTO and FETCH?

The SELECT INTO clause should be used when the result of the
query is known to return a single row. When more than one row is
be returned by the SQL query, then FETCH clause should be used.
If the FETCH clause is not used and the query returns more than
one row, then the runtime error is generated in the code.

PL/SQL Interview Questions Page 106


Question:

Distinguish between WHILE-LOOP and FOR-LOOP?

The while-loop associates a condition with a loop. First, the


condition is checked and then the loop is started.

The loop continues until the condition remains TRUE. If the


condition becomes FALSE, the loop is completed. The number of
iterations is not known as it is based only on a condition. The
loop may not be executed at all, as the condition is checked at
the start of the loop itself.

Following is the syntax of the WHILE-LOOP:

WHILE condition LOOP

statements....

END LOOP;

The FOR-LOOP also associates a condition with a loop but the


number of iterations is defined before the execution.

Following is the syntax of the FOR-LOOP:

FOR counter in startvalue..endvalue condition LOOP

statements....

END LOOP;

Therefore, WHILE-LOOP should be used when a condition has to be


checked initially and when the number of iterations is not known.

FOR-LOOP should be used when the number of iterations is known in


advanced.

PL/SQL Interview Questions Page 107


Question:

Can the PL/SQL block process more than one exception at a time?

No, the PL/SQL block cannot handle more than one exception. It
can process only one exception handler before terminating.

PL/SQL Interview Questions Page 108


Question:

What are the values of :new and :old in Insert/Delete/Update Triggers?

Within a row trigger, reference the value of a column before and


after the data change by prefixing it with the OLD and NEW
qualifiers.

Data operation Old value New value


INSERT NULL Inserted value
UPDATE Value before update Updated value
DELETE Value before delete NULL

PL/SQL Interview Questions Page 109

You might also like