Вы находитесь на странице: 1из 32

Advantages of using Cursor:

 Using Cursor we can perform row by row processing so we can perform row wise
validation or operations on each row.
 Cursors can provide the first few rows before the whole result set is assembled.
Without using cursors, the entire result set must be delivered before any rows are
displayed by the application. So using cursor, better response time is achieved.
 If we make updates to our without using cursors in your application then we must
send separate SQL statements to the database server to apply the changes. This can
cause the possibility of concurrency problems if the result set has changed since it
was queried by the client. In turn, this raises the possibility of lost updates. So using
cursor, better concurrency Control can be achieved.
 Cursors can be faster than a while loop but at the cost of more overhead.

Disadvantages of using Cursor:


 Cursor in SQL is temporary work area created in the system memory, thus it occupies
memory from your system that may be available for other processes. So occupies more
resources and temporary storage.
 Each time when a row is fetched from the cursor it may result in a network round trip.
This uses much more network bandwidth than the execution of a single SQL statement
like SELECT or DELETE etc that makes only one round trip.
 Repeated network round trips can degrade the speed of the operation using the cursor.

Advantages of trigger:

1) Triggers can be used as an alternative method for implementing referential integrity


constraints.

2) By using triggers, business rules and transactions are easy to store in database and can be used
consistently even if there are future updates to the database.

3) It controls on which updates are allowed in a database.

4) When a change happens in a database a trigger can adjust the change to the entire database.

5) Triggers are used for calling stored procedures.

Disadvantages of trigger:
1) It is easy to view table relationships , constraints, indexes, stored procedure in database but
triggers are difficult to view.

2) Triggers execute invisible to client-application application. They are not visible or can be
traced in debugging code.

3) It is hard to follow their logic as it they can be fired before or after the database insert/update
happens.

4) It is easy to forget about triggers and if there is no documentation it will be difficult to figure
out for new developers for their existence.

5) Triggers run every time when the database fields are updated and it is overhead on system. It
makes system run slower.

What are disadvantage of bulk collection?


Using the BULK COLLECT clause in PL/SQL implies following restrictions:
1. We cannot bulk collect into an associative array having a string type for the key.
2. BULK COLLECT clause can be used only in server-side programs (not in client-side programs)
else, error is reported that it is not supported in client-side programs.
3. Collections should be used as target variables listed in a BULK COLLECT INTO clause.
4. Composite targets (such as objects) cannot be used in the RETURNING INTO clause else
error is reported for feature with RETURNING clause.
5. Multiple composite targets cannot be used in the BULK COLLECT INTO clause when implicit
data type conversions are needed.
6. When an implicit data type conversion is needed, a collection of a composite target (such as
a collection of objects) cannot be used in the BULK COLLECT INTO clause.

What are the advantage & disadvantage of package

A package is a group of PL/SQL types, objects, and stored procedures and functions. The
specification part of a package declares the public types, variables, constants, and subprograms
that are visible outside the immediate scope of the package. The body of a package defines the
objects declared in the specification, as well as private objects that are not visible to applications
outside the package.

Advantages:

Modular approach, Encapsulation/hiding of business logic, security, performance improvement,


reusability.

Disadvantages:
More memory may be required on the Oracle database server when using Oracle PL/SQL
packages as the whole package is loaded into memory as soon as any object in the package is
accessed.

Updating one of the functions/procedures will invalid other objects which use different
function/procedures since whole package need to be compiled.

Predefined Exceptions

Oracle has predefined some common exception. These exceptions have a unique exception name
and error number. These exceptions are already defined in the 'STANDARD' package in Oracle.
In code, we can directly use these predefined exception name to handle them.

Below are the few predefined exceptions

Error
Exception Exception Reason
Code

ORA-
ACCESS_INTO_NULL Assign a value to the attributes of uninitialized objects
06530

ORA- None of the 'WHEN' clause in CASE statement satisfied and no


CASE_NOT_FOUND
06592 'ELSE' clause is specified

ORA- Using collection methods (except EXISTS) or accessing collection


COLLECTION_IS_NULL
06531 attributes on a uninitialized collections

ORA-
CURSOR_ALREADY_OPEN Trying to open a cursor which is already opened
06511

ORA- Storing a duplicate value in a database column that is a


DUP_VAL_ON_INDEX
00001 constrained by unique index

ORA-
INVALID_CURSOR Illegal cursor operations like closing an unopened cursor
01001

ORA- Conversion of character to a number failed due to invalid number


INVALID_NUMBER
01722 character

ORA- When 'SELECT' statement that contains INTO clause fetches no


NO_DATA_FOUND
01403 rows.

ORA- When cursor variable data type is incompatible with the actual
ROW_MISMATCH
06504 cursor return type
ORA- Referring collection by an index number that is larger than the
SUBSCRIPT_BEYOND_COUNT
06533 collection size

ORA- Referring collection by an index number that is outside the legal


SUBSCRIPT_OUTSIDE_LIMIT
06532 range (eg: -1)

ORA- When a 'SELECT' statement with INTO clause returns more than
TOO_MANY_ROWS
01422 one row

ORA- Arithmetic or size constraint error (eg: assigning a value to a


VALUE_ERROR
06502 variable that is larger than the variable size)

ORA-
ZERO_DIVIDE Dividing a number by '0'
01476

ORA-08103: object no longer exists


