Vous êtes sur la page 1sur 44

Oracle Apps PL-SQL Interview Questions Summary

Summary
This is our attempt to make any Oracle Apps consultant clear the technical/functional interview. As a
first step, we have collected a list of PL-SQL questions from many different web sites. These
questions will sure make anyone refresh their pl-sql skills, and will definitely help you to face a
technical interview with lot of confidence.
It is completely free ! Do like and share us if you value the effort that we are putting in to make Oracle
Apps learning easier !
Oracle Apps PL-SQL Interview Questions Set 1
Oracle Apps PL-SQL Interview Questions Set 2
Oracle Apps PL-SQL Interview Questions Set 3
Oracle Apps PL-SQL Interview Questions Set 4
Oracle Apps PL-SQL Interview Questions Set 5
Oracle Apps PL-SQL Interview Questions Set 6
Oracle Apps PL-SQL Interview Questions Set 7
Oracle Apps PL-SQL Interview Questions Set 8

Oracle Apps PL-SQL Interview Questions Set 1

Introduction on PL-SQL
Q: What is PL/SQL and what is it used for?
SQL is a declarative language that allows database programmers to write a SQL declaration and hand
it to the database for execution. As such, SQL cannot be used to execute procedural code with
conditional, iterative and sequential statements. To overcome this limitation, PL/SQL was created.
PL/SQL is Oracles Procedural Language extension to SQL. PL/SQLs language syntax, structure and
data types are similar to that of Ada. Some of the statements provided by PL/SQL:
Conditional Control Statements:
IF THEN ELSIF ELSE END IF;
CASE WHEN THEN ELSE END CASE;
Iterative Statements:
LOOP END LOOP;

WHILE LOOP END LOOP;


FOR IN [REVERSE] LOOP END LOOP;
Sequential Control Statements:
GOTO ;
NULL;
The PL/SQL language includes object oriented programming techniques such as encapsulation,
function overloading, information hiding (all but inheritance).
PL/SQL is commonly used to write data-centric programs to manipulate data in an Oracle database.
Example PL/SQL blocks:
/* Remember to SET SERVEROUTPUT ON to see the output */
BEGIN
DBMS_OUTPUT.PUT_LINE(Hello World);
END;
/
BEGIN
A PL/SQL cursor
FOR cursor1 IN (SELECT * FROM table1) This is an embedded SQL statement
LOOP
DBMS_OUTPUT.PUT_LINE(Column 1 = || cursor1.column1 ||
, Column 2 = || cursor1.column2);
END LOOP;
END;
/
Q: What is the difference between SQL and PL/SQL?
Both SQL and PL/SQL are languages used to access data within Oracle databases.
SQL is a limited language that allows you to directly interact with the database. You can write queries
(SELECT), manipulate objects (DDL) and data (DML) with SQL. However, SQL doesnt include all the
things that normal programming languages have, such as loops and IFTHENELSE statements.

PL/SQL is a normal programming language that includes all the features of most other programming
languages. But, it has one thing that other programming languages dont have: the ability to easily
integrate with SQL.
Some of the differences:
SQL is executed one statement at a time. PL/SQL is executed as a block of code.
SQL tells the database what to do (declarative), not how to do it. In contrast, PL/SQL tell the
database how to do things (procedural).
SQL is used to code queries, DML and DDL statements. PL/SQL is used to code program blocks,
triggers, functions, procedures and packages.
You can embed SQL in a PL/SQL program, but you cannot embed PL/SQL within a SQL statement.
Q: Should one use PL/SQL or Java to code procedures and triggers?
Both PL/SQL and Java can be used to create Oracle stored procedures and triggers. This often leads
to questions like Which of the two is the best? and Will Oracle ever desupport PL/SQL in favour of
Java?.
Many Oracle applications are based on PL/SQL and it would be difficult of Oracle to ever desupport
PL/SQL. In fact, all indications are that PL/SQL still has a bright future ahead of it. Many
enhancements are still being made to PL/SQL. For example, Oracle 9i supports native compilation of
Pl/SQL code to binaries. Not to mention the numerous PL/SQL enhancements made in Oracle 10g
and 11g.
PL/SQL and Java appeal to different people in different job roles. The following table briefly describes
the similarities and difference between these two language environments:
PL/SQL:
Can be used to create Oracle packages, procedures and triggers
Data centric and tightly integrated into the database
Proprietary to Oracle and difficult to port to other database systems
Data manipulation is slightly faster in PL/SQL than in Java
PL/SQL is a traditional procedural programming language
Java:
Can be used to create Oracle packages, procedures and triggers
Open standard, not proprietary to Oracle
Incurs some data conversion overhead between the Database and Java type
Java is an Object Orientated language, and modules are structured into classes
Java can be used to produce complete applications
PS: Starting with Oracle 10g, .NET procedures can also be stored within the database (Windows
only). Nevertheless, unlike PL/SQL and JAVA, .NET code is not usable on non-Windows systems.

PS: In earlier releases of Oracle it was better to put as much code as possible in procedures rather
than triggers. At that stage procedures executed faster than triggers as triggers had to be re-compiled
every time before executed (unless cached). In more recent releases both triggers and procedures
are compiled when created (stored p-code) and one can add as much code as one likes in either
procedures or triggers.
Q: How can one see if somebody modified any code?
The source code for stored procedures, functions and packages are stored in the Oracle Data
Dictionary. One can detect code changes by looking at the TIMESTAMP and LAST_DDL_TIME
column in the USER_OBJECTS dictionary view. Example:
SELECT OBJECT_NAME,
TO_CHAR(CREATED,

DD-Mon-RR HH24:MI) CREATE_TIME,

TO_CHAR(LAST_DDL_TIME, DD-Mon-RR HH24:MI) MOD_TIME,


STATUS
FROM USER_OBJECTS
WHERE LAST_DDL_TIME > &CHECK_FROM_DATE';

Note: If you recompile an object, the LAST_DDL_TIME column is updated, but the TIMESTAMP
column is not updated. If you modified the code, both the TIMESTAMP and LAST_DDL_TIME
columns are updated.
Q: How can one search PL/SQL code for a string/ key value?
The following query is handy if you want to know where certain tables, columns and expressions are
referenced in your PL/SQL source code.
SELECT type, name, line
FROM user_source
WHERE UPPER(text) LIKE UPPER(%&KEYWORD%);
If you run the above query from SQL*Plus, enter the string you are searching for when prompted for
KEYWORD. If not, replace &KEYWORD with the string you are searching for.
Q: How does one keep a history of PL/SQL code changes?
One can build a history of PL/SQL code changes by setting up an AFTER CREATE schema (or
database) level trigger (available from Oracle 8.1.7). This will allow you to easily revert to previous
code should someone make any catastrophic changes. Look at this example:
CREATE TABLE SOURCE_HIST

Create history table

AS SELECT SYSDATE CHANGE_DATE, ALL_SOURCE.*


FROM ALL_SOURCE WHERE 1=2;
CREATE OR REPLACE TRIGGER change_hist

Store code in hist table

AFTER CREATE ON SCOTT.SCHEMA

Change SCOTT to your schema name

DECLARE
BEGIN
IF ORA_DICT_OBJ_TYPE in (PROCEDURE, FUNCTION,
PACKAGE, PACKAGE BODY,
TYPE,

TYPE BODY)

THEN
Store old code in SOURCE_HIST table
INSERT INTO SOURCE_HIST
SELECT sysdate, all_source.* FROM ALL_SOURCE
WHERE TYPE = ORA_DICT_OBJ_TYPE DICTIONARY_OBJ_TYPE IN 8i
AND NAME = ORA_DICT_OBJ_NAME; DICTIONARY_OBJ_NAME IN 8i
END IF;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20000, SQLERRM);
END;
/
show errors
A better approach is to create an external CVS or SVN repository for the scripts that install the
PL/SQL code. The canonical version of whats in the database must match the latest CVS/SVN
version or else someone would be cheating.
Q: How can I protect my PL/SQL source code?
Oracle provides a binary wrapper utility that can be used to scramble PL/SQL source code. This utility
was introduced in Oracle7.2 (PL/SQL V2.2) and is located in the ORACLE_HOME/bin directory.
The utility use human-readable PL/SQL source code as input, and writes out portable binary object
code (somewhat larger than the original). The binary code can be distributed without fear of exposing
your proprietary algorithms and methods. Oracle will still understand and know how to execute the
code. Just be careful, there is no decode command available. So, dont lose your source!
The syntax is:

