Sunteți pe pagina 1din 65

Q 1: What are the key differences between SQL and PL SQL?

SQL is a Structured Query Language as opposed to P/L SQL which is a full procedural
language. SQL code is processed one statement block at a time, while P/L SQL code
is executed as a single program at one time. SQL can be within P/L SQL, but P/L SQL
cannot be within SQL.

Q 2: What is the basic structure of PL/SQL?


PL SQL is devided into blocks. These blocks which are the basic unit of codes are
primarily categorized by two types: anonymous blocks and named blocks.

[DECLARE]
Declaration statements;
BEGIN
Execution statements;
[EXCEPTION]
Exception handling statements;
END;
They are called anonymous because they have no names and are not saved in an Oracle
Database.

Header Section is for naming/labeling named blocks. This may or may not be used.
Declaration Section is for declaring variables, cursors, or sub-blocks that will be
used in the Execution Section and Exception Section.
Execution Section block is where runtime code is placed. Statements in this section
are required to exist for the structure to run.
Exception Section contains the exception and error handling of the code.
Essential keywords such as IS, BEGIN, EXCEPTION, and END are vital in the program
for the runtime engine to distinguish each block sections.

Q 3. How is a process of PL/SQL compiled?


Compilation process includes syntax check, bind and p-code generation
processes.Syntax checking checks the PL/SQL codes for compilation errors. When all
errors are corrected, a storage address is assigned to the variables that hold
data. It is called Binding. P-code is a list of instructions for the PL/SQL engine.
P-code is stored in the database for named blocks and is used the next time it is
executed.
Go through this tutorial to learn more about handling PL/SQL errors.

Q 4. Mention what PL/SQL package consists of?


A PL/SQL package consists of
PL/SQL table and record TYPE statements
Procedures and Functions
Cursors
Variables ( tables, scalars, records, etc.) and constants
Exception names and pragmas for relating an error number with an exception
Cursors

Q 5: What are the data types available in PL/SQL?


Data types define the ways to identify the type of data and their associated
operations. There are 4 types of predefined data types explained as follows

Scalar Data Types: A scalar data type is an atomic data type that does not
have any internal components. For example
o CHAR (fixed length character value between 1 and 32,767 characters)
o VARCHAR2 (variable length character value between 1 and 32,767
characters)
o NUMBER ( fixed-decimal, floating-decimal or integer values)
o BOOLEAN ( logical data type for TRUE FALSE or NULL values)
o DATE (stores date and time information)
o LONG (character data of variable length)

Composite Data Types: A composite data type is made up of other data types
and internal components that can be easily used and manipulated. For example
RECORD, TABLE, and VARRAY.

Reference Data Types: A reference data types holds values, called pointers
that designate to other program items or data items. For example REF CURSOR.

Large Object Data Types: A Large Object datatype holds values, called
locators, that defines the location of large objects( such as video clips, graphic
image, etc) stored out of line. For example
o BFILE (Binary file)
o BLOB (Binary large object)
o CLOB ( Character large object)
o NCLOB( NCHAR type large object)

Q 6: Explain the purpose of %TYPE and %ROWTYPE data types with the example?
Answer: %TYPE attribute is useful while declaring a variable that has the same
datatype as a table column.
For example, the variable m_empno has the same data type and size as the column
empno in table emp.
m_empno emp.empno%TYPE;
%ROWTYPE attribute is used to declare a variable to be a record having the same
structure as a row in a table. The row is defined as a record and its fields have
the same names and data types as the columns in the table or view.
For example: dept_rec dept%ROWTYPE;
This declares a record that can store an entire row for DEPT table.

DECLARE
name VARCHAR(50);
firstName name%TYPE;
lastName name%TYPE;
province name%TYPE;
nationality name%TYPE;

emp employees_table%ROWTYPE;
BEGIN
Execution section;
END;

Q 7. What Is The Advantage Of Using The %rowtype Datatype?


The advantages of using the %ROWTYPE datatype to declare variables are given as
follows:
It is useful to retrieve an entire row from a table. If you do not use the
%ROWTYPE datatype, then you have to declare variables for each column separately.
It can be used even if datatype of the table columns is not known
It ensures that datatype of the variable changes dynamically if the
underlying table is altered.

Q 8. Describe few restrictions on using "LONG" data type?


A LONG column is not copied when a table is created using a sub query. A LONG
column cannot be included in a GROUP BY or an ORDER BY clause. Only one LONG column
can be used per table. No constraint can be defined on a LONG column.

Q 9. Explain Conversion function in detail?


Conversion Functions converts a value from one data type to another. Conversion
functions are of two types:
Implicit Data type conversion:
1. VARCHAR2 or CHAR To NUMBER, DATE
2. NUMBER To VARCHAR2
3. DATE To VARCHAR2

Explicit data type conversion:


1. TO_NUMBER
2. TO_CHAR
3. TO_DATE

TO_NUMBER function is used to convert Character string to Number format.