ORA-01555: snapshot too old: rollback segment number 268 with name "_SYSSMU268_4055412817$" too small:
3
ORA-00904: "C"."INITIATIVE_NAME": invalid identifier: 6
ORA-20000: ORU-10027: buffer overflow, limit of 20000 bytes: 18
ORA-00942: table or view does not exist
ORA-04063: view "CX_DATA.CXD_CONTACTS_VW" has errors
ORA-00942: table or view does not exist
ORA-06502: PL/SQL: numeric or value error: character to number conversion error: 6
ORA-00904: "COMPANY_KEY": invalid identifierAPAC_HGBU_FB_SE_PROC :
ORA-01652: unable to extend temp segment by 4096 in tablespace CX_DATA_TEMP: 13
ORA-00054: resource busy and acquire with NOWAIT specified or timeout expired
ORA-00376: file 279 cannot be read at this time ORA-01110: data file 279:
'+RECO_DG/CDBX01P/2FD3822452AC3CEAE0530216E10AECF9/DATAFILE/cx_data.2621.1011040599'
ORA-06512: at "CX_NURTURE_CAMPAIGN.FY19_APP_CX_CLOUD_GENERAL_PR", line 167
ORA-12801: error signaled in parallel query server P001, instance mktcx5db07.us.oracle.com:cdbx01p3 (3) ORA-
01555: snapshot too old: rollback segment number 210 with name "_SYSSMU210_3056311004$" too small

ORA-00920: invalid relational operator: 3

Oracle Indexing - What, Where, When?


By Sean Hull
Introduction

If you are new to databases, or perhaps new to Oracle, you may find the discussion on indexes
and indexing strategy complicated. Don't fret. To get started it's fairly straightforward, and as
long as you pay attention to the options relevant to day-to-day dba needs, it should remain fairly
simple.

Common Usage Indexes

b-tree index

The most common index type is the b-tree index. It is named b-tree after a computer science
construct of the same name. Whenever you issue the basic CREATE INDEX statement without
further modifications, you're creating a b-tree index. Without going into a lot of depth about b-
trees which you can investigate on your own, basically these store the values of the column you
have created the index on, and pointers to the actual table data to find the row itself. Keep in
mind that also means multiple lookups, one for various nodes and the leaf node of the index, and
then the table row itself. That's why Oracle's optimizer will choose in certain circumstances to
do full table scans rather than index lookup, because it may actually be faster. Also note that if
your index is on more than one column, the leading column is very important. For example if
you have a multi-column (called concatenated) index on columns c and d in that order, you can
also do a query on column c alone and use that index. In some other cases using Oracle's skip-
scan technology, one can do a query on non-leading columns as well. Do a google search on
"skip scan index access" for details.

function-based index

We mentioned that Oracle would choose not to use an index sometimes, if you're reading a lot of
rows, or your index is not selective, or you're using a column other than the leading one in a
concatenated index. What about if you want to do a case-insensitive search? Something like:

WHERE UPPER(first_name) = 'JOHN'

This won't use an index on first_name. Why? Because Oracle would have to go and apply the
UPPER function on ALL values in the index, so it might as well do the full table scan. This was
such a common need that Oracle created the function-based index for this purpose.

reverse key indexes

You also may see these indexes, or want to use them from time to time. Consider a column,
which includes names like "restaurant A", "restaurant B", "restaurant C" and so on. Perhaps a
not very glamorous example, but the point is a column with many unique values but not much
variation at the front. Using a reverse-key index would be ideal here, because Oracle will simple
REVERSE the string before throwing it into the b-tree. So, the result will be a more balanced,
useful, and ultimately fast index.
More Exotic Index Types on Offer

Oracle offers quite a few more sophisticated types of indexes as well. Please note, these should
be used after you've fully read the docs as they fill very specific niches.

bitmap indexes

Have a column, which is not very selective, such as gender? You might consider using a bitmap
index on it. That's what they were created for. But also consider what's happening behind the
scenes. Generally bitmap indexes become useful when you have a whole bunch of them on
different columns so that they can all be used together to be more selective on rows that
otherwise you'd need a full table scan for. So one, use them when you can have quite a few on
different columns. Secondly, these indexes were designed for data warehouses, so the
presumption is data that does not change much. They are not meant for transactional or high
update databases. Updates on tables with bitmap indexes are, shall we say, less than efficient.

bitmap join indexes

These indexes take bitmap indexes one step further. They completely take the bitmapped
columns out of the table data, and store it in the index. The presumption is that those sets of
columns will always be queried together. Again, these are meant for data warehousing
databases. The create statement looks like a CREATE BITMAP INDEX except it has a WHERE
clause at the end!

compressed indexes

This is really an option to a normal b-tree index. It results in fewer leaf nodes, so less overall I/O
and less to cache. All of this means Oracle's optimizer will be just a little more likely to use
these than a normal uncompressed index. There is a cost to all of this, in CPU to uncompress
when you access these. Also, in reading about how the optimizer uses these, and choosing the
proper compression level, it begins to look daunting. Your mileage may vary.

descending

These are a special type of function-based index. They are obviously optimized for ORDER BY
x, y, z DESC clauses.

partitioned indexes

If you have a partitioned table, a whole world of new index types opens up to you, from ones that
index across all the partitions (global) to ones that are focused on each partition individually
(local). Check the documentation for details.

index organized tables


Imagine you take your concatenated index, and extend it to all the columns in the table. Then
you can remove the table itself. That's what an index organized table is.

cluster indexes

I personally have never seen these in the wild. All I've read is they have performance issues left
and right. Basically, you take two tables with one column in common, and that column has a
cluster index on it.

domain indexes

These indexes are used when creating custom indextypes for user defined datatypes.

invisible indexes

These are new in 11g. They are created as a normal index, but invisible to the cost based
optimizer. This can allow you to test out performance of large queries, without impacting the
live running application.

virtual (no segment) indexes

Another tool for the testers and developers. They allow you to test new indexes and their effect
on query plans, without actually building them. On gigabyte tables, the index build can be very
resource intensive, and take a lot of time. See also the Virtual Index Wizard of OEM.

miscellaneous

There are other types of indexes as well, such as Oracle TEXT for indexing CLOB or other large
text data, and Oracle Spatial. Investigation of those is left as an exercise to the reader.

It's All About the Optimizer

