Documente Academic
Documente Profesional
Documente Cultură
PL/SQL is Oracle's Procedural Language extension to SQL. PL/SQL's language syntax, structure and
datatypes are similar to that of ADA. The language includes object oriented programming techniques
such as encapsulation, function overloading, information hiding (all but inheritance), and so, brings
state-of-the-art programming to the Oracle database server and a variety of Oracle tools.
PL SQL is a block structured programming language. It combines data manipulation & data processing
power. It supports all SQL data types. Also has its own data types i,e BOOLEAN,BINARY INTEGER
a declarative part,
an executable part,
part.
Declare : optional
Variable declaration
Begin : Manadatory
Procedural statements.
Exception : Optional
any errors to be trapped
End : Mandatory
Scalar Types
BINARY_INTEGER
DEC
DECIMAL
DOUBLE PRECISION
FLOAT
INT
INTEGER
Reference Types
REF CURSOR
REF object_type
6. Wha t are % TYPE and % ROWTYPE ? What are the advantages of using these over datatypes?% TYPE
% ROWTYPE provides the record type that represents a entire row of a table or view or columns
Advantage is, if one change the type or size of the column in the table, it will be reflected in our
program unit without making any change.
%type is used to refer the column's datatype where as %rowtype is used to refer the whole
record in a table.
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.
by integers
One-dimensional
A PL/SQL table can have only one column. It is, in this way, similar to a one-dimensional array.
Unbounded or Unconstrained
There is no predefined limit to the number of rows in a PL/SQL table. The PL/SQL table grows
dynamically as you add more rows to the table. The PL/SQL table is, in this way, very different from
an array.
Related to this definition, no rows for PL/SQL tables are allocated for this structure when it is defined.
Sparse
In a PL/SQL table, a row exists in the table only when a value is assigned to that row. Rows do not
have to be defined sequentially. Instead you can assign a value to any row in the table. So row 15
could have a value of `Fox' and row 15446 a value of `Red', with no other rows defined in between.
Homogeneous elements
Because a PL/SQL table can have only a single column, all rows in a PL/SQL table contain values of the
With PL/SQL Release 2.3, you can have PL/SQL tables of records. The resulting table is still, however,
Indexed by integers
Cursor is a named private SQL area from where information can be accessed. Cursors are required
implicit cursor: implicit cursor is a type of cursor which is automatically maintained by the
DECLARE CURSOR cursor name, OPEN cursor name, FETCH cursor name INTO or Record types,
% FOUND - to check whether cursor has fetched any row. True if rows are fetched.
% NOT FOUND - to check whether cursor has fetched any row. True if no rows are featched.
These attributes are proceeded with SQL for Implicit Cursors and with Cursor name for Explicit
Cursors
Cursor for loop implicitly declares %ROWTYPE as loop index,opens a cursor, fetches rows of values
END LOOP;
PL/SQL provides the WHERE CURRENT OF clause for both UPDATE and DELETE statements inside a
cursor in order to allow you to easily make changes to the most recently fetched row of data.
Notice that the WHERE CURRENT OF clause references the cursor and not the record into which the
The most important advantage to using WHERE CURRENT OF where you need to change the row
fetched last is that you do not have to code in two (or more) places the criteria used to uniquely
identify a row in a table. Without WHERE CURRENT OF, you would need to repeat the WHERE clause of
your cursor in the WHERE clause of the associated UPDATEs and DELETEs. As a result, if the table
structure changes in a way that affects the construction of the primary key, you have to make sure
that each SQL statement is upgraded to support this change. If you use WHERE CURRENT OF, on the
other hand, you only have to modify the WHERE clause of the SELECT statement.
This might seem like a relatively minor issue, but it is one of many areas in your code where you can
leverage subtle features in PL/SQL to minimize code redundancies. Utilization of WHERE CURRENT OF,
%TYPE, and %ROWTYPE declaration attributes, cursor FOR loops, local modularization, and other
PL/SQL language constructs can have a big impact on reducing the pain you may experience when you
Let's see how this clause would improve the previous example. In the jobs cursor FOR loop above, I
want to UPDATE the record that was currently FETCHed by the cursor. I do this in the UPDATE
statement by repeating the same WHERE used in the cursor because (task, year) makes up the
This is a less than ideal situation, as explained above: I have coded the same logic in two places, and
this code must be kept synchronized. It would be so much more convenient and natural to be able to
or:
A perfect fit for WHERE CURRENT OF! The next version of my winterization program below uses this
clause. I have also switched to a simple loop from FOR loop because I want to exit conditionally from
the loop:
fall_jobs_cur;END;
A database trigger is a stored procedure that is invoked automatically when a predefined event
occurs.
Database triggers enable DBA's (Data Base Administrators) to create additional relationships
For example, the modification of a record in one database could trigger the modification of a
17. How many types of database triggers can be specified on a table ? What are they ?
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 returned Boolean value.
the different types of triggers: * Row Triggers and Statement Triggers * BEFORE and AFTER Triggers *
18. What are two virtual tables available during database trigger execution ?
For triggers related to UPDATE only OLD.column_name NEW.column_name values only available.
To avoid the mutation table error ,the procedure should be declared as an AUTONOMOUS
TRANSACTION.
Predefined
NO_DATA_FOUND
TOO_MANY_ROWS
INVALID_CURSOR
ZERO_DIVIDE
INVALID_CURSOR
Non predefined
Declare within the declarative section and allow allow Oracle server to
raise implicitly
User defined
Pragma exception_init Allow you to handle the Oracle predefined message by you'r own
message. means you can instruct compiler toassociatethe specific message to oracle predefined
message at compile time.This way you Improve the Readbility of your program,and handle it
example
declare
salary number;
FOUND_NOTHING exception;
begin
dbms_output.put_line(salary);
exception
dbms_output.put_line(SQLERRM);
end;
Raise_application_error is used to create your own error messages which can be more
Raise_application_error (error_number,error_messages);
24. What are the return values of functions SQLCODE and SQLERRM ?
Pl / Sql Provides Error Information via two Built-in functions, SQLCODE & SQLERRM.
Returns 1.
Stored Procedure
A program running in the database that can take complex actions based on the inputs you send it.
28. What are the modes of parameters that can be passed to a procedure ?
1.in:
in parameter mode is used to pass values to subprogram when invoked.
2.out:
3.in out:
is
BEGIN
Executable statements.
Exception.
exception handlers
end;
Begin
executable statements
Exception
execution handlers
End;
32. Explain how procedures and functions are called in a PL/SQL block ?
Procedure can be called in the following ways
a) EXCECUTE <Function name> from calling environment. Always use a variable to get the
return value.
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.
33.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.
Example:
This will create a package Now You can use this cursor any where.
Like:
set serveroutput on
begin
dbms_output.put_line(r1.empno||' '||r1.ename);
end loop;
end;
35. How packaged procedures and functions are called from the following?
c. SQL *PLUS
b.
BEGIN
END;
END EXEC;
c. EXECUTE PACKAGE NAME.PROCEDURE if the procedures does not have any
Overloading procs are 2 or more procs with the same name but different arguments.
Arguments needs to be different by class it self. ie char and Varchar2 are from same class.
Packages -
1- Since packages has specification and body separate so, whenever any ddl is run and if any
proc/func(inside pack) is dependent on that, only body gets invalidated and not the spec. So any
2- Whenever any func/proc from package is called, whole package is loaded into memory and
hence all objects of pack is availaible in memory which means faster execution if any is called.
And since we put all related proc/func in one package this feature is useful as we may need to
38.Is it possible to use Transaction control Statements such a ROLLBACK or COMMIT in Database Trigger
? Why ?
its transactions and save it , to affect with the commit or rollback of the
surrounding transactions.
2 Procedure InsertInTest_Table_B
3 is
4 BEGIN
6 Commit;
7 END ;
8 BEGIN
10 InsertInTest_Table_B;
11 Rollback;
12 END;
user defined exception are the exception name given by user (explicitly decalred and used) and
they are raised to handle the specific behaviour of program.
system exceptions are raised due to invalid data(you dont have to deaclre these). few examples
44. Can we use commit or rollback command in the exception part of PL/SQL block?
Yes, we can use the TCL commands(commit/rollback) in the exception block of a stored
procedure/function. The code in this part of the program gets executed like those in the body without
any restriction. You can include any business functionality whenever a condition in main block(body of
a proc/func) fails and requires a follow-thru process to terminate the execution gracefully!
DECALRE
…..
BEGIN
…….
EXCEPTION
err_code, code_desc)
COMMIT;
RAISE;
END
Bulk Binds (BULK COLLECT , FORALL ) are a PL/SQL technique where, instead of multiple
individual SELECT, INSERT, UPDATE or DELETE statements are executed to retrieve from, or
store data in, at table, all of the operations are carried out at once, in bulk.
This avoids the context-switching you get when the PL/SQL engine has to pass over to the SQL
engine, then back to the PL/SQL engine, and so on, when you individually access rows one at a
time. To do bulk binds with Insert, Update and Delete statements, you enclose the SQL statement
To do bulk binds with Select statements, you include the Bulk Collect INTO a collection clause
Collections, BULK COLLECT and FORALL are the new features in Oracle 8i, 9i and 10g
Bulk Binding is used for avoiding the context switching between the sql engine and pl/sql
engine. If we use simple For loop in pl/sql block it will do context switching between
sql and pl/sql engine for each row processing that degrades the performance of pl/sql
bloack.
So that for avoiding the context switching betn two engine we user FORALL keyword by using
47.Why Functions are used in oracle ?Can Functions Return more than 1 values?Why Procedures are
used in oracle ?
What are the Disadvantages of packages?What are the Global Variables in Packages?
The functions are used where we can't used the procedure.i.e we can use a function the in select
statments,in the where clause of delete/update statments.But the procedure can't used like that.
It is true that function can return only one value, but a function can be used to return more than
one value,by using out parameters and also by using ref cursors.
There is no harm in using the out parameter,when functins are used in the DML statements we
Function cannot have DML statemets and we can use select statement in function
If you create function with DML statements we get message function will be created
when a package is initialised that is called for the first time the entire package is loaded into SGA and
Pl/Sql table is a type of datatype in procedural language Extension.It has two columns.One for the
index,say Binary index And another column for the datas,which might further extend to any number of
PL/SQL table is nothing but one dimensional array. It is used to hold similar type of data for temporary
Yes you can write PL/SQL block inside exception section. Suppose you want to insert the exception
detail into your error log table, that time you can write insert into statement in exception part. To
handle the exception which may be raised in your exception part, you can write the PL/SQL code in
exception part.
54. Can we truncate some of the rows from the table instead of truncating the full table.
You can truncate few rows from a table if the table is partitioned. You can truncate a single partition
and keep remaining.
state VARCHAR2(2),
sales NUMBER(10,2))
TABLESPACE uwdata,
TABLESPACE uwdata);
COMMIT;
56. What is the difference between a reference cursor and normal cursor ?
REF cursors are different than your typical, standard cursors. With standard cursors, you know
the cursor's query ahead of time. With REF cursors, you do not have to know the query ahead of
time. With REF Cursors, you can build the cursor on the fly
Refcusor is a type which is going to hold set of records which can be sent out through the
58. Based on what conditions can we decide whether to use a table or a view or a materialized view ?
Table is the basic entity in any RDBMS , so for storing data you need table .
for view - if you have complex query from which you want to extract data again and again ,
moreover it is a standard data which is required by many other user also for REPORTS
generation then create view . Avoid to insert / update / delete through view unless it is essential.
for materialized view - this view ia mainly used in datawarehousing . if you have two databases
datasize . So create a summary table in a database and make the replica(materialized view) in
other database.
[1] if data is in bulk and you need same data in more than one database then create summary
[1] it save data in database whether simple view's definition is saved in database
[2] can create parition or index on materialize view to enhance the performance of view , but
An ALL_ view displays all the information accessible to the current user, including information from
the current user's schema as well as information from objects in other schemas, if the current user
While
A USER_ view displays all the information from the schema of the current user. No special
User_tables data dictionary contains all the tables created by the users under that schema.
whereas All_tables stores all the tables created in different schema. If any user id have the Grants
for access table of diff. schema then he can see that table through this dictionary.
P-code is Pre-complied code stored in Public cache memory of System Global Area after the
Oracle instance is started, whereas sourcecode is a simple code of sp, package, trigger, functions
etc which are stored in Oracle system defined data dictionary. Every session of oracle access the
63. Is there any limitation on no. of triggers that can be created on a table?
you can write as many u want for insert,update or delte by diff names.
if table has got n columns. we can create n triggers based on each column.
64.What happens when DML Statement fails?A.User level rollbackB.Statement Level RollbackC.Sustem
evel Rollback
table t1. Insert a record in t1. Then again to create the same object t1.
pl/sql table is temparary table which is used to store records temrparaily in PL/SQL Block,
Binary Integer
72.What is the difference between User-level, Statement-level and System-level Rollback? Can you
please give me example of
each?
Rollback the current transaction entirely on errors. This was the unique
8.0.
2. Statement
Rollback the current (ODBC) statement on errors (in case of 8.0 or later
version servers). The driver calls a SAVEPOINT command just before starting
You can(have to) call some SAVEPOINT commands and rollback to a savepoint
the application
Generally we are not supposed to create a view without base table. If you want to create any
view without base table that is called as Force View or invalid view.
Once you create the table that invalid view will become as valid one.
79. How can I speed up the execution of query when number of rows in the tables increased
Standard practice is -
3. check the explain paln for the query and avoid for the nested loops / full table scan (depending
on the size of data retrieved and / or master table with few rows)
1) When u try to do delete, update, insert into a table through a trigger and at the same time u r
3) Apart from that, if u r deleting (delete cascade),update,insert on the parent table and doing a
select in the child tableAll these happen only in a row level trigger
During bulk collect you can save the exception and then you can process the exception.
errors NUMBER;
SAVE EXCEPTIONS
EXCEPTION WHEN OTHERS THEN -- this is not in the doco, thanks to JL for
errors := SQL%BULK_EXCEPTIONS.COUNT;
%BULK_EXCEPTIONS(i).ERROR_CODE;
END LOOP;END;
Bulk collect is part of PLSQL collection where data is stored/ poped up into a variable.
example:
declare
v_sal sal_rec;
begin
dbms_output.put_line(v_sal(r));
end loop;
end;
insted of triggers: They provide a transparent way of modifying view that can't be modified
Table is logical entity which holds the data in dat file permanently . where as scope of plsql table
is limited to the particular block / procedure . refer above example sal_rec table will hold data
111.Can anyone tell me the difference between instead of trigger, database trigger, and schema trigger?
INSTEAD OF Trigger control operation on view , not table. They can be used to make nonupdateable
views updateable and to override the behvior of view that are updateable.
Database triggers fire whenever the database startup or is shutdown, whenever a user logs on or
log off, and whenever an oracle error occurs. these tigger provide a means of tracking activity in
the database
if we have created a view that is based on join codition then its not possibe to apply dml
operations like insert, update and delete on that view. So what we can do is we can create instead
Flahsback is used to take your database at old state like a system restore in windows. No DDL
132. what is the difference between database server and data dictionary
Data Dictionary contains the information of for all the objects like when created, who created
etc.
Database server is a server on which the instance of oracle as server runs..whereas datadictionary
is the collection of information about all those objects like tables indexes views triggers etc in a
database..
134. Mention the differences between aggregate functions and analytical functions clearly with
examples?
Disadvantages of Package - 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
Disadvantages: Updating one of the functions/procedures will invalid other objects which use
Prior to Oracle 8i there were three types of parameter-passing options to procedures and functions:
The technique of OUT and IN OUT parameters was designed to protect original values of them in case
exceptions were raised, so that changes could be rolled back. Because a copy of the parameter set
was made, rollback could be done. However, this method imposed significant CPU and memory
overhead when the parameters were large data collections—for example, PL/SQL Table or VARRAY
types.
With the new NOCOPY option, OUT and IN OUT parameters are passed by reference, which avoids
copy overhead. However, parameter set copy is not created and, in case of an exception rollback,
NOCOPY is a hint given to the compiler, indicating that the parameter is passed as a reference
and hence actual value should not be copied in to the block and vice versa. The processing will
be done accessing data from the original variable. (Which other wise, oracle copies the data from
the parameter variable into the block and then copies it back to the variable after processing. This
would put extra burdon on the server if the parameters are of large collections/sizes)
For better understanding of NOCOPY parameter, I will suggest u to run the following code and
DECLARE
n NUMBER := 10;
PROCEDURE do_something (
n1 IN NUMBER,
n2 IN OUT NUMBER,
BEGIN
n2 := 20;
DBMS_OUTPUT.PUT_LINE(n1); -- prints 10
n3 := 30;
DBMS_OUTPUT.PUT_LINE(n1); -- prints 30
END;
BEGIN
do_something(n, n, n);
DBMS_OUTPUT.PUT_LINE(n); -- prints 20
END;
140. What is materialized view?
A materialized view is a database object that contains the results of a query. They are local copies
of data located remotely, or are used to create summary tables based on aggregations of a table's
data. Materialized views, which store data based on remote tables are also, know as snapshots.A
materialized view can query tables, views, and other materialized views. Collectively these are
called master tables (a replication term) or detail tables (a data warehouse term).
144. what happens when commit is given in executable section and an error occurs ?please tell me what
ha
Whenever the exception is raised ..all the transaction made before will be commited. If the
exception is not raised then all the transaction will be rolled back.
cursor is basically a pointer as it's like a address of virtual memory which is being used storage
related to sql query & is made free after the values from this memory is being used
146. What will happen to an anonymus block,if there is no statement inside the block?eg:-
declarebeginend
We cant have
declare
begin
end
we must have something between the begin and the end keywords
The triggers will be fired on the basis of TimeStamp of their creation in Data Dictionary. The
LOB datatypes can be used to store blocks of unstructured data like graphic images, video,
audio, etc
A strong REF CURSOR type definition specifies a return type, but a weak definition does not.
DECLARE
in a strong cursor structure is predetermined --so we cannot query having different structure
in weak cursor structure is not predetermined -- so we can query with any structure
Strong Ref cursor type is less Error prone, because oracle already knows what type you are going
154. Explain, Is it possible to have same name for package and the procedure in that package.
Yes, its possible to have same name for package and the procedure in that package.
159. Without closing the cursor, If you want to open it what will happen. If error, get what is the error
If you reopen a cursor without closing it first,PL/SQL raises the predefined exception
CURSOR_ALREADY_OPEN.
packge state.W
array is set of values of same datatype.. where as tables can store values of diff datatypes.. also
Disadvantages of Packages:
Disadvantages of Trigger:
172. how can we avoid duplicate rows. without using distinct command
Using Self join like :
This query will return the first row for each unique id in the table.
173. Why we use instead of trigger. what is the basic structure of the instead of trigger. Explain speci
Conceptually, INSTEAD OF triggers are very simple. You write code that the Oracle server will execute
when a program performs a DML operation on the view. Unlike a conventional BEFORE or AFTER
trigger, an INSTEAD OF trigger takes the place of, rather than supplements, Oracle's usual DML
behavior. (And in case you're wondering, you cannot use BEFORE/AFTER triggers on any type of view,
BEGIN
*/
:NEW.bytes);
DECLARE
BEGIN
LOOP
END LOOP;
END;
END IF;
END;
Once we've created this INSTEAD OF trigger, we can insert a record into this object view (and hence
This statement causes the INSTEAD OF trigger to fire, and as long as the primary key value (image_id
= 41265) does not already exist, the trigger will insert the data into the appropriate tables.
Similarly, we can write additional triggers that handle updates and deletes. These triggers use the
180. what is the difference between database trigger and application trigger?
Database triggers are backend triggeres and perform as any event occurs on databse level (ex.
Inset,update,Delete e.t.c) wheras application triggers are froentend triggers and perform as
any event taken on application level (Ex. Button Pressed, New Form Instance e.t.c)
185. Compare EXISTS and IN Usage with advantages and disadvantages.
Use Exists whenever possible. EXISTS only checks the existence of records
(True/False), and in the case of IN each and every records will be
*************