You are on page 1of 8

Oracle PLSQL Questions

Commonly Asked Oracle PLSQL Interview Question with Real time scenario Based Question

PLSQL Exceptions
1. What are the two types of exceptions?
i. user defined
ii. Predefined.

2. Show some predefined exceptions.

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

3. Give me examples for following Exception


DUP_VAL_ON_INDEX,
VALUE_ERROR,
CURSOR_ALREADY_OPEN
TOO_MANY_ROWS

4. How to retrying the transaction (continue) even after Exception raised OR How do you
handle exception when you want to do DML and Skip Error Values.
I. Encase the transaction in a sub-block.
II. Place the sub-block inside a loop that repeats the transaction.
III. Before starting the transaction, mark a save point. If the transaction succeeds,
commit, then exit from the loop. If the transaction fails, control transfers to the
exception handler, where you roll back to the savepoint undoing any changes,
then try to fix the problem.

5. DECLARE
6. name VARCHAR2(20);
7. ans1 VARCHAR2(3);
8. ans2 VARCHAR2(3);
9. ans3 VARCHAR2(3);
10. suffix NUMBER := 1;
11. BEGIN
12. FOR i IN 1..10 LOOP -- try 10 times
13. BEGIN -- sub-block begins
14. SAVEPOINT start_transaction; -- mark a savepoint
15. /* Remove rows from a table of survey results. */
16. DELETE FROM results WHERE answer1 = 'NO';
17. /* Add a survey respondent's name and answers. */
18. INSERT INTO results VALUES (name, ans1, ans2, ans3);
19. -- raises DUP_VAL_ON_INDEX if two respondents have the same
name
20. COMMIT;
21. EXIT;
22. EXCEPTION
23. WHEN DUP_VAL_ON_INDEX THEN
24. ROLLBACK TO start_transaction; -- undo changes
25. suffix := suffix + 1; -- try to fix
problem
26. name := name || TO_CHAR(suffix);
27. END; -- sub-block ends
28. END LOOP;
29. END;
30. /

OR

Declare
v1 varchar2(100);
v2 varchar2(100);
begin
for i in (select * from a) loop
begin
insert into
b(EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_I
D,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID)
values
(i.EMPLOYEE_ID,i.FIRST_NAME,i.LAST_NAME,i.EMAIL,i.PHONE_NUMBER,i.HIRE_DATE,i
.JOB_ID,i.SALARY,i.COMMISSION_PCT,i.MANAGER_ID,i.DEPARTMENT_ID);
commit;
exception
when others then
v1:=sqlcode;
v2:=sqlerrm;
insert into log_tab(sql_code,sql_err)
values (v1,v2);
commit;
end;
end loop;
end;

4. How do you track exception handler for a sequence of DML statements that caused an error
If you need to know which statement failed, you can use a locator variable.
DECLARE
stmt INTEGER;
name VARCHAR2(100);
BEGIN
stmt := 1; -- designates 1st SELECT statement
SELECT table_name INTO name FROM user_tables WHERE table_name LIKE
'ABC%';
stmt := 2; -- designates 2nd SELECT statement
SELECT table_name INTO name FROM user_tables WHERE table_name LIKE
'XYZ%';
EXCEPTION
WHEN NO_DATA_FOUND THEN
dbms_output.put_line('Table name not found in query ' || stmt);
END;
/

5. Can I use one or more exceptions to execute the same sequence of statements?

If you want two or more exceptions to execute the same sequence of statements, list the
exception names in the WHEN clause, separating them by the keyword OR, as follows:

EXCEPTION
WHEN over_limit OR under_limit OR VALUE_ERROR THEN
-- handle the error

6. Can I use When OTHERS exception in the beginning and others predefined exception in
subsequent.

No, The optional OTHERS exception handler, which is always the last handler in a block or
subprogram, acts as the handler for all exceptions not named specifically. Thus, a block or
subprogram can have only one OTHERS handler.

7. How Do you handle user defined exception?.


You can place RAISE statements for a given exception anywhere within the
scope of that exception. In the following example, you alert your PL/SQL block
to a user-defined exception named out_of_stock:
DECLARE
out_of_stock EXCEPTION;
number_on_hand NUMBER(4);
BEGIN
...
IF number_on_hand < 1 THEN
RAISE out_of_stock;
END IF;
EXCEPTION
WHEN out_of_stock THEN
-- handle the error
END;

8. Can we raise Pre-defined Exception explicitly?.

You can also raise a predefined exception explicitly. That way, an exception
handler written for the predefined exception can process other errors, as the
following example shows:
DECLARE
acct_type INTEGER := 7;
BEGIN
IF acct_type NOT IN (1, 2, 3) THEN
RAISE INVALID_NUMBER; -- raise predefined exception
END IF;
EXCEPTION
WHEN INVALID_NUMBER THEN
ROLLBACK;
END;