Having worked extensively with MySQL, and some other databases, I can tell you it is not
Oracle's user-friendliness that makes it the world leader. I could go digress on this point, but
primarily Oracle's bread and butter is it's optimizer. This is the special sauce. And it keeps
getting better and better. There are whole books written on the topic of the Oracle's CBO (Cost
Based Optimizer) discussing hints (comments embedded in SQL to push the optimizer one way
or another), strategies for analyzing your tables and indexes, and histograms for those finicky
columns where data distribution is not balanced.

Besides keeping your statistics up to date, you'll want to always test your new queries. Use the
explain plan mechanism, and optimize to reduce overall I/O and computational sorting and
merging of data, and you will be on the path to better performance.

Conclusion
Although the Oracle landscape of index types can be intimidating, there are really only a few that
you'll use most often day-to-day. Furthermore, the optimizer has gotten so good that despite
what the naysayers may go on about; on the whole Oracle is good at getting your data
efficiently. That doesn't mean you don't need to tune your SQL, but it does mean if you keep
your statistics up to date, and ask Oracle for the minimal dataset you need, it'll probably get it for
you lickety-split!

https://www.databasejournal.com/features/oracle/article.php/3739071/Oracle-Indexing---What-
Where-When.htm

PLSQL Interview Questions :- FORALL and BULK


COLLECT
1. How is a FORALL loop different from FOR Loop?

FOR loop acts on each and every record


FORALL acts on many number of records at once. It is faster when compared to FOR

FORALL i in 1..count

UPDATE student st
FOR i in 1..count
SET st.Total =
LOOP
st.mark1+st.mark2
UPDATE student st
SET st.Total =
st.mark1+st.mark2
END LOOP

2. If FORALL is faster, then why FOR is not replaced by FORALL?

FORALL works faster but it has got few restrictions

i. It works in server side programs and cannot be used in client side program
ii. You have to specify the entire row in Update's SET or Insert's Values with collections.
iii. Within a FORALL loop, you cannot refer to the same collection in both the SET clause and
the WHERE clause of an UPDATE statement. You might need to make a second copy of the collection and
refer to the new name in the WHERE clause.
iv. FORALL processes only one statement that is placed after the FORALL statement.
3. What is Bulk Collect?
It is the way of fetching rows in bulk and storing in the collection. The number of rows to be fetched is
determined by the limit variable. In the below example limit is fixed as 1000. Each time 1000 records are
fetched from cursor c1 in to c1_record and processed. The below example deletes duplicate records
using BULK COLLECT

DECLARE

limit_in integer;
CURSOR C1 is
Select min(b.rowid)
from table_name a, table_name b
where a.primary_key = b.primary_key;

TYPE C1_rec IS TABLE OF C1%ROWTYPE


INDEX BY PLS_INTEGER;

C1_record C1_rec

BEGIN
limit_in:=10000 --- Can be changed based on performance
OPEN C1;
LOOP
FETCH C1 BULK COLLECT INTO C1_record LIMIT limit_in;
FORALL indx in 1..c1_record.count
DELETE FROM table_name where row_id = C1_record(i);
commit;
END LOOP;
END;

4. How is performance improved with Bulk Collect?


Bulk Collect fetches large number of rows in to a collection (rather than one row at a time) and process
it. This improves the performance and reduces the time when compared to processing each and every
row.

Especially when a program does a DML, use of Bulk collect and FORALL will improve the performance.

5. How to determine the limit value of Bulk Collect?

The limit is clause is optional and is placed in the FETCH statement. This determines the number of rows
to be collected. It is determined based on the size of the result fetched and the process memory
available. If result set has 1000 rows. You can make the limit to 100, t runs 10 times and process all the
1000 records.
When you set the limit higher than the memory available, out of process memory exception will be
thrown.
6. Say 100 rows are inserted in to the table using bulk collect. How to continue inserting when there are
exception in 50th record?
This can be achieved by using SAVE EXCEPTIONS. It saves the exception details, skips the record and
continue with the next.

FETCH STUDENTINFO BULK COLLECT INTO INTO STUDENT_REC LIMIT 100;


EXIT WHEN STUDENT_REC.count = 0;
BEGIN
FORALL i IN 1.. STUDENT_REC.COUNT SAVE EXCEPTIONS
INSERT INTO TARGET VALUES STUDENT_REC(i);
EXCEPTION
WHEN dml_errors THEN
errorCnt := SQL%BULK_EXCEPTIONS.COUNT;
--errorCNt is the number of exceptions during bulk
collect
FOR i IN 1..errorCnt LOOP
dbms_output.put_line(i || ' '||
SQL%BULK_EXCEPTIONS(i).ERROR_CODE);
RAISE;
END LOOP;
END;
END LOOP;

7. What are the errors encountered while using BULK COLECT

1. Out of Process memory error is thrown out when there is no enough space to hold the collection.
2. If a collection holds 100 items, and the 50th item is deleted. Then there is a nothing in the place of 50th item. It
fails on seeing a null value in the collection.

8. What are the attributes of Bulk Collect?

1) %BULK_ROWCOUNT:-
%BULK_ROWCOUNT(i) stores the number of rows processed by the ith execution of an DML statement. If the ith
execution affects no rows, %BULK_ROWCOUNT(i) returns zero.

2) %BULK_EXCEPTIONS:-
It is an associative array that stores information about any exceptions encountered when using the SAVE
EXCEPTIONS clause.
SQL%BULK_EXCEPTIONS.COUNT: Represents the number of exceptions.

SQL%BULK_EXCEPTIONS(i).ERROR_INDEX Specifies which item in the collection caused the exception

SQL%BULK_EXCEPTIONS(i).ERROR_CODE Specifies the Oracle error code that corresponds to the exception.

9.What are Collections in PL/SQL?

Collections are like array of elements. All elements should be of same datatypes. They are retrieved by indexes.
There are three different types.

Index-by tables or Associative array:-