TO_NUMBER function use fx modifier. Format: TO_NUMBER ( char[, ` format_model'] ).
fx modifier specifies the exact matching for the character argument and number
format model of TO_NUMBER function.

TO_CHAR function is used to convert NUMBER or DATE data type to CHARACTER


format. TO_CHAR Function use fm element to remove padded blanks or suppress leading
zeros. TO_CHAR Function formats:TO_CHAR (date, `format_model').Format model must be
enclosed in single quotation marks and is case sensitive.
For ex: Select TO_CHAR (hiredate, `MM/YY') from employee.

TO_DATE function is used to convert Character string to date format. TO_DATE


function use fx modifier which specifies the exact matching for the character
argument and date format model of TO_DATE function. TO_DATE function format:
TO_DATE ( char[, ` format_model'] ).
For ex: Select TO_DATE (`may 24 2007','mon dd rr') from dual;

Q 10. Explain character, number and date function in detail?


Character functions: accept character input and return both character and number
values. Types of character function are:
a) Case-Manipulation Functions: LOWER, UPPER, INITCAP
b) Character-Manipulation Functions: CONCAT, SUBSTR, LENGTH, INSTR,
LPAD/RPAD, TRIM, REPLACE
Number Functions: accept Numeric input and return numeric values. Number Functions
are: ROUND, TRUNC and MOD
Date Functions: operates on values of the Date data type. (All date functions
return a value of DATE data type except the MONTHS_BETWEEN Function, which returns
a number. Date Functions are MONTHS_BETWEEN, ADD_MONTHS, NEXT_DAY, LAST_DAY, ROUND,
TRUNC.

Cursor--------------

Q 11) What do you understand by PL/SQL cursors?


Answer: PL/SQL requires a special capability to retrieve and process more than one
row and that resource is known as Cursors. A cursor is a pointer to the context
area, which is an area of memory containing SQL statements and information for
processing the statements.
PL/SQL Cursor is basically a mechanism under which multiple rows of the data from
the database are selected and then each row or only one row individually processed
inside a PL/SQL program.

Q 12) When a DML statement is executed, in which cursor attributes, the outcome of
the statement is saved?
or
Q) What are the cursor attributes used in PL/SQL?
% ISOPEN - to check whether cursor is open or not
% ROWCOUNT - check the number of rows featched/updated/deleted.
% FOUND - to check whether cursor has fetched any row. True if rows are featched.
% NOT FOUND - to check whether cursor has featched any row. True if no rows are
featched.
These attributes are proceded with SQL for Implict Cursors and with Cursor name for
Explict Cursors.

Q 13) Why is %ISOPEN always false for an implicit cursor?


Answer: An implicit cursor, SQL%ISOPEN attribute is always false because the
implicit cursor is opened for a DML statement and is closed immediately after the
execution of DML statement.

Q 14) What are PL/SQL cursor exceptions?


Answer: The exceptions related to PL/SQL cursors are
CURSOR_ALREADY_OPEN
INVALID_CURSOR

Q 15) Explain the difference between cursor declared in procedures and cursors
declared in the package specification?
Answer: The cursor declared in the procedure is treated as local and thus cannot be
accessed by other procedures.
The cursor declared in the package specification is treated as global
and thus can be accessed by other procedures.

Q 16. When Is The Cursor_already_open Exception Raised?


This exception is raised when the program tries to open an already opened cursor.
The cursor should be closed before it can be opened again.

Q 17. When Is The Row_type_mismatch Exception Raised?


The ROW__TYPE_MISMATCH exception is raised when a host cursor variable and a PL/SQL
cursor variable involved in an assignment have incompatible return types.

Q 18. Can Cursors Be Part Of A Trigger Body?


Yes, cursors can be a part of code in trigger.

Q 19. Write a PL/SQL cursor program which is used to calculate total salary from
emp table without using sum() function?
Declare
cursor c1 is select sal from emp;
v_sal number(10);
n.number(10):=0;
begin
open c1;
loop
fetch c1 into v_sal;
exit when c1%not found;
n:=n+v_sal;
end loop;
dbms_output.put_line(`tool salary is'||' ` ||n);
close c1;
end;
/
Output: total salary is: 36975

Q 20. Write a PL/SQL cursor program to display all employee names and their salary
from emp table by using % not found attributes?
Declare
Cursor c1 is select ename, sal from emp;
v_ename varchar2(10);
v_sal number(10);
begin
open c1;
loop
fetch c1 into v_ename, v_sal;
exist when c1 % notfound;
dbms_output.put_line(v_name ||' `||v_sal);
end loop;
close c1;
end;
/

Q 21. What is the method to find out whether a Cursor is open or not?
The Cursor Status Variable can be used to find out whether the Cursor is open or
not. It is %ISOPEN.

Q 22) Differentiate between syntax errors and runtime errors?


Answer: Syntax errors are the one which can be easily identified by a PL/SQL
compiler. These errors can be the spelling mistake, etc.
Runtime errors are those errors in PL/SQL block for which exception handling
section is to be included for handling the errors. These errors can be SELECT INTO
statement which does not return any rows.

Q 23) Enlist some predefined exceptions?


Answer: Some of the predefined exceptions are
NO_DATA_FOUND: Single row SELECT statement where no data is returned.
TOO_MANY_ROWS: Single row SELECT statement where more than one rows are
returned.
INVALID_CURSOR: Illegal cursor operation occurred.
ZERO_DIVIDE: Attempted to divide by zero.
DUP_VAL_ON_INDEX
CURSOR_ALREADY_OPEN
INVALID_NUMBER
PROGRAM_ERROR
TIMEOUT _ON_RESOURCE
STORAGE_ERROR
LOGON_DENIED
VALUE_ERROR
etc.

Q 24. What Will Be The Value Of %NOTFOUND Attribute After A Cursor Is Opened But
Before A Fetch Statement Is Executed?
Answer :
The value of %NOTFOUND attribute will be NULL after the cursor is opened but before
the FETCH statement is executed. After the FETCH statement, the value of %NOTFOUND
attribute will be TRUE OR FALSE depending on the result of the FETCH statement.

Q 25. What Is The Function Of Open Cursor Command?


The following operations occur when the OPEN cursor command is executed for a
cursor:
Memory area for processing is allocated
The SELECT statement is parsed
The input variables are assigned the values by obtaining the memory addresses
The active set of rows that fulfill the select criteria are identified
The pointer is set just before the first row of the active set

Q 26. How Can Explicit Cursors Be Used To Fetch Multiple Rows?


Answer :
A loop must be defined to fetch multiple rows from an explicit cursor. It will
fetch one row from the active cursor set on each iteration of the loop, as shown in
the following code:
Declare
v_emp_code
t_employees.emp_code%TYPE;
v_emp_name t_employees.emp_name%TYPE;
v_emp_salary
t_employees.emp_salary%TWE:
v_increment number (10.2);
Cursor emp_cursor IS
Select emp_code, emp_name,
emp_salary from t_employees:
Begin
Open emp_cursor;
LOOP FETCH emp_cursor into v_emp_code,
v_emp_name, v_emp_salary:
EXIT WHEN emp_cursoMBOutOuNT > 10 or
emp_cursor%NOTPOuND or emp_cursor%NOTFOuND IS NULL;
V_increment := v_emp_salary # 0.20 DBMS_OUTPUT.
PUTLINE(v_emp_code II' 'Ilv_emp_name It " II v_increment);
END LOOP;
CLOSE emp_cursor;
END;

Q 27. Can You Define A Record Type Based On An Explicit Cursor?


Yes, It is possible to define a record type based on the selected columns of an
explicit cursor. This helps in retrieving the entire row together into the defined
record and further processing. The values of the row are directly loaded into the
fields of the record.

Q 28. What Is A Cursor For Loop And How Does It Differ From An Explicit Cursor?
Cursor FOR loop is a shortcut to use explicit cursors. It does not require explicit
opening, fetching, and closing of the cursor. In other words, the cursor FOR loop
implicitly opens the cursor, fetches the record, and closes the cursor. In the
cursor FOR loop, the cursor is defined and its attributes are checked within the
processing of the FOR loop. The records are also implicitly defined within the
loop, as shown in the following code:
Declare
v_increment number(10.2);
Cursor em P_cursor IS
Select emp_code. emp_name. emp_salary from t_employeeS;
Begin
FOR emp_record IN em p_cursor
v_increment emp_record.emp_salary # 0.20
D13MS_OUTPUT.PUTLINE
(emp_FREOFthent_COOR 11 'Ilemp_record.emp_name II " II v_increment);
END LOOP;
END;
It is also possible to use a cursor FOR loop with a subquery, where the cursor name
is not defined. In this case, the attributes of the cursor cannot be checked as no
explicit cursor name is defined.

Q 29. What Is Select For Update And How Can It Be Used In A Cursor?
The SELECT FOR UPDATE clause is used to lock rows in a table when an update or
delete transaction is performed on the active set. It selects the rows of the table
that have to be modified and locks each row in the result set. This prevents any
other user from accessing the same set of records while modification is being
executed on the table. You should add the NOWAIT clause to the SELECT FOR UPDATE
statement to prevent the procedure from waiting indefinitely in case the lock
cannot be acquired. If the NOWAIT clause is used, the control will return to the
program in case the requested rows have been locked by another user.
Q 30. How Is It Possible To Fetch A Current Row From A Cursor Without Using Rowid?
The WHERE CURRENT OF clause is used to reference the current row of an active
explicit cursor. When this clause is used, ROWID is not needed to access the
current row for modifications.

Q 31. What Are Open, Fetch, And Close Cursor Commands? Are They Used With The
Implicit Or Explicit Cursor?
These commands are used with explicit cursors. First, the cursor is opened to make
it active using the OPEN command. Then, the FETCH command is used to retrieve the
rows from the active cursor. After all the rows are retrieved, the cursor is closed
using the CLOSE command that can again be reopened. Any other operation on a closed
cursor returns the predefined exception, INVALID_CURSOR. However, these commands
cannot be used to control the SQL implicit cursors.

Q 32. Why Does Sql%isopen 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.

Q 33. In What Order Should A Open/fetch/loop Set Of Commands In A Pl/sql Block Be


Implemented If You Use The %notfound Cursor Variable In The Exit When Statement?
Why?
OPEN then FETCH then LOOP followed by the exit when. If not specified in this order
will result in the final return being done twice because of the way the %NOTFOUND
is handled by PL/SQL.

Q 34. How Can You Find Within A Pl/sql Block, If A Cursor Is Open?
Use the %ISOPEN cursor status variable.

Q 35. What is difference between a Cursor declared in a procedure and Cursor


declared in a package specification?
A cursor declared in a package specification is global and can be accessed by
other procedures or procedures in a package.
A cursor declared in a procedure is local to the procedure that can not be accessed
by other procedures.

Q 36. What are the PL/SQL Statements used in cursor processing?


DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO
<variable list> or Record types, CLOSE cursor name.

Q 37. What is a cursor for loop?


Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor,
fetches rows of values from active set into fields in the record and closes when
all the records have been processed.

eg. FOR emp_rec IN C1 LOOP


salary_total := salary_total +emp_rec sal;
END LOOP;

Q 38. What will happen after commit statement ?


Cursor C1 is
Select empno,
ename from emp;
Begin
open C1; loop
Fetch C1 into
eno.ename;
Exit When
C1 %notfound;-----
commit;
end loop;
end;

The cursor having query as SELECT .... FOR UPDATE gets closed after
COMMIT/ROLLBACK.

The cursor having query as SELECT.... does not get closed even after
COMMIT/ROLLBACK.

Q 39. Explain the usage of WHERE CURRENT OF clause in cursors ?


WHERE CURRENT OF clause in an UPDATE,DELETE statement refers to the latest
row fetched from a cursor.

Q 40. What are the disadvantages of Cursors and is there any alternative to it?
The processing of Cursors is very slow as compared to Joins. Hence, Joins can be an
alternative to Cursors.

Q 41. What is the method to display messages in Output Files and Log Files?
The Output Files and Log Files can be used to display messages by using the
following: Fnd_file.put_line.

Q 42. What is an Active Set?


The set of rows that a Cursor holds at a single point of time is called as an
Active Set.

Q 43. What are the different Loop Control Structures used in PL/SQL?
The different Loop Control Structures in PL/SQL are as follows:
1. Exit
2. Exit-When
3. Continue
4. Goto

Q 44. What are the different parts of an Explicit Cursor?


The different parts in the process of making an Explicit Cursor are as follows:
1. Declaring the Cursor
2. Opening the Cursor
3. Fetching the Cursor
4. Closing the Cursor

Q 45. How can you assign a Name to an Un-Named PL/SQL Exception Block?
You can assign a name to an Un-Named Exception using Pragma, also known as
Exception_init.

Q 46. 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.

Q 47. What is Context Area in PL/SQL?


Oracle processes the executed SQL Statement in a separate memory zone called as
Context Area. It contains information regarding SQL Query, number of rows accessed
by it, information retrieved from database tables/records and many more.

Q 48. Which is the Default Cursor in Oracle PL/SQL?


Implicit Cursors are the Default Cursor in PL/SQL. These cursors are automatically
activated when DML statements are encountered such as Insert, Delete or Update.

Q 49. Why is closing the Cursor required during explicit cursor development?
It is important because it will consume system memory while it is in active state
and if it is not closed or terminated then it won't let the other things in the
memory as memory will be occupied and later on it will be full. Hence, deletion is
necessary.

Q 50. How Is An Exception Raised And Handled?


Answer : When a runtime error occurs, an exception is raised. The exception is
handled when this error is successfully handled by the PL/SQL code and is not
allowed to propagate to the outward environment. Compilation error cannot be
handled within the program; only runtime errors can be handled within the PL/SQL
code.
An exception can be raised:
By a runtime Oracle error
By the RAISE statement
By calling the RAISE_APPLICATION_ERROR procedure
After an exception is raised, the control is passed to the exception section, where
the code is written about how to handle the error that has occurred. The control
cannot pass back to the executable section of the same block after the exception is
handled.
There are 3 types of EXCEPTION:
Predefined Exceptions: Common errors with predefined names.
Undefined Exceptions: Less common errors with no predefined names.
User-defined Exceptions: Do not cause runtime error but violate
business rules.

Q 51. 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.

Q 52. Is It Possible To Have More Than One Others Clause?


No, it is not possible to have more than one OTHERS clause in the exception
section.

Q 53. Describe The Sqlcode And Sqlerrm Functions ?


The SQLCODE function returns the Oracle error number for internal exceptions. This
error number can be passed to the SQLERRM function to get the message associated
with the error number. The SQLCODE function returns the value +1; whereas, the
SQLERRM function returns the User-Defined Exception message for the user-defined
exceptions.
These functions can be used with the OTHERS exception handler to get the error
number and the error message that has caused the OTHERS exception to be raised.

Q 54. How Are User-defined Exceptions Trapped?


User-defined exceptions are defined in the declarative section of the PL/SQL code
and raised explicitly using the RAISE statement.

Q 55. What is Raise_Application_Error?


When user wants to insert Error message then user needs to use the
Raise_Application_Error procedure. Raise_Application_Error is the system defined
procedure of package named DBMS_STANDARD.
Syntax :
Raise_Application_Error(Error_Code,Error_Message);
Example :
Raise_Application_Error (-20343, `The balance is too low.');

When the RAISE_APPLICATION_ERROR procedure is encountered, it ends the program unit


and returns the error number and message to the application.

Q 56. Can Raise_application_error Be Called In The Executable Section Of The


Program Unit?
Yes, the RAISE_APPLICATION_ERROR procedure can be called in the executable section
as well as the exception section of the PL/SQL code.

Q 57. What Happens After A Sub-block Handles An Exception?


When a sub-block handles an exception, the control passes to the next statement in
the executable section of the enclosing block immediately after the END statement
of the sub-block.

Q 58. What Happens If An Exception Is Not Handled In A Sub- Block?


If an exception is not handled in a sub-block, the exception propagates to the
enclosing blocks until the associated handler is found. If none of the blocks has a
handler for the exception, an unhandled exception error is passed back to the host
environment.

Q 59. Can Processing Be Resumed From The Point Exception Was Raised After The
Exception Is Handled?
After the exception is handled, processing cannot be resumed within the executable
section of the current block from where the exception was raised. The current block
where the exception handler is declared will be terminated. The control will pass
to the statement in the enclosing executable block. If there is no enclosing block,
control will pass back to the calling host environment.

Q 60. How Can A Transaction Be Retried After An Exception?


The following method can be used to retry a transaction after an exception is
raised:
The transaction should be written within a sub-block
The sub-block can be placed inside a loop that repeats the transaction.
Mark a savepoint before starting the transaction. If the transaction succeeds, then
commit and exit from the loop. If the transaction fails, the control is transferred
to the exception handler where the transaction is rolled back to the savepoint to
undo the changes, and then try to fix the problem.

Q 61. Does Raise_application_error Overwrite The Error Stack Or Append Messages To


The Error Stack?
The default behavior of the RAISE_APPLICATION_ERROR procedure is to overwrite the
error message stack. However, if the parameter is passed, then the messages can be
appended to the error stack as well.

Q 62. What Causes The Invalid_cursor Exception?


This exception is raised when the program attempts to perform an illegal operation,
such as closing an unopened cursor.

Q 63. What are the differences between Implicit and Explicit Cursors?
Explicit cursors are cursors created by the programmer to improve the manipulation
of the context area. It is declared within the Declaration Section of the PL/SQL
Block using the SELECT Statement. For multiple records user needs to use explicit
cursor.Explicit cursor operations are done by the user.

In order to use explicit cursor in PL/SQL, 4 steps are followed


Declare the cursor
Syntax: CURSOR <cursor_name> is
SELECT statement;
Where <cursor_name> is the name assigned to the cursor and SELECT
statement is the query that returns rows to the cursor active set.
Open the cursor
Syntax: OPEN <cursor_nam>;
Where, <cursor_name> is the name of the previously defined
cursor.
Fetch rows from the cursor
Syntax: FETCH <cursor_name> INTO <record_list>;
Where <cursor_name> refers to the name of the previously defined
cursor from which rows are being fetched.
<record_list> represents the list of variables that will receive
the data being fetched.
Closing the cursor
Syntax: CLOSE <cursor_name>;
Where <cursor_name> is the name of the cursor being closed.

For example:

CURSOR cursorName [ parameter ] [ RETURN returnType ]


IS SELECT STATEMENT;

On the other hand, When any SQL statement is executed, PL/SQL automatically creates
a cursor without defining such cursors are known as implicit cursors. Implicit
Cursors are automatically generated by Oracle if there is no existing explicit
cursor for the statement. This happens at the instant the SQL statement is ran. The
developer has no control over the content and data within implicit cursors.
Implicit cursor will process single record at a time. For following statements,
PL/SQL employs implicit cursors
INSERT
UPDATE
DELETE
SELECT ( queries that return exactly one row)

example :
declare
v_Ename varchar2(100);
begin
select ename into V_Ename from Employee where empno=101;
dbms_output.put_line(V_Ename );
end;
The above cursor is implicit cursor where all the operations are defined by oracle
engine internally like declaring the cursor,fetching values from the cursor and
close cursor.

Q 64.How to write Cursor with for loop?


Cursor declares %ROWTYPE as loop index implicitly. It then opens a cursor, gets
rows of values from the active set in fields of the record and shuts when all
records are processed.Means while using the for loop user dont need to Open the
cursor and fetch the values from cursor or close cursor explicitly.
In For loop all cursor operations done implicitly..
Real Example:
FOR Sample_cursor IN C1 LOOP
Total_Salary=Total_Salary + Appraisals;
END LOOP;

Q 65. What is Discard File?


This file extension is .dsc
Discard file we must specify within control file by using discard file
clause.
Discard file also stores reflected record based on when clause condition
within control file. This condition must be satisfied into table tablename clause.

Q 66. What is REF CURSOR (or) CURSOR VARIABLE (or) DYNAMIC CURSOR ?
Oracle 7.2 introduced ref cursor, This is an user defined type which is used to
process multiple records and also this is a record by record process.
In static cursor database servers executes only one select statement at a time for
a single active set area where in ref cursor database servers executes number of
select statement dynamically for a single active set area that's why those cursor
are also called as dynamically cursor.
Generally we are not allowed to pass static cursor as parameters to use subprograms
where as we can also pass ref cursor as parameter to the subprograms because
basically refcursor is an user defined type in oracle we can also pass all user
defined type as parameter to the subprograms.
Generally static cursor does not return multiple record into client application
where as ref cursor are allowed to return multiple records into client application
(Java, .Net, php, VB, C++).
This is an user defined type so we are creating it in 2 steps process i.e first we
are creating type then only we are creating variable from that type that's why this
is also called as cursor variable.

Q 67.What is ref cursor?Why it is used?


As the name suggested ref cursor is a variable which will point to the address or
reference of the cursor.Ref cursor is variable not cursor but that variable points
to cursor.
There are 2 type of ref cursors :
1.Strong Ref cursor
2.Weak Ref cursor

Strong ref cursor is a ref cursor which have return type, whereas weak ref cursor
has no return type.
Syntax:
Type typename is ref cursor return record type data type;
Variable Name typename
Syntax
Type typename is ref cursor
Variable Name typename;
In Weak ref cursor we must specify select statement by using open for clause this
clause is used in executable section of the PL/SQL block.
Syntax:
Open ref cursor varname for SELECT * FROM tablename condition;

Q 68) What is an Intersect?


Intersect is the product of two tables and it lists only matching rows.

Q 69) What are sequences?


Sequences are used to generate sequence numbers without an overhead of locking. Its
drawback is that the sequence number is lost if the transaction is rolled back.

Q 70) How does ROWID help in running a query faster?


ROWID is the logical address of a row, it is not a physical column. It composes of
data block number, file number and row number in the data block. Thus, I/O time
gets minimized retrieving the row, and results in a faster query.

Q 71) What are database links used for?


Database links are created in order to form communication between various
databases, or different environments like test, development and production. The
database links are read-only to access other information as well.

Q 72) What does fetching a cursor do?


Fetching a cursor reads Result Set row by row.

Q 73) What does closing a cursor do?


Closing a cursor clears the private SQL area as well as de-allocates memory

Q 74) What is error ORA-01000: maximum open cursors exceeded


There are two common scenarios in which this error might occur:
(1) When the value for OPEN_CURSORS is very low compared to the demand of cursors
in your program. It is possible to increase the value of OPEN_CURSORS but
discouraged, as it doesn't identify the problem in your program and only allocates
more resources than it should, which is very inefficient and wasteful for a
developer.
(2) A more recommended approach is considering your program and search for problems
that are concerning cursors. Take note of the implicit and explicit cursors as they
also take up the available cursors available. Common issues of developers having
this problem is they failed to close their cursor that is inside a loop, which in
turn creates the error.

Q 75) What is error ORA-03113: end-of-file on communication channel?


This is a common error which developers tend to overthink. A rather no-brainer
cause for this is that the physical connection between the client's end and the
database server might have been severed. Check your connection and make sure the
cable properly connected to its intended port. Also make sure to check the status
of the server if it is still functioning, some developers report an issue in their
server that causes this error.
Most of the time, the problem lies on the physical layer and nothing more. But if
you think the problem lies on the server itself, try accessing the alert log and
take note of the catalog.

Q 76. How Can A Current Exception Be Re-raised?


The RAISE statement can be used to re-raise the current exception. It stops the
normal execution of a PL/SQL program and transfers the control to an exception
handler.

Q 77. Where Will The Control Be Transferred If An Exception Is Raised Within An


Exception Section Of The Block?
When an exception is raised within an exception section of a block, the control is
transferred to the exception section of the enclosing block.

Q 78. What Is The Advantage Of Having A Separate Exception Section Within A Pl/sql
Code?
The advantages of having a separate exception section within a PL/SQL code are as
follows:
It is easier to understand the program logic as it is easily visible and
readable
Any error in any statement will be detected and handled easily

Q 79. What Happen When There Is No Handler For A Raised Exception?


If an exception is raised and there is no handler in the current block, the
exception would propagate to the enclosing block. If no handler is found in the
enclosing block, the exception will be propagated to the calling environment as an
unhandled exception.

Q 80. What Is The Difference Between Raise And Raise_application_error?


RAISE is used to call pre-defined exceptions declared in the declarative section of
the PL/SQL block.
RAISE_APPLICATION_ERROR is used to call user-defined ORA - error messages from
stored subprograms.

Q 81. What is SQL and also describe types of SQL statements?


SQL stands for Structured Query Language. SQL is a language used to communicate
with the server to access, manipulate and control data.
There are 5 different types of SQL statements.
1. Data Retrieval: SELECT
2. Data Manipulation Language (DML): INSERT, UPDATE, DELETE, MERGE
3. Data Definition Language (DDL): CREATE, ALTER, DROP, RENAME, TRUNCATE.
4. Transaction Control Statements: COMMIT, ROLLBACK, SAVEPOINT
5. Data Control Language (DCL): GRANT, REVOKE

Q 82. What is a Literal? Give an example where it can be used?


A Literal is a string that can contain a character, a number, or a date that is
included in the SELECT list and that is not a column name or a column alias. Date
and character literals must be enclosed within single quotation marks (` `), number
literals need not.
For ex: Select last_name||'is a'||job_id As "emp details" from employee; (Here "is
a" is a literal).
Learn Oracle PL SQL Training: Become experts in components of Oracle PL/SQL, Oracle
database environment | Take Up Now Course at Mindmajix. Enroll & Become Certified

Q 83. What is a difference between SQL and iSQL*Plus?

Q. Define the order of Precedence used in executing SQL statements.


Order of Precedence used in executing SQL statements
Order Evaluated Operator
1 Arithmetic operators (*, /, +, -)
2 Concatenation operators (||)
3 Comparison conditions
4 Is[NOT] NULL, LIKE, [NOT] IN
5 [NOT] BETWEEN
6 NOT Logical condition
7 AND logical condition
8 OR logical condition

Q 84. What is a difference between Entity, Attribute and Tuple?


Entity: A significant thing about which some information is required. For ex:
EMPLOYEE (table).
Attribute: Something that describes the entity. For ex: empno, empname, empaddress
(columns).
Tuple: A row in a relation is called Tuple.

Q 85. What are Constraints? How many types of constraints are there?
Constraints are used to prevent invalid data entry or deletion if there are
dependencies. Constraints enforce rules at the table level. Constraints can be
created either at the same time as the table is created or after the table has been
created. Constraints can be defined at the column or table level. Constraint
defined for a specific table can be viewed by looking at the USER-CONSTRAINTS data
dictionary table. You can define any constraint at the table level except NOT NULL
which is defined only at column level. There are 5 types of constraints:
1. NOT NULL: NOT NULL Constraint ensures that the column contains no null values.
2. UNIQUE KEY: UNIQUE Key Constraint ensures that every value in a column or set of
columns must be unique, that is, no two rows of a table can have duplicate values
in a specified column or set of columns. If the UNIQUE constraint comprises more
than one column, that group of columns is called a Composite Unique Key. There can
be more than one Unique key on a table. Unique Key Constraint allows the input of
Null values. Unique Key automatically creates index on the column it is created.
3. PRIMARY KEY: Uniquely identifies each row in the Table. Only one PRIMARY KEY can
be created for each table but can have several UNIQUE constraints. PRIMARY KEY
ensures that no column can contain a NULL value. A Unique Index is automatically
created for a PRIMARY KEY column. PRIMARY KEY is called a Parent key.
4. FOREIGN KEY: Is also called Referential Integrity Constraint. FOREIGN KEY is one
in which a column or set of columns take references of the Primary/Unique key of
same or another table. FOREIGN KEY is called a child key. A FOREIGN KEY value must
match an existing value in the parent table or be null.
5. CHECK KEY: Defines a condition that each row must satisfy. A single column can
have multiple CHECK Constraints. During CHECK constraint following expressions is
not allowed:
1) References to CURRVAL, NEXTVAL, LEVEL and ROWNUM Pseudo columns.
2) Calls to SYSDATE, UID, USER and USERENV Functions

Q 86. What is a difference between ON DELETE CASCADE and ON DELETE SET NULL?
ON DELETE CASCADE Indicates that when the row in the parent table is deleted, the
dependent rows in the child table will also be deleted. ON DELETE SET NULL Coverts
foreign key values to null when the parent value is removed. Without the ON DELETE
CASCADE or the ON DELETE SET NULL options, the row in the parent table cannot be
deleted if it is referenced in the child table.

Q 87. What is a Candidate Key?


The columns in a table that can act as a Primary Key are called Candidate Key.

Q 88. What are the restrictions of DML operations on Views?


Few restrictions of DML operations on Views are:
You cannot DELETE a row if the View contains the following:
1. Group Functions
2. A Group By clause
3. The Distinct Keyword
4. The Pseudo column ROWNUM Keyword.

You cannot MODIFY data in a View if it contains the following:


1. Group Functions
2. A Group By clause
3. The Distinct Keyword
4. The Pseudo column ROWNUM Keyword.
5. Columns defined by expressions (Ex; Salary * 12)
You cannot INSERT data through a view if it contains the following:

Q 89. What are triggers and its uses?


Triggers are blocks of code which are run whenever the criteria for a specific
event is satisfied. They are hardcoded within the PL SQL program and listens to
events such as: DML(database manipulation), DDL(database definition), and database
operation. They can be coded within a view, table, database, or scheme for which
the mentioned event belongs.
There are many uses of triggers. They can be used to generate column values upon
activating. For event logging within the table activities, auditing, and creating
table duplicates. For security, they can implement security authorization, and
handle invalid transactions.
General Structure of creating a Trigger:

CREATE [OR REPLACE ] TRIGGER triggerName


{BEFORE | AFTER | INSTEAD OF }
{INSERT [OR] | UPDATE [OR] | DELETE}
[OF colName]
ON tableName
[REFERENCING OLD AS o NEW AS n]
[FOR EACH ROW]
WHEN (condition)
DECLARE
Declaration-statements
BEGIN
Executable-statements
EXCEPTION
Exception-handling-statements
END;

Q 90) Explain the difference in execution of triggers and stored procedures?


Answer: A stored procedure is executed explicitly by issuing procedure call
statement from another block via a procedure call with arguments.
The trigger is executed implicitly whenever any triggering event like the
occurrence of DML statements happens.

Q 91) What are INSTEAD of triggers?


Answer: The INSTEAD OF triggers are the triggers written especially for modifying
views, which cannot be directly modified through SQL DML statements.

Q 92. What are the different functionalities of a Trigger ?


Trigger is also same as stored procedure & also it will automatically invoked
whenever DML operation performed against table or view.
There are two types of triggers supported by PL/SQL
1. Statement Level Trigger.
2. Row Level Trigger

Row-level triggers are activated once for each row, which is modified by a DML
statement. For example, consider a table, STUDENT_MARKS_AUDIT, used for the
auditing of the STUDENT_MARKS table. A row-level trigger would insert a row in the
STUDENT_MARKS_AUDIT table every time any value is modified in any row of the
STUDENT_MARKS table.

Statement-level triggers are executed only once for each DML statement. For
example, if there is an INSERT statement, which inserts 100 rows in a STUDENT_MARKS
table, then the statement-level trigger would be executed only once on that table;
whereas, a row-level trigger would be executed 100 times.
Row-level triggers are generally used for data auditing applications; whereas,
statement-level triggers are used to enforce security features for the types of
actions that may be performed on a table.

Q 93. What Are The System Privileges That Are Required By A Schema Owner (user) To
Create A Trigger On A Table?
A user must be able to alter a table to create a trigger on the table. The user
must own the table and either have the ALTER TABLE privilege on that table or have
the ALTER ANY TABLE system privilege. In addition, the user must have the CREATE
TRIGGER system privilege. User should have the CREATE ANY TRIGGER system privilege
to be able to create triggers in any other user account or schema.
A database-level event trigger can be created if the user has the ADMINISTER
DATABASE TRIGGER system privilege.

Q 94. Can Triggers Reference Other Tables Through A Role?


Triggers may require referencing other tables while triggering an event. Therefore,
privileges required to reference other tables must be granted directly to the owner
of the trigger, as the trigger cannot reference other user tables through roles.
For example, consider a trigger, which is used for any audit table. To insert a row
in the audit table, the owner of the trigger must have the insert privilege on that
audit table.

Q 95. Is It Possible To Combine Several Triggering Events Into One Trigger?


Yes, it is possible to combine various triggering events and create one trigger.
Special conditional predicates such as INSERTING, UPDATING, and DELETING are used
within the trigger body to represent the triggering events, as shown in the
following code snippet:

Q 96. How Can Triggers Be Used For The Table Auditing?


Triggers can be used to track values for data operations on tables. This is done
using the old and new qualifiers within the trigger code. These two clauses help
keep track of the data that is being inserted, updated, or deleted in the table;
and therefore, facilitate in application auditing of DML statements. The audit
trail can be written to a user-defined table and audit records can be generated for
both row-level and statement-level triggers.

Q 97. What Are Instead Of Triggers?


The INSTEAD OF triggers are used in association with views. The standard table-
based triggers cannot be used by views. These triggers inform the database of what
actions are to be performed instead of the actions that invoked the trigger.
Therefore, the INSTEAD OF triggers can be used to update the underlying tables,
which are part of the views. They can be used on both relational views and object
views. The INSTEAD OF triggers can only be defined as row-level triggers and not as
statement-level triggers.

Q 98. What Is The Difference Between Database Trigger And Stored Procedure?
The main difference between database trigger and stored procedure is that the
trigger is invoked implicitly and stored procedure is invoked explicitly.
Transaction Control statements, such as COMMIT, ROLLBACK, and SAVEPOINT, are not
allowed within the body of a trigger; whereas, these statements can be included in
a stored procedure.

Q 99. How Can The Performance Of A Trigger Be Improved?


The performance of a trigger can be improved by using column names along with the
UPDATE clause in the trigger. This will make the trigger fire when that particular
column is updated and therefore, prevents unnecessary action of trigger when other
columns are being updated.

Q 100. What Are The Events On Which A Database Trigger Can Be Based?
Database triggers are based on system events and can be defined at database or
schema level. The various events on which a database trigger can be based are given
as follows:
Data definition statement on a database or schema object
Logging off or on of a specific user
Database shutdown or startup
On any specific error that occurs

Q 101. What Is A Call Statement? Explain With An Example ?


A CALL statement within a trigger enables you to call a stored procedure within the
trigger rather than writing the Procedural Language/Structured Query Language
(PL/SQL) code in it, The procedure may be in PL/SQL, C, or Java language. Following
is an example of the CALL statement:

Q 102. What Is A Mutating Table?


A mutating table is a table, which is in the state of transition. In other words,
it is a table, which is being updated at the time of triggering action. If the
trigger code queries this table, then a mutating table error occurs, which causes
the trigger to view the inconsistent data.

Q 103. What Are Schema-level Triggers?


Schema-level triggers are created on schema-level operations, such as create table,
alter table, drop table, rename, truncate, and revoke. These triggers prevent DDL
statements, provide security, and monitor the DDL operations.

Q 104. What Is A Database Event Trigger?


Trigger that is executed when a database event, such as startup, shutdown, or
error, occurs is called a database event trigger. It can be used to reference the
attributes of the event and perform system maintenance functions immediately after
the database startup.

Q 105. In What Condition Is It Good To Disable A Trigger?


It is good to disable triggers during data load operations. This improves the
performance of the data loading activities. The data modification and manipulation
that the trigger would have performed has to be done manually after the data
loading.

Q 106. Which Column Of The Userjtriggers Data Dictionary View Displays The Database
Event That Will Fire The Trigger?
The Description column of the USERJTRIGGERS view combines information from many
columns to display the trigger header, which includes the database event.

Q 107. What Is The Meaning Of Disabling A Trigger?


When a trigger is disabled, it does not mean that it is deleted. The code of the
trigger is still stored in the data dictionary but the trigger will not have any
effect on the table.

Q 108. Can Triggers Stop A Dml Statement From Executing On A Table?


Yes, triggers have the capability of stopping any DML statement from execution on a
table. Any logical business rule can be implemented using PL/SQL to block
modification on table data.

Q 109. Can A View Be Mutating? If Yes, Then How?


No, a view cannot be mutating like a table. If an UPDATE statement fires an INSTEAD
OF trigger on a view, the view is not considered to be mutating. If the UPDATE
statement had been executed on a table, the table would have been considered as
mutating.

Q 110. Can A Commit Statement Be Executed As Part Of A Trigger?


No, A COMMIT statement cannot be executed as a part of a trigger because it is a
Transaction Control statement, which cannot be executed within a trigger body.
Triggers fire within transactions and cannot include any Transaction Control
statement within its code.

Q 111. What Is The Difference Between Alter Trigger And Drop Trigger Statements?
An ALTER TRIGGER statement is used to recompile, disable, or enable a trigger;
whereas, the DROP TRIGGER statement is used to remove the trigger from the
database.

Q 112. Do Triggers Have Restrictions On The Usage Of Large Datatypes, Such As Long
And Long Raw?
Triggers have restrictions on the usage of large datatypes as they cannot declare
or reference the LONG and LONG RAW datatypes and cannot use them even if they form
part of the object with which the trigger is associated. Similarly, triggers cannot
modify the CLOB and BLOB objects as well; however, they can reference them for
read-only access.

Q 113. Are Ddl Triggers Fired For Ddl Statements Within A Pl/sql Code Executed
Using The Dbms.sql Package?
No, DDL triggers are not executed for DDL statements, which are executed within the
PL/SQL code using the DBMS_SQL package.

Q 114. How Can You View The Errors Encountered In A Trigger?


The USERJERRORS view can be used to show all the parsing errors that occur in a
trigger during the compilation until they are resolved.

Q 115. Does User-triggers Have Entry For Triggers With Compilation Errors?
Yes, USER_TRIGGERS have entries for all triggers that are created in the schema
with or without errors.

Q 116. Is It Possible To Pass Parameters To Triggers?


No, it is not possible to pass parameters to triggers. However, triggers fired by
INSERT and UPDATE statements can reference new data by using the mew prefix. In
addition, the triggers fired in response to UPDATE and DELETE statements can
reference old, modified, or deleted data using the :old prefix.

Q 117. Can A Select Statement Fire A Trigger?


No, a SELECT statement cannot fire a trigger. DML statements, such as INSERT,
UPDATE, and DELETE, can cause triggers to fire.

Q 118. Is It Possible To Create Startup Or Shutdown Trigger For On-schema?


No, It is not possible to create STARTUP or SHUTDOWN triggers for ON-SCHEMA.

Q 119. What Does The Base_object_type Column Shows In The User.triggers Data
Dictionary View?
The BASE_OBJECT_TYPE column identifies the type of database object with which the
trigger is associated. It shows whether the object of database is a TABLE, VIEW,
SCHEMA, or DATABASE.

Q 120. Is It Possible To Define An Exception Within A Trigger?


Yes, it is possible to define and use an exception within a trigger, as shown in
the following code snippet:

Q 121. Can Instead Of Triggers Be Used To Fire Once For Each Statement On A View?
No, INSTEAD OF triggers cannot be used for each statement; however, It can only be
used for each row on a view.

Q 122. Is It Possible To Include An Insert Statement On The Same Table To Which The
Trigger Is Assigned?
If an INSERT statement is used on the same table to which the trigger is
associated, then this will give rise to a mutating table, as it is not possible to
change the same table that is already in the process of being changed.

Q 123. Write The Alter Statement To Enable All The Triggers On The T.students Table
?
The ALTER statement is given as follows:
ALTER TABLE T_STUDENTS ENABLE ALL TRIGGERS;

Q 124. Which Column In The User.triggers Data Dictionary View Shows That The
Trigger Is A Pl/sql Trigger?
The ACTION_TYPE column of the USER_TRIGGERS data dictionary view shows that the
trigger is a PL/SQL trigger.

Q 125. Suppose A Schema A Has The Create Any Trigger Privilege And The Select
Privilege On The Table X In The Schema B. Can The Schema A Create A Trigger On The
Table X?
Yes, schema A can create a trigger on the table X of schema B.

Q 126. Which Privilege Is Required To Be Able To Drop A Trigger?


The CREATE TRIGGER privilege is required to create, alter, and drop triggers in a
schema.

Q 127. Suppose The Trig_1 Trigger On The Tab_1 Table Exists In The Schema A, And
The Schema B Has Privilege To Access The Tab_1 Table. What Additional Privilege Is
Required By Schema B To Be Able To Execute The Trig_1 Trigger?
No additional privilege is required to execute the trigger as the schema B already
has access privilege to the triggered table, TAB_1.

Q 128. Write a PL/SQL Program which raise a user defined exception on thursday?
declare
a exception
begin
If to_char(sysdate, `DY)='THU'
then
raise a;
end if;
exception
when a then
dbms_output.put_line(`my exception raised on thursday');
end;
Output: my exception raised on thursday

Q 129.Write a PL/SQL program to retrieve emp table and then display the salary?
declare
v_sal number(10);
begin
select max(sal)intr v_sal;
from emp;
dbms_output.put_line(v.sal);
end;
/
(or)
declare
A number(10);
B number(10);
C number(10);
begin
a:=70;
b:=30;
c:=greatest+(a,b);
dbms_output.put_line(c);
end;
/
Output:70

Q 130) What is the difference between ROLLBACK and ROLLBACK TO statements?


Answer: The transaction is completely ended after ROLLBACK statement i.e. ROLLBACK
command completely undoes a transaction and release all locks.
On the other hand, a transaction is still active and running after ROLLBACK TO
command as it undoes a part of the transaction up till the given SAVEPOINT.

Q 131. Define Commit, Rollback and Savepoint.


The COMMIT Statement finalizes to end your transaction and sets all changes to
permanent. A transaction in SQL is any of statements that the Oracle Database
treats as a single block. This also enables users to see the updates and changes
made by the transaction. Finally, the COMMIT statement deletes all the savepoints
prior to the transaction and releases transaction locks.
The ROLLBACK statement undoes the changes that the transaction has made. This is
practically the opposite of the COMMIT Statement. Also, any locks made due to the
transaction are released.
In conjunction, the SAVEPOINT statement is also used to set a restoration point
when the ROLLBACK Statement is used. This limits the bounds of the ROLLBACK
Statement by only reverting to the SAVEPOINT set point.

Q 132) What is the mutating table and constraining table?


A table which is currently being modified by a DML statement like defining triggers
in a table is known as a Mutating table.
A table that might need to be read from for a referential integrity constraint is
known as constraining table.
Q 133) What are the 3 modes of parameter?
Answer: 3 modes of the parameter are IN, OUT, IN OUT. These can be explained as
follows
IN parameters: IN parameters allow you to pass values to the procedure being
called and can be initialized to default values. IN parameters acts like a constant
and cannot be assigned any value.
OUT parameters: OUT parameters return value to the caller and they must be
specified. OUT parameters act like an uninitialized variable and cannot be used in
an expression.
IN OUT parameters: IN OUT parameters passes initial values to a procedure and
returns updated values to the caller. IN OUT parameters act like an initialized
variable and should be assigned a value.

Q 134) What are the ways on commenting in a PL/SQL code?


Answer: Comments are the text which is included with the code to enhance
readability and for the understanding of the reader. These codes are never
executed. There are two ways to comment in PL/SQL
1) Single line comment: This comment starts with double -.
Example:
DECLARE
num NUMBER(2); - it is a local variable.
BEGIN

2) Multi-line comment: This comment starts with /* and ends with */.
Example:
BEGIN
num := &p_num; /* This is a host variable used in program body
*/
....
END

Q 135. What is a Dual Table?


Dual table is owned by the user SYS and can be accessed by all users. It contains
one columnDummy and one row with the value X. The Dual Table is useful when you
want to return a value only once. The value can be a constant, pseudocolumn or
expression that is not derived from a table with user data.

Q 136. Describe different types of General Function used in SQL?


General functions are of following types:
1. NVL: Converts a null value to an actual value. NVL (exp1, exp2) .If
exp1 is null then NVL function return value of exp2.
2. NVL2: If exp1 is not null, nvl2 returns exp2, if exp1 is null, nvl2
returns exp3. The argument exp1 can have any data type. NVL2 (exp1, exp2, exp3)
3. NULLIF: Compares two expressions and returns null if they are equal or
the first expression if they are not equal. NULLIF (exp1, exp2)
4. COALESCE: Returns the first non-null expression in the expression list.
COALESCE (exp1, exp2. expn). The advantage of the COALESCE function over NVL
function is that the COALESCE function can take multiple alternative values.
5. Conditional Expressions: Provide the use of IF-THEN-ELSE logic within a
SQL statement. Example: CASE Expression and DECODE Function.

Q 137. What is difference between COUNT (*), COUNT (expression), COUNT (distinct
expression)? (Where expression is any column name of Table)
COUNT (*): Returns number of rows in a table including duplicates rows and rows
containing null values in any of the columns.
COUNT (EXP): Returns the number of non-null values in the column identified by
expression.
COUNT (DISTINCT EXP): Returns the number of unique, non-null values in the column
identified by expression.
Q 138. What is difference between ANY and ALL operators?
ANY Operator compares value to each value returned by the subquery. ANY operator
has a synonym SOME operator.
> ANY means more than the minimum.
< ANY means less than the maximum
= ANY is equivalent to IN operator.
ALL Operator compares value to every value returned by the subquery.
> ALL means more than the maximum
< ALL means less than the minimum
<> ALL is equivalent to NOT IN condition.

Q 139. What are SQL functions? Describe in brief different types of SQL functions?
SQL Functions are very powerful feature of SQL. SQL functions can take arguments
but always return some value.
There are two distinct types of SQL functions:
1) Single-Row functions: These functions operate on a single row to give one
result per row. Types of Single-Row functions:
1. Character
2. Number
3. Date
4. Conversion
5. General
2) Multiple-Row functions: These functions operate on groups of rows to give
one result per group of rows. Types of Multiple-Row functions:
1. AVG
2. COUNT
3. MAX
4. MIN
5. SUM
6. STDDEV
7. VARIANCE

Q 140. What are the uses of MERGE?


MERGE is used to combine multiple DML statements into one.
Syntax : merge into tablename
using(query)
on(join condition)
when not matched then
[insert/update/delete] command
when matched then
[insert/update/delete] command

Q 141. What is a difference between "VERIFY" and "FEEDBACK" command?


VERIFY Command: Use VERIFY Command to confirm the changes in the SQL statement (Old
and New values). Defined with SET VERIFY ON/OFF.
Feedback Command: Displays the number of records returned by a query.

Q 142. What is the use of Double Ampersand (&&) in SQL Queries? Give example?
Use "&&" if you want to reuse the variable value without prompting the user each
time.
For ex: Select empno, ename, &&column_name from employee order by &column_name;

Q 143. What is a Transaction? Describe common errors can occur while executing any
Transaction?
Transaction consists of a collection of DML statements that forms a logical unit of
work.
The common errors that can occur while executing any transaction are:
1. Data type mismatch.
2. Value too wide to fit in column.
3. The system crashes or Server gets down.
4. The session Killed.
5. Locking take place. Etc.
6. The violation of constraints.

Q 144. What is locking in SQL? Describe its types?


Locking prevents destructive interaction between concurrent transactions. Locks
held until Commit or Rollback. Types of locking are:
Implicit Locking: Occurs for all SQL statements except SELECT.
Explicit Locking: Can be done by user manually.

Further there are two locking methods:


1. Exclusive: Locks out other users
2. Share: Allows other users to access

Q 145. Describe naming rules for creating a Table?


Naming rules to be consider for creating a table are:
1. Table name must begin with a letter,
2. Table name can be 1-30 characters long,
3. Table name can contain only A-Z, a-z, 0-9,_, $, #.
4. Table name cannot duplicate the name of another object owned by the same
user.
5. Table name cannot be an oracle server reserved word.

Q 146. What is a DEFAULT option in a table?


A column can be given a default value by using the DEFAULT option. This option
prevents null values from entering the column if a row is inserted without a value
for that column. The DEFAULT value can be a literal, an expression, or a SQL
function such as SYSDATE and USER but the value cannot be the name of another
column or a pseudo column such as NEXTVAL or CURRVAL.

Q 147. What is a difference between USER TABLES and DATA DICTIONARY?


USER TABLES: Is a collection of tables created and maintained by the user. Contain
USER information. DATA DICTIONARY: Is a collection of tables created and maintained
by the Oracle Server. It contains database information. All data dictionary tables
are owned by the SYS user.

Q 148. In what scenario you can modify a column in a table?


During modifying a column:
1. You can increase the width or precision of a numeric column.
2. You can increase the width of numeric or character columns.
3. You can decrease the width of a column only if the column contains null
values or if the table has no rows.
4. You can change the data type only if the column contains null values.
5. You can convert a CHAR column to the VARCHAR2 data type or convert a
VARCHAR2 column to the CHAR data type only if the column contains null values or if
you do not change the size.

Q 149. What is a SET UNUSED option?


SET UNUSED option marks one or more columns as unused so that they can be dropped
when the demand on system resources is lower. Unused columns are treated as if they
were dropped, even though their column data remains in the table's rows. After a
column has been marked as unused, you have no access to that column. A select *
query will not retrieve data from unused columns. In addition, the names and types
of columns marked unused will not be displayed during a DESCRIBE, and you can add
to the table a new column with the same name as an unused column. The SET UNUSED
information is stored in the USER_UNUSED_COL_TABS dictionary view.
Q 150. What are different methods to trace the PL/SQL code?
Tracing code is a crucial technique to measure the code performance during the
runtime. Different methods for tracing includes
DBMS_APPLICATION_INFO
DBMS_TRACE
DBMS_SESSION and DBMS_MONITOR
trcsess and tkproof utilities

Q 151. What is the difference between FUNCTION, PROCEDURE AND PACKAGE in PL/SQL?
Function: The main purpose of a PL/SQL function is generally to compute and return
a single value. A function has a return type in its specification and must return a
value specified in that type.
Procedure: A procedure does not have a return type and should not return any value
but it can have a return statement that simply stops its execution and returns to
the caller. A procedure is used to return multiple values otherwise it is generally
similar to a function.
Package: A package is schema object which groups logically related PL/SQL types ,
items and subprograms. You can also say that it is a group of functions, procedure,
variables and record type statement. It provides modularity, due to this facility
it aids application development. It is used to hide information from unauthorized
users.

Q 152. What is stored Procedure?


A stored procedure is a sequence of statement or a named PL/SQL block which
performs one or more specific functions. It is similar to a procedure in other
programming languages. It is stored in the database and can be repeatedly executed.
It is stored as schema object. It can be nested, invoked and parameterized.
Learn more about PL/SQL Collections & Records.

Q 153. Day-to -Day activities?


1. creating Database objects-Tables,synonyms, sequences
2. To implement Business Rules- creat procedures, functions
3. To impose Business Rules- create constraints, Trigers.
4. Data manipulation---- create cursors.

Q 154. Display records having max salary?


Select * from emp where sal= (select max(sal) from emp)

Q 155. Display 2nd Highest salary from table?


Select max(sal) from emp where sal not in ( select max(sal) from emp)

Q 156. What are Views and why they are used?


A View logically represents subsets of data from one or more table. Views not need
any memory space. A View contains no data of its own but is like a window through
which data from tables can be viewed or changed. The tables on which a view is
based are called Base Tables. The View is stored as a SELECT statement in the data
dictionary. View definitions can be retrieved from the data dictionary table:
USER_VIEWS.
Views are used:
To restrict data access
To make complex queries easy
To provide data Independence
Views provide groups of user to access data according to their requirement.

Q 157. What is a Sub Query? Describe its Types?


A sub query is a SELECT statement that is embedded in a clause of another SELECT
statement. Sub query can be placed in WHERE, HAVING and FROM clause.
Guidelines for using sub queries:
1. Enclose sub queries within parenthesis
2. Place sub queries on the right side of the comparison condition.
3. Use Single-row operators with single-row sub queries and Multiple-row
operators with multiple-row sub queries.
Types of sub queries:
1. Single-Row Sub query: Queries that return only one row from the Inner
select statement. Single-row comparison operators are: =, >, >=, <, <=, <>
2. Multiple-Row Sub query: Queries that return more than one row from the
inner Select statement. There are also multiple-column sub queries that return more
than one column from the inner select statement. Operators includes: IN, ANY, ALL.

Q 158) What is a PL/SQL block?


Answer: In PL/SQL, statements are grouped into units called Blocks. PL/SQL blocks
can include constants, variables, SQL statements, loops, conditional statements,
exception handling. Blocks can also build a procedure, a function or a package.
Broadly, PL/SQL blocks are two types

1) Anonymous blocks: PL/SQL blocks without header are known as anonymous


blocks. These blocks do not form the body of a procedure, function or triggers.
Example:

DECLARE
num NUMBER(2);
sq NUMBER(3);
BEGIN
num:= &Number1;
sq := num*num;
DBMS_OUTPUT.PUT_LINE(`Square:' ||sq);
END;

2) Named blocks: PL/SQL blocks having header or labels are known as Named
blocks. Named blocks can either be subprograms (procedures, functions, packages) or
Triggers. Example:

FUNCTION sqr (num IN NUMBER)


RETURN NUMBER is sq NUMBER(2);
BEGIN
sq:= num*num;
RETURN sq;
END;

Q 159) Write a PL/SQL script to display the following series of numbers:


99,96,93..9,6,3?
Answer
SET SERVER OUTPUT ON
DECLARE
BEGIN
FOR i IN REVERSE 1..99
LOOP
IF Mod(i,3) = 0 THEN
DBMS_OUTPUT.PUT_LINE(i);
END IF;
END LOOP;
END;
/

Q 160) Differentiate PL/SQL and SQL?


Answer: Difference between SQL and PL/SQL can be categorized as follows
SQL is a natural language which is very useful for interactive processing. PL/SQL
is a procedural extension of Oracle - SQL.
No procedural capabilities like condition testing, looping is offered by SQL.
PL/SQL supports procedural capabilities as well as high language features
such as conditional statements, looping statements, etc.
All SQL statements are executed by the database server one at a time, thus it is a
time-consuming process. PL/SQL statements send the entire block of statements to
the database server at the same time, thus network traffic is reduced considerably.
No error handling procedures are there in SQL. PL/SQL supports customized error
handling.

Q 161. Give The Usage Of Dbms_ddl Package ?


The DBMSJDDL package provides access to certain DDL statements within PL/SQL
blocks. This package runs with the privileges of the calling user and not the owner
of the SYS package. Some of the procedures included in this package are as follows:
DBMS_DDL.ALTER_COMPILE object_type, owner, object__name)
DBMS_DDL.ANALYZE_OBJECT(object_type, owner, object_name, method)