9. Can we define exceptions twice in same block ?


No
10. Where the Pre_defined_exceptions are stored ?
In the standard package.
11. Explain about SQLERRM and SQLCODE and their importance.
SQLERRM Returns the Error Message for the Last Error that came across.
SQLERRM is useful for WHEN OTHERS Exception. They can be used for Reporting
purpose in Error Handling. They can also store the Error in the Code and store it
in the Error Log Table. SQLCODE Returns the Value of the Error Number for the
previous error. 
12. What is the Difference between Runtime Errors and Syntax Errors?
A Runtime Error is handled with the help of Exception Handling Mechanism in a
PL/SQL Block whereas a Syntax Error such as a spelling mistake is efficiently
detected by the SQL Compiler.

13. What is Pragma?


PRAGMA refers to a compiler directive or "hint" it is used to provide an instruction to
the compiler. 
14. What is Pragma Autonomous transaction
The term "autonomous transaction" refers to the ability of PL/SQL temporarily suspend
the current transaction and begin another, fully independent transaction (which will not
be rolled-back if the outer code aborts).  The second transaction is known as an
autonomous transaction. The autonomous transaction functions independently from
the parent code.

An autonomous transaction has the following characteristics:

15. What is PRAGMA SERIALLY_REUSABLE


 This directive tells Oracle that the package state is needed only for the duration of one
call to the server. After the call is made the package may be unloaded to reclaim
memory.

16. What is PRAGMA INLINE(11g Feature)?.


This directive specifies that a subprogram call either is or is not to be inlined. Inlining
replaces a subprogram call with a copy of the called subprogram.
create or replace package inline_demo is
  procedure runtest;
end;
/

create or replace package body inline_demo as 

function newadd(n1 number) return number


as
 n11 number;
begin
  n11:= n1+n1;
  return n11;
end;

procedure runtest as  


  n2 number := 0;
begin
  n2 := 3;
  dbms_output.put('Num: '||n2);
  PRAGMA INLINE (newadd,'YES');
  n2 := newadd(n2);
  dbms_output.put('  Num2: '||n2);
  PRAGMA INLINE (newadd,'NO');
  n2 := newadd(n2);
  dbms_output.put_line('  Num3: '||n2);
end;

end inline_demo;
/

SQL> exec inline_demo.runtest;


Num: 3  Num2: 6  Num3: 12

PL/SQL procedure successfully completed.

17. What is Pragma EXECPTION_INIT? Explain the usage?


The pragma EXCEPTION_INITs associates an exception name with an Oracle error number.
You can intercept any ORA- error and write a specific handler for it instead of using
the OTHERS handler.
DECLARE

v_name VARCHAR2(2);

Short_Data_size EXCEPTION;

PRAGMA exception_init( Short_Data_size,-6502 );

BEGIN

SELECT 'BASAVARAJ' INTO v_name FROM DUAL;

EXCEPTION

WHEN Short_Data_size THEN

DBMS_OUTPUT.PUT_line('DATA size mismatch');

WHEN OTHERS THEN

DBMS_OUTPUT.PUT_line(SQLERRM);

END;

18. What is RAISE_APPLICATION_ERROR ?


The procedure RAISE_APPLICATION_ERROR lets you issue user-defined ORA- error
messages from stored subprograms. That way, you can report errors to your application
and avoid returning unhandled exceptions.

To call RAISE_APPLICATION_ERROR, use the syntax :

raise_application_error(error_number, message[, {TRUE | FALSE}]);

where error_number is a negative integer in the range -20000 .. -20999 and message is
a character string up to 2048 bytes long. If the optional third parameter is TRUE, the
error is placed on the stack of previous errors. If the parameter is FALSE (the default),
the error replaces all previous errors. RAISE_APPLICATION_ERROR is part of package
DBMS_STANDARD, and as with package STANDARD, you do not need to qualify
references to it.

In the following example, you call raise_application_error if an employee's salary is


missing:
CREATE PROCEDURE raise_salary (emp_id NUMBER, amount NUMBER) AS

curr_sal NUMBER;

BEGIN

SELECT sal INTO curr_sal FROM emp WHERE empno = emp_id;

IF curr_sal IS NULL THEN

/* Issue user-defined error message. */

raise_application_error(-20101, 'Salary is missing');

ELSE

UPDATE emp SET sal = curr_sal + amount WHERE empno = emp_id;

END IF;

END raise_salary;

19. What is the range of the Error Codes in PL/SQL Exceptions?


The range of Error Code in PL/SQL Exception is between -20000 and -20899.
20. Can We use Pragma Autonomous_Transaction in Package Level?
You can apply to Procedure and Function inside the Package, but you can’t apply this
Pragma to entire Package

You might also like