The element of the array is accessed by a key which is unique.

For example:-

TYPE Students_score IS TABLE OF NUMBER INDEX BY VARCHAR2(20);

score Students_score

BEGIN

score('John'):=80;

score('Joe'):=90;

score('Eve'):=78;

Nested Tables:-
It is a one dimensional array. The length of the array can be extended and the elements can be deleted. If elements
are deleted, it creates a space and that position is skipped.

For Example:-

TYPE students_name IS TABLE of student%rowtype

It creates a datatype which has all the columns that are in student table and in the same order.
Say the table has two columns name , id and marks
name student_name -- creating a object for the nested table
SELECT *
BULK COLLECT INTO name
FROM student

They can be accessed with continuos numbers from 1. name.count gives the number of elements in the array. The
length of the array is not prefixed. You can extend (name.extend)the array and add values. you can delete an ith item
by name.delete(i) or delete(i,j) to delete items between i and j

The nested tables can be stored in Database and Associative arrays cannot be stored in database.
VARRAYS:-
It is the fixed length array. The length of the array is declared along with the datatype it can hold.
TYPE student_name is VARRAY(14) of student%rowtype

name student_name

It is same as the nested table except the maximum size being specified. The advantage of VARRAY over nested
table is it can retrieve the elements in the same order that it has been entered.
10. INSERT ALL can be used only with collections like BULK COLLECT or FOR ALL?

It is not necessary to use INSERT ALL with collections data type , Insert ALL is used to insert records multiple
records in to same or different tables at the same time.

INSERT ALL
INTO MyTable VALUES ('a', 1, 'TRUE')
INTO MyTable VALUES ('b', 2, 'FALSE')
INTO OnTable VALUES ('Structure', 'LION', 1234)
SELECT * FROM dual;

http://easetheinterview.blogspot.com/2017/09/plsql-interview-questions-forall-and.html

https://www.techfaq360.com/viewTutorial.jsp?tutorialId=197

https://sql-plsql-database.blogspot.com/p/records.html

PL-SQL Interview Questions Collections

2. What is the basic structure of PL/SQL?


PL/SQL uses block structure as its basic structure. Anonymous blocks or nested blocks can be used in
PL/SQL.
5.

What are the datatypes a available in PL/SQL?

Some scalar data types such as


NUMBER, VARCHAR2, DATE, CHAR, LONG, BOOLEAN.
Some composite data types such as RECORD & TABLE.

6.

What are % TYPE and % ROWTYPE? What are the advantages of using these over datatypes?

% TYPE provides the data type of a variable or a database column to that variable.
% ROWTYPE provides the record type that represents a entire row of a table or view or columns selected
in the cursor.

The advantages are: I. need not know about variable's data type
ii. If the database definition of a column in a table changes, the data type of a variable changes
accordingly.

7.

What is difference between % ROWTYPE and TYPE RECORD ?

% ROWTYPE is to be used whenever query returns a entire row of a table or view.


TYPE rec RECORD is to be used whenever query returns columns of different table or views and
variables.

E.g. TYPE r_emp is RECORD (eno emp.empno% type,ename emp ename %type );
e_rec emp% ROWTYPE
Cursor c1 is select empno,deptno from emp;
e_rec c1 %ROWTYPE.

8.

What is PL/SQL table?

Objects of type TABLE are called "PL/SQL tables", which are modelled as (but not the same as) database
tables, PL/SQL tables use a primary PL/SQL tables can have one column and a primary key.

9.

What is a cursor? Why Cursor is required?

Cursor is a named private SQL area from where information can be accessed.
Cursors are required to process rows individually for queries returning multiple rows.

10.

Explain the two types of Cursors?

There are two types of cursors, Implict Cursor and Explicit Cursor.
PL/SQL uses Implic

it Cursors for queries. (SQL%NOTFOUND,%FOUND,%ROWCOUNT,%ISOPEN)


User defined cursors are called Explicit Cursors. They can be declared and used.

11.
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.

12.

What are the cursor attributes used in PL/SQL?


%ISOPEN - to check whether cursor is open or not
% ROWCOUNT - 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.

13.

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;

14.

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.

15.

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.
16.

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.

17.

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.

18.

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.

19.

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.

20.

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.


21.

Write the order of precedence for validation of a column in a table ?

I. done using Database triggers.


ii. done using Integarity Constraints.

22.

What is an Exception? What are types of Exception?

Exception is the error handling part of PL/SQL block. The types are Predefined and user_defined. Some
of Predefined execptions are.

CURSOR_ALREADY_OPEN
DUP_VAL_ON_INDEX
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
INVALID_NUMBER
LOGON_DENIED
NOT_LOGGED_ON
PROGRAM-ERROR
STORAGE_ERROR
TIMEOUT_ON_RESOURCE
VALUE_ERROR
ZERO_DIVIDE
OTHERS.

23.

What is Pragma EXECPTION_INIT? Explain the usage?

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)

24.

What is Raise_application_error?

Raise_application_error is a procedure of package DBMS_STANDARD which allows to issue an


user_defined error messages from stored sub-program or database trigger.

25.
What are the return values of functions SQLCODE and SQLERRM?

SQLCODE returns the latest code of the error that has occured.
SQLERRM returns the relevant error message of the SQLCODE.

26.

Where the Pre_defined_exceptions are stored?

In the standard package.


Procedures, Functions & Packages;

27.

What is a stored procedure?

A stored procedure is a sequence of statements that perform specific function.

30.

What is difference between a PROCEDURE & FUNCTION?

A FUNCTION is alway returns a value using the return statement.


A PROCEDURE may return one or more values through parameters or may not return at all.

31.

What are advantages of Stored Procedures?

Extensibility,Modularity, Reusability, Maintainability and one time compilation.

32.

What are the modes of parameters that can be passed to a procedure?

IN,OUT,IN-OUT parameters.