Q 162. Which Oracle Package Is Used For Scheduling Job?


The DBMS_JOB package is used for scheduling and executing PL/SQL programs.

Q 163. Which Are The Subprograms Of The Dbms_job Package?


The subprograms of the DBMS_JOB package are as follows:
SUBMIT-Submits a job to the job queue
REMOVE-Removes the specified job from the job queue
CHANGE -Alters the specified job that has already been submitted to the job
queue
WHAT-Alters the specified job
NEXT__DATE-Alters the execution time
INTERVAL -Alters the interval between execution of specified job
BROKEN-Disables the job execution
RUN-Forces a specified job to be executed

Q 164. Which Procedure Of The Dbms_job Package Is Used To Disable The Execution Of
A Particular Job?
The DBMS_JOB.BROKEN procedure disables the execution of the specified job. This job
will not be executed by the Oracle server.

Q 165. Give The Parameters Of The Dbms_job.submit Procedure ?


The DBMS_JOB.SUBMIT procedure adds a new job to the job queue. It takes four
parameters as input and returns the job number as the output though the JOB
parameter. The parameters of the DBMSJOB.SUBMIT procedure are as follows:
JOB- Refers to the OUT parameter that gives the output of the job number,
which is the unique identifier for the job
WHAT- Refers to the IN parameter, which provides the PL/SQL code to be
executed
NEXT_DA TE -Refers to the IN parameter, which provides the next execution
date of the job
INTERVAL -Refers to the IN parameter for the interval used to calculate the
next execution date
NO_PARSE -Refers to the IN parameter, which is a Boolean flag indicating
whether to parse the job at the time of job submission