wrap iname=myscript.pls oname=xxxx.plb


Please note: there is no way to unwrap a *.plb binary file. You are supposed to backup and keep your
*.pls source files after wrapping them.
Q: Can one print to the screen from PL/SQL?
One can use the DBMS_OUTPUT package to write information to an output buffer. This buffer can be
displayed on the screen from SQL*Plus if you issue the SET SERVEROUTPUT ON; command. For
example:
set serveroutput on
begin
dbms_output.put_line(Look Ma, I can print from PL/SQL!!!);
end;
/
DBMS_OUTPUT is useful for debugging PL/SQL programs. However, if you print too much, the output
buffer will overflow. In that case, set the buffer size to a larger value, eg.: set serveroutput on size
200000
If you forget to set serveroutput on type SET SERVEROUTPUT ON once you remember, and then
EXEC NULL;. If you havent cleared the DBMS_OUTPUT buffer with the disable or enable procedure,
SQL*Plus will display the entire contents of the buffer when it executes this dummy PL/SQL block.
Note that DBMS_OUTPUT doesnt print blank or NULL lines. To overcome this problem, SET
SERVEROUTPUT ON FORMAT WRAP; Look at this example with this option first disabled and then
enabled:
SQL> SET SERVEROUTPUT ON
SQL> begin
dbms_output.put_line(The next line is blank);
dbms_output.put_line();
dbms_output.put_line(The above line should be blank);
end;
/
The next line is blank
The above line should be blank
SQL> SET SERVEROUTPUT ON FORMAT WRAP
SQL> begin

dbms_output.put_line(The next line is blank);


dbms_output.put_line();
dbms_output.put_line(The above line should be blank);
end;
/
The next line is blank
The above line should be blank
Q: Can one read/write files from PL/SQL?
The UTL_FILE database package can be used to read and write operating system files.
A DBA user needs to grant you access to read from/ write to a specific directory before using this
package. Here is an example:
CONNECT / AS SYSDBA
CREATE OR REPLACE DIRECTORY mydir AS /tmp';
GRANT read, write ON DIRECTORY mydir TO scott;
Provide user access to the UTL_FILE package (created by catproc.sql):
GRANT EXECUTE ON UTL_FILE TO scott;
Copy and paste these examples to get you started:
Write File
DECLARE
fHandler UTL_FILE.FILE_TYPE;
BEGIN
fHandler := UTL_FILE.FOPEN(MYDIR, myfile, w);
UTL_FILE.PUTF(fHandler, Look ma, Im writing to a file!!!\n);
UTL_FILE.FCLOSE(fHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, Invalid path. Create directory or set UTL_FILE_DIR.);
END;

/
Read File
DECLARE
fHandler UTL_FILE.FILE_TYPE;
buf

varchar2(4000);

BEGIN
fHandler := UTL_FILE.FOPEN(MYDIR, myfile, r);
UTL_FILE.GET_LINE(fHandler, buf);
dbms_output.put_line(DATA FROM FILE: ||buf);
UTL_FILE.FCLOSE(fHandler);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, Invalid path. Create directory or set UTL_FILE_DIR.);
END;
/
NOTE: UTL_FILE was introduced with Oracle 7.3. Before Oracle 7.3 the only means of writing a file
was to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
Q: Can one call DDL statements from PL/SQL?
One can call DDL statements like CREATE, DROP, TRUNCATE, etc. from PL/SQL by using the
EXECUTE IMMEDIATE statement (native SQL). Examples:
begin
EXECUTE IMMEDIATE CREATE TABLE X(A DATE)';
end;
begin execute Immediate TRUNCATE TABLE emp'; end;
DECLARE
var VARCHAR2(100);
BEGIN
var := CREATE TABLE temp1(col1 NUMBER(2))';

EXECUTE IMMEDIATE var;


END;
NOTE: The DDL statement in quotes should not be terminated with a semicolon.
Users running Oracle versions below Oracle 8i can look at the DBMS_SQL package.

Oracle Apps PL-SQL Interview Questions


Set 2
Q: Can one use dynamic SQL statements from PL/SQL?
Starting from Oracle8i one can use the EXECUTE IMMEDIATE statement to execute dynamic SQL
and PL/SQL statements (statements created at run-time). Look at these examples. Note that the
statements within quotes are NOT semicolon terminated:
EXECUTE IMMEDIATE CREATE TABLE x (a NUMBER)';
Using bind variables
sql_stmt := INSERT INTO dept VALUES (:1, :2, :3)';
EXECUTE IMMEDIATE sql_stmt USING dept_id, dept_name, location;
Returning a cursor
sql_stmt := SELECT * FROM emp WHERE empno = :id';
EXECUTE IMMEDIATE sql_stmt INTO emp_rec USING emp_id;
One can also use the older DBMS_SQL package (V2.1 and above) to execute dynamic statements.
Look at these examples:
CREATE OR REPLACE PROCEDURE DYNSQL AS
cur integer;
rc integer;
BEGIN
cur := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(cur, CREATE TABLE X (Y DATE), DBMS_SQL.NATIVE);
rc := DBMS_SQL.EXECUTE(cur);
DBMS_SQL.CLOSE_CURSOR(cur);
END;

/
More complex DBMS_SQL example using bind variables:
CREATE OR REPLACE PROCEDURE DEPARTMENTS(NO IN DEPT.DEPTNO%TYPE) AS
v_cursor integer;
v_dname char(20);
v_rows integer;
BEGIN
v_cursor := DBMS_SQL.OPEN_CURSOR;
DBMS_SQL.PARSE(v_cursor, select dname from dept where deptno > :x, DBMS_SQL.V7);
DBMS_SQL.BIND_VARIABLE(v_cursor, :x, no);
DBMS_SQL.DEFINE_COLUMN_CHAR(v_cursor, 1, v_dname, 20);
v_rows := DBMS_SQL.EXECUTE(v_cursor);
loop
if DBMS_SQL.FETCH_ROWS(v_cursor) = 0 then
exit;
end if;
DBMS_SQL.COLUMN_VALUE_CHAR(v_cursor, 1, v_dname);
DBMS_OUTPUT.PUT_LINE(Deptartment name: ||v_dname);
end loop;
DBMS_SQL.CLOSE_CURSOR(v_cursor);
EXCEPTION
when others then
DBMS_SQL.CLOSE_CURSOR(v_cursor);
raise_application_error(-20000, Unknown Exception Raised: ||sqlcode|| ||sqlerrm);
END;
/
Q: What is the difference between %TYPE and %ROWTYPE?

Both %TYPE and %ROWTYPE are used to define variables in PL/SQL as it is defined within the
database. If the datatype or precision of a column changes, the program automatically picks up the
new definition from the database without having to make any code changes.
The %TYPE and %ROWTYPE constructs provide data independence, reduces maintenance costs,
and allows programs to adapt as the database changes to meet new business needs.
%TYPE
%TYPE is used to declare a field with the same type as that of a specified tables column. Example:
DECLARE
v_EmpName emp.ename%TYPE;
BEGIN
SELECT ename INTO v_EmpName FROM emp WHERE ROWNUM = 1;
DBMS_OUTPUT.PUT_LINE(Name = || v_EmpName);
END;
/
%ROWTYPE
%ROWTYPE is used to declare a record with the same types as found in the specified database
table, view or cursor. Examples:
DECLARE
v_emp emp%ROWTYPE;
BEGIN
v_emp.empno := 10;
v_emp.ename := XXXXXXX';
END;
/
Q: How does one get the value of a sequence into a PL/SQL variable?
As you might know, one cannot use sequences directly from PL/SQL; Oracle prohibits this:
i := sq_sequence.NEXTVAL;
However, one can use embedded SQL statements to obtain sequence values:
select sq_sequence.NEXTVAL into :i from dual;