33.

What are the two parts of a procedure?

Procedure Specification and Procedure Body.

34.

Give the structure of the procedure?

PROCEDURE name (parameter list.....)


is
local variable declarations

BEGIN
Executable statements.
Exception.
exception handlers

end;

35.

Give the structure of the function?

FUNCTION name (argument list .....) Return datatype is


local variable declarations
Begin
executable statements
Exception
execution handlers
End;

36.

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');

37.

What is Overloading of procedures?

The Same procedure name is repeated with parameters of different datatypes and parameters in
different positions, varying number of parameters is called overloading of procedures.

e.g. DBMS_OUTPUT put_line

38.

What is a package? What are the advantages of packages?

Package is a database object that groups logically related procedures.


The advantages of packages are Modularity, Easier Applicaton Design, and Information.
Hiding,. Reusability and Better Performance.

39.
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.

40.

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.

41.

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.

42.

Name the tables where characteristics of Package, procedure and functions are stored?

User_objects, User_Source and User_error.

Part-2
 What’s a PL/SQL table? Its purpose and Advantages?
A PL/SQL table is one dimensional, indexed, unbounded sparsed collection of homogeneous
Data.
PLSQL tables are used to move data into and out of the database and between client side applications and stored
sub-programs. They have attributes such as exits, prior, first, last, delete ,next . These attributes make PLSQL tables
easier to use and applications easier to maintain.
Advantages:
1 PL\SQL tables give you the ability to hold multiple values in a structure in memory so that a PL\SQL block does not
have to go to the database every time it needs to retrieve one of these values - it can retrieve it directly from the
PL\SQL table in memory.
2 Global temporary tables act as performance enhancers when compared to standard tables as they greatly reduce
the disk IO.
3 They also offer the ease-of-use of standard tables, since standard SQL can be used with them; no special array-
processing syntax is required.

 What is a Cursor? How many types of Cursor are there?


A) Cursor is an identifier/name to a work area that we can interact with to access its information. A cursor points to
the current row in the result set fetched. There are three types of cursors. They are
1 Implicit cursors – created automatically by PL/SQL for all SQL Dml statements such as
Insert Update, delete and Select
2 Explicit cursors – Created explicitly. They create a storage area where the set of rows
Returned by a query are placed.
3 Dynamic Cursors – Ref Cursors( used for the runtime modification of the select querry).
Declaring the cursor, Opening the cursor, Fetching data , Closing the cursor(Releasing the work area) are the steps
involved when using explicit cursors.

 What is the difference between Function and Procedure?


1..Procedure is a sub program written to perform a set of actions and returns multiple valuesUsing out parameters or
return no value at all.
2..Function is a subprogram written to perform certain computations and return a single value.

 What are the modes for passing parameters to Oracle?


There are three modes for passing parameters to subprograms
1.IN - An In-parameter lets you pass values to the subprogram being called. In the subprogram it acts like a constant
and cannot be assigned a value.
2. OUT – An out-parameter lets you return values to the caller of the subprogram. It acts like an initialized variable its
value cannot be assigned to another variable or to itself.
3.INOUT – An in-out parameter lets you pass initial values to the subprogram being called and returns updated
values to the caller.

 What is the difference between Truncate and Delete Statement?


1.Truncate – Data truncated by using truncate statement is lost permanently and cannot be retrieved even by
rollback. Truncate command does not use rollback segment during its execution, hence it is fast.
2. Delete – Data deleted by using the delete statement can be retrieved back by Rollback. Delete statement does not
free up the table object allocated space.

 What are Exceptions? How many types of Exceptions are there?


Exceptions are conditions that cause the termination of a block. There are two types of exceptions
1.Pre-Defined – Predefined by PL/SQL and are associated with specific error codes.
2.User-Defined – Declared by the users and are rose on deliberate request. (Breaking a condition etc.)
Exception handlers are used to handle the exceptions that are raised. They prevent exceptions from propagating out
of the block and define actions to be performed when exception is raised.

 What is a Pragma Exception_Init? Explain its usage?


Pragma Exception_Init is used to handle undefined exceptions. It issues a directive to the compiler asking it to
associate an exception to the oracle error. There by displaying a specific error message pertaining to the error
occurred. Pragma Exception_Init (exception_name, oracle_error_name).

 What is a Raise and Raise Application Error?


1.Raise statement is used to raise a user defined exception.
2. A raise application error is a procedure belonging to dbms_standard package. It allows to display a user defined
error message from a stored subprogram.

 What is the difference between Package, Procedure and Functions?


1.A package is a database objects that logically groups related PL/SQL types, objects, and Subprograms.
2.Procedure is a sub program written to perform a set of actions and can return multiple values.
3.Function is a subprogram written to perform certain computations and return a single value. Unlike subprograms
packages cannot be called, passed parameters or nested.

 How do you make a Function and Procedure as a Private?


Functions and Procedures can be made private to a package by not mentioning their declaration in the package
specification and by just mentioning them in the package body.

 How do you kick a Concurrent program from PL/SQL?


Using FND_REQUEST.SUBMIT_REQUEST.

 What is an Anonymous block?


Anonymous Block is a block of instructions in PL/SQL and SQL which is not saved under a name as an object
in database schema It is also not compiled and saved in server storage, so it needs to be parsed and executed each
time it is run. However, this simple form of program can use variables, can have flow of control logic, can return query
results into variables and can prompt the user for input using the SQL*Plus '&' feature as any stored procedure.

 What are the two basic parameters that we have to pass while registering PL/SQL procedure?
Error code and Error Buffer.

 How to display messages in Log file and Output file?


Using FND_FILE.PUT_LINE

 What is a Trigger ? How many types of Triggers are there?