Q 166. Provide A Program Code In Which The Dbms_job.submit Procedure Is Used To


Schedule A Database Backup Job In The Queue For Midnight ?

Q . When Is An Exception Raised By The Dbms_job Package?


An exception is raised if the time specified for the job does not evaluate to a job
in future.

Q 167. What Is Use Of The Dbms_job.next_date Parameter?


The DBMS_JOB.NEXT_DATE parameter is used to reschedule a particular job. This
parameter is used when the next execution date for a particular job needs to be
changed.

Q 168. Give A Statement In Which The Dbms_job.change Procedure Is Used To Change


The Backup Job Submitted To Morning 8am And Above ?
The job can be rescheduled as follows:

Q 169. Is It Possible To Run A Job Scheduled For A Particular Time To Be Run


Immediately? If Yes, Then How?
Yes, It is possible to run a job scheduled for a particular time immediately using
the DBMS_JOB.RUN procedure.

Q 170. Which Data Dictionary View Is Used To See The Status Of Submitted Jobs?
The DBA_JOBS data dictionary view is used to display the status of the submitted
jobs.

Q 171. Which Data Dictionary View Is Used To See The Status Of Currently Running
Jobs?
The DBA_JOBS_RUNNING data dictionary view is used to display the status of the jobs
currently running.

Q 172. What Is The Use Of Dbms_output Package?


The DBMS_OUTPUT package is used to display output messages from the PL/SQL block.

Q 173. How Can The Dbms_output Package Used To Get An Array Of Lines From Buffer
Into The Procedure?
The DBMS_OUTPUT package uses the GET_LINES procedure to get an array of lines from
output buffer into the procedure.

Q 174. What Is The Utl_file Package?


The UTL_FILE package provides text files input/output functionality within PL/SQL.
The security on client-side is handled using normal operating system file
permissions; whereas, server-side security is handled though restrictions on the
directories that are accessed.

Q 175. What Is Essential To Be Set In The Init.ora File Before Using The Utl_file
Package?
It is essential to initialize the UTL_FILE_DIR parameter in the init.ora file
before using the UTL_FILE package. This parameter is initialized to the directory
that is to be accessed as follows:

Q 176. How Can All The Directories Be Made Available To The Utl_file Package?
The following settings will turn off all the database permissions on the
directories that are accessible to the database processes and make all of them
available to the UTL_FILE package:

Q 177. What Is The Difference Between The Put_line And Putf Functions Of The
Utl_file Package?
The difference between the PUT_LINE and PUTF functions of the UTL_FILE package is
as follows:
PUT_LINE -Refers to a function used to write text string, which is stored in the
buffer, to the opened file with a line terminator.
PUTF- Refers to a function used to write text string, which is stored in the
buffer, to the opened file but in a formatted form with format specifiers - %s and
n. The %s format specifier is used to substitute a value in the output string and n
is a new line character.

Q 178. What Is The Use Of Fflush Procedure Of The Utl_file Package?


The FFLUSH procedure is used to write all data buffered in memory to a file.

Q 179. Can The Utl_file Package Raise Predefined Pl/sql Error?


Yes, the UTL_FILE package can raise predefined exceptions, such as NO_DATA_FOUND or
VALUE_ERROR.

Q 180. Name A Few Exceptions Of The Utl_file Package ?


A few exceptions of the UTL_FILE package are as follows:
INVALID_PATH - Specifies that a file location or filename is invalid
INVALID_MODE - Specifies that the OPEN_MODE parameter in the FOPEN procedure is
incorrect
READ__ERROR - Specifies that an operating system error has occurred during the
read operation
WRITE_ERROR - Specifies that an operating system error has occurred during the
write operation
INVALID__OPERATION - Specifies that a file cannot be opened or used

Q 181. What Is The Difference Between Fopen And Is_open Functions?


The difference between FOPEN and IS_OPEN functions is given as follows:
FOPEN -Opens a file for input/output and returns a file handle used in I/O
operations. Following is the syntax of the FOPEN function:
IS_OPEN - Returns a Boolean value when the file handle is passed as a parameter to
the function to an open file. Following is the syntax of the IS_OPEN function:

Q 182. What Packages (if Any) Has Oracle Provided For Use By Developers?
Oracle provides the DBMS_ series of packages. There are many which developers
should be aware of such as DBMS_SQL, DBMS_PIPE, DBMS_TRANSACTION, DBMS_LOCK,
DBMS_ALERT, DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_DDL, UTL_FILE.

Q 183. How Can You Generate Debugging Output From Pl/sql?


Use the DBMS_OUTPUT package. Another possible method is to just use the SHOW ERROR
command, but this only shows errors. The DBMS_OUTPUT package can be used to show
intermediate results from loops and the status of variables as the procedure is
executed. The new package UTL_FILE can also be used.

Q 184. Can One Read/write Files From Pl/sql?


Included in Oracle 7.3 is a UTL_FILE package that can read and write files. The
directory you intend writing to has to be in your INIT.ORA file (see
UTL_FILE_DIR=... parameter). Before Oracle 7.3 the only means of writing a file was
to use DBMS_OUTPUT with the SQL*Plus SPOOL command.
DECLARE
fileHandler UTL_FILE.FILE_TYPE;
BEGIN
fileHandler := UTL_FILE.FOPEN('/home/oracle/tmp','myoutput','W');
UTL_FILE.PUTF(fileHandler, 'Value of func1 is %sn',func1(1));
UTL_FILE.FCLOSE(fileHandler);
END;

Q 185. Is it possible to read/write files to-and-from PL/SQL?