This restriction has been removed in oracle 11g and the former syntax can be used.
Q: Can one execute an operating system command from PL/SQL?
There is no direct way to execute operating system commands from PL/SQL. PL/SQL doesnt have a
host command, as with SQL*Plus, that allows users to call OS commands. Nevertheless, the
following workarounds can be used:
Database Pipes
Write an external program (using one of the precompiler languages, OCI or Perl with Oracle access
modules) to act as a listener on a database pipe (SYS.DBMS_PIPE). Your PL/SQL program then put
requests to run commands in the pipe, the listener picks it up and run the requests. Results are
passed back on a different database pipe. For an Pro*C example, see chapter 8 of the Oracle
Application Developers Guide.
CREATE OR REPLACE FUNCTION host_command( cmd IN VARCHAR2 )
RETURN INTEGER IS
status NUMBER;
errormsg VARCHAR2(80);
pipe_name VARCHAR2(30);
BEGIN
pipe_name := HOST_PIPE';
dbms_pipe.pack_message( cmd );
status := dbms_pipe.send_message(pipe_name);
RETURN status;
END;
/
External Procedure Listeners:
From Oracle 8 one can call external 3GL code in a dynamically linked library (DLL or shared object).
One just write a library in C/ C++ to do whatever is required. Defining this C/C++ function to PL/SQL
makes it executable. Look at this External Procedure example.
Using Java
See example at http://www.orafaq.com/scripts/plsql/oscmd.txt
DBMS_SCHEDULER

In Oracle 10g and above, one can execute OS commands via the DBMS_SCHEDULER package.
Look at this example:
BEGIN
dbms_scheduler.create_job(job_name
job_type

=> executable,

job_action

=> /app/oracle/x.sh,

enabled

=> TRUE,

auto_drop

=> myjob,

=> TRUE);

END;
/
exec dbms_scheduler.run_job(myjob);
Q: How does one loop through tables in PL/SQL?
One can make use of cursors to loop through data within tables. Look at the following nested loops
code example.
DECLARE
CURSOR dept_cur IS
SELECT deptno
FROM dept
ORDER BY deptno;
Employee cursor all employees for a dept number
CURSOR emp_cur (v_dept_no DEPT.DEPTNO%TYPE) IS
SELECT ename
FROM emp
WHERE deptno = v_dept_no;
BEGIN
FOR dept_rec IN dept_cur LOOP
dbms_output.put_line(Employees in Department ||TO_CHAR(dept_rec.deptno));
FOR emp_rec in emp_cur(dept_rec.deptno) LOOP

dbms_output.put_line(Employee is ||emp_rec.ename);
END LOOP;
END LOOP;
END;
/
Q: How often should one COMMIT in a PL/SQL loop? / What is the best commit strategy?
Contrary to popular belief, one should COMMIT less frequently within a PL/SQL loop to prevent ORA1555 (Snapshot too old) errors. The higher the frequency of commit, the sooner the extents in the
undo/ rollback segments will be cleared for new transactions, causing ORA-1555 errors.
To fix this problem one can easily rewrite code like this:
FOR records IN my_cursor LOOP
do some stuff
COMMIT;
END LOOP;
COMMIT;
to
FOR records IN my_cursor LOOP
do some stuff
i := i+1;
IF mod(i, 10000) = 0 THEN

Commit every 10000 records

COMMIT;
END IF;
END LOOP;
COMMIT;
If you still get ORA-1555 errors, contact your DBA to increase the undo/ rollback segments.
NOTE: Although fetching across COMMITs work with Oracle, is not supported by the ANSI standard.
Q: I can SELECT from SQL*Plus but not from PL/SQL. What is wrong?

PL/SQL respect object privileges given directly to the user, but does not observe privileges given
through roles. The consequence is that a SQL statement can work in SQL*Plus, but will give an error
in PL/SQL. Choose one of the following solutions:
Grant direct access on the tables to your user. Do not use roles!
GRANT select ON scott.emp TO my_user;
Define your procedures with invoker rights (Oracle 8i and higher);
create or replace procedure proc1
authid current_user is
begin

Move all the tables to one user/schema.


Q: What is a mutating and constraining table?
Mutating means changing. A mutating table is a table that is currently being modified by an update,
delete, or insert statement. When a trigger tries to reference a table that is in state of flux (being
changed), it is considered mutating and raises an error since Oracle should not return data that has
not yet reached its final state.
Another way this error can occur is if the trigger has statements to change the primary, foreign or
unique key columns of the table off which it fires. If you must have triggers on tables that have
referential constraints, the workaround is to enforce the referential integrity through triggers as well.
There are several restrictions in Oracle regarding triggers:
A row-level trigger cannot query or modify a mutating table. (Of course, NEW and OLD still can be
accessed by the trigger).
A statement-level trigger cannot query or modify a mutating table if the trigger is fired as the result of a
CASCADE delete.
Etc.
Q: Can one pass an object/table as an argument to a remote procedure?
The only way to reference an object type between databases is via a database link. Note that it is not
enough to just use similar type definitions. Look at this example:
Database A: receives a PL/SQL table from database B
CREATE OR REPLACE PROCEDURE pcalled(TabX DBMS_SQL.VARCHAR2S) IS
BEGIN
do something with TabX from database B

null;
END;
/
Database B: sends a PL/SQL table to database A
CREATE OR REPLACE PROCEDURE pcalling IS
TabX DBMS_SQL.VARCHAR2S@DBLINK2;
BEGIN
pcalled@DBLINK2(TabX);
END;
/
Q: What is the difference between stored procedures and functions?
Functions MUST return a value, procedures dont need to.
You can have DML (insert,update, delete) statements in a function. But, you cannot call such a
function in a SQL query. For example, if you have a function that is updating a table, you cannot call
that function from a SQL query.
select myFunction(field) from sometable; will throw error.
However an autonomous transaction function can.
You cannot call a procedure in a SQL query.

Oracle Apps PL-SQL Interview Questions Set 3

Oracle Apps PL-SQL Interview Questions Set 3


Q: Is there a PL/SQL Engine in SQL*Plus?
No. Unlike Oracle Forms, SQL*Plus does not have an embedded PL/SQL engine. Thus, all your
PL/SQL code is sent directly to the database engine for execution. This makes it much more efficient
as SQL statements are not stripped off and sent to the database individually.
Q: Is there a limit on the size of a PL/SQL block?
Yes, the max size is not an explicit byte limit, but related to the parse tree that is created when you
compile the code. You can run the following select statement to query the size of an existing package
or procedure:

SQL> select * from dba_object_size where name = procedure_name';


Q: What are the PL/SQL compiler limits for block, record, subquery and label nesting?
The following limits apply:
Level of Block Nesting: 255
Level of Record Nesting: 32
Level of Subquery Nesting: 254
Level of Label Nesting: 98
Q: Can one COMMIT/ ROLLBACK from within a trigger?
A commit inside a trigger would defeat the basic definition of an atomic transaction (see ACID).
Trigger logic is by definition an extension of the original DML operation. Changes made within triggers
should thus be committed or rolled back as part of the transaction in which they execute. For this
reason, triggers are NOT allowed to execute COMMIT or ROLLBACK statements (with the exception
of autonomous triggers). Here is an example of what will happen when they do:
SQL> CREATE TABLE tab1 (col1 NUMBER);
Table created.
SQL> CREATE TABLE log (timestamp DATE, operation VARCHAR2(2000));
Table created.
SQL> CREATE TRIGGER tab1_trig
AFTER insert ON tab1
BEGIN
INSERT INTO log VALUES (SYSDATE, Insert on TAB1);
COMMIT;
END;
/
Trigger created.
SQL> INSERT INTO tab1 VALUES (1);
INSERT INTO tab1 VALUES (1)
*
ERROR at line 1:

ORA-04092: cannot COMMIT in a trigger


ORA-06512: at SCOTT.TAB1_TRIG, line 3
ORA-04088: error during execution of trigger SCOTT.TAB1_TRIG
Autonomous transactions:
As workaround, one can use autonomous transactions. Autonomous transactions execute separate
from the current transaction.
Unlike regular triggers, autonomous triggers can contain COMMIT and ROLLBACK statements.
Example:
SQL> CREATE OR REPLACE TRIGGER tab1_trig
AFTER insert ON tab1
DECLARE
PRAGMA AUTONOMOUS_TRANSACTION;
BEGIN
INSERT INTO log VALUES (SYSDATE, Insert on TAB1);
COMMIT; only allowed in autonomous triggers
END;
/
Trigger created.
SQL> INSERT INTO tab1 VALUES (1);
1 row created.
Note that with the above example will insert and commit log entries even if the main transaction is
rolled-back!
Retrieved from http://www.orafaq.com/wiki/PL/SQL_FAQ
You might have got a good idea about PL-SQL already. In that case, maybe you wouldnt need to
refer the below sections. This is another reference from Wikipedia about PL-SQL.
PL/SQL (Procedural Language/Structured Query Language) is Oracle Corporations proprietary
procedural extension to the SQL database language, used in the Oracle database. Some other SQL
database management systems offer similar extensions to the SQL language. PL/SQLs syntax
strongly resembles that of Ada, and just like some Ada compilers of the 1980s, the PL/SQL runtime
system uses Diana as intermediate representation.
The key strength of PL/SQL is its tight integration with the Oracle database.