Trigger is a procedure that gets implicitly executed when an insert/update/delete statement is issued against an
associated table. Triggers can only be defined on tables not on views, how ever triggers on the base table of a view
are fired if an insert/update/delete statement is issued against a view.
There are two types of triggers, Statement level trigger and Row level trigger.
Insert
After / For each row
Trigger is fired / Update /
Before / For Each statement
Delete

 Can we use Commit in a Database Trigger, if ‘No’ then why?


No. Committing in a trigger will violate the integrity of the transaction.

 What is Commit, Rollback and Save point?


Commit – Makes changes to the current transaction permanent. It Erases the savepoints and releases the
transaction locks.
Savepoint –Savepoints allow to arbitrarily hold work at any point of time with option of later committing. They are
used to divide transactions into smaller portions.
Rollback – This statement is used to undo work.

 What is the difference between DDL, DML and DCL structures?


DDL statements are used for defining data. Ex: Create, Alter, Drop,Truncate,Rename.
DML statements are used for manipulating data. Ex: Insert, update, truncate.
DCL statements are used for to control the access of data. Ex; Grant, Revoke.
TCL statements are used for data saving.Ex; Commit,Rollback,Savepoint.

 How can u create a table in PL/SQL procedure?


By using execute immediate statement we can create a table in PLSQL.
Begin
Execute immediate ‘create table amit as select * from emp’;
End;
All DDL,DML,DCL commands can be performed by using this command.

 How do we Tune the Queries?


Queries can be tuned by Checking the logic (table joins), by creating Indexes on objects in the where clause, by
avoiding full table scans. Finally use the trace utility to generate the trace file, use the TK-Prof utility to generate a
statistical analysis about the query using which appropriate actions can be taken.

 What is Explain Plan? How do u use Explain Plan in TOAD?


It is a utility provided by toad that gives the statistics about the performance of the query. It gives information such as
number of full table scans occurred, cost, and usage of indexes

 What is a TK-PROF and its usage?


Tk-Prof is a utility that reads the trace files and generates more readable data that gives the statistics about the
performance of the query on a line to line basis.

 What is Optimization? How many types of Optimization are there?


Rule based Optimization and Cost Based Optimization.

 What is the default optimization chosen by Oracle?


Cost based Optimization.

 What is the difference between the snapshot and synonym?


7 A snapshot refers to read-only copies of a master table or tables located on a remote node. A snapshot can be
queried, but not updated; only the master table can be updated. A snapshot is periodically refreshed to reflect
changes made to the master table. In this sense, a snapshot is really a view with periodicity.
8 A synonym is an alias for table, view, sequence or program unit. They are of two types private and public.

 What is the difference between data types char and varchar?


Char reserves the number of memory locations mentioned in the variable declarations, even though not used (it can
store a maximum of 255 bytes). Where as Varchar does not reserve any memory locations when the variable is
declared, it stores the values only after they are assigned (it can store a maximum of 32767 bytes).

 Items are imported from the legacy system using the item import interface using the SRS. How are items
imported using the UNIX /PLSQL commands with out using SRS?
1.From the operating system, use CONCSUB to submit a concurrent program. It's an easiest way to test a concurrent
program.
Normally, CONCSUB submits a concurrent request and returns control to the OS prompt/shell script without waiting
for the request to complete. The CONCSUB WAIT parameter can be used to make CONCSUB wait until the request
has completed before returning control to the OS prompt/shell script
By using the WAIT token, the utility checks the request status every 60 seconds and returns to the operating system
prompt upon completion of the request. concurrent manager does not abort, shut down, or start up until the
concurrent request completes. If your concurrent program is compatible with itself, we can check it for data integrity
and deadlocks by submitting it many times so that it runs concurrently with itself.
Syntax: CONCSUB [WAIT= [START=] [REPEAT_DAYS=] [REPEAT_END=]
To pass null parameters to CONCSUB, use '""' without spaces for each null parameter.
In words: single quote double quote double quote single quote
Following is an example of CONCSUB syntax with null parameters:
CONCSUB oe/oe OE 'Order Entry Super User' JWALSH CONCURRENT XOE XOEPACK 4 3 '""' 3
2. To Invoke a Concurrent Program using PL/SQL:
i) Just insert a row in FND_CONCURRENT_REQUESTS with the apropriate parameters and commit.
ii) Invoke the SUBMIT_REQUEST procedure in FND_REQUEST package.
FND_REQUEST.SUBMIT_REQUEST( 'AR', 'RAXMTR', '', '', FALSE, 'Autoinvoice Master Program', sc_time, FALSE,
1, 1020, 'VRP', '01-JAN-00', chr(0)

 How can the duplicate records be deleted from the table?


delete from t1 a where rowid not in (select max(rowid) from t1 b where a.no=b.no)

 What is the significance of _all tables?


All tables are multi-org tables which are associated with the company as a whole. Multiple Organizations is enabled in
Oracle
Applications by partitioning some database tables by the Operating Unit. Other tables are shared across Operating
Units (and therefore across set of books). Examples of Applications with partitioned tables are Oracle Payables,
Oracle Purchasing, Oracle Receivables, Oracle Projects, Oracle Sales & Marketing etc. The name of each
corresponding partitioned table is the view name appended by '_ALL'

 What are mutating tables? And what is mutating error?


A mutating table is a table that is currently being modified by an UPDATE, DELETE, or INSERT statement, or it is a
table that might need to be updated by the effects of a declarative DELETE CASCADE referential integrity constraint.
A mutating error occurs when a trigger which fires when updation/deletion/insertion is done on a table A performs
insertion/updation/deletion on the same table A. This error results in an infinite loop which is termed as a mutating
error.

 What is difference between oracle 7 andoracle 8i?


A) Oracle 7 is a simple RDBMS, where as Oracle 8i is ORDBMS i.e., RDBMS with Object Support.
The main add-ons in version 8 are…
Abstract Data types
Varrays
PL/SQL Tables
Nested Tables
Partitioned Tables

 What is Data cleaning and testing.