By making use of the UTL_FILE package, which was introduced in Oracle 7.3, we can
make our PL/SQL code write and read files to and from our computer. However, you
still need to receive an access grant by a DBA user to do such an activity. This
promotes security and prevent intrusive coding.
For example:
CONNECT / AS SYSDBA
CREATE OR REPLACE DIRECTORY dir AS `/temp';
GRANT read, write ON DIRECTORY dir to test;
To grant the user to access to UTL_FILE:
GRANT EXECUTE ON UTL_FILE to test;
To write to a File:

DECLARE
handlerOne UTL_FILE.FILE_TYPE;
BEGIN
handlerOne := UTL_FILE.FOPEN(`DIR', `tofile', `w');
UTL_FILE.PUTF(handlerOne, `Write To File. \n');
UTL_FILE.FCLOSE(handlerOne);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, `Path is Invalid. Check UTL_FILE_DIR');
END;
To read from a File:

DECLARE
handlerOne UTL_FILE.FILE_TYPE;
bufferOne varchar2(4000);
BEGIN
handlerOne := UTL_FILE.FOPEN(`DIR', `tofile', `r');
UTL_FILE.GET_LINE(handlerOne, bufferOne);
Dbms_output.put_line(`The Contents from the File are: ' || bufferOne);
UTL_FILE.FCLOSE(handlerOne);
EXCEPTION
WHEN utl_file.invalid_path THEN
raise_application_error(-20000, `Path is Invalid. Check UTL_FILE_DIR');
END;

Q 186. What is a Statement Level Trigger?


A Statement Level trigger is executed when a statement or a command affects the
whole table which is independent of a row in any table.

Q 187. How can you enable or disable a trigger?


To Enable a Trigger, the Syntax is: Alter Trigger Trigger_Name Enable;
To Disable a Trigger, the Syntax is: Alter Trigger Trigger_Name Disable;

Q 188) Explain mutating table error.


It occurs when a trigger tries to update a row that it is currently in execution
stage. It is fixed by using views or temporary tables, so database selects one and
updates the other.

Q 189. What is the maximum limit of applying Triggers to a Table?


The maximum number of Triggers that can be applied to one table is 12.

Q 190. What is a Row Level Trigger?


A Statement Level Trigger is executed whenever a statement or a command affects a
row in a table by Database Manipulation Command (DML) statements like Delete,
Insert or Update.

Q 191. What is a Mutating Table Error and how can you solve it?
It occurs if the Trigger tries to update a row that is currently being used. This
is solved either by using the Temporary Tables or by the Views.

Q 192. What is a database trigger ? Name some usages of database trigger ?


Database trigger is stored PL/SQL program unit associated with a specific database
table. Usages are Audit data modificateions, Log events transparently, Enforce
complex business rules Derive column values automatically, Implement complex
security authorizations. Maintain replicate tables.

Q 193. How many types of database triggers can be specified on a table? What
are they?
Insert Update Delete

Before Row o.k. o.k. o.k.

After Row o.k. o.k. o.k.

Before Statement o.k. o.k. o.k.

After Statement o.k. o.k. o.k.

If FOR EACH ROW clause is specified, then the trigger for each Row affected by the
statement.

If WHEN clause is specified, the trigger fires according to the retruned boolean
value.

Q 194. Is it possible to use Transaction control Statements such a ROLLBACK or


COMMIT in Database Trigger? Why?
It is not possible. As triggers are defined for each table, if you use COMMIT
of ROLLBACK in a trigger, it affects logical transaction processing.

Q 195. What are two virtual tables available during database trigger
execution?
The table columns are referred as OLD.column_name and NEW.column_name.
For triggers related to INSERT only NEW.column_name values only available.
For triggers related to UPDATE only OLD.column_name NEW.column_name values only
available.
For triggers related to DELETE only OLD.column_name values only available.

Q 196. What happens if a procedure that updates a column of table X is called


in a database trigger of the same table?
Mutation of table occurs.

Q 197. What Is A Mutating Table Error And How Can You Get Around It?
This happens with triggers. It occurs because the trigger is trying to update a row
it is currently using. The usual fix involves either use of views or temporary
tables so the database is selecting from one while updating the other.

Q 198. What are the different components of a PL/SQL trigger?


Trigger Action, Trigger Restriction and Trigger Action are the different components
of a PL/SQL Trigger.

Q 199. Describe the disadvantage of Database Trigger over Stored Procedures?


We cannot control the execution of a Trigger whereas a Stored Procedure Execution
can be controlled by the programmer.

Q 200.) Is it possible to use Transaction control Statements such a ROLLBACK or


COMMIT in Database Trigger ? Why ?
Ans: It is not possible. As triggers are defined for each table, if you use COMMIT
of ROLLBACK in a trigger, it affects logical transaction processing.

Q 201.What is Database Trigger?What is real use of trigger?


A trigger is a PL/SQL program that is stored in the database and executed
immediately before or after the INSERT, UPDATE, and DELETE commands.Examples of
Trigger :
1)Audit data modifications.
2)Log events transparently.
3)Enforce complex business rules.
4)Maintain replica tables
5)Derive column values
6)Implement Complex security authorizations.

Q 202. What is mutating error?(90% asked PL SQL Interview Qs)


It occurs when a trigger tries to update a row that it is currently using. It is
fixed by using views or temporary tables, so database selects one and updates the
other.

Q 203. How can we implement Rollback or Commit statement in a Trigger?


We cannot. It is not logical to put a Rollback or Commit within a Trigger because
these statements impose a savepoint which affects the logical transaction
processing.

Q 204.) What is the difference between execution of triggers and stored procedures?
A trigger is automatically executed without any action required by the user, while,
a stored procedure is explicitly invoked by the user.

Q 205) What happens when a trigger is associated to a view?


When a trigger is associated to a view, the base table triggers are normally
enabled.

Q 206) What is the usage of WHEN clause in trigger?


A WHEN clause specifies the condition that must be true for the trigger to be
triggered.

Q 207) How to disable a trigger name update_salary?


ALTER TRIGGER update_salary DISABLE;

Q 208) Which command is used to delete a trigger?


DROP TRIGGER command.

Q 209. What is Mutating Trigger?


Into a row level trigger based on a table trigger body cannot read data from same
table and also we cannot perform DML operation on same table.
If we are trying this oracle server returns mutating error oracle-4091: table is
mutating.
This error is called mutating error, and this trigger is called mutating trigger,
and table is called mutating table. Mutating errors are not occured in statement
level trigger because through these statement level trigger when we are performing
DML operations automatically data committed into the database, whereas in row level
trigger when we are performing transaction data is not committed and also again we
are reading this data from the same table then only mutating errors is occured.

Q 210. What is Triggering Events (or) Trigger Predicate Clauses?


If we want to perform multiple operations in different tables then we must use
triggering events within trigger body. These are inserting, updating, deleting
clauses. These clauses are used in statement, row-level trigger. These triggers are
also called as trigger predicate clauses.
Syntax:
If inserting then
stmts;
else if updating then
stmts;
else if deleting then
stmts;
end if;

Q 211) How would you reference column values BEFORE and AFTER you have inserted and
deleted triggers?
Using the keyword "new.column name", the triggers can reference column values by
new collection. By using the keyword "old.column name", they can reference column
vaues by old collection.

Q 212. How can we implement Rollback or Commit statement in a Trigger?


We cannot. It is not logical to put a Rollback or Commit within a Trigger because
these statements impose a savepoint which affects the logical transaction
processing.

Q 213) Explain the difference between Triggers and Constraints?


Answer: Triggers are different from constraints in the following ways
Triggers Constraints
Only affect those rows added after the trigger is enabled. Affect all rows of the
table including that already exist when the constraint is enabled.
Triggers are used to implement complex business rules which cannot be implemented
using integrity constraints. Constraints maintain the integrity of the database.

Q 214. Cite the differences between execution of triggers and stored procedures?
Triggers are activated automatically if the criteria for activation is met. This
requires virtually no input or action from the user. On the other hand, a stored
procedure requires to be explicitly called for it to be activated.
What is the cause of mutating table error and how can we solve it?
This error occurs when an activated trigger causes a change or update in currently
used table row. This is fixed using views or temp tables instead of the actual
table being used so that the database can provide use for the table row, while
updating/changing the other.

Q 215. Is It Possible To Create A Package Body And Store It In A Database?


Yes, it is possible to create a package body and store it in the database, although
it would be in an invalid state and cannot be executed.

Q 216) What do you understand by PL/SQL packages?


Answer: PL/SQL packages are schema objects that groups functions, stored
procedures, cursors and variables at one place. Packages have 2 mandatory parts
Package Specifications
Package body

Q 217. Give The Sql Statement To Drop The Package Specification For Pack_a Without
Dropping The Package Body ?
It Is not possible to drop a package specification and leave the package body. If
the package is dropped, the whole package is removed from a database.

Q 218. Where Can A Package Be Stored?


A package can be stored on the server side within a schema in the database. It can
also be stored on the client side in the form of Oracle Reports, Oracle Forms, or
as part of PL/SQL library.

Q 219. Does A Package Is Recompiled If The Database Objects That The Package Uses
Are Modified?
Yes, if the database objects associated with the package are modified, the package
specification and the package body become invalid; and therefore, the package needs
recompilation using the following syntax:

Q 220. Are Global Constructs Declared In Packages Available To The Entire User
Session?
Global constructs once declared in package are available throughout the user
session. Until the user session is terminated, the global construct retains its
value across the PL/SQL blocks. This is applicable for all the packaged global
constructs, such as constants, exceptions, and cursors. For example, a globally
declared cursor may be opened in one PL/SQL block, fetched in another block, and
closed in some other block.

Q 221. Where Can A Constant Be Referenced If The Constant Is Declared In A Package


Specification?
The constant declared in a package specification can be referenced in the same
package where it is declared, stored procedure, stored function, or an anonymous
b : c.

Q 222. Can A Variable Be Referenced In A Package If It Is Declared In The Package


Body Of Another Package?
Variables declared in a package body are private variables. Therefore, these cannot
be referenced in other packages.

Q 223. How Many Entries Does The User_objects Data Dictionary Have For A Package?
Two separate entries are created for package specification and package body in the
USER_OBJECTS data dictionary.
Q. What Is The Minimum Requirement To Create A Package?
Package specification, which declares constructs, such as variables, constants,
user-defined exceptions, and cursors, is enough to create a complete package.
Package body is not required if there are no procedures and functions to be defined
in the package.

Q 224. How Can A Public Exception, Which Is Global In Nature, Be Created In A


Package?
An exception is called a public exception if it is declared in a package
specification as a separate construct, as shown in the following code:

Q 225. Write A Statement To Display The Text Of The Test_packl Package From Data
Dictionary View ?
The statement is given as follows:

Q 226. How The Concept Of Overloading Is Implemented Within A Package?


PL/SQL allows you to overload the subprogram names and type methods. The package
can include subprograms that have the same name as long as they have different
formal parameters. PL/SQL determines which subprogram to be called depending on the
formal parameters. In PL/SQL, only packaged subprograms can be overloaded.

Q 227) Explain polymorphism in PL SQL.


Polymorphism is a feature of OOP. It is the ability to create a variable, an object
or function with multiple forms. PL/SQL supports Polymorphism in the form of
program unit overloading inside a member function or package..Unambiguous logic
must be avoided whilst overloading is being done.

Q 228. What Is The Difference Between Local And Global Variables Within A Package?
A local variable is defined within a package body and is only available to the
constructs within the same package.

A global variable is one that is declared in the package specification. This can be
referenced outside the package and is visible, to external objects that have access
privilege on the package.

Q 229. How Is Global Variable Declared Within A Nested Block?


Any variable declared within a block is local to the block and global to the nested
blocks. The variables declared within the nested blocks are unknown to the outer
blocks. They override the references to any outer declared variables with the same
name unless they are used with the block label name.
Q 230) What are two parts of package ?
The two parts of package are PACKAGE SPECIFICATION & PACKAGE BODY.
Package Specification contains declarations that are global to the packages and
local to the schema.
Package Body contains actual procedures and local declaration of the procedures and
cursor declarations.

Q 231) Mention what does PLVtab enables you to do when you show the contents of
PL/SQL tables?
PLVtab enables you to do following things when you show the contents of PL/SQL
tables
Display or suppress a header for the table
Display or suppress the row numbers for the table values
Show a prefix before each row of the table

Q 232. Do Stored Procedures And Functions Within The Same Schema Share The Same
Namespace?
Yes, stored procedures and functions within the same schema share the same
namespace.

Q 233. Suppose A Procedure Proc_1 Refers To A Procedure Proc_2 Within The Pack_1
Package. If The Definition Of The Proc_2 Procedure Is Changed And It Is Recompiled
Again, Then Does The Proc_1 Procedure Is Invalidated ?
If the declaration of the proc_2 procedure is not altered in the package
specification, then the proc_1 procedure is not invalidated. However, if the
specification of the procedure is altered, then the dependent procedure gets the
invalid status.

Q 234. Give A Sql Statement To Grant Access On The Procedure Proc_sample In The
Schema, Schema_a.

Q 235. Give A Sql Statement So That The Procedure Proc_1 In The Package Pack_sample
Is Granted Access To All The Users In The Database?

Q 236. Suppose A Package Pack.a With A Procedure Proc_1 Exists In The Schema
Sample_one_schema. If The Schema Sample_two_schema Needs To Be Given Privilege To
Execute The Procedure Proc_1, Which Privilege Has To Be Granted ?
The statement is as follows:
GRANT EXECUTE ON PACK_A TO SAMPLE_TWO_SCHEMA
The privilege is always granted on the whole package and not on the individual
procedures or functions.

Q 237. What are expressions?


Answer: Expressions are represented by a sequence of literals and variables that
are separated by operators. In PL/SQL, operations are used to manipulate, compare
and calculate some data. An expression is a composition of `Operators' and
`Operands'.
Operands: These are an argument to the operators. Operands can be a variable,
function call or constant.
Operators: These specify the actions to be performed on operators. E.g. `+',
`*', etc.

Q 238. List different type of expressions with the example.


Answer: Expressions can be as mentioned below
Numeric or Arithmetic expressions : e.g. 20* 10+ 15
Boolean expressions: e.g. `spot' LIKE `sp%t'
String expressions: e.g. LENGTH (`NEW YORK'|| `NY')
Date expressions: e.g. SYSDATE>TO_DATE('15-NOV-16', "dd-mm-yy")
Q 239. Write a program that shows the usage of WHILE loop to calculate the average
of user entered numbers and entry of more numbers are stopped by entering number 0?
Answer

DECLARE
n NUMBER;
avg NUMBER :=0 ;
sum NUMBER :=0 ;
count NUMBER :=0 ;
BEGIN
n := &enter_a_number;
WHILE(n<>0)
LOOP
count := count+1;
sum := sum+n;
n := &enter_a_number;
END LOOP;
avg := sum/count;
DBMS_OUTPUT.PUT_LINE(`the average is'||avg);
END;

Q 240. Mention what PLVcmt and PLVrb does in PL/SQL?


PL/Vision offers two packages that help you manage transaction processing in PL/SQL
application. It is PLVcmt and PLVrb.
PLVcmt: PLVcmt package wraps logic and complexity for dealing with commit
processing
PLVrb: It provides a programmatic interface to roll-back activity in PL/SQL

Q 241. How are functions and procedures called in PL/SQL?


For Procedures:
o CALL <procedure name> to call it directly
o EXECUTE <procedure name> from calling environment
o <Procedure name> from other procedures or functions or packages
Functions are called directly from other programs or procedures, no additional
keyword is required.

Q 242. Define Overloaded Procedure


An overloaded procedure is a feature in PL/SQL that enables the developer to re-use
and existing procedure with the exact name by varying the parameter structure such
as the data type and parameter number. This is synonymous to the overloaded
methods/functions in fundamental programming. This promotes uniformity and
versatility of a PL/SQL block by giving a specific name procedure multiple ways to
be called and multiple circumstances to operate.
An overloaded procedure is nothing more than a mechanism that allows the coder to
reuse the same procedure name for different subprograms inside a PL/SQL block by
varying the number of parameters or the parameter data type. Below is an example of
where the same subprogram (callit) is reused but the data type for the input
parameter is changed from INTEGER to VARCHAR2; Oracle is smart enough to know the
input parameter type and call the proper subprogram.

SQL>
DECLARE
PROCEDURE ovlprocedure (num1 INTEGER) IS
BEGIN
DBMS_OUTPUT.PUT_LINE('Parameter is an INTEGER');
END ovlprocedure;

PROCEDURE ovlprocedure (character VARCHAR2) IS


BEGIN
DBMS_OUTPUT.PUT_LINE('Parameter is a VARCHAR2');
END ovlprocedure;
BEGIN
ovlprocedure (99);
ovlprocedure ('Hello');
* END;
SQL> /
Parameter is an INTEGER
Parameter is a VARCHAR2
PL/SQL procedure successfully completed.

Q 243. What are Integrity Rules?


The Entity Integrity Rule(EIR) states that the Primary key must have value always
or not Null.
The Foreign Key Integrity Rule(FKIR) states that if there exists a database
relationship between a foreign key and a primary key, the Master Table cannot be
deleted WHEN THERE IS DATA EXISTING IN THE CHILD TABLE.
The Business Integrity Rules encompasses the underlying processing not included in
FKIR and EIR.

Q 244. How can we make an IF Statement within a SELECT Statement?


We make use of the DECODE keyword. For example,
e.g. select DECODE (EMP_CAT,'3?,'Third','4?,'Fourth'Null);

Q 245. What is Normalization?


Normalization is a neat feature where redundant tables and duplicate attributes are
purposely removed to optimize the logical layout of the structure makes it easier
to manage. This also improves data retrieval and nowadays, more and more servers
implement normalized databases because of improvisations.
a) 1 Normal Form : This states that the database doesn't have duplicate attributes.
b) 2 Normal Form: This states that all the candidate keys are linked on the primary
key. Problems related to 2 Normal Form occurs when a multiple columned primary key
exists.
c) 3rd Normal Form : This states that if transitive dependency doesn't occur in a
table, it is of 3rd Normal Form

Q 246. What is an example of translating a date into Julian Format?


We make use of the String Format: `J'
For example, SQL > select to_char(to_date(`5-Dec-2017','dd-mon-yyyy'),'J')

Q 247. What are the various restrictions imposed on View in terms of DML?
These are you are NOT ALLOWED to delete rows of Views containing: The Distinct
keyword, Group Functions, The Pseudocolumn ROWNUM keyword, or a Group by Clause.
The other restriction is that you are NOT ALLOWED to change contents in a View that
contains: The Distinct keyword, Group Functions, The Pseudocolumn ROWNUM keyword, a
Group by Clause, or Expression-defined Columns (e.g. number_of_days * 7)
Few restrictions of DML operations on Views are:
You cannot DELETE a row if the View contains the following:
1) Group Functions
2) A Group By clause
3) The Distinct Keyword
4) The Pseudo column ROWNUM Keyword.
You cannot MODIFY data in a View if it contains the following:
1) Group Functions
2) A Group By clause
3) The Distinct Keyword
4) The Pseudo column ROWNUM Keyword.
5) Columns defined by expressions (Ex; Salary * 12)
Q 248. What is PL/SQL Records?
PS/SQL Records is type of data structure that contain a set of data(can be of
various types), or distinct information values that can be referenced with each
other as fields. They are useful for classifying and retrieving data with common
attributes or properties. With this, it is much easier to identify similar data by
tracing the attributes.
PL/SQL can manage three types of records:
Table based records
Programmer based records
Cursor based records

Q 249. How to Fix Oracle Error ORA-00942: table or view does not exist
There are two ways to check and fix this error.
o Check for typo error in your program, also check if the table and views are
created or not and you are connecting to correct database.
o Check if your user has required permissions or not, this is also one of the
reason where you can't see the table or view.

Q 250. How can we debug in PL/SQL?


We can make use of the DBMS_OUTPUT for printing breakpoint activities. We can also
use DBMS_DEBUG.

Q 251. Is it possible to pass an object or table to a procedure as an argument?


Using database links, we can pass an object type of a certain database into another
database. By this, we can pass these as arguments and be used by another procedure
that contains the appropriate parameter argument type to receive this object. For
example

-- Database One: receives the table as an argument and stored to TableTest

CREATE OR REPLACE PROCEDURE receiveTable(TableTest DBMS_SQL.VARCHAR2S) IS


BEGIN
--
null;
END;
/

-- Database Two: passes the table as an argument and is hoped to be received by


`receiveTable'

CREATE OR REPLACE PROCEDURE sendTable IS


TableTest DBMS_SQL.VARCHAR2S@DBLINK2;
BEGIN
receiveTable @DBLINK2(TableTest);
END;
/

Q 252. How many times can we COMMIT in a loop?


It is advised to commit as least as possible especially within loops or iterative
statements. This is to minimize resource over usage on instances that the loops
were poorly constructed or no end keyword, resulting in a leak and infinite calls
to the COMMIT block. This scenario results in a ORA-1555 error.
In declaring undo or rollback statements, having the least number COMMITS lessens
the stress and code execution of these state, resulting in a faster and much more
responsive rollbacks.
Also it is of good programming habit to allocate the least amount of memory
resource as much as possible while keeping the same functionality of the code. This
is done by minimizing the overuse of COMMIT within the code.
Q 253. How do we accept inputs from user during runtime?
The ACCEPT keyword is used to receive inputs from the user. It also allows the
received data to be buffered to a variable for storage.
For example:

> accept y number prompt 'Enter your desired number: '

>declare
z number;
begin
z := &y;
end;

Q 254. How can we connect an Android App to an Oracle database and use the PL/SQL
procedural code?
Before getting into the PL/SQL, we must create a REST API using JSON for
establishing connection. You can import the Retrofit libraries along with
dependencies to establish communication with your Android App. Then prepare the
functions and procedures using PL/SQL, and then once your oracle database is
connected you are good to go.

Q 255. Show how functions and procedures are called in a PL SQL block.
Function is called as a part of an expression.
total:=calculate_sal('b644')
Procedure is called as a statement in PL/SQL.
calculate_bonus('b644');

Q 256. What are the rules to be applied to NULLs whilst doing comparisons?
NULL is never TRUE or FALSE
NULL cannot be equal or unequal to other values
If a value in an expression is NULL, then the expression itself evaluates to NULL
except for concatenation operator (||)

Q 257. How is a process of PL SQL compiled?


Compilation process includes syntax check, bind and p-code generation processes.
Syntax checking checks the PL SQL codes for compilation errors. When all errors are
corrected, a storage address is assigned to the variables that hold data. It is
called Binding. P-code is a list of instructions for the PL SQL engine. P-code is
stored in the database for named blocks and is used the next time it is executed.

Q 258. What operators deal with NULL?


NVL converts NULL to another specified value.
var:=NVL(var2,'Hi');
IS NULL and IS NOT NULL can be used to check specifically to see whether the value
of a variable is NULL or not.

Q 259. Does SQL*Plus also have a PL/SQL Engine?


No, SQL*Plus does not have a PL/SQL Engine embedded in it. Thus, all PL/SQL code is
sent directly to database engine. It is much more efficient as each statement is
not individually stripped off.

Q 260. What packages are available to PL SQL developers?


DBMS_ series of packages, such as, DBMS_PIPE, DBMS_DDL, DBMS_LOCK, DBMS_ALERT,
DBMS_OUTPUT, DBMS_JOB, DBMS_UTILITY, DBMS_SQL, DBMS_TRANSACTION, UTL_FILE.

Q 261. What are character functions?


INITCAP, UPPER, SUBSTR, LOWER and LENGTH are all character functions. Group
functions give results based on groups of rows, as opposed to individual rows. They
are MAX, MIN, AVG, COUNT and SUM.
Q 262. Explain TTITLE and BTITLE.
TTITLE and BTITLE commands that control report headers and footers.

Q 263. Explain Consistency


Consistency shows that data will not be reflected to other users until the data is
commit, so that consistency is maintained.

Q 264. Differ between Anonymous blocks and sub-programs.


Anonymous blocks are unnamed blocks that are not stored anywhere whilst sub-
programs are compiled and stored in database. They are compiled at runtime.

Q 265. Differ between DECODE and CASE.


DECODE and CASE statements are very similar, but CASE is extended version of
DECODE. DECODE does not allow Decision making statements in its place.
select decode(totalsal=12000,'high',10000,'medium') as decode_tesr from smp where
smpno in (10,12,14,16);
This statement returns an error.
CASE is directly used in PL SQL, but DECODE is used in PL SQL through SQL only.

Q 266. Explain autonomous transaction.


An autonomous transaction is an independent transaction of the main or parent
transaction. It is not nested if it is started by another transaction.
There are several situations to use autonomous transactions like event logging and
auditing.

Q 267. Can 2 queries be executed simultaneously in a Distributed Database System?


Yes, they can be executed simultaneously. One query is always independent of the
second query in a distributed database system based on the 2 phase commit.

Q 268. What is out parameter used for eventhough return statement can also be used
in pl/sql?
Out parameters allows more than one value in the calling program. Out parameter is
not recommended in functions. Procedures can be used instead of functions if
multiple values are required. Thus, these procedures are used to execute Out
parameters.

Q 269. Mention what PL/SQL package consists of?


A PL/SQL package consists of
PL/SQL table and record TYPE statements
Procedures and Functions
Cursors
Variables ( tables, scalars, records, etc.) and constants
Exception names and pragmas for relating an error number with an exception
Cursors

Q 270. Mention what are different methods to trace the PL/SQL code?
Tracing code is a crucial technique to measure the code performance during the
runtime. Different methods for tracing includes
DBMS_APPLICATION_INFO
DBMS_TRACE
DBMS_SESSION and DBMS_MONITOR
trcsess and tkproof utilities

Q 271. Mention what does PLV msg allows you to do?


The PLV msg enables you to
Assign individual text message to specified row in the PL/SQL table
It retrieves the message text by number
It substitutes automatically your own messages for standard Oracle error
messages with restrict toggle
Batch load message numbers and text from a database table directly PLV msg
PL/SQL table

Q 272. Mention what is the PLV (PL/Vision) package offers?


Null substitution value
Set of assertion routines
Miscellaneous utilities
Set of constants used throughout PL vision
Pre-defined datatypes

Q 273. Mention what is the use of PLVprs and PLVprsps?


PLVprs: It is an extension for string parsing for PL/SQL, and it is the
lowest level of string parsing functionality
PLVprsps: It is the highest level package to parse PL/SQL source code into
separate atomics. It relies on other parsing packages to get work done.

Q 274. Explain how you can copy a file to file content and file to PL/SQL table in
advance PL/SQL?
With a single program call - "fcopy procedure", you can copy the complete
contents of one file into another file. While to copy the contents of a file
directly into a PL/SQL table, you can use the program "file2pstab".

Q 275. Explain how exception handling is done in advance PL/SQL?


For exception handling PL/SQl provides an effective plugin PLVexc. PLVexc
supports four different exception handling actions.
Continue processing
Record and then continue
Halt processing
Record and then halt processing
For those exceptions that re-occurs you can use the RAISE statement.

Q 276. Mention what problem one might face while writing log information to a data-
base table in PL/SQL?
While writing log information to a database table, the problem you face is
that the information is only available only once the new rows are committed to the
database. This might be a problem as such PLVlog is usually deployed to track
errors and in many such instances the current transaction would fail or otherwise
needed a rollback.

Q 277. Mention what is the function that is used to transfer a PL/SQL table log to
a database table?
To transfer a PL/SQL table log a database log table function "PROCEDURE ps2db" is
used.

Q 278. When you have to use a default "rollback to" savepoint of PLVlog?
The default "rollback to" savepoint of PLVlog is used when the users has turned on
the rollback activity and has not provided an alternative savepoint in the call to
put_line. The default savepoint is initialized to the c none constant.

Q 279. Why PLVtab is considered as the easiest way to access the PL/SQL table?
The PL/SQL table are the closest to arrays in PL/SQL, and in order to access this
table you have to first declare a table type, and then you have to declare PL/SQL
table itself. But by using PLVtab, you can avoid defining your own PL/SQL table
type and make PL/SQL data-table access easy.

Q 280. Explain how can you save or place your msg in a table?
To save msg in a table, you can do it in two ways
Load individual messages with calls to the add_text procedure
Load sets of messages from a database table with the load_from_dbms procedure

Q 281. Mention what is the use of function "module procedure" in PL/SQL?


The "module procedure" enables to convert all the lines of code in a definite
program unit with one procedure call. There are three arguments for modules
module_in
cor_in
Last_module_in

Q 282. What is Difference Between trim, delete collection method?

Q 283. What is Forward Declaration?


In oracle declaring procedures within package body is called forward declaring
generally before we are calling private procedures into public procedure first we
must implements private into public procedure first we must implements private
procedure within body otherwise use a forward declaration within package body.

Q.284 What is Invalid_number, Value_Error?


In oracle when we try to convert "string type to number type" or" data string into
data type" then oracle server returns two types of errors.
1. Invalid.number
2. Value_error (or) numeric_error

a) Invalid_number:
When PL/SQL block have a SQL statements and also those SQL statements try to
convert string type to number type or data string into data type then oracle server
returns an error: ora-1722-Invalid Number
For handling this error oracle provides number exception Invalid_number
exceptionname.
Example:
begin
Insert into
emp(empno, ename, sal) values(1,'gokul', `abc')
exception
when invalid_number then
dbms_output.put_line(`insert proper data only');
end;
/

b)value_error
Whenever PL/SQL block having procedural statements and also those statements find
to convert string type to number type then oracle servers returns an error: ora-
6502:numeric or value error: character to number conversion error
For handling this error oracle provided exception value_error exception name
Example:
begin
declare
z number(10);
begin
z:= `&x' + `&y';
dbms_output.put_line(z);
exception
when value_error then
dbms_output.put_line(`enter numeric data value for x & y only');
end;
/

Output:
Enter value for x:3
Enter value for y:2
z:=5
Enter value for x:a
Enter value for y:b
Error:enter numeric data value for x & y only.

Q 285. What is the difference between FUNCTION, PROCEDURE AND PACKAGE in PL/SQL?
Function: The main purpose of a PL/SQL function is generally to compute and return
a single value. A function has a return type in its specification and must return a
value specified in that type.
Procedure: A procedure does not have a return type and should not return any value
but it can have a return statement that simply stops its execution and returns to
the caller. A procedure is used to return multiple values otherwise it is generally
similar to a function.
Package: A package is schema object which groups logically related PL/SQL types ,
items and subprograms. You can also say that it is a group of functions, procedure,
variables and record type statement. It provides modularity, due to this facility
it aids application development. It is used to hide information from unauthorized
users.

Q 286. How to write a single statement that concatenates the words ?Hello? and ?
World? and assign it in a variable named Greeting?
Greeting := 'Hello' || 'World';

Q 287. Does PL/SQL support CREATE command?


No. PL/SQL doesn't support the data definition commands like CREATE.

Q 288. Write a unique difference between a function and a stored procedure.


A function returns a value while a stored procedure doesn?t return a value.

Q 289. How exception is different from error?


Whenever an Error occurs Exception arises. Error is a bug whereas exception is a
warning or error condition.

Q 290. How do you declare a user-defined exception?


You can declare the User defined exceptions under the DECLARE section, with the
keyword EXCEPTION.
Syntax:
1. <exception_name> EXCEPTION;

Q 291. What are some predefined exceptions in PL/SQL?


A list of predefined exceptions in PL/SQL:
DUP_VAL_ON_INDEX
ZERO_DIVIDE
NO_DATA_FOUND
TOO_MANY_ROWS
CURSOR_ALREADY_OPEN
INVALID_NUMBER
INVALID_CURSOR
PROGRAM_ERROR
TIMEOUT _ON_RESOURCE
STORAGE_ERROR
LOGON_DENIED
VALUE_ERROR
etc.

Q 292. What is mean by Unique Indexes?(90% asked PL SQL Interview Qs)


1.To create unique index you must have CREATE ANY INDEX privilege.Here the concept
is bit different.User needs to check the values of the table to create unique
index.If table contains uniquely identified values in specified column then you
should use unique index.
2.Especially while creating the table if we specify the primary key then unique
index is automatically created on that column.
3.But for Unique key constaint columns you separately need to do indexing.Kindly
make sure that Unique key indexes created on the columns which has unique values
only.
4.The unique indexes are also called as clustered indexes when primary key is
defined on the column.
Example:
Create Unique index Index_name on Table_name(Unique column name);
Example:
CREATE UNIQUE INDEX UI1_EMP on EMP(EMP_ID);
NO TIME TO READ CLICK HERE TO GET THIS ARTICLE

Q 293. What is Bit-map index?Explain with Example.(80 % Asked in PL SQL Interview


Qs)
1.If Table contains the distinct values which are not more than 20 distinct values
then user should go for Bit map indexes.
2.User should avoid the indexing on each and every row and do the indexing only on
distinct records of the table column.You should able to check drastic change in
query cost after changing the normal index to Bit map index.
3.The bit map indexes are very much useful in dataware housing where there are low
level of concurrent transactions.Bit map index stores row_id as associated key
value with bitmap and did the indexing only distinct values.
4.Means If in 1 million records only 20 distinct values are there so Bitmap index
only stores 20 values as bitmap and fetches the records from that 20 values only.
Syntax:
Create bitmap index Index_name on Table_name(Columns which have distinct values);
Example:
CREATE BITMAP index BM_DEPT_NAME on DEPT(Department_name);

Q 294. What is sequences in PL SQL?


Sequences are used to generate sequence numbers without an overhead of locking. Its
drawback is that the sequence number is lost if the transaction is rolled back.

Q 295. What is database link used for?


Database links are used to communicate between 2 databases.Database links are
created in order to form communication between various databases, or different
environments like test, development and production.When user wants to insert or
update data from one environment to another environment then database links are
used.

Q 296. Give us example of Predefined Exceptions?


Answer :
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

Q 297. What is cost based optimizer?


Answer:
Cost Based Optimizer (CBO) uses the artificial intelligence to execute the Query.
The Optimizer itself decides the execution plan based on the cost of query. The
cost based method means the database must decide which query execution plan to
choose. It decides the query execution plan by deciding the statistical information
based on the database objects.(tables, indexes and clusters).The Oracle cost based
optimizer is designed to determine the most effective way to carry out the SQL
statement.
"Cost based optimizer considers the statistical information of the table for query
execution"

Q 298. Difference between SUBSTR and INSTR?


INSTR (String1, String2 (n, (m)), INSTR returns the position of the m-th occurrence
of the string 2 in string1. The search begins from nth position of string1.
SUBSTR (String1 n, m) SUBSTR returns a character string of size m in string1,
starting from n-th position of string1.

Q 299. What is Pragma EXECPTION_INIT ? Explain the usage ?


Ans: The PRAGMA EXECPTION_INIT tells the complier to associate an exception with an
oracle error. To get an error message of a specific oracle error.
E.g.: PRAGMA EXCEPTION_INIT (exception name, oracle error number)

Q 300. Give the structure of the procedure ?


Ans: PROCEDURE name (parameter list...)
is local variable declarations
BEGIN
Executable statements.
Exception.
exception handlers
end;

Q 301. Give the structure of the function ?


Ans:
FUNCTION name (argument list ...) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;

Q 302. Explain how procedures and functions are called in a PL/SQL block ?
Ans: Function is called as part of an expression.
sal : = calculate_sal (`a822');
procedure is called as a PL/SQL statement
calculate_bonus (`A822');

Q 303. What is a package ? What are the advantages of packages ?


Ans: Package is a database object that groups logically related procedures. The
advantages of packages are Modularity, Easier Application Design, Information.
Hiding,. reusability and Better Performance.

Q 304. Name the tables where characteristics of Package, procedure and functions
are stored ?
Ans: User_objects, User_Source and User_error

Q 305. Explain the difference between Varchar and Char?


Varchar doesn't sets aside memory location during declaration of a variable. It
stores the value only after a variable is defined or assigned a value. Its storage
capacity is 32767 Bytes.
Char however preserves the memory location mentioned in the variable declaration
even if it is not used. The maximum storage capacity for a Character variable is
255 Bytes.

Q 306. Explain Union, Union All, Intersect and Minus in PL/SQL.


Union: It returns all the distinct rows selected by either of the Queries.
Union All: It returns all the rows selected by one of the queries which includes
all the duplicates.
Intersect: It returns all the distinct rows selected by both the queries.
Minus: It returns all the distinct rows selected by the first query and not by the
second one.

Q307. What is the difference between Varchar2 and Varchar?


Varchar2 Datatype is memory efficient as it variable memory storage datatype
whereas a Varchar Datatype variable is not memory efficient as it has fixed memory
storage. Varchar occupies space for NULL values whereas Varchar2 variable does not.
Varchar can store upto 2KB whereas a Varchar2 Datatype can store upto 4KB.

Q 308. Explain Bulk Collect.


It is a way of fetching a very big collection of data. With the help of Oracle Bulk
Collect, the PL/SQL Engine indicates the SQL Engine to collect more than one row at
a single point of time and stores them into a collection. Then it switches back to
the PL/SQL Engine. During the Bulk Collect, Context Switch at one point. The
performance improvement would be better with the more number of rows fetched into
the collection.

Q 309. Give the structure of the procedure?


PROCEDURE name (parameter list.....)
is
local variable declarations

BEGIN
Executable statements.
Exception.
exception handlers

end;

Q 310. Give the structure of the function?


FUNCTION name (argument list .....) Return datatype is
local variable declarations
Begin
executable statements
Exception
execution handlers
End;

Q 311. Explain how procedures and functions are called in a PL/SQL block ?
Function is called as part of an expression.
sal := calculate_sal ('a822');
procedure is called as a PL/SQL statement
calculate_bonus ('A822');

Q 312. How packaged procedures and functions are called from the following ?
a. Stored procedure or anonymous block
b. an application program such a PRC *C, PRO* COBOL
c. SQL *PLUS
a. PACKAGE NAME.PROCEDURE NAME (parameters);
variable := PACKAGE NAME.FUNCTION NAME (arguments);
EXEC SQL EXECUTE
b.
BEGIN
PACKAGE NAME.PROCEDURE NAME (parameters)
variable := PACKAGE NAME.FUNCTION NAME (arguments);
END;
END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any out/in-out
parameters. A function can not be called.

Q 313. Name the tables where characteristics of Package, procedure and


functions are stored?
User_objects, User_Source and User_error.

Q 314. Is There A Limit On The Size Of A Pl/sql Block?


Currently, the maximum parsed/compiled size of a PL/SQL block is 64K and the
maximum code size is 100K. 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 315. What Is The Use Of Cascade Constraints?


When this clause is used with the DROP command, a parent table can be dropped even
when a child table exists.

Q 316. When Is A Declare Statement Needed ?


The DECLARE statement is used in PL/SQL anonymous blocks such as with stand alone,
non-stored PL/SQL procedures. It must come first in a PL/SQL stand alone file if it
is used.

Q 317. Give The Two Types Of Tables Involved In Producing A Star Schema And The
Type Of Data They Hold ?
Fact tables and dimension tables. A fact table contains measurements while
dimension tables will contain data that will help describe the fact tables.

Q 318. What Type Of Index Should You Use On A Fact Table ?


A Bitmap index.

Q 319. Give Two Examples Of Referential Integrity Constraints ?


primary key and a foreign key.

Q 320. A Table Is Classified As A Parent Table And You Want To Drop And Re-create
It. How Would You Do This Without Affecting The Children Tables?
Disable the foreign key constraint to the parent, drop the table, re-create the
table, enable the foreign key constraint.

Q 321. How Would You Determine The Time Zone Under Which A Database Was Operating?
select DBTIMEZONE from dual;

Q 322. What Command Would You Use To Encrypt A Pl/sql Application?


WRAP

Q 323. Explain The Difference Between A Function, Procedure And Package ?


A function and procedure are the same in that they are intended to be a collection
of PL/SQL code that carries a single task. While a procedure does not have to
return any values to the calling application, a function will return a single
value. A package on the other hand is a collection of functions and procedures that
are grouped together based on their commonality to a business function or
application.

Q 324. Explain The Use Of Table Functions ?


Table functions are designed to return a set of rows through PL/SQL logic but are
intended to be used as a normal table or view in a SQL statement. They are also
used to pipeline information in an ETL process.

Q 325. Explain Materialized Views And How They Are Used ?


Materialized views are objects that are reduced sets of information that have been
summarized, grouped, or aggregated from base tables. They are typically used in
data warehouse or decision support systems.

Q 326. How Would You Force A Log Switch ?


ALTER SYSTEM SWITCH LOGFILE;

Q 327. What Does Coalescing A Table Space Do?


Coalescing is only valid for dictionary-managed table spaces and de-fragments space
by combining neighboring free extents into large single extents.

Q 328. How Would You Determine Who Has Added A Row To A Table?
Turn on fine grain auditing for the table.

Q 329. How Can You Rebuild An Index?


ALTER INDEX REBUILD;

Q 330. Explain What Partitioning Is And What Its Benefit Is ?


Partitioning is a method of taking large tables and indexes and splitting them into
smaller, more manageable pieces.

Q 331. You Have Just Compiled A Pl/sql Package But Got Errors, How Would You View
The Errors?
SHOW ERRORS;

Q 332. How Can You Gather Statistics On A Table?


The ANALYZE command.

Q 333. How Can You Enable A Trace For A Session?


Use the DBMS_SESSION.SET_SQL_TRACE or
Use ALTER SESSION SET SQL_TRACE = TRUE;

Q 334. How Would You Go About Increasing The Buffer Cache Hit Ratio?
Use the buffer cache advisory over a given workload and then query the
v$db_cache_advice table. If a change was necessary then I would use the alter
system set db_cache_size command.

Q 335. Explain An Ora-01555 ?


You get this error when you get a snapshot too old within rollback. It can usually
be solved by increasing the undo retention or increasing the size of rollbacks. You
should also look at the logic involved in the application getting the error
message.

Q 336. Explain The Difference Between $oracle_home And $oracle_base ?


ORACLE_BASE is the root directory for oracle. ORACLE_HOME located beneath
ORACLE_BASE is where the oracle products reside.

Q 337. How Do You Prevent Oracle From Giving You Informational Messages During And
After A Sql Statement Execution?
The SET options FEEDBACK and VERIFY can be set to OFF.
Q 338. How Do You Prevent Output From Coming To The Screen?
The SET option TERMOUT controls output to the screen. Setting TERMOUT OFF turns off
screen output. This option can be shortened to TERM.

Q 339. What Is The Difference Between Sql And Pl/sql?


Structured Query Language (SQL) is a non-procedural language that interacts with
the database, and is used for database manipulation using the Data Definition
Language (DDL) and Data Manipulation Language (DML) statements. Control statements
cannot be used in SQL, which is compiled and executed statement by statement at the
runtime (late-binding).

PL/SQL is a programming language that allows the usage of Cursor Control statements
and Transaction Control statements, such as if...then...else. It integrates with
SQL functions and statements to interact and manipulate with the database. Unlike
SQL, PL/SQL statements are compiled and processed as a block of code into the
machine-readable code, which is executed at runtime (early binding); and therefore,
improves the performance.

Q 340. What Are The Mandatory Keywords In A Pl/sql Program Block?


The BEGIN and END keywords are mandatory for any PL/SQL block.

Q 341. Can Arrays Be Used Within A Pl/sql Program Block?


Yes, arrays can be defined and used in a PL/SQL block using the composite
datatypes, such as RECORD, TABLE, NESTED TABLE, and VARRAY.

Q 342. Can A Variable Be Assigned A Value From Database? If Yes, Then How?
Yes, a variable can be assigned a value from a database. You can fetch the value
from the database and assign it to the variable using the into keyword, as shown in
the following code:
select emp_sal * 0.20 into var_increment from
t_emolovee where emo_no = emo_id

Q 343. Explain about Package in short.


A Package is a Schema Object which assembles logically relate PL/SQL Datatypes and
Sub-Programs. It is actually a combination of Procedures, Functions, Record Type
and Variables. It enhances Application Development and this provides Modular
Programs. It also provides Encapsulation which hides data from Unauthorized Users.

Q 344. 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. These variables can be assigned a null value in a PL/SQL block, as shown
in the following code snippet:
DECLARE
var_emp_code t_employee.emp_codeflPE;
BEGIN
var_emp_code NULL;

Q 345. Can Sql Group Functions Be Used Within The Procedural Statements?
The SQL group functions, such as AVG, MIN, MAX, COUNT, SUM, STDDEV, and VARIANCE,
cannot be directly used within PL/SQL. However, they can be embedded within SQL
statements and then can be utilized in the procedural statements.

Q 346. 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 built-in Native
Dynamic SQL or Dynamic SQL Package, which allows the execution of the DDL
statements at runtime.

Q 347. What Is An Anonymous Block And How Is It Executed?


Anonymous blocks, as the name suggests, are PL/SQL blocks that are not given any
name and cannot be stored in the database. These blocks can call another blocks but
they cannot be called by any other block, as they do not have a name. An anonymous
block is executed by either storing the block code in a file or writing the block
code at the SQL prompt.

Q 348. What Is A Bind Variable And How Is It Used?


A bind variable is a variable within a SQL statement that has to be replaced by a
valid value on the successful execution of the statement. This value can be
referenced into the PL/SQL block. Bind variable is always preceded by a colon (:),
as shown in the following code:
Declare
y_emp_age number;
Begin
Select emp-age into :v_empLage from t_employee
where emp_code.121;
End;

In the preceding code, v_emp_age is a bind variable.

Q 349. What Are Transaction Control Statements? Can They Be Used Within The Pl/sql
Block?
Transaction Control statements are the COMMIT and REVOKE commands that control the
logic of transactions within a database. These statements are valid within a PL/SQL
block. The COMMIT command terminates the active transaction and makes the changes
permanent to the database. The ROLLBACK command terminates the active transaction
but cancels any changes that were made to the database.

Q 350. What Are Pseudo-columns? How Can You Use Pseudo Columns In Procedural
Statements?
Pseudo columns are not actual columns in a table but they behave like columns. They
are used in SQL statements to retrieve specific information. PL/SQL recognizes
pseudo-columns as a part of SQL statements but they cannot be used directly in a
procedural language. The following pseudo-columns are used in SQL:
ROWID
ROWNUM
LEVEL
CURRVAL
NEXTVAL

Q 351. How Can You Check If An Update Statement In Pl/sql Is Successfully Executed?
You can use the SQL%NOTFOUND attribute to check if the UPDATE statement has
successfully updated any rows or not. This attribute returns the TRUE value if the
last executed SQL statement has not affected any rows.

Q 352. In A For-loop, Can The Counter Value Be Assigned A Value Within The Loop?
The counter of a FOR-LOOP can only be used as a constant within the loop. It cannot
be assigned a value inside the loop, as that would change the bounds of the loop,
which is logically not possible.

Q 353. Is It Possible To Assign A Dynamic Value To A Loop Counter?


Yes, it is possible to assign a dynamic value to the loop counter at the time of
execution.

Q 354. What Is The Difference Between Nested Tables And Varrays?


Both nested tables and VARRAYs are collection types that can be stored in the
database. They differ in two properties, bounding and sparsity. Bounding refers to
the limit on the number of elements that a collection can have; whereas, sparsity
means whether there can be gaps within the subscripts or not.
Nested tables are not bounded and can be sparse; whereas, VARRAYs are bounded and
cannot be sparse. It means that VARRAYs have a limit on the number of elements and
are bounded; whereas, nested tables does not have a limit on the number of elements
and are unbounded. Nested tables can become sparse if elements are deleted;
whereas, VARRAYs can never become sparse.

Q 355. What Is The Difference In The 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 to be returned by the SQL query,
then the 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.

Q 356. How Can Two Pl/sql Records Be Compared?


Two records can be compared by using the equality (comparison) operator for each
field of the record. However, the entire record cannot be compared as a whole.

Q 357. Which Datatype Is Not Allowed In The Definition Of Pl/sql Record?


A collection type cannot be used for defining the datatype of fields; only scalar
datatype can be used for a PL/SQL record.

Q 358. What Is The Value Of Sql%found Attribute After And Before An Insert
Statement Is Executed?
The value of SQL%F0UND attribute will be NULL before an INSERT statement is
executed and TRUE after the successful insertion into a table.

Q 359. What Is A Constructor And Why Is It Used?


A constructor is a special built-in function that is used to initialize nested
tables and VARRAYs. Constructor has the same name as the collection and can take
any number of arguments, as shown in the following code:

Q 360. Can An If-then-else If Block Have Infinite Number Of Else Clauses?


No, the IF-THEN-ELSIF block can have only one ELSE clause at the end of the it,
which is executed if no other condition is evaluated to TRUE.

Q 361. What Are Implicitly Defined Records?


Implicitly defined records are those that do not have the need to describe each
field separately in the record definition. The structure of the record is not
defined using the TYPE statement; instead, the %ROWTYPE attribute is used to define
the implicit record to have the same structure as the database record. Following
code shows the declaration of the implicit defined records:

Q 362. What Is The Advantage Of Defining Implicit Records?


Implicit records are useful as there is no hard-code description needed. As they
are based on a database table record, any change in the database table record will
be automatically reflected in the record.

Q 363. How Can An Implicitly Defined Record Be Populated?


The implicitly defined record can be populated field by field or the entire record
can be populated in one statement, as shown in the following code:

Q 364. Is It Possible To Define A Not Null Field In A Record?


Yes, it is possible to define a NOT NULL field in a record so that it will always
require a value.

Q 365. Is It Possible To Copy Contents Of One Record To Another?


Yes, the contents of one record can be copied to another by copying either each
field using the assignment operator or whole record using the assignment operator.

Q 366. What Is The Difference Between Initialization Of Index-by Table And Nested
Table?
Index-By table is initialized automatically by referencing an element in the
collection; whereas, nested tables have to be initialized using a built-in function
called constructor.

Q 367. Do Collections Have Methods? If Yes, Give An Example ?


Yes, collections have built-in methods, which are used to examine and manipulate
the attributes of the collection, as shown in the following code:

Q 368. Can Collections Be Compared With Boolean Operators?


No, collections cannot be compared with Boolean operators.

Q 369. Can The Exists Method Be Used For Index-by Table?


Yes, the EXISTS method can be used for all collection types. It returns a Boolean
value, TRUE, if the collection element is initialized and FALSE, if the collection
element is not initialized.

Q 370. What Will The Result Of The Next() Method, If X Is The Last Element Of The
Collection?
The NEXT (<x>) method will return NULL if the last element of the collection is
reached.

Q 371. What Are Lob Locators?


LOB locators are values, which specify the location of the large object.

Q 372. What Are Conditional Predicates?


Triggers use conditional predicates, such as INSERTING, UPDATING, and DELETING, to
determine which particular event will cause the trigger to fire. All the three
predicates have Boolean values and are useful in triggers, such as AFTER INSERT or
UPDATE.

Q 373. What Is The Basic Difference Between Procedure And Function?


A procedure is executed as a PL/SQL statement. It can accept more than one
parameter as an input from the calling environment and may return none, one, or
more than one value.

A function is invoked as a part of expression. It can have more than one parameter
as an input from the calling environment and it should return a single value to the
calling environment using the RETURN statement.

Q 374. What Is The Difference Between The Code Syntax Of An Anonymous Block And
Named Subprogram Block?
A subprogram has two parts: subprogram specification and subprogram body.
1. The subprogram specification is the header section, which contains the
details such as program name, subprogram type, parameter list, and return clause
(for functions).
2. The subprogram body is a PL/SQL block, which has the declaration,
executable, and exception sections.
An anonymous block has no specification or header section. It only consists of a
PL/SQL block in the body that contains the declaration, executable, and exception
sections.

Q 375. Can The Size Of The Parameter Passed To The Procedure Be Restricted In The
Procedure Definition?
No, the size of the parameter passed to the procedure cannot be restricted in the
procedure declaration. The datatype for the parameter has to be specified only.

Q 376. What Is The Difference Between Formal And Actual Parameters In A Subprogram
Specification?
Formal parameters are variables declared as the parameter list in the subprogram
specification.
Actual parameters are the values that are passed to the subprogram from the calling
environment. The actual parameter values are evaluated and resultant values are
assigned to the formal parameters when the program is executed. Both formal and
actual parameters should be of compatible datatypes. Following code shows the
formal parameters of the function:

In the preceding function, p_student_id and p_percentage are the formal parameters.
In the following function code, v_student_id and v_percentage are the actual
parameters:
proc_disp_percentage (v_student_id, v_percentage);

Q 377. Which Datatypes Can Be Used For Parameters Within A Procedure?


Explicit datatypes, %TYPE and %ROWTYPE, without size specification can be used for
parameters in a procedure.

Q 378. What Are The Different Parameter Modes, Which Can Be Used In The Procedure
Specification?
There are three parameter modes for a procedure, given as follows:
IN -Refers to a constant value, which is assigned to this parameter from the
calling environment. The IN parameter value cannot be modified within a procedure.
It is a default mode.
OUT- Refers to a return value, which is passed from the procedure back to
the calling environment.
IN OUT -Refers to a value, which is assigned from the calling environment to
this parameter and a same or different value is passed back from the procedure to
the calling environment using this parameter.

Q 379. How Can A Parameter Be Initialized In A Procedure?


The IN OUT parameter mode can be used to initialize a parameter in a procedure, as
any value can be initially assigned to this parameter when the procedure is called
from the calling environment. The value of this parameter can be changed during the
execution of the procedure and the result can be returned back to the calling
environment from the procedure.

Q 380. Can Default Values Be Assigned To In Out Parameters In A Procedure?


No, default values cannot be assigned to IN OUT parameters; only IN parameters can
be assigned default values.

Q 381. What Are The Different Methods For Passing Parameters To A Procedure?
There are following three different methods to pass values to a procedure:
Positional -Refers to a method in which actual parameters of a procedure are
passed in the same order as the formal parameters.
Named-Refers to a method in which actual parameters of a procedure are passed
in any arbitrary order but are associated with their corresponding formal
parameters.
Combination-Refers to a method in which some parameters are passed as
positional and some are passed as named parameters.

Q 382. Can A Procedure Be Declared And Defined Within A Pl/sql Block?


Yes, any procedure can be declared and defined within a PL/SQL block.

Q 383. What Is The Scope Of The Procedure Defined Within A Pl/sql Block?
The scope of any procedure that is defined within the PL/SQL block will be limited
as it can be called only within the PL/SQL block and not by any other procedure or
calling environment.

Q 384. How Can You Reference Remote Tables In Procedures?


Remote tables can be referenced within procedures through SQL statements. A remote
table can be queried through a database link in the procedure. The following code
inserts a record in the STUDENT_MARKS table, which is in another schema, using the
CONNECT_STUDENT database link:

Q 385. What Happens If An Exception Is Unhandled Within A Procedure?


If an exception is unhandled within a procedure, the control is passed back to the
calling environment. Any DML statements, which were executed within the procedure,
are rolled back.

Q 386. Can There Be Multiple Return Statements Within A Function?


Yes, there can be multiple RETURN statements within a function though only one is
executed. After the value is retuned, the control passes back to the calling
environment and function processing is stopped.

Q 387. Is It Possible To Define A Return Statement In The Exception Part Of A


Function?
Yes, it is possible to define RETURN statement in the exception section. This
RETURN statement would be executed if an exception is raised and control is passed
to the exception section of the code.

Q 388. Can A Function Be Defined Without A Return Statement?


No, a function cannot be defined without a RETURN statement because it has to
return a value back to the calling environment. In case a RETURN statement is not
defined, runtime error is raised.

Q 389. Can User Defined Functions Be Called Within Sql Statements? If Yes, Then
How?
Yes, user defined functions can be called in SQL statements as shown in the
following code:

Q 390. Can Functions Be Stored Within A Database As Database Objects?


Yes, functions can be stored as database objects in the database.

Q 391. Which Datatypes Can Be Used Within Functions That Can Be Invoked In Sql
Statements?
Stored functions can use valid SQL datatypes, such as NUMBER, VARCHAR2, and DATE.
However, they cannot use PL/SQL datatypes, such as BOOLEAN, RECORD, and TYPE.

Q 392. What Restrictions Can Be Applied On Stored Functions, Which Are Called From
Sql Statements?
The main restrictions on stored functions that are called from SQL statements are:
These functions can use only positional methods for passing the parameters.
These functions can use only SQL specific datatypes. PL/SL datatypes, such
as RECORD or TYPE, cannot be used.
User should have EXECUTE privilege on the function to use it within SQL
statements
These functions cannot have the OUT and IN OUT parameter modes

Q 393. What Is The Difference Between Create Or Replace Function And Drop Function
Commands?
The CREATE OR REPLACE FUNCTION command creates the function if it does not exist
and replaces it with the new version if it already exists. The DROP FUNCTION
command deletes the function altogether from the database. Any privilege assigned
on the function remains the same when the CREATE OR REPLACE FUNCTION command is
used; however, in the case of the DROP FUNCTION command, all the privileges are
revoked.

Q 394. Can A Role Be Used To Define Privileges To Access Database Objects Of


Another Schema In Procedures And Functions?
Database objects of another schema cannot be accessed in a procedure or function
through roles; however, explicit privileges have to be granted to the user for
those database objects.

Q 395. How Can A Compiled Object Code Be Viewed?


Compiled object code cannot be viewed, as it is not accessible to the user.

Q 396. 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.

Q 397. How Can The Text Of A Procedure Or Function Specification Be Viewed?


The text of a procedure or function specification can be viewed using the
USER_SOURCE data dictionary view.

Q 398. How Can The Parameter List For A Function Or Procedure Be Displayed?
The parameter list for a function or procedure can be displayed using the DESCRIBE
command, given as follows:
DESCRIBE subprogram_name

Q 399. What Are The Advantages Of Using Stored Procedures And Functions?
Stored procedures are a collection of SQL, PL/SQL, and Java statements that allow a
programmer to shift the code from the application side to the database side. This
enables the business rules and application logic to be stored as procedures within
the database. The main advantages of using stored procedures and functions are as
follows:
The complex business rules processing is performed within the database on the
server side. Therefore, this change of processing from the application on the
client side to the database on the server side enhances and improves the
performance of the application.
The procedural code stored within the database can be reused anywhere within the
application.
When a stored procedure is executed for the first time, the shared SQL area in the
System Global Area (SGA) of the database stores the parsed versions of the executed
commands. After this, whenever the command is executed, it takes the advantage of
the parsing, which was performed the first time, and improves the performance of
the procedure's execution.
Developmental efforts are reduced by keeping the code in a stored procedure. As
the business rules are part of the database, they need not be re-written in each
code module of the application; and therefore, saves the creation time of the
application.
As the code is stored in a common place, any change can be easily managed; and
therefore, reduces the maintenance effort.

Q 400. What Is A Package And How Does It Differ From Procedure And Function?
A package is a group of logically related PL/SQL subprograms bundled together with
PL/SQL types and other associated objects. It consists of the following two parts:
Package specification -Includes declaration of all the objects and
subprograms that are part of the package.
Package body-Includes the total definition of all the parts of a package that
have been declared in the specification.
The whole package is fully loaded into the memory when any package construct is
called for the first time. Therefore, it does not require any disk input/output on
later calls to constructs in the same package.

Q 401. What Is The Difference Between Private Package Construct And Public Package
Construct?
Public package constructs are declared in the package specification but defined in
the package body and can be invoked from any other object in the oracle
environment.
Private package constructs are those that are declared and defined only within the
package body. They are not declared in the package specification and can only be
referenced by other constructs, which are part of the same package.
Private package construct is always defined before a public package construct
within the package body.

Q 402. Can A Complete Package Be Called?


No, a complete package is not possible to call, invoke, or parameterize; however,
any construct from the package can be called or invoked.

Q 403. Is It Possible To Write A Package Specification Without A Package Body?


Yes, it is possible to write a package specification without a package body but not
the vice versa. This is specifically used if there is a package, which is only used
for the declaration of public variables, types, constants, and exceptions. In such
case, there is no need for a package body and only package specification is enough.

Q 404. What Is Written As Part Of The Package Specification And The Package Body?
The package specification consists of the declaration of all the global variables,
cursors, types, procedures, and functions that are public and required to be called
from within or outside the package.
The package body consists of the definition of all the public constructs that are
declared within the package specification and the definition of all the private
variables, cursors, types, procedures, and functions that are required only within
the package. Following code snippet shows the implementation of the package
specification and the package body:

Q 405. 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 ?
The statement is given as follows:

Q 406. When Does A Package Need To Be Recompiled?


A package needs to be recompiled completely whenever any changes are made in the
package specification. Any change to the package body does not require
recompilation of the package.

Q 407. What Are The Advantages Of Using Packages?


The main advantages of using packages are given as follows:
Encapsulation -Packages provide encapsulation of all the logically related
constructs together in a single module, which is easy to code and understand.
Better application design -Both modularity and encapsulation leads to better
designing of applications. Separate package specification and body helps in
simplifying the coding and better definition of the subprograms.
Hiding -Public and private constructs can be defined and declared so that any
definition can be hidden to protect integrity of the package. Any changes in the
private constructs only need the package body to be recompiled without the need for
the entire application to be recompiled.
Better performance -A call to any construct within the package loads the
entire package in the memory; therefore, enables better performance of the
application.

Q 408. Is Drop Package Command Used To Drop The Package Specification Or The
Package Body?
The DROP PACKAGE command is used to drop the entire package including the
specification and the body.

Q 409. Is It Possible To Drop The Package Body Without Dropping The Package
Specification?
Yes, it is possible to drop the package body without dropping the package
specification using the DROP PACKAGE BODY command.

Q 410. What Is Forward Declaration And How Can It Be Achieved Within A Package?
PL/SQL does not allow the use of any subprogram before it is declared and defined.
However, in a package, forward declaration is allowed in case the subprogram
specification is terminated by a semi-colon. This enables the subprogram to be
defined in a logical manner and groups the subprograms in a package. It also helps
in defining mutually recursive programs that call each other directly or
indirectly.

Q 411. What Is A One-time-only Procedure And How Is It Declared Within A Package?


A One-Time-Only procedure is executed only once, when the package is called for the
first time. While declaring a One-Time-Only procedure the keyword END is not used
at the end of the one-time-only procedure; however, the procedure uses the package
body's END clause, as the procedure's code is placed at the bottom of the package
body.

Q 412. Which Privileges Are Required To Execute A Subprogram Owned By Another User?
To execute a subprogram owned by another user, the user must be granted either the
EXECUTE privilege on a procedure or function or the EXECUTE ANY PROCEDURE system
privilege.

Q 413. How Can A Procedure Or Function Be Executed Which Is Owned By Another User?
A procedure or function, which is owned by another user, may be executed by either
creating a synonym for the subprogram or prefixing it with the user name, as shown
in the following code snippet:

Q 414. 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, and has no
meaning for blocks that have no code, such as collection types.

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.

Q 415. How Can You Bug A Procedure Or Function For Errors?


The procedures or functions can be debugged using the SHOW_ERROR command or the
DBMS_OUTPUT command within the subprogram code.

Q 416. When Does A Subprogram Need Recompilation?


When any database object associated with the subprogram changes, the program needs
to be recompiled. When the program is executed the next time, after the object is
changed, the system will automatically perform runtime recompilation. To avoid this
performance overhead, it is better to explicitly recompile the subprogram using the
ALTER [PROCEDURE | FUCNTION] command, as shown in the following statement:
ALTER PROCEDURE proc_get_marks compile;

Q 417. When Should A Procedure And A Function Be Used?


Procedure is used when there are more than one return values; however, if there is
only one return value, then a function should be used. Although functions may have
more than one OUT parameters, it is considered as a poor programming style. In
addition, when a subprogram has to be invoked within an SQL statement, function
should be used.
Q 418. Can Stand-alone Programs Be Overloaded?
No, stand-alone programs cannot be overloaded; however, packaged sub-programs can
be overloaded within the same package.

Q 419. What Are Function Purity Levels?


Function purity levels define what type of data structures can be read or modified
by a function. There are four function purity levels, which are given as follows:
WNDS -Writes no database state. The function does not modify any database
table using any DML statement.
RNDS-Reads no database state. The function does not read any database tables
using the SELECT statement.
WNPS -Writes no package state. The function does not modify any packaged
variables.
RNPS- Reads no package state. The function does not read any packaged
variables.

Q 420. What Are The Restrictions On Functions That Are Called Within Sql
Statements?
The functions that are called within SQL statements have the following
restrictions:
They must be stored in a database.
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.
The return type of a function should be of SQL datatype.
They cannot have the COMMIT and ROLLBACK statements.
They cannot have the ALTER SESSION and ALTER SYSTEM commands.

Q 421. Suppose A Procedure Proc__calc_student_marks Inserts The Values Into The


Student_total_marks Table. If The Table Is Modified By Adding Another Column, What
Needs To Be Done To Make The Procedure Valid?
Oracle recompiles the procedure automatically when the procedure is invoked.
Therefore, no action has to be taken if the INSERT statement is using column names.
However, if the INSERT statement is just adding values without using the column
names, then the procedure has to be modified, as another column has been added.

Q 422. Suppose A Procedure Is Created Using The Create Procedure Command; However,
It Gives A Syntax Error. Which Data Dictionary Views Will Have The Source Code Of
The Procedure?
The USER_SOURCE, ALL_SOURCE, and DBA_SOURCE data dictionary views will have the
source code, as a procedure is stored in the database even if it has a syntax
error.

Q 423. Can An Out Parameter, V_totalmarks, Be Referenced Within The Procedural Code
Without Being Assigned A Value?
Any OUT parameter cannot be referenced without being assigned a value, as the OUT
parameter cannot be assigned a default value. Therefore, the v_total_marks
parameter cannot be referred within the code until the executable statements of the
procedure have begun; the OUT parameter is assigned a value using the PL/SQL
assignment statements.

Q 424. Can An In Parameter Be Assigned A Value Within A Procedure?


No, an IN parameter cannot be assigned values within a procedure.

Q 425. Suppose A Procedure Proc_get_highest_rank Is Stored In The User Schema,


User_a. How Can You Access The Procedure Within This Schema?
The proc_get_highest_rank procedure can be accessed within the user_a schema from
another stored procedure. It can also be accessed either from an anonymous PL/SQL
block executed on the SQL prompt logged in as user_a or directly at the SQL prompt
using the EXECUTE command. In addition, it can be accessed by other users if they
have the EXECUTE privilege.

Q 426. Can Boolean Datatype Be Used In Functions That Are Called From Sql
Statements?
No, BOOLEAN datatype cannot be used in functions that are called from SQL
statements.

Q 427. Is It Possible To Make Procedure Or Function Part Of The If Then Else Block?
Procedure cannot be called from within the IF THEN ELSE block; however, functions
can become a part of the IF THEN ELSE block because functions return the value in
such a manner that the function call in the block acts like a variable.

Q 428. What Is The Meaning Of The Following Error Statement: Ora-06575: Package Or
Function Func_test Is In An Invalid State?
This error is displayed if the function is executed when it is in the invalid
state. The ORA-06575 error indicates that for some reason the function is not valid
and needs to be checked and compiled again.

Q 429. Suppose A Function Named Func_test_a Calls Another Function, Func_test_b. If


The Func_test_b Function Is Dropped, What Will Be The Effect On The Func_test_a
Function?
The calling function func__test_a becomes invalid. It has to be edited and compiled
again to become valid.

Q 430. Can Functions Be Called As Stand-alone Programs Like Procedures?


No, functions cannot be called as stand-alone programs like procedures. They have
to be a part of an expression or they should be invoked as part of SQL statements.

Q 431. Can A Function Be Compiled Without A Return Statement?


Yes, a function can be compiled without a RETURN statement, but it cannot be
executed.

Q 432. Can A Return Statement In The Function Code Be Followed By Other Valid
Pl/sql Statements?
It is advisable to keep the RETURN statement at the end of the function code. This
is because the function processes the statements until the RETURN statement is
encountered and then the control is passed back to the calling environment.

Q 433. How Does A Package Support Information Hiding?


A package consists of two parts: package specification and package body. The
package specification contains the names of procedures and functions, their
parameters, and return types; whereas, the subprogram code is part of the package
body. Developers who require calling the procedures or functions just need to have
access on the package specification. Therefore, the package owner can grant
privilege on the package specification while hiding the package body. In this way,
the developers can use the package without seeing the actual code. In addition,
package owners can create procedures and functions that are private for the package
and need not be part of the package specification. In this way, information hiding
is achieved within a package.

Q 434. What Is Catproc.sql?


The catproc.sql is a SQL file, which has the script to create packages in the
database, This file has to be executed on the SQL prompt for the packages to be
available in the database.
Q 435. What Is Dynamic Sql And What Is Its Usage?
Dynamic SQL is used by PL/SQL to execute Data Definition Language (DDL) statements,
Data Control (DCL) statements, or Transaction Control statements within PL/SQL
blocks. These statements are not stored within the source code but are stored as
character variables in the program. The SQL statements are created dynamically at
runtime by using variables. This is used either using native dynamic SQL or through
the DBMS_SQL package.

Q 436. How Is An Sql Statement Processed? What Are The Steps That An Sql Statement
Undergoes For Compilation?
SQL statements are compiled using the following steps:
Parse-Refers to a step in which statements are checked for existence of all
objects used and the syntax is validated.
Bind- Refers to a step In which the values for the variables are obtained.
This process is also called binding variables.
Execute -Refers to a step in which the statement is executed by Oracle.
Fetch -Refers to a step in which rows are selected and retrieved one by one
until last row is fetched.

Q 437. What Is The Use Of Dbms_sql Package?


The DBMS_SQL package is used to access dynamic SQL and dynamic PL/SQL from within a
PL/SQL program. It allows you to execute statements that are otherwise impossible
from within PL/SQL programs, which includes DDL, DCL, or Transaction Control
statements.

Q 438. Does Dynamic Sql Support All Sql Data Types?


Yes, dynamic SQL supports all SQL data types. It is possible to define variables
and bind arguments of collection type, LOBs, and REFs.

Q 439. Are The Pl/sql Specific Datatypes Supported By Dynamic Sql To Define
Variables And Bind Arguments?
No, PL/SQL datatypes are not supported by dynamic SQL; only PL/SQL RECORD datatype
can be used in the INTO clause. No other PL/SQL datatype, such as BOOLEAN, can be
used within dynamic SQL.

Q 440. What Is The Use Of Execute Immediate Command? Explain With Example ?
The native dynamic SQL can be executed within a PL/SQL block using the EXECUTE
IMMEDIATE command.

Q 441. Explain The Functionality Of Utl_http Package ?


The UTL_HTTP package enables PL/SQL and SQL to access the Internet data using the
REQUEST and REQUEST_PIECES functions. These functions take the Uniform Resource
Locator (URL) of the website as input and return the HyperText Markup Language
(HTML) data from the website.

Q 442. What Is The Size Of Data That Can Be Retrieved For The Database Using The
Utl_http Package?
The size of the data that can be accessed from the Internet is based on the
functions used. The REQUEST function returns up to the first 2000 bytes of data
retrieved from the website. The REQUEST_PIECES function returns a PL/SQL table of
2000 bytes from the accessed URL.

Q 443. Which Exception Is Raised If The Utl_http Package Fails Due To Wrong Url
Specified?
If wrong URL is specified in the UTL_HTTP package call, the REQUEST_FAILED
exception is raised.

Q 444. What Is The Utility Of Utl_tcp Package? How Is The Connection Opened And
Closed?
The UTL_TCP package is used by PL/SQL applications to access external Transmission
Control Protocol/Internet Protocol (TCP/IP) based servers using the TCP/IP
protocol.

The connection is opened using the OPEN_CONNECTION function, which opens a TCP/IP
connection when the remote host, local host, and both the port numbers are
specified. It returns a connection of PL/SQL RECORD type.

The connection is closed using the CLOSE_CONNECTION function, which closes the
connection of the port whose details are provided as input.

Q 445. What Is The Difference Between Close_connection And Close_all_connections


Procedure Of The Utl_tcp Package?
The CLOSE_CONNECTION procedure closes the connection whose details are provided as
input where as the CLOSE_ALL_CONINJECTIONS procedure closes all the opened
connections.

Q 446. Which Oracle Package Is Used To Check The Status Of A Schema And Analyze The
Objects Of The Schema?
The DBMS_UTILITY package is used to check the status of a schema and analyze the
objects of the schema.

Q 447. What Is The Use Of Dbms_transaction Package?


The DBMS_TRANSACTION package controls logical transactions and improves the
performance of short and non-distributed transactions.

Q 448. Is It Possible To Access Sql Session Information?


Yes, it is possible to access the SQL sessions using the DBMS_SESSION package.

Q 449. Which Oracle Package Is Used To Manage The Oracle Lock Management Services?
The DBMS_LOCK package is used to manage the Oracle Lock Management services. This
package is used to request, convert, and release the locks using the Oracle Lock
Management services.

Q 450. What Is The Difference Between Blob And Clob?


The BLOB datatype is used to store a binary large object, such as a video image
file; whereas, the CLOB datatype is used to store a character large object.

Q 451. Is It Possible To Convert Long Objects To Lob Objects?


Yes, it is possible to convert LONG and LONG RAW objects to LOB objects using the
TO_LOB function.

Q 452. What Are The Two Components Of Lob Datatype?


Answer :
The two components of the LOB datatype are given as follows:
LOB locator - Refers to a locator, which points to the location in the
database where the value is stored. This value is stored along with the record in
the table row and is similar to a pointer to the actual location of LOB value.
LOB value - Refers to an actual image or value of the LOB datatype.

Q 453. What Is The Difference Between Internal And External Lobs?


LOB datatype can be internal or external. Internal LOBs are CLOB, NCLOB, and BLOB
that are stored in the database; whereas, external LOBs are BFILEs that are stored
outside the database as external files. Although both LOB types have the pointer to
the location, the BFILEs are stored externally across hard disks or on external
storage; whereas, internal LOBs have to be stored in the different location within
the database itself.

Q 454. What Is The Difference Between Referenced Object And Dependent Object?
If the definition of an object A references object B, then A is the dependent
object and B is the referenced object. If a table is being queried in a procedure,
then the table is the referenced object and the procedure is the dependent object.
However, if the definition of the table is modified, the procedure may or may not
execute correctly.

Q 455. Does Oracle Automatically Record The Dependencies Among The Schema Objects?
Yes, Oracle automatically records the dependencies among objects through the
USER_OBJECTS data dictionary view, where the schema objects have a valid or invalid
status.

Q 456. Which Schema Objects Can Be Referenced Directly Or Indirectly?


Any procedure or function can be referenced directly or indirectly using the
following objects:
Tables
Views
Procedures
Functions
Sequences
Package procedures or functions

Q 457. What Is Indirect Reference Of Schema Objects?


When any procedure or function references another schema object through an
intermediate procedure, function, or view, then the reference is called indirect
reference.

Q 458. How Does An Object Get An Invalid Status?


If there is any change in any of the referenced object, the dependent object will
get an invalid status. For example, if the structure of base table of a view is
modified, the view will get an invalid status.

Q 459. What Happens When An Object Has An Invalid Status?


Whenever an invalid object is called again, the Oracle server automatically
recompiles the object and it gets a valid status. For example, if a view with an
invalid status is queried, it will be recompiled before the results are displayed.

Q 460. Suppose The Student_grades View Is Based On The Student_marks Table. If The
Length Of The Student_name Column Is Modified, Will The View Become Invalid?
If the STUDENT_GRADES view Includes the STUDENT_NAME column then it will become
invalid; and therefore, needs to be recompiled. If the view does not include the
column, which is modified, then it is valid.

Q 461. What Is The Effect On The Dependent Objects If An Object Is Renamed?


All the dependent objects become invalid if an object, which the dependent objects
reference, is renamed.

Q 462. Which View Is Used To Track The Security Dependencies?


The security dependencies can be tracked using the USER_TAB_PRIVS data dictionary
view.

Q 463. What Is The Effect On The Dependent Object When A Package Body Is Modified?
When a package body is modified, there is no change in the dependent objects.

Q 464. Is A View Invalidated When A New Column Is Added To The Table It References?
No, a view is not invalidated if a new column is added to the table it references.

Q 465. What Is The Advantage Of Referring Tables Indirectly Using Views?


Referencing tables indirectly using views allows:
Adding columns to the table without invalidating dependent views or dependent
PL/SQL objects
Modifying or deleting columns of the table that are not referenced by the
view without invalidating the dependent objects

Q 466. What Is The Meaning Of Signature Of A Procedure?


The signature of a procedure refers to:
The name of the procedure
The datatype of the parameters
The modes of the parameters
The number of parameters
The datatype of the return value in case of function

Q 467. What Is The Disadvantage Of Time-stamped Checking?


The disadvantage of time-stamped checking is that it causes unnecessary
recompilation of the dependent objects across networks when it may not be required,
leading to the degradation of system performance.

Q 468. How Is Signature Checking Better Than The Time-stamped Checking?


Signature checking eliminates the problem of unnecessary recompilation of the
program units across networks. The signature of the remote procedure is stored in
the p-code of the local procedure. In signature checking, the signature of the
remote procedure is compared and not the time stamp. If the remote program is
modified and recompiled but its signature does not change, then the local procedure
can be executed without any runtime error. Therefore, signature checking does not
degrade the system performance by repetitive compilation of the local procedure.

Q 469. What Happens If The Time-stamped Checking Is Used For Dependency Checking
Across Remote Databases In Different Time Zones?
The time stamp of the remote procedure and the local procedure will not match and
the dependency checking will not be successful. Therefore, while working on remote
databases across time zones, signature checking should be used.

Q 470. Can A Table Or Synonym Be Invalidated?


A table or synonym can never be invalidated; only dependent objects are
invalidated.

Q 471. Suppose A Schema 2 Has Granted Necessary Privileges To The Schema 1 Through
Roles. Is It Possible For A Program Unit In The Schema 1 To Refer The Database
Objects In The Schema 2 ?
No, a program unit in the schema 1 cannot reference the database objects in the
schema 2, even if the schema 2 has granted necessary privileges to the schema 1
through roles. This is because granting privileges through roles does not work for
program units. They can reference other schemp objects only if the necessary
privilege has been granted directly to the schema.

Q 472. In The Time-stamped Checking Mode, Which Value Of The Two Program Units Is
Compared To Determine The Dependency Checking?
The LAST_DDL_TIME column of the USER_OBJECTS data dictionary view records the last
time a SQL statement was issued to change the structure of the objects. This column
is compared to determine if the referenced program unit has been changed since the
dependent unit was last compiled.

Q 473. What Is A System Privilege?


A system privilege is the right to perform a particular action in the database.
Privileges are granted to a schema. They may be granted to a role, which in turn is
granted to schemas.

Q 474. What Is The Meaning Of Granting A Privilege To Public?


Granting a privilege to PUBLIC means it is granted to all the schemas in the
database that already exist or created in the future.

Q 475. What System Privileges Are Required By An End User?


The end user may not require any system privilege except the CREATE ANY SESSION,
which grants them the privilege to log in as an Oracle user.

Q 476. What Is The Difference Between The Create Table And Create Any Table
Privileges?
The CREATE TABLE privilege grants the schema to create tables in its own schema;
however, CREATE ANY TABLE grants the privilege to create any table owned by any
other schema as well.

Q 477. What Is The Meaning Of Granting System Privilege With Admin Option?
Granting system privilege WITH ADMIN OPTION means that the schema can in turn grant
the same privilege to any other schema.

Q 478. Suppose A Schema A Grants The Create Any Trigger With Admin Option Privilege
To A Schema B And The Schema B Grants The Create Any Trigger Privilege To A Schema
C. If The Schema A Revokes This Privilege On The Schema B, Then Does The Privilege
On Schema C Be Revoked As Well?
No, the privilege on the schema C will not be revoked automatically; only the
privilege on the schema B is revoked.

Q 479. What Is The Advantage Of Using Roles For System Privilege?


Roles are easy to manage and helpful in granting multiple system privileges to
schemas. Any privilege can be added to a role or removed from a role. This would
automatically affect all the schemas with that role.

Q 480. What Does Create Any Procedure System Privilege Grant To A Schema?
The CREATE ANY PROCEDURE system privilege allows the schema to create any package,
procedure, or function within its schema or owned by any other schema.

Q 481. Can A Schema A With The Create Any Procedure Privilege Alter Or Modify A
Package X In A Schema B?
No, a schema A with the CREATE ANY PROCEDURE privilege cannot alter or modify a
package X in the schema B. The schema must have the ALTER ANY PROCEDURE system
privilege for altering or modifying any program unit.

Q 482. What Are Indirectly Granted Privileges?


Indirectly granted privileges are those privileges that have been granted to a
role, which in turn granted to a schema through a role.

Q 483. Which Data Dictionary View Is Used To View Information About All The
Privileges That Have Been Made By And To The Current Schema?
The USER_TAB_PRIVS data dictionary view is used to view information about all the
privileges that have been made by and to the current schema.

Q 484. Which Data Dictionary View Shows All Directly And Indirectly Granted System
Privileges In Effect To A Schema?
The SESSION_PRIVS data dictionary view shows all the directly and indirectly
granted system privileges to a schema.

Q 485. Which Data Dictionary View Will Give The Owner Name Along With The
Privileges On A Schema Object?
The USER_TABS_PRIVS data dictionary view gives the list of system and object
privileges on the object along with the owner name of the object.

Q 486. Explain The Grant And Revoke Dcl Statements ?


DCL statements control the security of the database. The two statements, GRANT and
REVOKE, are used to give permissions to users to access the different schema
objects; therefore, enabling security and access control on the database.

Q 487) What is stored Procedure?


A stored procedure is a sequence of statement or a named PL/SQL block which
performs one or more specific functions. It is similar to a procedure in other
programming languages. It is stored in the database and can be repeatedly executed.
It is stored as schema object. It can be nested, invoked and parameterized.

Q 488) What do you understand by PL/SQL packages?


A PL/SQL package can be specified as a file that groups functions, cursors, stored
procedures, and variables in one place.

Q 489) Which command is used to delete a package?


The DROP PACKAGE command is used to delete a package.

Q 490) How to execute a stored procedure?


There are two way to execute a stored procedure.
From the SQL prompt, write EXECUTE or EXEC followed by procedure_name.
1. EXECUTE or [EXEC] procedure_name;
Simply use the procedure name
1. procedure_name;

491) What is the difference between a procedure and a function?


Ans: This is one of those Qs that, depending on your interview, you may get right
or wrong depending on how you answer it. In the past, I've often stated that the
difference between a procedure and a function is that a procedure is a program that
performs one or more actions while a function's main purpose is to return a value.
This is true but since a procedure can also return (interestingly with a RETURN
clause) values, there is something else missing. The difference, that should get
you some brownie points, is in the way procedures and functions are called. A
procedure is called as an executable PL/SQL statement while a function is called
like a PL/SQL expression.

492) What is an autonomous transaction and how does it affect the commit process?
Ans: An autonomous transaction creates, when called from another transaction, an
independent and separate transaction that can issue commits without affecting the
calling transaction.

493) What are packages?


Ans: A package is nothing more than a way to consolidate/group/organize/etc.,
common elements of PL/SQL code into a single named entity. While packages do help
improve things like portability and maintainability of code, packages can also help
improve the performance of the code.

494) How might you hide/protect your source code if distributed to customers?
Ans: Oracle's wrap utility provides a good way of hiding PL/SQL source code;
protecting it and making it difficult for others to view. You can either wrap
source code with the wrap utility or use the DBMS_DDL subprograms.

Q 495. What are the properties of a Database?


The properties of a Database are also known as ACID Properties. These are
Atomicity, Consistency, Isolation and Durability.

Q 496. How can you take an Input from a User of the Database?
You can take it using the Input Operator. This is as follow:
val1:=&val1;

Q 497. What is %rowtype used for?


This is used if you want to create new variable which needs to fetch in a variable
value from the database and you don't know the Datatype of that variable. %rowtype
will automatically change its datatype to the one in the database.

Q 498. Enlist various loops in PL/SQL Database.


The various loops used in PL/SQL are as follows:
1. Simple Loop
2. For Loop
3. Nested Loop
4. While Loop

Q 499. What rules are to be taken care of when doing comparisons using NULL?
1. A NULL should never be TRUE or FALSE.
2. If a value in an expression is NULL, then the expression itself evaluates to
NULL except for Concatenation Operator.
3. A NULL is never equal or unequal to other values.
4.NULL is not a value, it represents absence of data. So NULL is something UNIQUE

Q 500. 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.

Q 501. Explain about Pragma Exception_Init.


It allows us to handle Oracle Pre Defined Messages wherein we can replace our own
Message. We can therefore instruct the compiler to link the user specified message
to Oracle Pre Defined Message during Compilation Time.
Syntax: Pragma Exception_Init (Exception_Name, Error_Code)

Q 502. What is set serveroutput function used for in PL/SQL?


In PL/SQL, we frequently require to produce the Output on the console. We generally
do it using dbms_output.put_line() function. For this to work properly and display
the output on the console screen, we need to first set the server output to ON
state. For this, the command is: set serveroutput on;

Q 503. Explain the difference between Truncate and Delete?


Truncate is much faster than Delete Command. It basically resets the Memory Blocks
after Execution. Delete is a Database Manipulation Language (DML) Command whereas
Truncate is a Data Definition Language (DDL) Command and it is comparatively
slower.