PL/SQL is one of three languages embedded in the Oracle Database, the other two being SQL and
Java.
Contents
1 Functionality
2 Basic code structure
2.1 Functions
2.2 Procedures
2.3 Anonymous Blocks
2.4 Packages
2.5 Numeric variables
2.6 Character variables
2.7 Date variables
2.8 Datatypes for specific columns
3 Conditional Statements
4 Array handling
5 Looping
5.1 LOOP statements
5.2 FOR loops
5.3 Cursor FOR loops
5.3.1 Example
6 Similar languages
7 See also
8 References
9 External links
Q: Functionality

PL/SQL supports variables, conditions, loops, arrays (in somewhat unusual way) and exceptions.
Implementations from version 8 of Oracle Database onwards have included features associated with

object-orientation. PL/SQL, however, as a Turing-complete procedural language that fills in these


gaps, allows Oracle database developers to interface with the underlying relational database in an
imperative manner. SQL statements can make explicit in-line calls to PL/SQL functions, or can cause
PL/SQL triggers to fire upon pre-defined Data Manipulation Language (DML) events.
PL/SQL stored procedures (functions, procedures, packages, and triggers) performing DML will get
compiled into an Oracle database: to this extent, their SQL code can undergo syntax-checking.
Programmers working in an Oracle database environment can construct PL/SQL blocks of
functionality to serve as procedures, functions; or they can write in-line segments of PL/SQL within
SQL*Plus scripts.
While programmers can readily incorporate SQL DML statements into PL/SQL (as cursor definitions,
for example, or using the SELECT INTO syntax), Data Definition Language (DDL) statements such
as CREATE TABLE/DROP INDEX etc. require the use of Dynamic SQL. Earlier versions of Oracle
Database required the use of a complex built-in DBMS_SQL package for Dynamic SQL where the
system needed to explicitly parse and execute an SQL statement. Later versions have included an
EXECUTE IMMEDIATE syntax called Native Dynamic SQL which considerably simplifies matters.
Any use of DDL in an Oracle database will result in an implicit COMMIT. Programmers can also use
Dynamic SQL to execute DML where they do not know the exact content of the statement in advance.
PL/SQL offers several pre-defined packages for specific purposes. Such PL/SQL packages include:
DBMS_OUTPUT for output operations to non-database destinations
DBMS_JOB for running specific procedures/functions at a particular time (i.e. scheduling)
DBMS_XPLAN for formatting Explain Plan output
DBMS_SESSION provides access to SQL ALTER SESSION and SET ROLE statements, and other
session information.
DBMS_METADATA for extracting meta data from the data dictionary (such as DDL statements)
DBMS_EPG for managing the built-in webserver (Embedded PL/SQL Gateway) in the database
UTL_FILE for reading and writing files on disk
UTL_HTTP for making requests to web servers from the database
UTL_SMTP for sending mail from the database (via an SMTP server)
and many more Oracle Corporation customarily adds more packages and/or extends package
functionality with each successive release of Oracle Database.
Q: Basic code structure
Anonymous blocks are the basis of standalone PL/SQL scripts, and have the following structure:
<<label>>
DECLARE
TYPE / item / FUNCTION / PROCEDURE declarations

BEGIN
Statements
EXCEPTION
EXCEPTION handlers
END label;
The <<label>> and the DECLARE and EXCEPTION sections are optional.
Exceptions, errors which arise during the execution of the code, have one of two types:
Predefined exceptions
User-defined exceptions.
User-defined exceptions are always raised explicitly by the programmers, using the RAISE or
RAISE_APPLICATION_ERROR commands, in any situation where they have determined that it is
impossible for normal execution to continue. RAISE command has the syntax:
RAISE <exception name>;
Oracle Corporation has pre-defined several exceptions like NO_DATA_FOUND, TOO_MANY_ROWS,
etc. Each exception has a SQL Error Number and SQL Error Message associated with it.
Programmers can access these by using the SQLCODE and SQLERRM functions.
The DECLARE section defines and (optionally) initialises variables. If not initialised specifically, they
default to NULL.
For example:
DECLARE
number1 NUMBER(2);
number2 NUMBER(2)

:= 17;

value default

text1 VARCHAR2(12) := Hello world';


text2 DATE

:= SYSDATE;

BEGIN
SELECT street_number
INTO number1
FROM address
WHERE name = BILLA';

current date and time

END;
The symbol := functions as an assignment operator to store a value in a variable.
The major datatypes in PL/SQL include NUMBER, INTEGER, CHAR, VARCHAR2, DATE,
TIMESTAMP, TEXT etc.
Q: Functions
Functions in PL/SQL are a collection of SQL and PL/SQL statements that perform a task and should
return a value to the calling environment.
CREATE OR REPLACE FUNCTION <function_name> [(input/output variable declarations)] RETURN
return_type
<IS|AS>
[declaration block]
BEGIN
<PL/SQL block WITH RETURN statement>
[EXCEPTION
EXCEPTION block]
END;
Q: Procedures
Procedures are the same as Functions, in that they are also used to perform some task with the
difference being that procedures cannot be used in a SQL statement and although they can have
multiple out parameters they do not return a value. This is not always true for when an NVL function
is used.
Q: Anonymous Blocks
Anonymous PL/SQL blocks can be embedded in an Oracle Precompiler or OCI program. At run time,
the program, lacking a local PL/SQL engine, sends these blocks to the Oracle server, where they are
compiled and executed. Likewise, interactive tools such as SQL*Plus and Enterprise Manager, lacking
a local PL/SQL engine, must send anonymous blocks to Oracle.
Q: Packages
Packages are groups of conceptually linked Functions, Procedures,Variable,Constants & Cursors etc.
The use of packages promotes re-use of code. Packages usually have two parts, a specification and
a body, although sometimes the body is unnecessary. The specification (spec for short) is the
interface to your applications; it declares the types, variables, constants, exceptions, cursors, and
subprograms available for use. The body fully defines cursors and subprograms, and so implements
the spec.

Oracle Apps PL-SQL Interview Questions Set 4

Oracle Apps PL-SQL Interview Questions Set 4


Q: Numeric variables
variable_name NUMBER(P[,S]) := VALUE;
To define a numeric variable, the programmer appends the variable type NUMBER to the name
definition. To specify the (optional) precision(P) and the (optional) scale (S), one can further append
these in round brackets, separated by a comma. (Precision in this context refers to the number of
digits which the variable can hold, scale refers to the number of digits which can follow the decimal
point.)
A selection of other datatypes for numeric variables would include: binary_float, binary_double, dec,
decimal, double precision, float, integer, int, numeric, real, smallint, binary_integer
Q: Character variables
variable_name varchar2(L) := Text';
To define a character variable, the programmer normally appends the variable type VARCHAR2 to the
name definition. There follows in brackets the maximum number of characters which the variable can
store.
Other datatypes for character variables include:
varchar, char, long, raw, long raw, nchar, nchar2, clob, blob, bfile
Q: Date variables
variable_name date := 01-Jan-2005;
Oracle provides a number of data types that can store dates (DATE, DATETIME, TIMESTAMP etc.),
however DATE is most commonly used.
Programmers define date variables by appending the datatype code DATE to a variable name. The
TO_DATE function can be used to convert strings to date values. The function converts the first
quoted string into a date, using as a definition the second quoted string, for example:
TO_DATE(31-12-2004,dd-mm-yyyy)
or
TO_DATE (31-Dec-2004,dd-mon-yyyy, NLS_DATE_LANGUAGE = American)
To convert the dates to strings one uses the function TO_CHAR (date_string, format_string).
PL/SQL also supports the use of ANSI date and interval literals.[1] The following clause gives an 18month range:

WHERE dateField BETWEEN DATE 2004-12-31 INTERVAL 1-6 YEAR TO MONTH