Data Cleaning: Transformation of data in its current state to a pre-defined, standardized format using packaged
software or program modules.
Data Testing: The agreed upon conversion deliverables should be approved by the client representatives who are
responsible for the success of the conversion. In addition, three levels of conversion testing have been identified and
described in the prepare conversion test plans deliverables.
Eg: for Summary Balances in GL we set Test Criteria as Record Counts, Hash Totals, Balances, Journal Debit and
Credit.

 While registering a report and a pl/sql block we pass some parameters, for any pl/sql block we pass 2
additional parameters. Can u list them?
It requires two IN parameters for a PL/SQL procedure that's registered as a concurrent program in Apps. They are
1. Errcode IN VARCHAR2
2. Errbuff IN VARCHAR2

 what is a trace file?


when ever an internal error is detected by a process in oracle it dumps the information about the error into a trace file.
Alter session set sql_trace=TRUE

 When do you use Ref Cursors?


We base a query on a ref cursor when you want to:
1.More easily administer SQL
2. Avoid the use of lexical parameters in your reports
3. Share data sources with other applications, such as Form Builder
4. Increase control and securityv) Encapsulate logic within a subprogram

https://appsoracle-abhi.blogspot.com/2013/04/pl-sql-interview-questions-collections.html

https://www.orafaq.com/wiki/Send_mail_from_PL/SQL

Example:

BEGIN
EXECUTE IMMEDIATE 'ALTER SESSION SET smtp_out_server = ''127.0.0.1''';
UTL_MAIL.send(sender => 'me@address.com',
recipients => 'you@address.com',
subject => 'Test Mail',
message => 'Hello World',
mime_type => 'text; charset=us-ascii');
END;
/

tkyte@TKYTE816> create or replace
2 PROCEDURE send_mail (p_sender IN VARCHAR2,
3 p_recipient IN VARCHAR2,
4 p_message IN VARCHAR2)
5 as
6 l_mailhost VARCHAR2(255) := 'yourserver.acme.com';
7 l_mail_conn utl_smtp.connection;
8 BEGIN
9 l_mail_conn := utl_smtp.open_connection(l_mailhost, 25);
10 utl_smtp.helo(l_mail_conn, l_mailhost);
11 utl_smtp.mail(l_mail_conn, p_sender);
12 utl_smtp.rcpt(l_mail_conn, p_recipient);
13 utl_smtp.open_data(l_mail_conn );
14 utl_smtp.write_data(l_mail_conn, p_message);
15 utl_smtp.close_data(l_mail_conn );
16 utl_smtp.quit(l_mail_conn);
17 end;
18 /
Procedure created.
tkyte@TKYTE816> begin
2 send_mail( 'me@acme.com',
3 'you@acme.com',
4 'Hello Tom' );
5 end;
6 /

PL/SQL procedure

. Explain Trigger and trigger types?


A trigger is a special kind of a store procedure that executes in response to certain
action performed on the table like insertion, deletion or updating of data

Basically there are two logical types

a. DDL triggers
b. DML triggers

DDL triggers you can categorize:

1. Transact-SQL DDL Trigger


2. CLR DDL Trigger

DML trigger types are:

1. INSTEAD OF DML trigger


2. AFTER DML trigger

There is one special type trigger called logon trigger in sql server.

2. What are DDL Triggers and types of DDL trigger?

DDL triggers fire in response to an event happening on the server. However, DDL
triggers do not fire in response to UPDATE, INSERT, or DELETE (DML) statements
on a table or view. Instead, they fire in response to Data Definition Language (DDL)
statements that start with the keywords CREATE, ALTER, and DROP.

DDL triggers you can categorize:

1. Transact-SQL DDL Trigger


2. CLR DDL Trigger

3. What are DML triggers and types of DML triggers?

DDL triggers fire in response to UPDATE, INSERT, or DELETE (DML) statements on a


table or view.

DML trigger types are:


1. INSTEAD OF DML trigger
2. AFTER DML trigger

4. What is Transact-SQL DDL Trigger?

A special type of Transact-SQL stored procedure that executes one or more


Transact-SQL statements in response to a server-scoped or database-scoped
event. For example, a DDL Trigger may fire if a statement such as ALTER SERVER
CONFIGURATION is executed or if a table is deleted by using DROP TABLE.

5. What is CLR DDL Trigger?

Instead of executing a Transact-SQL stored procedure, a CLR trigger executes one


or more methods written in managed code that are members of an assembly
created in the .NET Framework and uploaded in SQL Server.

Example:
CREATE TRIGGER safety
ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You must disable Trigger "safety" to drop or
alter tables!'
ROLLBACK;

6. What is AFTER DML trigger?


AFTER triggers are executed after the action of the INSERT, UPDATE, MERGE, or
DELETE statement is performed successfully.

More … http://codechef4u.com/post/2015/04/15/after-trigger

7. What is INSTEAD OF DML trigger?


DML trigger is executed instead of the triggering SQL statement, therefore,
overriding the actions of the triggering statements. Therefore, they can be used to
perform error or value checking on one or more columns and the perform
additional actions before insert, updating or deleting the row or rows.
More … http://codechef4u.com/post/2015/04/15/instead-of-trigger

8. What is logon trigger?


Special type of trigger fire when LOGON event of Sql Server is raised is called lo
logon trigger. You can use this trigger to audit Sql server activities, control server
sessions, such as to track login activity or limit the number of sessions for a
specific login.

More … http://codechef4u.com/post/2015/04/16/logon-trigger

9. Why the Trigger Fires Multiple Times in Single Login?


Reason multiple SQL Server services are running as well as intelligence is turned
on.

10. Is it possible to create trigger on views?


Yes, only InsteadOf trigger.

11. How many triggers are possible per table?


One InsteadOfTrigger and any After Triggers.

12. When multiple after triggers are attached to sql table, how to control the
order of execution?
Using sp_settriggerorder procedure.