AND DATE 2004-12-31
Q: Datatypes for specific columns
Variable_name Table_name.Column_name%type;
This syntax defines a variable of the type of the referenced column on the referenced tables.
Programmers specify user-defined datatypes with the syntax:
type data_type is record (field_1 type_1 :=xyz, field_2 type_2 :=xyz, , field_n type_n :=xyz);
For example:
DECLARE
TYPE t_address IS RECORD (
name address.name%TYPE,
street address.street%TYPE,
street_number address.street_number%TYPE,
postcode address.postcode%TYPE);
v_address t_address;
BEGIN
SELECT name, street, street_number, postcode INTO v_address FROM address WHERE ROWNUM
= 1;
END;
This sample program defines its own datatype, called t_address, which contains the fields name,
street, street_number and postcode.
so according the example we are able to copy the data from database to the fields in program. Using
this datatype the programmer has defined a variable called v_address and loaded it with data from the
ADDRESS table.
Programmers can address individual attributes in such a structure by means of the dot-notation, thus:
v_address.street := High Street';
Q: Conditional Statements
The following code segment shows the IF-THEN-ELSIF construct. The ELSIF and ELSE parts are
optional so it is possible to create simpler IF-THEN or, IF-THEN-ELSE constructs.
IF x = 1 THEN

sequence_of_statements_1;
ELSIF x = 2 THEN
sequence_of_statements_2;
ELSIF x = 3 THEN
sequence_of_statements_3;
ELSIF x = 4 THEN
sequence_of_statements_4;
ELSIF x = 5 THEN
sequence_of_statements_5;
ELSE
sequence_of_statements_N;
END IF;
The CASE statement simplifies some large IF-THEN-ELSE structures.
CASE
WHEN x = 1 THEN sequence_of_statements_1;
WHEN x = 2 THEN sequence_of_statements_2;
WHEN x = 3 THEN sequence_of_statements_3;
WHEN x = 4 THEN sequence_of_statements_4;
WHEN x = 5 THEN sequence_of_statements_5;
ELSE sequence_of_statements_N;
END CASE;
CASE statement can be used with predefined selector:
CASE x
WHEN 1 THEN sequence_of_statements_1;
WHEN 2 THEN sequence_of_statements_2;
WHEN 3 THEN sequence_of_statements_3;
WHEN 4 THEN sequence_of_statements_4;

WHEN 5 THEN sequence_of_statements_5;


ELSE sequence_of_statements_N;
END CASE;
Q: Array handling
PL/SQL refers to arrays as collections. The language offers three types of collections:
Index-by tables (associative arrays)
Nested tables
Varrays (variable-size arrays)
Programmers must specify an upper limit for varrays, but need not for index-by tables or for nested
tables. The language includes several collection methods used to manipulate collection elements: for
example FIRST, LAST, NEXT, PRIOR, EXTEND, TRIM, DELETE, etc. Index-by tables can be used to
simulate associative arrays, as in this example of a memo function for Ackermanns function in
PL/SQL.
Q: Looping
As a procedural language by definition, PL/SQL provides several iteration constructs, including basic
LOOP statements, WHILE loops, FOR loops, and Cursor FOR loops.
Q: LOOP statements
Syntax:
<<parent_loop>>
LOOP
statements

<<child_loop>>
LOOP
statements
EXIT parent_loop WHEN <condition>; Terminates both loops
EXIT WHEN <condition>; Returns control to parent_loop
END LOOP;

EXIT WHEN <condition>;


END LOOP parent_loop;
Loops can be terminated by using the EXIT keyword, or by raising an exception.
Q: FOR loops
Q: Cursor FOR loops
FOR RecordIndex IN (SELECT person_code FROM people_table)
LOOP
DBMS_OUTPUT.PUT_LINE(RecordIndex.person_code);
END LOOP;
Cursor-for loops automatically open a cursor, read in their data and close the cursor again
As an alternative, the PL/SQL programmer can pre-define the cursors SELECT-statement in advance
in order (for example) to allow re-use or to make the code more understandable (especially useful in
the case of long or complex queries).
DECLARE
CURSOR cursor_person IS
SELECT person_code FROM people_table;
BEGIN
FOR RecordIndex IN cursor_person
LOOP
DBMS_OUTPUT.PUT_LINE(RecordIndex.person_code);
END LOOP;
END;
The concept of the person_code within the FOR-loop gets expressed with dot-notation (.):
RecordIndex.person_code
Q: Example
DECLARE
var NUMBER;
BEGIN

/*N.B. for loop variables in pl/sql are new declarations, with scope only inside the loop */
FOR var IN 0 10 LOOP
DBMS_OUTPUT.put_line(var);
END LOOP;

IF (var IS NULL) THEN


DBMS_OUTPUT.put_line(var is null);
ELSE
DBMS_OUTPUT.put_line(var is not null);
END IF;
END;
Output:
0
1
2
3
4
5
6
7
8
9
10
var is null
Q: Similar languages
PL/SQL functions analogously to the embedded procedural languages associated with other relational
databases. Sybase ASE and Microsoft SQL Server have Transact-SQL, PostgreSQL has PL/pgSQL

(which tries to emulate PL/SQL to an extent), and IBM DB2 includes SQL Procedural Language,[2]
which conforms to the ISO SQLs SQL/PSM standard.
The designers of PL/SQL modelled its syntax on that of Ada. Both Ada and PL/SQL have Pascal as a
common ancestor, and so PL/SQL also resembles Pascal in numerous aspects. The structure of a
PL/SQL package closely resembles the basic Pascal program structure or a Borland Delphi unit.
Programmers can define global data-types, constants and static variables, public and private, in a
PL/SQL package.
PL/SQL also allows for the definition of classes and instantiating these as objects in PL/SQL code.
This resembles usages in object-oriented programming languages like Object Pascal, C++ and Java.
PL/SQL refers to a class as an Advanced Data Type (ADT) or User Defined Type(UDT), and
defines it as an Oracle SQL data-type as opposed to a PL/SQL user-defined type, allowing its use in
both the Oracle SQL Engine and the Oracle PL/SQL engine. The constructor and methods of an
Advanced Data Type are written in PL/SQL. The resulting Advanced Data Type can operate as an
object class in PL/SQL. Such objects can also persist as column values in Oracle database tables.
PL/SQL does not resemble Transact-SQL, despite superficial similarities. Porting code from one to the
other usually involves non-trivial work, not only due to the differences in the feature sets of the two
languages, but also due to the very significant differences in the way Oracle and SQL Server deal with
concurrency and locking.
The Fyracle project aims to enable the execution of PL/SQL code in the open-source Firebird
database.

Oracle Apps PL-SQL Interview Questions Set 5

Oracle Apps PL-SQL Interview Questions Set 5


1- Difference b/w procedure and function? A procedure may return (one or more values using OUT &
INOUT Parameters) or may not return a value. But a function has to return a single value and has the
return clause in its definition. Function can be called in select statements but procedure can only be
called in a pl/sql block. Procedures parameters can have IN or OUT or INOUT parameters. But
functions parameters can only have IN parameters.
2.

Difference b/w ROWID and ROWNUM? ROWID : It gives the hexadecimal string
representing the address of a row.It gives the location in database where row is physically
stored. ROWNUM: It gives a sequence number in which rows are retrieved from the database.
3.
Give some examples of pseudo columns? NEXTVAL, CURRVAL, LEVEL, SYSDATE
4.
Difference b/w implicit cursor and explicit cursor? Implicit cursors are automatically
created by oracle for all its DML stmts. Examples of implicit cursors: SQL%FOUND, SQL
%NOTFOUND, SQL%ROWCOUNT, SQL%ISOPEN; Explicit cursors are created by the users for
multi row select stmts.
5.
How to create a table in a procedure or function? See the below piece of code: Since
create stmt can be used only at the sql prompt, we have used dynamic sql to create a table.
DECLARE
L_STMT VARCHAR2(100);
BEGIN
DBMS_OUTPUT.PUT_LINE(STARTING );

L_STMT := create table dummy1 (X VARCHAR2(10) , Y NUMBER)';


EXECUTE IMMEDIATE L_STMT;
DBMS_OUTPUT.PUT_LINE(end );
END;
The above piece of code can be written In procedure and function DDLs can be used in function
provided that function should be invoked in Begin-End block not from Select statement.

6.

Explain the usage of WHERE CURRENT OF clause in cursors ?Look at the following
pl/sql code:
DECLARE
CURSOR wip_cur IS
SELECT acct_no, enter_date
FROM wip
WHERE enter_date < SYSDATE -7
FOR UPDATE;
BEGIN
FOR wip_rec IN wip_cur
LOOP
INSERT INTO acct_log (acct_no, order_date)
VALUES (wip_rec.acct_no, wip_rec.enter_date);

DELETE FROM wip


WHERE CURRENT OF wip_cur;
END LOOP;
END;
WHERE CURRENT OF has to be used in concurrence with FOR UPDATE in the cursor select
stmt.
WHERE CURRENT OF used in delete or update stmts means, delete/update the current record
specified by the cursor.

By using WHERE CURRENT OF, you do not have to repeat the WHERE clause in the SELECT
statement.

7.

What is the purpose of FORUPDATE? Selecting in FOR UPDATE mode locks the result set
of rows in update mode, which means that row cannot be updated or deleted until a commit or
rollback is issued which will release the row(s). If you plan on updating or deleting records that have
been referenced by a Select For Update statement, you can use the Where Current Of statement.
8.
What is RAISE_APPLICATION_ERROR? The RAISE_APPLICATION_ERROR is a
procedure defined by Oracle that allows the developer to raise an exception and associate an error
number and message with the procedure other than just Oracle errors. Raising an Application Error
With raise_application_error
DECLARE
num_tables NUMBER;
BEGIN
SELECT COUNT(*) INTO num_tables FROM USER_TABLES;
IF num_tables < 1000 THEN
/* Issue your own error code (ORA-20101) with your own error message.
Note that you do not need to qualify raise_application_error with
DBMS_STANDARD */
raise_application_error(-20101, Expecting at least 1000 tables);
ELSE
NULL; Do the rest of the processing (for the non-error case).
END IF;
END;
/
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.
9.

What is mutating error? Mutating error occurs in the following scenario:


WHEN WE ARE UPDATING A TABLE (TRIGGER WRITTEN ON A TABLE FOR UPDATE) AND AT
THE SAME TIME TRYING TO RETRIEVE DATA FROM THAT TABLE. IT WILL RESULT INTO
MUTATING TABLE AND IT WILL RESULT INTO MUTATING ERROR.

10. Can we have commit/rollback in DB triggers? Having Commit / Rollback inside a trigger
defeats the standard of whole transactions commit / rollback all together. Once trigger execution is
complete then only a transaction can be said as complete and then only commit should take place. If
we still want to carry out some action which should be initiated from trigger but should be committed
irrespective of trigger completion / failure we can have AUTONOMUS TRANSACTION. Inside
Autonomous transaction block we can have Commit and it will act as actual commit.
11. Can we make the trigger an autonomous transaction? This makes all the difference because
within the autonomous transaction (the trigger), Oracle will view the triggering table as it was before
any changes occurredthat is to say that any changes are uncommitted and the autonomous
transaction doesnt see them. So the potential confusion Oracle normally experiences in a mutating
table conflict doesnt exist.
12. What is autonomous transaction? Autonomous transaction means a transaction that is
embedded in some other transaction, but functions independently.
13. What is a REF Cursor? The REF CURSOR is a data type in the Oracle PL/SQL language. It
represents a cursor or a result set in Oracle Database
14. What is the difference between ref cursors and normal pl/sql cursors?
Declare
type rc is ref cursor;
cursor c is
select * from dual;
l_cursor rc;
begin
if ( to_char(sysdate,dd) = 30 ) then
open l_cursor
for select * from emp;
elsif ( to_char(sysdate,dd) = 29 ) then
open l_cursor
for select * from dept;
else
open l_cursor
for select * from dual;
end if;

open c;
end;
Given that block of code you see perhaps the most salient difference, no matter how many times
you run that block The cursor C will always be select * from dual. The ref cursor can be anything.
15. Is Truncate a DDL or DML statement? And why? Truncate is a DDL statement. Check the
LAST_DDL_TIME on USER_OBJECTS after truncating your table. TRUNCATE will automatically
commit, and its not rollback able. This changes the storage definition of the object. Thats why it is a
DDL.
16. What are the actions you have to perform when you drop a package? If you rename a
package, the other packages that use it will have to be MODIFIED. A simple compilation of the new
renamed package wont do. If you have toad, go to the used by tab that will show you the packages
that call the package being renamed.
17. What is cascading triggers? When a trigger fires, a SQL statement within its trigger action
potentially can fire other triggers, resulting in cascading triggers.
18. What are materialized views? A materialized view is a database object that stores the results of
a query (possibly from a remote database). Materialized views are sometimes referred to as
snapshots.
Example
If the materialized view will access remote database objects, we need to start by creating a database
link to the remote DB:

CREATE DATABASE LINK remotedb


CONNECT TO scott IDENTIFIED BY tiger
USING orcl';

Now we can create the materialized view to pull in data (in this example, across the database link):

CREATE MATERIALIZED VIEW items_summary_mv


ON PREBUILT TABLE
REFRESH FORCE AS
SELECT a.PRD_ID, a.SITE_ID, a.TYPE_CODE, a.CATEG_ID,
sum(a.GMS)

GMS,

sum(a.NET_REV) NET_REV,
sum(a.BOLD_FEE) BOLD_FEE,
sum(a.BIN_PRICE) BIN_PRICE,
sum(a.GLRY_FEE) GLRY_FEE,
sum(a.QTY_SOLD) QTY_SOLD,
count(a.ITEM_ID) UNITS
FROM items@remotedb a
GROUP BY a.PRD_ID, a.SITE_ID, a.TYPE_CODE, a.CATEG_ID;

Materialized view logs:


Materialized view logs are used to track changes (insert, update and delete) to a table. Remote
materialized views can use the log to speed-up data replication by only transferring changed records.
Example:
CREATE MATERIALIZED VIEW LOG ON items
19. Commonly occurring Errors in Reports?
Some of the errors are defined below
1.
2.
3.
4.
5.

There Exists uncompiled unit: When the report is not compiled before loading in the Oracle
Applications.
Report File not found: When the rdf is not uploaded in proper directory
Width or margin is zero: When the repeating frame is not within proper frames
Not in proper group: When the repeating frame is not referred to proper group
What is the difference between Compile and Incremental Compile in oracle reports?
In Full compile all the PL/SQL within the reports are compiled but in incremental compile only the
changed PL/SQL units are compiled.
When compiling the report for the first time, we should do the full compilation and not the Incremental
compile.
20. How to compile Procedures and Packages?
ALTER <proc/package> <name>COMPILE;

Oracle Apps PL-SQL Interview Questions Set 6

Oracle Apps PL-SQL Interview Questions Set 6


Explain the difference between trigger and stored procedure.
Trigger in act which is performed automatically before or after a event occur
Stored procedure is a set of functionality which is executed when it is explicitly invoked.
Explain Row level and statement level trigger.
Row-level: They get fired once for each row in a table affected by the statements.
Statement: They get fired once for each triggering statement.
Advantage of a stored procedure over a database trigger
Firing of a stored procedure can be controlled whereas on the other hand trigger will get fired
whenever any modification takes place on the table.
What are cascading triggers?
A Trigger that contains statements which cause invoking of other Triggers are known as cascading
triggers. Heres the order of execution of statements in case of cascading triggers:

Execute all BEFORE statement triggers that apply to the current statement.
Loop for each row affected statement.
Execute all BEFORE row triggers that apply to the current statement in the loop.
Lock and change row, perform integrity constraints check; release lock.
Execute all AFTER row triggers that apply to the current statement.
Execute all AFTER statement triggers that apply to the current statement.
What is a JOIN? Explain types of JOIN in oracle.
A JOIN is used to match/equate different fields from 2 or more tables using primary/foreign keys.
Output is based on type of Join and what is to be queries i.e. common data between 2 tables, unique
data, total data, or mutually exclusive data.
Types of JOINS:
JOIN Type
Simple JOIN

Description
Find name and
department name of
students who have
been allotted a
department
Inner/Equi/Natural JOIN
SELECT * from Emp INNER JOIN Extracts data that
Dept WHERE
meets the JOIN
Emp.empid=Dept.empid
conditions only. A
JOIN is by default
INNER unless
OUTER keyword is
specified for an
OUTER JOIN.
Outer Join
SELECT distinct * from Emp LEFT It includes non
OUTER JOIN Dept Where
matching rows also
Emp.empid=Dept.empid
unlike Inner Join.
Self JOIN
SELECT a.name,b.name from emp a, Joining a Table to
emp b WHERE a.id=b.rollNumber itself.
What is object data type in oracle?
New/User defined objects can be created from any database built in types or by their combinations. It
makes it easier to work with complex data like images, media (audio/video). An object types is just an
abstraction of the real world entities. An object has:

Name

Example
SELECT p.last_name, t.deptName
FROM person p, dept t
WHERE p.id = t.id;

Attributes
Methods
Example:
Create type MyName as object (first varchar2(20), second varchar2(20));
Now you can use this datatype while defining a table below:
Create table Emp (empno number(5),Name MyName);
One can access the Atributes as Emp.Name.First and Emp.Name.Second
What is composite data type?
Composite data types are also known as Collections .i.e RECORD, TABLE, NESTED TABLE,
VARRAY.
Composite data types are of 2 types:
PL/SQL RECORDS
PL/SQL Collections- Table, Varray, Nested Table
Differences between CHAR and NCHAR in Oracle
NCHAR allow storing of Unicode data in the database. One can store Unicode characters regardless
of the setting of the database characterset
Differences between CHAR and VARCHAR2 in Oracle
CHAR is used to store fixed length character strings where as Varchar2 can store variable length
character strings. However, for performance sake Char is quit faster than Varchar2.
If we have char name[10] and store abcde, then 5 bytes will be filled with null values, whereas in
case of varchar2 name[10] 5 bytes will be used and other 5 bytes will be freed.
Differences between DATE and TIMESTAMP in Oracle
Date is used to store date and time values including month, day, year, century, hours, minutes and
seconds. It fails to provide granularity and order of execution when finding difference between 2
instances (events) having a difference of less than a second between them.
TimeStamp datatype stores everything that Date stores and additionally stores fractional seconds.
Date: 16:05:14Timestamp: 16:05:14:000
Define CLOB and NCLOB datatypes.
CLOB: Character large object. It is 4GB in length.
NCLOB: National Character large object. It is CLOB datatype for multiple character sets , upto 4GB in
length.
What is the BFILE datatypes?
It refers to an external binary file and its size is limited by the operating system.
What is Varrays?
Varrays are one-dimensional, arrays. The maximum length is defined in the declaration itself. These
can be only used when you know in advance about the maximum number of items to be stored.
For example: One person can have multiple phone numbers. If we are storing this data in the tables,
then we can store multiple phone numbers corresponding to single Name. If we know the maximum
number of phone numbers, then we can use Varrays, else we use nested tables.

What is a cursor? What are its types?


Cursor is used to access the access the result set present in the memory. This result set contains the
records returned on execution of a query.
They are of 2 types:
1.
2.

Explicit
Implicit
Explain the attributes of implicit cursor

1.
2.
3.
4.

%FOUND True, if the SQL statement has changed any rows.


%NOTFOUND True, if record was not fetched successfully.
%ROWCOUNT The number of rows affected by the SQL statement.
%ISOPEN True, if there is a SQL statement being associated to the cursor or the cursor is
open.

Explain the attributes of explicit cursor.

1.
2.
3.
4.

%FOUND True, if the SQL statement has changed any rows.


%NOTFOUND True, if record was not fetched successfully.
%ROWCOUNT The number of rows affected by the SQL statement.
%ISOPEN True, if there is a SQL statement being associated to the cursor or the cursor is
open.

What is the ref cursor in Oracle?

REF_CURSOR allows returning a recordset/cursor from a Stored procedure.


It is of 2 types:
Strong REF_CURSOR: Returning columns with datatype and length need to be known at compile
time.
Weak REF_CURSOR: Structured does not need to be known at compile time.
Syntax till Oracle 9i
create or replace package REFCURSOR_PKG asTYPE WEAK8i_REF_CURSOR IS REF
CURSOR;TYPE STRONG REF_CURSOR IS REF CURSOR RETURN EMP%ROWTYPE;end
REFCURSOR_PKG;
Procedure returning the REF_CURSOR:
create or replace procedure test( p_deptno IN number , p_cursor OUT
REFCURSOR_PKG.WEAK8i_REF_CURSOR)isbeginopen p_cursor FOR select *from empwhere
deptno = p_deptno;end test;
Since Oracle 9i we can use SYS_REFCURSOR
create or replace procedure test( p_deptno IN number,p_cursor OUT
SYS_REFCURSOR)isbeginopen p_cursor FOR select *from empwhere deptno = p_deptno;end test;

For Strong
create or replace procedure test( p_deptno IN number,p_cursor OUT REFCURSOR_PKG.STRONG
REF_CURSOR)isbeginopen p_cursor FOR select *from empwhere deptno = p_deptno;end test;

What are the drawbacks of a cursor?

Cursors allow row by row processing of recordset. For every row, a network roundtrip is made unlike
in a Select query where there is just one network roundtrip. Cursors need more I/O and temp storage
resources, thus it is slower.

What is a cursor variable?

In case of a cursor, Oracle opens an anonymous work area that stores processing information. This
area can be accessed by cursor variable which points to this area. One must define a REF CURSOR
type, and then declare cursor variables of that type to do so.
E.g.:
/* Create the cursor type. */TYPE company_curtype IS REF CURSOR RETURN company
%ROWTYPE; /* Declare a cursor variable of that type. */company_curvar company_curtype;

What is implicit cursor in Oracle?

PL/SQL creates an implicit cursor whenever an SQL statement is executed through the code, unless
the code employs an explicit cursor. The developer does not explicitly declare the cursor, thus, known
as implicit cursor.
E.g.:
In the following UPDATE statement, which gives everyone in the company a 20% raise, PL/SQL
creates an implicit cursor to identify the set of rows in the table which would be affected.
UPDATE empSET salary = salary * 1.2;

Can you pass a parameter to a cursor? Explain with an explain

Parameterized cursor:
/*Create a table*/
create table Employee(
ID VARCHAR2(4 BYTE)NOT NULL,
First_Name VARCHAR2(10 BYTE)
);
/*Insert some data*/
Insert into Employee (ID, First_Name) values (01,Harry);
/*create cursor*/
declare
cursor c_emp(cin_No NUMBER)is select count(*) from employee where id=cin_No;
v_deptNo employee.id%type:=10;
v_countEmp NUMBER;
begin
open c_emp (v_deptNo);
fetch c_emp into v_countEmp;
close c_emp;
end;

/*Using cursor*/
Open c_emp (10);

What is a package cursor?

A Package that returns a Cursor type is a package cursor.


Eg:
Create or replace package pkg_Util is
cursor c_emp is select * from employee;
r_emp c_emp%ROWTYPE;
end;
/*Another package using this package*/
Create or replace package body pkg_aDifferentUtil is
procedure p_printEmps is
begin
open pkg_Util.c_emp;
loop
fetch pkg_Util.c_emp into pkg_Util.r_emp;
exit when pkg_Util.c_emp%NOTFOUND;
DBMS_OUTPUT.put_line(pkg_Util.r_emp.first_Name);
end loop;
close pkg_Util.c_emp;

end;
end;

Explain why cursor variables are easier to use than cursors.

Cursor variables are preferred over a cursor for following reasons:


A cursor variable is not tied to a specific query.
One can open a cursor variable for any query returning the right set of columns. Thus, more flexible
than cursors.
A cursor variable can be passed as a parameter.
A cursor variable can refer to different work areas.

Oracle Apps PL-SQL Interview Questions Set 7

Oracle Apps PL-SQL Interview Questions Set 7


What is locking, advantages of locking and types of locking in oracle?
Locking is a mechanism to ensure data integrity while allowing maximum concurrent access to data. It
is used to implement concurrency control when multiple users access table to manipulate its data at
the same time.
Advantages of locking:
1.
2.

Avoids deadlock conditions


Avoids clashes in capturing the resources
Types of locks:

1.
2.

Read Operations: Select


Write Operations: Insert, Update and Delete
What are transaction isolation levels supported by Oracle?
Oracle supports 3 transaction isolation levels:

1.
2.
3.

Read committed (default)


Serializable transactions
Read only
What is SQL*Loader?
SQL*Loader is a loader utility used for moving data from external files into the Oracle database in
bulk. It is used for high performance data loads.
What is Program Global Area (PGA)?
The Program Global Area (PGA): stores data and control information for a server process in the
memory. The PGA consists of a private SQL area and the session memory.
What is a shared pool?
The shared pool is a key component. The shared pool is like a buffer for SQL statements. It is to
store the SQL statements so that the identical SQL statements do not have to be parsed each time
theyre executed.