13. What is the difference between For Trigger and after trigger?
It’s same.

https://codechef4u.com/post/2016/03/04/trigger-interview-questions-and-answers

 Question 1. Explain Trigger And Trigger Types?

Answer :

A trigger is a special kind of a store procedure that executes in response to certain action
performed on the table like insertion, deletion or updating of data
Basically there are two logical types:

 DDL triggers
 DML triggers

DDL triggers you can categorize:

 Transact-SQL DDL Trigger


 CLR DDL Trigger

DML trigger types are:

 INSTEAD OF DML trigger


 AFTER DML trigger

There is one special type trigger called logon trigger in sql server.

 Question 2. What Are Ddl Triggers And Types Of Ddl Trigger?

Answer :

DDL triggers fire in response to an event happening on the server. However, DDL triggers do not
fire in response to UPDATE, INSERT, or DELETE (DML) statements on a table or view.
Instead, they fire in response to Data Definition Language (DDL) statements that start with the
keywords CREATE, ALTER, and DROP.

DDL triggers you can categorize:

 Transact-SQL DDL Trigger


 CLR DDL Trigger

PL/SQL Interview Questions

 Question 3. What Are Dml Triggers And Types Of Dml Triggers?

Answer :

DDL triggers fire in response to UPDATE, INSERT, or DELETE (DML) statements on a table or
view.

DML trigger types are:

 INSTEAD OF DML trigger


 AFTER DML trigger

 Question 4. What Is Transact-sql Ddl Trigger?


Answer :

A special type of Transact-SQL stored procedure that executes one or more Transact-SQL
statements in response to a server-scoped or database-scoped event. For example, a DDL Trigger
may fire if a statement such as ALTER SERVER CONFIGURATION is executed or if a table is
deleted by using DROP TABLE.

SQL Server 2008 Tutorial

 Question 5. What Is Clr Ddl Trigger?

Answer :

Instead of executing a Transact-SQL stored procedure, a CLR trigger executes one or more
methods written in managed code that are members of an assembly created in the .NET
Framework and uploaded in SQL Server.

Example:

CREATE TRIGGER safety

ON DATABASE

FOR DROP_TABLE, ALTER_TABLE

AS

PRINT 'You must disable Trigger "safety" to drop or

alter tables!'

ROLLBACK;

SQL Server 2008 Interview Questions

 Question 6. What Is After Dml Trigger?

Answer :

AFTER triggers are executed after the action of the INSERT, UPDATE, MERGE, or DELETE
statement is performed successfully.

 Question 7. What Is Instead Of Dml Trigger?

Answer :
DML trigger is executed instead of the triggering SQL statement, therefore, overriding the
actions of the triggering statements. Therefore, they can be used to perform error or value
checking on one or more columns and the perform additional actions before insert, updating or
deleting the row or rows.

SQL Database Tutorial SQL Database Interview Questions

 Question 8. What Is Logon Trigger?

Answer :

Special type of trigger fire when LOGON event of Sql Server is raised is called lo logon trigger.
You can use this trigger to audit Sql server activities, control server sessions, such as to track
login activity or limit the number of sessions for a specific login.

 Question 9. Why The Trigger Fires Multiple Times In Single Login?

Answer :

Reason multiple SQL Server services are running as well as intelligence is turned on.

PostgreSQL Interview Questions

 Question 10. It Is Possible To Create Trigger On Views?

Answer :

Yes, only Instead Of trigger.

Apex Tutorial

 Question 11. How Many Triggers Are Possible Per Table?

Answer :

One Instead Of Trigger and any After Triggers.

SQL DBA Interview Questions

 Question 12. When Multiple After Triggers Are Attached To Sql Table, How To Control
The Order Of Execution?

Answer :

Using sp_settriggerorder procedure.


PL/SQL Interview Questions

 Question 13. What Is The Difference Between For Trigger And After Trigger?

Answer :

It’s same.

Spark SQL Programming Tutorial

 Question 14. What Are The Types Of Triggers?

Answer :

It's Instead Of trigger and For Trigger.

 Question 15. What Is The Difference Between Instead Of And After/for Trigger?

Answer :

Instead Of trigger will be fired on behalf of DML statements whereas After trigger will be fired
after DML statements.

SQL Interview Questions

 Question 16. Is It Possible To Create Trigger On Views?

Answer :

Yes, only Instead Of trigger.

https://www.wisdomjobs.com/e-university/trigger-interview-questions.html

https://www.webcodeexpert.com/2013/11/what-is-cursor-advantages-and.html

https://www.scribd.com/doc/26315804/Advantage-and-Disadvantages-of-Cursor-in-Oracle

https://www.scribd.com/document/14004160/Pl-SQL-Interview-Questions

https://www.scribd.com/document/257896001/Oracle-PL-SQL-Interview-Questions

https://www.scribd.com/doc/279220171/Oracle-Pl-SQL-Interview-Questions-and-Answers-for-
Experienced

https://www.scribd.com/doc/244977462/Oracle-Pl-SQL-Interview-Questions-and-Answers-docx

http://oracle-sqlserver.over-blog.com/2015/09/what-are-the-advantage-disadvantage-of-package.html
https://www.quora.com/What-are-the-advantages-and-disadvantages-of-using-Database-Triggers

https://www.careerride.com/Oracle-disadvantages-of-trigger.aspx

https://www.developer.com/db/article.php/3379271/Oracle-Programming-with-PLSQL-Collections.htm

http://oracleappps.blogspot.com/2013/05/what-are-disadvantage-of-bulk-collection.html

http://www.oraclechennai.com/Avoiding-Collection-Exceptions.html

https://oracle-base.com/articles/9i/bulk-binds-and-record-processing-9i

https://oracle-base.com/articles/9i/bulk-binds-and-record-processing-9i

Вам также может понравиться