What is snapshot in oracle?


A snapshot is a recent copy of a table from db or in some cases, a subset of rows/cols of a table.
They are used to dynamically replicate the data between distributed databases.
What is a synonym?
A synonym is an alternative name tables, views, sequences and other database objects.
What is a schema?
A schema is a collection of database objects. Schema objects are logical structures created by users
to contain data. Schema objects include structures like tables, views, and indexes.
What are Schema Objects?
Schema object is a logical data storage structure. Oracle stores a schema object logically within
a tablespace of the database.
What is a sequence in oracle?
Is a column in a table that allows a faster retrieval of data from the table because this column contains
data which uniquely identifies a row. It is the fastest way to fetch data through a select query. This
column has constraints to achieve this ability. The constraints are put on this column so that the value
corresponding to this column for any row cannot be left blank and also that the value is unique and
not duplicated with any other value in that column for any row.
Difference between a hot backup and a cold backup
Cold backup: It is taken when the database is closed and not available to users. All files of the
database are copied (image copy). The datafiles cannot be changed during the backup as they are
locked, so the database remains in sync upon restore.
Hot backup: While taking the backup, if the database remains open and available to users then this
kind of back up is referred to as hot backup. Image copy is made for all the files. As, the database is
in use the entire time, so there might be changes made when backup is taking place. These changes
are available in log files so the database can be kept in sync
What are the purposes of Import and Export utilities?
Export and Import are the utilities provided by oracle in order to write data in a binary format from the
db to OS files and to read them back.

These utilities are used:


To take backup/dump of data in OS files.
Restore the data from the binary files back to the database.
move data from one owner to another
Difference between ARCHIVELOG mode and NOARCHIVELOG mode
Archivelog mode is a mode in which backup is taken for all the transactions that takes place so as to
recover the database at any point of time.
Noarichvelog mode is in which the log files are not written. This mode has a disadvantage that the
database cannot be recovered when required. It has an advantage over archivelog mode which is
increase in performance.
What are the original Export and Import Utilities?
SQL*Loader, External Tables
What are data pump Export and Import Modes?
It is used for fast and bulk data movement within oracle databases. Data Pump utility is faster than the
original import & export utilities.
What are SQLCODE and SQLERRM and why are they important for PL/SQL developers?

SQLCODE: It returns the error number for the last encountered error.
SQLERRM: It returns the actual error message of the last encountered error.
Explain user defined exceptions in oracle.
A User-defined exception has to be defined by the programmer. User-defined exceptions are declared
in the declaration section with their type as exception. They must be raised explicitly using RAISE
statement, unlike pre-defined exceptions that are raised implicitly. RAISE statement can also be used
to raise internal exceptions.
Exception:
DECLARE
userdefined EXCEPTION;
BEGIN
<Condition on which exception is to be raised>
RAISE userdefined;
EXCEPTION
WHEN userdefined THEN
<task to perform when exception is raised>
END;
Explain the concepts of Exception in Oracle. Explain its type.
Exception is the raised when an error occurs while program execution. As soon as the error occurs,
the program execution stops and the control are then transferred to exception-handling part.
There are two types of exceptions:
1.

Predefined : These types of exceptions are raised whenever something occurs beyond
oracle rules. E.g. Zero_Divide
2.
User defined: The ones that occur based on the condition specified by the user. They must
be raised explicitly using RAISE statement, unlike pre-defined exceptions that are raised implicitly.
How exceptions are raised in oracle?
There are four ways that you or the PL/SQL runtime engine can raise an exception:

Exceptions are raised automatically by the program.


The programmer raises a user defined exceptions.
The programmer raises pre defined exceptions explicitly.
What is tkprof and how is it used?
tkprof is used for diagnosing performance issues. It formats a trace file into a more readable format
for performance analysis. It is needed because trace file is a very complicated file to be read as it
contains minute details of program execution.
What is Oracle Server Autotrace?
It is a utility that provides instant feedback on successful execution of any statement (select, update,
insert, delete). It is the most basic utility to test the performance issues.

Oracle Apps PL-SQL Interview Questions Set 8

Oracle Apps PL-SQL Interview Questions Set 8


1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.
42.
43.
44.

1. From an Employee table, how will you display the record which has a maximum salary?
2. What is the difference between the Primary and Foreign key?
3. How will you delete a particular row from a Table?
4. How will you select unique values from a list of records?
5. What is meant by Join? What are the different types of Joins available? Explain.
6. Overloading of stored procedure is possible in oracle?
7. How to create table with in the procedure or function?
8. what is overloading procedure or overloading function ?
9. what is HASH join?
10. what is SCALAR Queries?
11. what is the use of HASH, LIST partitions?
12. <<labele>> declare a=10 b=20, begin some statements declare a=30 c=40 end; what is
the A value in nested block?
13. cursor types? explain with example programs?
14. what is difference b/w pravite procedures and public procedures?
15. How to export the table data (this table having 18 million records) to .csv file. Please tell
me is there any faster way to export the data.
16. How to get employee name from employee table which is the fiveth highest salary of the
table
17. need to split a string into seperate values. eg. col1 col2 - 100 a,b,c 200
a,x,b,d,e 300 c result: value count - a 2 b 1 c 2 etc.
18. How many levels can subqueries be nested in a FROM clause?
19. what is meant by databases
20. what is the correct way of selection statement a.
select/from/table_name/orderby/groupby/having b. select/from/table_name/groupby/having/orderby
21. Can we have exception part in trigger ?
22. using comand prompt how can import table data and table space with example
23. how can create data base link for tow servers (scott schema) give examples plz
24. if a table is getting updated what happens if a function is called from sql query?
25. There is a sequence with min value 100. I want to alter this sequence to min value as 101.
If the table has already data in the sequence column as 100,101,102 Is it possible to do so ?
26. Write a query to find five highest salaries from EMP table. (there is a column SALARY)
27. what is the difference between cursor FETCH and FOR LOOP ?
28. what will be the output: select 1 from emp union all select 2 from emp;
29. Write a query to find the name of employees those who have joined on Monday.(based on
column hire_date)
30. i have a table eno dno sal 1 10 200 2 10 150 3 10 100 4 20 75 5 20 100 i want to get sal
which is less than the avg sal of thri dept. eno dno sal 2 10 150 3 10 100 4 20 75
31. write a query to find out the no. of employees whose age is less than 25 and max of
salary for the employees belonging to a particular department is less than 20000
32. What is mutating trigger?How to avoid it??
33. can we delete the trigger in a view? if yes why if not why?
34. what is the difference between implicit and explicit trigger
35. how to sort records in sql?
36. can we call a procedure from a function?
37. Talk about views
38. Difference between DBMS and RDBMSCODDs rules
39. Initially question was asked to mention the types of indexes. Then asked about BITMAP
INDEX and B-Tree Index
40. Difference between IN and EXISTS
41. What is Primary Key?
42. how u can find the n row from a table?
43. What is normalization?
44. how can we replace the particular column value of a resulted set of executed query? I
mean write down a sql query to chane the particular columns value of a resulted set of executed
query

45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.

45. Table Student has 3 columns,Student_id,Student_Name & Course_Id. Table Course has 2
columns, Course_Id & Course_Name.Write a query to listdown all the Courses and number of student
in each course.
46. Table Order_Name has a column Order_Date which gives the date & Time at which the
order is passed.Find the table to write a query to find out the latest order.
47. please explain database architecture..
48. what is single byte over head in oracle..?
49. What are wait events. Describe the wait event tables.
50. I have done oracle 10g. I need a project knowledge. So if u please send a project how it
should be done,Or you can send email link. I will be very grateful to u.
51. I have a Employee table with columns ename,eid,salary,deptno. How to retrieve sum of
salary for each deptno?
52. why sql is used as interpreter frequently rather than a compile?
53. Describe the Index, Types of index, At what situation we have used? Which one s better
than others?
54. how many tupples can insert in 1 second in sql
55. What is the default value of CHAR type?
56. I have 2 Databases. How can create a table in particular database? How can i know the
list of tables presented each database?( in oracle 10g)
57. suppose we have a table in which 200 rows. i want to find 101 row ? what the query.
and how we find 4th and 5th highest salary and 1 to 10 highest salary
58. What does select count(1) from tab result?