You are on page 1of 33

Oracle Interview Tips

1. When you alter a table to modify the datatype, if you want to decrease the column length, the new
length should be greater than or equal to the longest data present in the column.
2. dbms_out.put_line(); ma 2!! characters.

". Why #$%%s come last in ascending order sort, in &racle'
&racle treats #$%%s as the highest possible (alues.
)o a(oid #$%% (alues coming last , we can gi(e *#$%%+ ,-.+)* clause
+elect / from table order by column_name asc #$%%+ ,-.+)

)o a(oid #$%l (alues coming first in desc sort, we can use
+elect / from table order by column_name desc #$%%+ %0+)

1atatype of #$%% char (2), (archar (2)
3. #$%%+ don t wor4 well with indees.
Whene(er possible, a(oid the use of #$%%05%6 columns in 7oins, outer 7oins etc.

!. -n outer 7oins, what happens to the unmatched columns'
6g8 %eft outer 7oin on tables 0 and 5
i.e 0ll records from 0 and matching records from 5.
0.col1 , 5.col2 9: 0ll unmatched 5 column (alues will be #$%%.

;. )he table user_source contains source codes for
1. ,unction
2. <ac4age spec
". <ac4age body
3. <rocedure
!. )rigger

=. What are -nde organi>ed tables'
-n +tandard 5)ree inde contains only rowids
-&)(-nde &rgani>ed )ables) .ow data is physically stored along with the inde data.
?. @an we use when others before when Aeception: in the eception handler bloc4'
0ns 8 #o. we canBt
6g 8 when others then
dbms_output( 9 9 )
When no_data_found
dbms_output( 9 9 )
When others should always be the last.

C. @an we use only -nsert and a(oid $pdate in D6.E6 statement'
0ns8 #o.
5oth insert and update must be there.
-n update
1. We can update only non97oined columns.
2. <rimary Fey is not necessary.
". We can update only the table getting merged.(not the one used)
3. #o option to gi(e where clause for insert and update.

6g 8 Derge into emp e
$sing (select / from emp) em
&n (e.emp_no G em.emp_no) (#eed not be <F)
When matched then
$pdate set e.ename G em.ename
When not matched then
-nsert (emp_no) (alues (emp_no)
12. -f you gi(e ,or update with a cursor, you need to do a rollbac4 or commit to release the rows in the
procedure. 0nd .ollbac4 or commit should be gi(en outside the fetch loop.
11. 6g for @0+6 +tatement
+elect ename , (case shift
when *0* then *0_+H-,)*
when *5* then *5_+H-,)*
else *0#I_+H-,)*
end) as shift_name from emp_shift

12. &racle ,unction 9 #$%%-,
.eturns #$%% if both (alues are equal
+elect #$%%-,(col1, 1222 ) from table;
.eturns #$%% if col1G1222
1". &racle ,unction 9 #J%
@on(erts #$%% Jalue to a specific (alue.
#J%(@ol1,2) )his con(erts null (alues of column1 to 2.
13. &racle ,unction 9 #J%2
+elect #J%2(col1,1,2) from table
@on(erts col1 to 1 if #$%%
col1 to 2 if #&) #$%%
1!. &racle ,unction 9 @&0%6+@6
@ompares n items and returns the first #&) #$%% item
6g 8 select coalesce(col1,col2,col",col3,col!) from table.
+uppose col1 is #$%%, col2 is #$%%, col" is !, col3 is 22 and col! is #$%%.

)he statement returns ! ie the (alue of @ol" which is the first #&) #$%% item.
+elect coalesce (col1, col2, ", col3, col!) from table
)hen " is returned
1;. What is a +0J6<&-#) in &racle'
+a(e point is used to store intermediate state in transaction. -t allows user to undo part of
6g8 insert into 999 0
1elete from 999 5
$pdate 999 @
+a(epoint +0
$pdate 999 1
if not_proper_update then
.ollbac4 to +0;

#ote8 .ollbac4 to +0 doesnBt mean @ontrol goes to point +0.

-t means the transaction is rolled bac4 to the pre(ious state to which it is rolled bac4. #o matter
how many rollbac4s and sa(epoints, and 1D%s are in between &nly the STATE OF THE
TRANSACTION is rolled bac4 to the pre(ious state. @ontrol always go forward from the point where
the eception occurred.

1=. .601 &#%I ).0#+0@)-&#+ in &racle
,or ban4ing databases, to manage concurrent updates, inserts etc.
+6) ).0#+0@)-&# .601 &#%I;
+elect sum(amount) into K from feeaccount;
+elect sum (amount) into I from feeaccount;

1?. ,&. $<10)6 in &racle
+elect / from table for update;
,etch c1 into c";
6it when c1L#&) ,&$#1
$pdate batch
+et income G 1.1/income where current of c1;

1C. &racle 0$)&#&D&$+ ).0#+0@)-&#
@ommit or rollbac4 must for 0utonomous )ransaction.
<.0ED0 0$)&#&D&$+_).0#+0@)-&#;
-#+6.) -#)& M (alues(2,2);
-#+6.) -#)& I (alues(2,1);
+0J6<&-#) +01;
-#+6.) -#)& K (alues(1,2);
.&%%50@F )& +01;

#ote8 Dain transaction and autonomous transaction can ha(e sa(epoints with same name.
Oracle Triggers

Triggers are actions defined on tables.

1. Why are triggers required'
-f we want to perform certain actions whene(er an insertNupdateNdelete happens on a table, we could
achie(e this by using a trigger. .emember, only these " 1D%s 9 -nsertN$pdateNdelete could fire a
)runcate or drop or create or any other commands could not fire a trigger on a particular table.

2. 1ifferent types of @lassification for )riggers8
First type of classification
a. Row !evel Trigger
,or each row affected by the -nsertN$pdateN1elete operation, the trigger is fired and thus the action
associate with it.
1elete from emp where deptnoG"2; 99 deletes 12 records
For eg -f you want to log all the 6mployee -ds if they gets deleted, you could create an 0fter 1elete
.ow %e(el )rigger such that for each -1 getting deleted they could be inserted into an
0udit )able. +o, for the abo(e delete operation the trigger is fired 12 times.

b. State"ent !evel Trigger
)he trigger will be fired only once for the -nsertN$pdateN1elete operation happened on a table.
For eg
$pdate emp set salGsalO12!2 where deptnoG12;
)his update statement updates "2 records in a single update operation. 5ut if the )rigger on
table 6mp is statement le(el, the update action would fire the trigger only onceP
Second type of classification #efore and After triggers
#efore Trigger )he trigger gets fired before an -nsertN$pdateN1elete operation happens on the table
After Trigger )he trigger gets fired after an -nsertN$pdateN1elete operation happens on the table
5ased on the 2 types of classifications, we could ha(e 12 types of triggers.
/ 5efore -nsert row le(el
/ 0fter -nsert row le(el
/ 5efore 1elete row le(el
/ 0fter 1elete row le(el
/ 5efore $pdate row le(el
/ 0fter $pdate row le(el

/ 5efore -nsert +tatement %e(el
/ 0fter -nsert +tatement %e(el
/ 5efore 1elete +tatement %e(el
/ 0fter 1elete +tatement %e(el
/ 5efore $pdate +tatement %e(el
/ 0fter $pdate +tatement %e(el
Fre$%ently As&ed '%estions

1. What is a Dutating table error (D)6)'
&racle manages read consistent (iew of data. )he error occurs when a row9le(el trigger accesses the
same tables on which it is based while eecuting.

2. How to get rid of Dutating table error'
-n the .ow le(el trigger we cannot update, insert or select from the mutating table. +o we create a
pac4age with a collection type in it. )hen in the .ow le(el trigger store the (alues (to be used) into the
@ollection type. )hen add a +tatement le(el trigger to the same table which calls the <ac4age uses the
stored data to do the data manipulation.

Eg create pac4age pac41
arr J0..0I(122);

create or replace trigger row_trg1
before update on table1
for each row
pac41.arr(2)8G 8old.col1;

create or replace trigger stmt_trg1
before update on table1
(_col number;
(_col8G pac41.arr(2);
". Daimum )rigger si>e in &racle 8 "24 (but functions, procedures etc could be called inside)

3. @an we create trigger on (iews'
No. 5ut we can use -#+)601 &, )riggers
Eg create or replace trigger trg_logon
-nstead of update on (iew_(1
,or each row
Aprocessing: 99 can call a procedure or a function too.

!. @an we do commit or rollbac4 in a trigger'
E(ception -f the trigger is an 0$)&#&D&$+ ).0#+0@)-&# we can commit or rollbac4

;. When a table or (iew is dropped, what happens to the associated triggers'
)riggers associated to the dropped )ables, Jiews also gets )RO**E)

=. What is an -#+)601 &, )rigger in &racle'
Jiews cannot ha(e triggers. +o, when someone tries to update a (iew, you can re9direct the data to
the underlying table using an -#+)601 &, trigger.
Eg create or replace trigger ins_trigger
-#+)601 &, update on emp_(iew
,or each row
if 8new. +alA8old. +al then
update emp set salG8old. +al where empnoG8new.empno;
update emp set salG8new. +al where empnoG8new.empno;
end if;
/When -#+)601 &, trigger is written, e(en if the (iew is directly updateable, it updates %sing the
trigger only.
?. 1oes )runcate on a table fires a )rigger'
No. 0 )runcate table operation wonBt fire the trigger e(en if it is defined as a delete trigger. &nly a
delete operation could fire a trigger and when the )rigger is a 1elete trigger.
Oracle +iews , FA's
1. @an we define an inde on a (iew'
0n inde cannot be defined on a (iew. 5ecause (iew is (irtual table, which consists of a subset of
columns from one more tables. 0nd to be precise, (iew is 7ust a query sa(ed in the Detadata. We
cannot inde a query.
Restrictions i"posed on views
1. 0 (iew can be created only in the current database.
2. 0 (iew can be created only if there is a +6%6@) permission on its base table
". 0 )rigger or an -nde cannot be defined on a (iew.
3. 0 (iew cannot deri(e its data from temporary tables.
!. )he @.60)6 J-6W statement cannot be combined with other +Q% statements in a single batch.

2. How can we create a (iew on a non eisting table 9
$se the 4eyword force with the create command.
Eg create force (iew (222
as select / from emp111; 99 #ote 8 (iew name should not be eisting

". 6(en if default (alues are there, to use Rinsert into table val%esR option, once should pro(ide all
column names to be inserted.
Eg- table8 Jacation
(empid (archar2(=) primary 4ey,
ename (archar2(!2) not null,
annual_lea(e number(3) default 2,
casual_lea(e number(3) default 2,
%op number(3) default 2,
Iear number(3) chec4 (year between 222= and 222?),
status (archar2(1) default *#*)
.rong insert into (acation (alues(*2?==*,*Sames*,222=,*0*); 99 #ote8 0ll column names ae not gi(en
O%tp%t 6..&. at line 18 &.0922C3=8 not enough (alues

Correct insert into (acation (empid,ename,Iear,status) (alues(*2;=?"3*,*S&se Dathew*,222=,*0*);
3. How can you do multiple column updates using $pdate @ommand'
$pdate (acation set 0##$0%_%60J6G1?, @0+$0%_%60J6G=;
$pdate (acation set (0##$0%_%60J6, @0+$0%_%60J6) G (select 1?, = from dual)

!. @an you insert into, or update a (iew'
/es or No could be the answer. -t (aries on case to case. @ases whoBs below eplains, when and where
it is possible to insert into or update a (iew.
Note Jiew doesnBt contain any data. &nly the underlying tables gets inserted or updated.
Case0 Jiew is created from a single table and is not created .ead &nly.
Ies. )his 4ind of (iews could be updated. )he changes are effected in the underlying table.
Case1 Jiew is created from multiple tables using 7oin conditions
$pdateable -,, (only if both of the following conditions are satisfied)
a) )ables should ha(e proper <rimay 4ey foreign 4ey relationships AN)
b) 0ll columns used in the (iews should unambiguously point to the columns of the respecti(e tables
which is being updated through the (iew.
Case2 Jiew created with .601 &#%I option cannot be updated.
Case3 0ll other (iews which doesnBt satisfy @ase1 and @ase2 could not be updated.

;. @an you create a (iew on a (iew'
Ies. We can. 6(en (iew on combination of (iews is also possible.
Eg create (iew (2 as select / from (1
&racle <ac4ages, <rocedures, ,unctions
1. What is a <ac4age' What are the meritsNdemerits of pac4ages'
0 pac4age is nothing but a grouping together of %ogically related procedures, functions, (ariables
(global and local) etc. -t pro(ides many &&<s features, li4e information hiding, polymorphism etc. 0nd
the biggest ad(antage is, when any <rocedure or function is called from the pac4age, the whole
pac4age gets loaded into the memory and so it is (ery fast to call all related procedures and functions
from the same pac4age. 5ut again, it acts as a demerit when (ery few procedures or functions from the
pac4age are used, but still the whole pac4age resides in the memory until the called
proceduresNfunctions eit.
.egarding &&<s concepts, a <ac4age hides the information about a <rocedure or function to the
outside world. )hat means, a user can use the inbuilt proceduresNfunctions without 4nowing how it is
built in the pac4age. 0gain, a procedureNfunction could be written pri(ate, i.e they could not be
accessed from outside the pac4age but could be used by other proceduresNfunctions inside the same
pac4age. - shall eplain this later in this page.

So4 5erits
/ <ac4aged proceduresNfunctions could ehibit polymorphism.
/ @ould create <ri(ate (ariables, functions, procedures etc inside the pac4age; not accessible outside.
/ @ould share (ariables and pri(ate proceduresNfunctions between other proceduresNfunctions.
/ Whole pac4age is loaded into memory whene(er any procedureNfunction is called. 5enefit when
?29C2L of the proceduresNfunctions in the pac4age are used.
)he main demerit is again, the whole pac4age is loaded into memory whene(er any procedureNfunction
is called. -f only 22L of the proceduresNfunctions in the pac4age are used, memory consumption gets
high for minimal pac4age usage

2. <ac4age, <rocedure and ,unction +ynta8
0 pac4age has got 2 components 9 a +pec and a 5ody
Spec is nothing but is li4e a header which holds all <rocedureN,unction declarations and Elobal
(ariables, collections etc if used.
#ody body has the actual definition of the +tored proceduresN,unctions. 0ll 1ata manipulation is
done in the procedures and functions, which are defined in the body.

@.60)6 &. .6<%0@6 <0@F0E6 6K_<0@F_221 99@reate pac4age spec
<.&@61$.6 6K_<.&@_221 99declaring procedure 6K_<.&@_221
<_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2,
<_.6)_@&16 &$) #$D56.

,$#@)-&# 6K_,$#@_221 99declaring function 6K_,$#@_221
<_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2
.6)$.# #$D56.;

6#1 6K_<0@F_221;

@.60)6 &. .6<%0@6 <0@F0E6 5&1I 6K_<0@F_221
<.&@61$.6 6K_<.&@_221(<_#$D56. -# #$D56., <_@H0. -# J0.@H0.2,
<_.6)_@&16 &$) #$D56.)
99@&16 H6.699
996K@6<)-&# 5%&@F99
6#1 6K_<.&@_221;
,$#@)-&# 6K_,$#@_221(<_#$D56. -# #$D56., <_@H0. -# J0.@H0.2)
.6)$.# #$D56.
J_@&16 #$D56.;
99@&16 H6.699
.6)$.# J_@&16;
996K@6<)-&# 5%&@F99
6#1 6K_,$#@_221;
6#1 6K_<0@F_221;

". How to call the pac4aged proceduresNfunctions in another <rogram.
5efore showing how to call proceduresNfunctions in another <rogram, - hope that you 4now what an
anonymous bloc4 is. ,or those who dont 4now, an anonymous bloc4 is a piece of code that is similar to
a procedure but doesnt ha(e any name or cannot be stored in the database. ,or eg8 the anonymous
bloc4 below is used to call our procedure and function, but could not be stored in the 15 li4e the
<ac4age, procedure or function.
(_code number;
(_number number;
(_char (archar2(!2);

6K_<0@F_221. 6K_<.&@_221((_number,(_char,(_code); 99(_code is an &$) parameter
dbms_output.put_line((_code); 99displays data returned to the &$) param
(_code8G 6K_<0@F_221. 6K_,$#@_221((_number,(_char); 99function
returns the code

3. <ac4aged <rocedures (ersus #ormal <rocedures
0s - had mentioned earlier, pac4aged procedures can ehibit some of the &&<s beha(ior. &ne main
character is polymorphism. -n the same pac4age, we can ha(e different proceduresNfunctions with the
same name but different signatures. +ignature is nothing but the parameter list. 2 procedures with same
name could eist in the same pac4age with different number of parameters or different data types for
For eg
a. )iffers in n%"ber of para"eters
@.60)6 &. .6<%0@6 <0@F0E6 6K_<0@F_221 99showing only spec
<.&@61$.6 6K_<.&@_221
( <_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2,
<_.6)_@&16 &$) #$D56. );
<.&@61$.6 6K_<.&@_221
( <_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2 );

6#1 6K_<0@F_221;

b. )iffers in datatype of para"eters4 b%t sa"e n%"ber of para"eters
@.60)6 &. .6<%0@6 <0@F0E6 6K_<0@F_221 99showing only spec
<.&@61$.6 6K_<.&@_221
( <_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2,
<_.6)_@&16 &$) #$D56. );
<.&@61$.6 6K_<.&@_221
( <_@H0.1 -# J0.@H0.2,
<_@H0.2 -# J0.@H0.2,
<_.6)_@&16 &$) #$D56. );

6#1 6K_<0@F_221;

!. <rocedure Jersus ,unction
a. &nly function can .eturn a (alue (to be precise using the .eturn 4eyword)
b. <rocedures can use .eturn 4eyword but without any (alue being passed
c. ,unctions could be used in select statements, pro(ided they doesnBt do any data manipulation
inside and also s6o%ld not ha(e any &$), -# &$) parameters.
;. How to create <ri(ate global (ariables in a <ac4age'
@reate (ariables inside the body (but outside any procedure or function). 0ll of the
functionsNprocedures in the pac4age can use the (ariable, but could not be used outside

=. How to create <ri(ate <roceduresN,unctions'
Write the proceduresNfunctions only in the body. )hat means, do not declare the procedureNfunction
in the +pec.

?. @an a <ac4age +pec eist without a body'
Ies. 0d(antage being, we can create global (ariables or collections and put them in a pac4age +pec.
#o need to create any body since there are no proceduresNfunctions.
@.60)6 &. .6<%0@6 <0@F0E6 6K_<0@F_221
J_.6@&.1+ #$D56.;
6#1 6K_<0@F_221;

)his (ariable could be called outside in any code li4e this8
Oracle E(ceptions , Oracle )efined and 7ser defined
1. What are eceptions in &racle'
6ceptions are the ways in which &racle could handle runtime errors in a <%N+Q% bloc4. 6ceptions
are always useful to debug the code as well as ensure a smooth end for a <rogram without interrupting
the calling <rogramN5loc4.

2. What are the different types of &racle 6ceptions'
)he main classification is Oracle )efined and 7ser defined 6ceptions
Oracle defined
)here are many built in eceptions which we can use. Dost commonly used ones are8
a. #&_10)0_,&$#1
b. )&&_D0#I_.&W+_,&$#1
c. J0%$6_6..&.
d. M6.&_1-J-16
e. -#J0%-1_#$D56.
f. 1$<_J0%$6_&#_-#16K
g. @$.+&._0%.601I_&<6#
h. -#J0%-1_@$.+&.
7ser )efined
$ser defined eceptions are defined in many ways.
a. #ew user defined 6ceptions can be created using eisting &racle defined 6ceptions
b. 6ntirely new 6ceptions can be according to a userBs need.
6g8 .aise an eception if employee salary entered is less than 2.
)here are mainly " ways to use $ser 1efined 6ceptions
ec_user 6ception; 99declare eception
When others then
raise ec_user; 99eception raised
When ec_user 99handler for ec_user. 6ception handled
When others then 99handler for others
ec_user 6ception; 99declare eception
<.0ED0 6K@6<)-&#_-#-)(ec_user, 9Aoracle_error_code:); 99 &racle code with *9*sign
When ec_user 99handler for ec_user
99handled when error occurs with the specified &racle @ode
When others then
99handler for others
ec_user 6ception; 99declare eception
-f (Alogic:) then
.0-+6_0<<%-@0)-&#_6..&.(922221, ec_user); 99code greater than 922222
When ec_user then
99Handler for ec_user
99handled when error occurs with the +pecified &racle @ode
When others then
99handler for others

". What is 6ception propagation in &racle'
6ceptions which are not handled in a sub bloc4 gets propagated to the outer bloc4. When an eception
occurs, it terminates from the line where the eception occurs and the control goes to the calling
program or the net outer bloc4. -f not handled in the outer bloc4, it terminates that bloc4 and
propagates to the net outer bloc4 and so on. 0nd, if eception occurs in the outermost bloc4, then the
whole program gets terminated.

3. 0n inner bloc4 has got an eception with the same name as in the outer bloc4. )he eception doesnBt
ha(e any handler defined in the inner bloc4, but has got a handler defined in the outer bloc4. Will the
6ception get handled assuming that when others eception handler is not defined'
0 6ception ;
0 6ception; 996ception with same name declare in inner bloc4
if 1G1 then
raise 0;
6nd if;
6nd; 99#o handler for eception 0 in inner bloc4
When 0 then 99handler
)he eception 0 in the inner bloc4 W-%% get propagated to the outer bloc4 but W-%% #&) get handled
in the outer bloc4. &racle considers both 6ceptions to be etremely different, e(en if they ha(e the
same name.
Oracle C%rsors
0 cursor is a pointer to a memory location where the results of a Rselect statementR could be stored and
we could manipulate the information by fetching the records.
)wo types of classification 9 - and --
-. -mplicit and 6plicit
a. I"plicit
Dore fast and less coding effort.
Will ne(er raise -#J0%-1_@$.+&. error
@annot be opened outside the statement
.aises #&_10)0_,&$#1 and )&&_D0#I_.&W+ eceptions (eg8 select Astmt:)
-mplicit cursor returning more than one record' ,&. %&&< cursors.
b. E(plicit
2 networ4 round trips. +tore data first then retrie(e data. Dore programmatic control.
<rogrammer could open; fetch data, close, chec4 attributes etc.

-- +tatic and 1ynamic
a. Static #ormal cursor (implicit or eplicit)

b. )yna"ic Ref c%rsor
@ursor created only when it is opened.
@ould be declared once and defined many times in different procedures.
.ef @ursors can ha(e .ecordNs as return types. +o could be used for returning data to other
languages li4e Sa(a, @OO etc
II.b; Ref c%rsor 9 )wo types
Strong .ef cursor with a specified return type.
.ea& #o return type specified.
". C%rsor attrib%tes
L,&$#1 9 records fetched successfully
L#&),&$#1 9 no records fetched
L.&W@&$#) 9 #umber of records fetched
L-+&<6# 9 returns ).$6 if cursor is open

@ould be used for implicit and eplicit cursors.
+elect / from emp 99 also for delete operations
-f +Q%L,&$#1 then
(_count8G +Q%L.&W@&$#)
end if;

&pen c1; 99 cursor c1 is select Astmt:
fetch A:
eit when c1L#&),&$#1

Eg E(plicit c%rsor
@ursor cur1 is
+elect ename,empno,sal from emp
Where empno between C222 and 1222
0nd salA!2222
0nd deptnoG!2
&pen cur1;
fetch cur1 into (_ename,(_empno,(_sal;
6it when cur1L#&),&$#1;
999<do processing-
@lose cur1;
Oracle Se$%ence
What is a sequence'
0 sequence is nothing but a number generator in sequence as the name says. -t could be used for
generating unique 4eys alone and concatenating to the field (alues.

How to create a sequence'
@reate sequence seq21
+tart with 1
-ncrement by 1
Da(alue 122 Anoma(alue:
#ocycle Acycle:
@ache 22 Anocache:
+equence is initiali>ed when the user calls Se$

1. What will be the output if user tries to use +eq21.curr(al before +equence is initiali>ed'
6rror8 &.092?2228 +equence +6Q21.@$..J0% is not yet initiali>ed in this session.

2. What will be the output of when +equence is initiali>ed'
+tart (alue of the sequence. Here it is 1

". How to change sequence attributes'
0ll sequence attributes could be changed e(en after it is created and used.
0lter sequence seq21 increment by 1222
0lter sequence seq21 nocache
0lter sequence seq21 cycle
0lter sequence seq21 ma(alue 1222

5ateriali>ed +iews
1. What is a materiali>ed (iew'
0 materiali>ed (iew is a snapshot of data which could be refreshed at defined inter(als. ,rom the
name, it is unclear that a materiali>ed (iew can hold data, since (iews dont. Jiews are nothing but a
query stored in a 1atabase. Whene(er we do a select / from (iew, it runs the sa(ed query and fetches
+ometimes there would be a need for a huge query with many 7oin operations between more than
12922 tables containing millions of records and many where conditions. 6specially in a dataware9
housing en(ironment or for reporting purposes. -n such conditions, running the query each time
whene(er required, is not a feasible option. +o, there should be a technique to store the data such that
we should run the query only if there is a change in data in the underlying tables.
)here comes the usage of a materiali>ed (iew as they can store the data they ha(e queried

2. 1ifferent type of materiali>ed (iews'
a. <rimary Fey materiali>ed (iews
b. .&W-1 materiali>ed (iews
c. &b7ect materiali>ed (iews 99 @reated based on &b7ect types other than tables
d. @omple materiali>ed (iews 99 @omple queries li4e @onnect by prior, intersect etc

". How to create a Dateriali>ed (iew'
Eg 0 Dateriali>ed (iew which gets refreshed automatically e(ery day at 3 0D.
@.60)6 &. .6<%0@6 D0)6.-0%-M61 J-6W
)05%6+<0@6 Atb_name:
5$-%1 -DD61-0)6 99or A 16,,6.61:
.6,.6+H @&D<%6)6
W-)H .&W-1
+)0.) W-)H +I+10)6
#6K) $<10)6 +I+10)6O3N23
+6%6@) A@&%$D#+: ,.&D A)1,)2,)": WH6.6 A@&#1-)-&#+, S&-#+:

)05%6+<0@6 9 in which tablespace DJ is to be created
%&EE-#EN#&%&EE-#E 9 %ets you specify whether the creation log of the DJ would be written
to the .edo log file (%&EE-#E) or not (#&%&EE-#E)
@0@H6N#&@0@H6 9 ,or data that will be accessed frequently, @0@H6 specifies those
bloc4s retrie(ed are placed in the most recently used place of %.$
list in the buffer cache when full table scan is done.
16,6..61 9 16,,6.61 is another option instead of the 5$-%1 -DD61-0)6
one. When this is gi(en DJ will be populated only by net
.6,.6+H &peration. ,irst 16,6..61 .6,.6+H must always be
a complete refresh
-DD61-0)6 9 )his as4s the DJ to populate the data as soon as it is created.

Ado: ,0+) 9 -ncremental refresh method, which performs according to the changes that ha(e
occurred in the master tables. #ote8 DJ %og is a must for using this method to
store the changes.
Ado: ,&.@6 9 )his is the default if none of these options are specified. )his indicates that
whene(er a refresh occurs, &racle will perform a fast refresh, if one is possible
else a complete refresh.
Ado: &# @&DD-) 9 When this option is specified, &racle performs a ,0+) .6,.6+H
whene(er the 15 commits a transaction on the Daster )ableNs
Ado: &# 16D0#1 9 .efresh according to user need. $se the 15D+_DJ-6W pac4age

W-)H .&W-1 9 )his option is used if the underlying tables used doesnBt ha(e any
primary 4eyNs.
W-)H <.-D0.I F6I 9 )his option is used if the underlying tables used ha(e primary 4eyNs
+)0.) W-)H +I+10)6 9 )his option required only if user wants to get the DJ
#6K) $<10)6 +I+10)6OAinter(al: refreshed automatically at specified time inter(als
,&. $<10)6 9 @ould be added if the DJ needs to be updated.
Oracle *l?S'! , NOCO*/ *ara"eter
)he <%N+Q% has two different methods for passing parameter (alues between stored procedures and
0. *ass by val%e
0ctual (alue is being copied to another memory location for the calling procedureNfunction to use
i.e it copies the actual (alue of the parameter into the formal parameter. +o, both called and calling
procedures has got 2 different memory locations to store the (alue
1. *ass by reference
&nly the memory location (address) is passed so that the data is not copied. )he calling procedure and
the called procedure, both uses the same (alue stored in a single memory location. +o the actual and
the formal parameters refer to the same memory location that holds the (alue.

0s we 4now, there are three different type of parameters in <%N+Q%8
We specify any one of the below types, along with the parameters so classify them as8
-# 9 <arameters passed to the procedureNfunction
&$) 9 <arameters that store the (alues returned (eplicitly) from the procedureNfunction
-# &$) 9 @an pass (alues to the procedure and store the returned (alues
0nd by default, &$) and -# &$) parameters are passed by (alue whereas the -# parameters are
always passed by reference. -# parameters are designed in such a way to reduce memory consumption
and at the same time, the (alues won t get o(erwritten since -# doesn t allow gi(e write access to the
memory location.
0nd for &$) and -# &$), when the (alues are modified by either the called procedureNfunction or the
calling procedureNfunction, only their local copies get affected and not the original ones.
E(planation of NOCO*/ para"eter
When you use a @ollection (.ecords, J0..0I etc ha(ing records of data) as a .eturn type (&$) or
-# &$) parameter) as we 4now, it will be passed by (alue only. )hat means the entire data will be
copied to the formal parameter location, which leads to lot of @<$ and memory consumption.
Here comes the usage of #&@&<I parameter. <ro(ide #&@&<I after the &$)N-# &$) parameter,
which instructs the <%N+Q% 6ngine to a(oid using the pass by (alue method. +o, the 6ngine uses pass
by reference instead. )his helps reducing a lot of @<$ usage as well as memory consumption.
Eg Sust an eample how to put the #&@&<I parameter.
<.&@61$.6 <.@_#&@&<I_6K0D<%6
( <_6D<#& -# #$D56.,
<_6#0D6 -# J0.@H0.2(!2),
<_+0% &$) #&@&<I .6@&.1_+0% 99<%N+Q% .ecord
.6@_+0% .6@&.1_+0%;
#ow if you call the <rocedure <.@_#&@&<I_6K0D<%6, the parameter <_+0% would only use
<ass by reference method.
Howe(er, you need to be etremely careful while using this method in coding for high priority data
transactions. When you pass parameters to a procedure by reference, any change that happens on the
passed <arameters gets updated in the same memory location as the 0ctual parameter. +o when an
eception occurs in a procedureNfunction, these changes are not Rolled bac& . )o be precise, the
<%N+Q% engine cannot rollbac4 these parameter changes. +o, if the actual (alues get changed, then it
may result in incorrect res%lts.
)hus, to conclude, it is up to a 1e(eloper to ta4e a trade9off between using or not using the
#&@&<I parameter. #&@&<I could pro(ide better performance by reducing Demory and @<$ cost,
but at the same time, could result in incorrect results too.
5oth +Q% )race and )F<.&, help to find the statistics of an +Q% statement which could be used for
query optimi>ation.
Start Oracle S'!TRACE
-n &racle, to start an +Q%).0@6 for the current session, eecute8
Stop Oracle S'!TRACE
-n &racle, to stop +Q% tracing for the current session, eecute8
A!TER SESSION SET s$l:trace A falseB
Oracle S'!TRACE provides generates t6e following statistics for eac6 S'! state"ent
@ount #umber of times &@- procedure was eecuted
@<$ @<$ time in seconds eecuting
6lapsed 6lapsed time in seconds eecuting
1is4 #umber of physical reads of buffers from dis4
Query #umber of buffers gotten for consistent read
@urrent #umber of buffers gotten in current mode (usually for update)
.ows #umber of rows processed by the fetch or eecute call
Disses in library cache during parse
<arsing user id
&ptimi>er goal
When &racle +Q%).0@6 facility is enabled, all the statistics for all +Q% statements eecuted after that
are placed into trace files. )hese trace files are not in readable format. Here comes the usage of
)F<.&,. )F<.&, is used for formatting the trace files to produce a more readable format. -t stores
the following statistics of a Query8
.esources used by the +Q% statement.
#o. of times that the statement was called
#o of records processed
)his utility is also used for monitoring and tuning applications eecuting against the &racle ser(er.

)F<.&, tracefile outputfile UeplainGV UtableGV UprintGV UinsertGV UsysGV UsortGV

)able G schema.tablename
6plain G userNpassword to issue 6K<%0-# <%0#
<rint G -nteger %ist only the first *integer* +Q% statements.
0ggregate G yesNno
-nsert G filename %ist +Q% statements and data inside -#+6.) statements.
+ys G no )F<.&, does not list +Q% statements run as user +I+.
.ecord G filename .ecord non9recursi(e statements found in the trace file.
Waits G yesNno .ecord summary for any wait e(ents found in the trace file.
+ort G option +et of >ero or more of the following sort options8

Sort options are listed as follows

<.+@#) #o. of times parsed.
<.+@<$ @<$ parsing time
<.+6%0 6lapsed time parsing
<.+1+F #umber of dis4 reads during parse.
<.+Q.I #umber of consistent mode bloc4 reads during parse.
<.+@$ #umber of current mode bloc4 reads during parse.
<.+D-+ #umber of library cache misses during parse.
6K6@#) #umber of eecutes.
6K6@<$ @<$ time spent eecuting.
6K66%0 6lapsed time spent eecuting.
6K61+F #umber of physical reads from dis4 during eecute.
6K61+F #umber of physical reads from dis4 during eecute.
6K6Q.I #umber of consistent mode bloc4 reads during eecute.
6K6@$ #umber of current mode bloc4 reads during eecute.
6K6.&W #umber of rows processed during eecute.
6K6D-+ #umber of library cache misses during eecutes
,@H@#) #umber of fetches
,@H@<$ @<$ time spent fetching.
,@H6%0 6lapsed time spent fetching.
,@H1+F #umber of physical reads from dis4 during fetch.
,@HQ.I #umber of consistent mode bloc4 reads during fetch.
,@H@$ #umber of current mode bloc4 reads during fetch.
,@H.&W #umber of rows fetched.

Eg T@*ROF trace_output.trc insertGt4prof.sql recordGrecord.sql
Sa"ple o%tp%t

+elect / from emp where empno GC""3

call count cpu elapsed dis4 query current rows
999999 999999 99999999 9999999999 9999999999 9999999999 9999999999 9999999999 9999999999 999999999999
<arse 22 2.22 2.2" 2 2 2 2
6ecute 22 2.22 2.2= 2 2 2 2
,etch 32 2.!3 2.=! 32 1"1?3 2 12
9999999 999999 99999999 9999999999 9999999999 9999999999 9999999999 9999999999 9999999999 9999999999999
total ?2 2.!3 2.?! 32 1"1?3 2 12
Disses in library cache during parse8 2
&ptimi>er goal8 @H&&+6
<arsing user id8 122C2

.ows .ow +ource &peration
9999999 999999999999999999999999999999999999999999999999999
1 )05%6 0@@6++ ,$%% 6D<%&I66


$sing @&##6@) 5I <.-&. along with a select statement, we could retrie(e data in a hierarchical
-f we ha(e to query the employees reporting to a Danager Sames, directly, we do

+6%6@) 6D<#0D6, 6D<_-1, D0#0E6.
,.&D 6D<%&I66
WH6.6 D0#0E6.G Sames

6D<#0D6 6D<_-1 D0#0E6.
5ob "2!= Sames
+tacy CC;? Sames
.ichy ";?C Sames
.ichard 3223 Sames
Sones 113= Sames

#%t 6ow to find all e"ployees w6o report to t6e 5anager Ca"es4 directly and indirectlyD
We could use the @&##6@) 5I <.-&. facility in &racle.

)hus goes the query8

+6%6@) 6D<#0D6, D0#0E6., %6J6%
,.&D 6D<%&I66
+)0.) W-)H D0#0E6.G Sames
@&##6@) 5I <.-&. 6D<#0D6 G D0#0E6.

6D<#0D6 D0#0E6. %6J6%
Sames Dichael 1
5ob Sames 2
+tacy Sames 2
.ic4y Sames 2
.ichard Sames 2
Sones Sames 2
+tan Sones "
Dathew .ichard "
<erry +tacy "

+)0.) W-)H +pecifies the root of the hierarchy, i.e. where to start from.
Here, D0#0E6.G Sames gi(es the starting point for the hierarchical query.
@&##6@) 5I <.-&. eplains the relationship between the parent and the child.

-t connects to the net le(el using 6D<#0D6 G D0#0E6.. i.e. it connects to the net le(el
6mployee, to whom 6D<#0D6 is D0#0E6. to. )hus it goes down the le(els recursi(ely.
<.-&. )his is used to achie(e the recursi(e condition.
Now4 w6at if yo% want to find all )irect and Indirect "anagers of Ca"esD
We 7ust need to re(erse the direction of the query. 0nd it s simple.
Sust change the sides of 6D<#0D6 and D0#0E6.. )hat s it.
+6%6@) 6D<#0D6, D0#0E6., %6J6%
,.&D 6D<%&I66
+)0.) W-)H D0#0E6.G Sames
@&##6@) 5I <.-&. D0#0E6.G 6D<#0D6

6D<#0D6 D0#0E6. %6J6%
Sames 5astin 1
+tephen Sohn 3
Sohn Eates !
Di4e +tephen "
5astin Di4e 2
Eates ;
#ote8 Here the %e(el starts from Sames, since he is the root. )his %e(el only indicates the relati(e
position of others to the .oot. )his has nothing to do with the %e(el of a Danager or an employee.
*!?S'! Table and Nested Table
0s you 4now, a datatype is used to classify the data to be stored as number, (archar, boolean etc. 5ut a
(ariable declared using a dataype can hold only a single data (alue at a time, i.e a single memory

What if we need to store multiple rows of data in a single (ariable' )here comes the use of collections
in &racle. 0 (ariable declared as a collection could store an array of data of the same T/*E or
RO.T/*E. )his is beneficial when we need to pass multiple rows of data between <rocedures or
need to return multiple records from functions especially to other languages li4e Sa(a, @ etc.

)hese are the main classifications8
1. <%N+Q% )05%6 (inde9by tables) or #6+)61 )05%6
2. J0..0I
". .6@&.1
3. &5S6@)

Here - am discussing <%N+Q% )05%6 (inde9by tables) and #6+)61 )05%6 in detail

0. *!?S'! TA#!E Einde(,by tables; and NESTE) TA#!E
)hese are single9column tables and could be considered as an 0rray of data but which is unbounded; i.e
we cannot set a limit on number of rows li4e an array and that s sometimes an added ad(antage.
5oth <%N+Q% )05%6 and #6+)61 )05%6 has got the same structure and all, but the main difference
is, nested tables could be stored in a database column whereas *!?S'! tables could not be. )o eplain
further, Nested table 1ataypes can be created standalone they could be used for columns in normal
database )ables.
a.0 )elcare and %se in *!?S'! code

T/*E NTab:!ist0 is TA#!E OF T/*E INTE9ERB

@.60)6 &. .6<%0@6 <.&@61$.6 <.@_#)
)I<6 #)ab_%ist1 is )05%6 &, )I<6 -#)6E6.; 99create a @ollection type )I<6
99 #)ab_%ist1
)05 #)ab_%ist1; 99create a (ariable of #)ab_%ist1 )ype

99Acode here:

a.1 )eclare O%tside *!?S'!

CREATE T/*E NTab:!ist1 AS TA#!E OF N75#ERB 99 in +Q% <rompt
0nd use inside <%N+Q%8

@.60)6 &. .6<%0@6 <.&@61$.6 <.@_#)
TA# NTab:!ist0B 99 Sust create a (ariable of #)ab_%ist1 )ype since
99#)ab_%ist1 @ollection type already eists
99Acode here:

a.2 )eclare and %se o%tside *!?S'! code E7sed as Col%"n )atatypes in Tables;


@.60)6 )05%6 #+_)6+)
F6I #$D56.;
#0D6 J0.@H0.2(!2);
011.6++ #)ab_%ist
#6+)61 )05%6 J0." +)&.6 0+ %ist_)ab;

I. Inserting data into a Nested Table in a col%"n
)he address of a customer goes into the single column #)ab_%ist. 0s - said earlier, here comes the
ad(antage of an unbounded array. )he #ested table in the column pro(ides the fleibility of inserting
(arying number of address lines into the column. )he column 011.6++ could ha(e any number of
records in a single cell.
-#+6.) -#)& #+_)6+)
J0%$6+(1221,*%ynn +aunders*,
#)ab_%ist ( 122= , #orth 0(enue , .egent +treet , #t Jalley , 5erligton =3?"C )
II. Retrieving data
Eet address of customer with customer idG1221
#)05 #)05_%-+);
+6%6@) #)05_%-+) -#)& #)05 ,.&D #+_)6+)
WH6.6 -1 G 1221;
III. 7pdation
+uppose the customer with idG1221 needs to change his address. )hen
#6W_#)05 #)05_%-+)8G
#)05_%-+) ( ?C2 , +&$)H @-.@%6 , D0%%6I +).66) , ?C"CC );
$<10)6 16<)
+6) #)05_%-+) G #6W_#)05 WH6.6 -1G1221;

b. *!?S'! TA#!E
T6e difference is *!?S'! table s6o%ld always be inde(ed any of t6e below types.

5-#0.I_-#)6E6., 5&&%60#, %&#E, %&#E .0W, #0)$.0%, #0)$.0%#, <%+_-#)6E6.,
<&+-)-J6, <&+-)-J6#, +-E#)I<6, and +).-#E.

T/*E tab is TA#!E OF T/*E INTE9ER IN)E8 #/ #INAR/:INTE9ER
0lso, we can use the L)I<6 to ma4e use of the dynamic datatype functionality.
For eg
$sage is similar to that of #ested )able.
So"e ot6er &ey differences between *!?S'! and Nested Tables
)o etend a #ested table, you need to use a built9in procedure 6K)6#1, but to etend a <%N+Q% table,
you 7ust increment the subscripts.
)he (alue of an uninitiali>ed #ested table is #$%%, but an uninitiali>ed <%N+Q% table is empty. +o,
you can compare nested tables using -+ #$%% operator.
<%N+Q% tables are initially sparse. )hey can store reference data using a numeric primary 4ey as the
<%N+Q% supports implicit (automatic) datatype con(ersion between 0rrays and <%N+Q% tables.

9lobal Te"porary Tables
Elobal )emporary tables are session dependant tables which could be used as temporary storage for
calculations, sorting etc. What - mean by +ession dependant is, the data being stored in the Elobal
)emporary table is not written into the database or stored anywhere. &nce the session ends (in which
the Elobal )emporary table is used), the data also (anishes.

Howe(er the structure would still be a(ailable e(en after the +ession is logged out. 0lso, the structure
is a(ailable to other sessions e(en when one session is using it, but not the data. i.e multiple sessions
could use the same Elobal )emporary table without interfering the data. 6ach session could
insertNupdateNdelete their own data into the same Elobal )emporary table as if the table is a(ailable to
only that session. 0ny data inserted in one session is not a(ailable to another.

#ow, why do we need Elobal )emporary tables' Well, imagine a requirement where you need to fetch
some data from the database, do some 4ind of calculations, aggregations and pro(ide the .esult +et
(many records) to a ,ront 6nd. 0gain, in the ,ront 6nd, you need to fetch the .esult set many times,
for some purpose. )hen you could ma4e use of the Elobal )emporary table. $ntil the user gets
disconnected from that 1atabase session, the data is a(ailable for him in the memory.

How to Create 9lobal Te"porary Tables E9TTs;D
$sually, when we does a commit after insertingNupdatingNdeleting a table, the data gets written into the
1atabase. 5ut for E))s, as - said, it ne(er gets written to the database. )hen what happens if we issue
a commit after doing some insertNupdateNdelete on a E))'

Well, that depends on what you ha(e instructed the Elobal )emporary table to do while a commit is
begin issued. 0nd depending on that there are 2 different methods of creating a Elobal )emporary


@.60)6 E%&50% )6D<&.0.I )05%6 E))_6K
( Jar_int1 #$D56.,
Jar_char2 J0.@H0.2
) &# @&DD-) 16%6)6 .&W+;

)his is 7ust opposite of what happens to regular tables. -f a Elobal )emporary table is created with ON
CO55IT )E!ETE RO.S option, it remo(es all data when a commit is issued.
#ow you might thin4 why somebody needs such a table which remo(es all data when a commit
happens. Well, sometimes you need a temporary table to do some 4ind of calculation on "93 columns,
some 4ind of summation, then aggregation etc, record by record.

0ll these results, could be stored in the )emporary table column. 0nd you need to fetch only once to
get the whole data and store in some other .eporting )able ()arget). +o, after the calculation, you donBt
need the data in the )emporary table to be preser(ed anywhere, but you need the data in the .eporting
table. )hen, we ma4e use of ON CO55IT )E!ETE RO.S Elobal )emporary table, such that the
commit writes the 1ata for .eporting table into the 15 and the data in Elobal )emporary table is


@.60)6 E%&50% )6D<&.0.I )05%6 E))_6K
( Jar_int1 #$D56.,
Jar_char2 J0.@H0.2
) &# @&DD-) <.6+6.J6 .&W+;

ON CO55IT *RESER+E RO.S Elobal )emporary tables do not remo(e the data once a commit
is issued. -t 4eeps the data until the end of the session. .emember, preser(e rows doesn t mean, the data
is stored anywhere. )he data is remo(ed once the +ession ends.


1. @an we do insertNupdateNdelete on a Elobal )emporary table'
Ies we can do insertNupdateNdelete on a Elobal )emporary table as to a normal )able.

2. What happens if we ).$#@0)6 a Elobal )emporary table'
)he data is remo(ed only from that specific session where the ).$#@0)6 is issued. -t wont affect the
data in the same Elobal )emporary table in other sessions.

". @an we drop a Elobal )emporary table using the 1rop command.
Ies, we can. @reate and 1rop commands wor4 as usual as to a normal )able

3. What happens to the data in a Elobal )emporary table if the session ends abnormally'
Well, as - said earlier, no matter if the session ends normally or abnormally, the data will ne(er be
a(ailable once the session ends.

!. @an we ha(e all other features of a normal table on a Elobal )emporary table.
Ies, we can ha(e most of the features as that of a normal table on a Elobal )emporary table. We could
create indees, )riggers, Jiews etc.


TA#!E Creation

@.60)6 )05%6 6D<
6D<#& #$D56.,
6#0D6 J0.@H0.2(12 5I)6),
S&5 J0.@H0.2(C 5I)6),
DE. #$D56.(3),
H-.610)6 10)6,
+0% #$D56.,
@&DD #$D56.(=,2),
16<)#& #$D56.

C!7STER Creation
0. Create Cl%ster first
@.60)6 @%$+)6. @%+_16<) (16<)#& #$D56.)
1. Create inde( on it E"andatory;
@.60)6 -#16K @%+_16<)_-1K &# @%$+)6. @%+_16<)

2. T6en Create table in t6e cl%ster

@.60)6 )05%6 6D<
6D<#& #$D56.,
6#0D6 J0.@H0.2(12 5I)6),
S&5 J0.@H0.2(C 5I)6),
DE. #$D56.(3),
H-.610)6 10)6,
+0% #$D56.,
@&DD #$D56.(=,2),
16<)#& #$D56.
@%$+)6. @%+_16<)(16<)#&)

@.60)6 )05%6 16<)
16<)#& #$D56.,
1#0D6 J0.@H0.2(13 5I)6),
%&@ J0.@H0.2(1" 5I)6)
@%$+)6. @%+_16<)(16<)#&)

IN)E8 Creation

@.60)6 -#16K -1K &# )05%6_#0D6 (<F_F6I)

CO5*OSITE IN)E8 Creation

@.60)6 -#16K -1K_#0D6 &# 6D< (6D<#&, 16<)#&, DE.) U @&D<$)6
+)0)-+)-@+ V;

F7NCTION #ASE) IN)E8 Creation
@.60)6 -#16K -1K_#0D6 &# #J%(@&%$D#1,2);
99-nde 5ased &n &racle ,unction #(l

+IE. Creation

@.60)6 J-6W J1_6D<
+6%6@) 6D<#&, 6#0D6, +0%, DE.
,.&D 6D<;

@.60)6 J-6W J1_6D<
+6%6@) 6D<#&, 6#0D6, +0%, DE.
,.&D 6D<
WH6.6 16<)#&
+6%6@) 16<)#&
,.&D 16<)
WH6.6 %&@0)-&#G #6W S6.+6I

TRI99ER Creation


@.60)6 &. .6<%0@6 ).-EE6. 6D<_).-EE
56,&.6 -#+6.) &. $<10)6 &. 16%6)6
$<10)6 0$1-)_)05%6
+6) D0#-<$%0)-&#_@&$#)6.G<FE_@&$#)6..@&$#)O1;

RO. !E+E!

@.60)6 &. .6<%0@6 ).-EE6. 6D<_).-EE
56,&.6 -#+6.) &. $<10)6 &. 16%6)6
,&. 60@H .&W
-#+6.) -#)& 0$1-)_)05%6 J0%$6+(8&%1.6D<#&,8#6W.+0%);

S/NON/5 Creation

@.60)6 +I#&#ID +I#_6D< ,&. 6D<;
99@ould 5e $sed 5y )he $ser Who @reates -t

@.60)6 <$5%-@ +I#&#ID +I#_6D< ,&. 6D<;
99@ould 5e $sed 5y 0ll $sers

)IRECTOR/ Creation

@.60)6 &. .6<%0@6 1-.6@)&.I 1-._)6D< 0+ @8N)6D<N1-.N ;


CREATE OR RE*!ACE *AC@A9E E8:*AC@:==0 99@reate <ac4age +pec
<.&@61$.6 6K_<.&@_221 991eclaring <rocedure 6K_<.&@_221
<_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2,
<_.6)_@&16 &$) #$D56.

,$#@)-&# 6K_,$#@_221 991eclaring ,unction 6_,unc_221
<_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2
.6)$.# #$D56.;

6#1 6K_<0@F_221;

CREATE OR RE*!ACE *AC@A9E #O)/ E8:*AC@:==0
<.&@61$.6 6K_<.&@_221
<_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2,
<_.6)_@&16 &$) #$D56.
,,-Code Here,,-

,,-E(ception #loc&,,-

6#1 6K_<.&@_221;

,$#@)-&# 6K_,$#@_221
<_#$D56. -# #$D56.,
<_@H0. -# J0.@H0.2
.6)$.# #$D56.

J_@&16 #$D56.;


,,code 6ere,,

.6)$.# J_@&16;


,,E(ception #loc&,,

6#1 6K_,$#@_221;

6#1 6K_<0@F_221;

T/*E Creation

)I<6 #)05_%-+)1 -+ )05%6 &, )I<6 -#)6E6.;

Oracle Coin Operations
0 Soin is the process of combining data from two or more tables. )he 15D+ ta4es all combinations of
rows from the gi(en tables.
Cross Coin
Soin without filter conditions.
0 @ross Soin is the @artesian product or the result of all possible combinations of the rows from each of
the tables in(ol(ed in the 7oin operation.
)his occurs when, no specific Soin conditions (filters) are specified. ,or eg8 there are " tables 0,5 and
@ with 12,22 and "2 number of rows respecti(ely.
+o a @artesian production would happen in the below scenario,

Select A.col04 #.col14 C.col2 fro" A4 #4 C 99#o where condition
Which returns 1222"2G;222 records are result.

)hus the number of rows in a @artesian product of two tables is equal to the number of rows in the first
table times the number of rows in the second table.
#e(er use this 4ind of 7oins unless una(ailable as this ta4es huge amount of memory to sort and store

Nat%ral Coin EANSI Coins;
)hese are 0#+- Soins which are used for portability. Iou can use this in almost all +tandard 1atabases
li4e &racle, Dicrosoft +Q% +er(er etc.

+6%6@) 1#0D6, 6#0D6, DE.
,.&D 16<0.)D6#)+
NAT7RA! COIN 6D<%&I66+;
<+8 5oth tables should ha(e primary 4ey9referential 4ey relationship.

Self Coin
+ometimes there are scenarios where we might need to do Soin operations within the same table. +uch
7oins which refers to the same, single table are 4nown as a Self Coins.

,or 6g8 -f you need to get all employees and their managers, then you could do a self 7oin.

+6%6@) 61.6#0D6WW* reports to *WW62.6#0D6
,.&D 6D< 61, 6D< 62
WH6.6 61.DE. G 62.6D<#&;
<+8 )his is 7ust to show an eample for +elf Soin. )he results may not be accurate.

Inner Coin or Si"ple Coin or E$%i Coin
-nner 7oins returns only the rows from the cross product that meets the 7oin conditionNs.

+6%6@) 6#0D6, S&5, 16<).16<)#&, 1#0D6
,.&D 6D<, 16<)
WH6.6 6D<.16<)#& G 16<).16<)#&;

.eturns data only from those records which matches the condition
6D<.16<)#& G 16<).16<)#&, from both tables.

O%ter Coin
)hey are of 2 types8
a) %eft &uter Soin
b) .ight &uter Soin

+uppose there are 2 tables 0 and 5.

!eft O%ter Coin
.eturns all records from table 0 and only those matching with the 7oin operation from )able 5
For eg
+6%6@) / ,.&D 6D<, 16<)
WH6.6 6D<.16<)#& G 16<).16<)#& (O);
.eturns all records from 6D< and only those records from 16<) which matches the condition
6D<.16<)#& G 16<).16<)#&

Rig6t O%ter Coin
.eturns all records from table 5 and only those matching with the 7oin operation from )able 0 (7ust the
re(erse of left outer 7oin)
For eg
+6%6@) / ,.&D 6D<, 16<)
WH6.6 6D<.16<)#& (O) G 16<).16<)#& ;
.eturns all records from 16<) and only those records from 6D< which matches the condition
6D<.16<)#& G 16<).16<)#&


What is an -nde'
)o eplain in plain 6nglish, an -nde could be considered as a unique boo4mar4 to a database cell (of
those columns which are indeed).
,or each cell in an indeed column, there will be a unique identifier, which is 4nown as the inde.
-ndees are stored in the Inde( seg"ents in &racle database (unless it is an -nde &rgani>ed table
(-&)) which we are not discussing here). -n &racle Ci, -ndees contain an entry for each cell (alue that
appears in the indeed column(s) of the table or cluster.
+o, when an inde is used in a query, &racle 6ngine first searches through the indees and reaches the
inde of the particular cell (alue, it is searching for. )hen it goes to the table and fetches only that
particular (alue. )hus we could a(oid ,ull table scans. )hus an inde is a performance9tuning method
which allows faster retrie(al of records.
&racle supports different types of indees8
#,Tree inde(es ENor"al;
#it"ap inde(es
*artitioned inde(es
F%nction,based inde(es
)o"ain inde(es
Here we are going to discuss about 59)ree and 5itmap -ndees.
I. Oracle , #inary Tree Inde(
0s the name suggests it ma4es use of the 59)ree parsing method to find the (alue being searched for.
When it gets a (alue to be searched, it gets the nearest possible inde (alue. )hen it goes to the left
node if the (alue it lesser or to the right if the (alue is higher. -t goes on doing this until it reaches the
leaf node which contains the (alue it is searching for.

How to Create an Inde(D
@.60)6 -#16K -1K_#0D6
&# )05%6_#0D6 (@ol_nam1,@ol_nam2, )
@&D<$)6 +)0)-+)-@+ ; 99optional

// #ote8 by default, &racle creates 59tree indees
How to Rena"e an Inde(D
0%)6. -#16K -1K_#0D6
.6#0D6 )& #6W_-1K_#0D6;
How to Collect Statistics on an Inde(
0%)6. -#16K -1K_#0D6
@&D<$)6 +)0)-+)-@+;

How to )rop an Inde(
1.&< -#16K -1K_#0D6;
II. Oracle , #it"ap Inde(
&racle 5itmap -ndees are different from +tandard 59)ree -ndees in the way they store the
information about the indees. 5itmap -ndees stores the information about the (alue in bits; with 2s
and 1s; thus called 5itmaps. +omething li4e this8

5itmap -nde creates a two9dimensional array with one column for e(ery row in the table being
indeed. -f the (alue being indeed is found in the row, it will specify a 1 and if not found then a 2 .
+o while searching, &racle ta4es only the information from those rows which shows a 1 in the 5itmap
-nde. )hat means, the records which are pointed by the 1 s in the -nde, ha(e got the
searchedNindeed (alue.

0nd from a performance point of (iew, during the data retrie(al time, &racle decompresses the bitmap
into the .0D data buffers so that it can rapidly scan for matching (alues. )hese matching (alues are
the gi(en to the &racle engine in the form of a .&W-1 list, and .&W-1s as we 4now are unique
identifiers to recordsNrows.

'. How to Create a #it"ap Inde(D

@.60)6 5-)D0< -#16K -1K_#0D6
&# )05%6_#0D6 (@ol_nam1,@ol_nam2, )
@&D<$)6 +)0)-+)-@+ ;
59)ree Jersus 9 5itmap -ndees

)hese are some differences between 59)ree and 5itmap -ndees in +tructure and performance and their
0. )5! Operations
-f you ha(e too much 1D% operations (insertNupdateNdelete) on a table on which the columns are
indeed, it is better to use 59)ree indees.
For eg if you wor4 on a batch processing en(ironment, then it is ob(ious that you would ha(e frequent
1D% operations on the tables in(ol(ed.
$pdating bitmapped indees consumes lot of resources. +o, it is better to use 5itmap -ndees on
columns of )ables which are updatedNinsertedNdeleted less frequently .
1. *erfor"ance
5itmap -ndees ha(e highly compressed structure, ma4ing them fast to read and their structure ma4es
it possible for the system to combine multiple indees together for fast access to the underlying tableNs.
2. Str%ct%re
@ompressed structure in 5itmap -ndees ma4es it faster to read from dis4; but utili>es more @<$ to
decompress the information.
$ncompressed structure in 59)ree in(ol(es a lesser @<$ load compared to 5itmap but it requires more
bandwidth to read since it is uncompressed data.
3. Cardinality
@ardinality means, the ratio of distinct (alues to the total number of records. +o, a low cardinality
means, distinct (alues are (ery less.
-n such a scenario, 5itmap indees are considered to be more efficient that 59)ree indees.
Oracle F%nctions , Analytic and Aggregate
0 function is code that accepts one or more inputs and calculates an output.
-n an &racle function, the input may be one or more columns.

Single Col%"n %6#E)H(col1)

5%ltiple col%"ns E.60)6+)(col1, col2, XY;!!"";))

5%ltiple rows D0K(col1)

Single Row F%nctions
0 common single row function eample is the S7#STR function has three inputs8 a string, a starting
position, and a length. )he first two are required and the third is optional which means it has a default
(alue if none is specified. #ote that any of the inputs can be either constants or (ariables.

s%bstrE string4 start:position4 G lengt6 H ;

F%nction Classification?s
,unctions are often grouped in a (ariety of ways8 Erouping by what type of inputNoutput they require.

N%"eric 0ccept numeric input and return numeric (alues
C6aracter 0ccept character input and return character (e.g., +$5+).)
or numeric (e.g., %6#E)H)
)ate:ti"e &perate on date, timestamp, and inter(al (alues
)ata:"ining &perate on models built with the 15D+_10)0_D-#-#E
Conversion @on(ert from one datatype to another.
Collection &perate on nested tables and (arrays
85! &perate on or return KD% documents
5isc 6amples include encodingNdecoding (1$D<), null9related
(#J%), en(ironment ($+6.)
,unctions may also be classified as deter"inistic (always producing the same output, such as 2O2 or
+$5+).(phone_num,1,")) or non,deter"inistic (output may change if the function is rerun with the
same input, such as +I+10)6O2).

Aggregate and Analytic f%nctions
,unctions that ha(e multiple rows as input may be subdi(ided into 0ggregate and 0nalytic functions.

Aggregate f%nctions
0ggregate functions produce a single result from multiple rows.
Select 5A8Esalary; fro" e"ployeesB
)his will return one (alue.

+ubgroups within the query can be defined with the RE.&$< 5IR clause

fro" e"ployees 9RO7* #/ dept:idB

)he first eample will return one row for the table while the second produces one row for each distinct
dept_id in the employees table. -n other words, aggregate functions produce one result for the input
(table or group within the table) irrespecti(e of how many rows are in(ol(ed. +o they are etracting
general facts about the table (or subgroup).
Analytic f%nctions
0nalytic functions also produce a single result from a multiple rows. )he difference is that an analytic
function produces a result for each input row.

+elect D0K(salary) o(er() as ma_salary from employees;

)his will produce the same (alue for each row in the table, so the same (alue appears multiple times.
&racle recogni>es that it is an analytic function by the presence of the analytic clause overE;.

)his analytic clause defines the group of rows to be used as input. -n this case its empty, so the whole
table is used. -f it is not empty, it defines a subgroup of rows called a .IN)O.. )he analytic clause
has three optional sub9clauses8 one to define partitioning based on some (alue, the second to define the
ordering within the partition, and the third to define the rows to be used as input to the function.
0n eample of the partitioning subclause8
fro" e"ployeesB
Will return a row for each employee showing the employees department and the largest salary in that

$se an aggregate function when you want to aggregate the (alues in a table or group into one result.
$se an analytic function when you want the aggregated (alue a(ailable in each row. ,or eample, if -
want the o(erall a(erage, - will use the aggregate function 0JE but if - want a mo(ing a(erage, - will
use the 0JE analytic function8

A+9 Aggregate e(a"ple
Select na"e4 avgEprice; as average:price fro" stoc&s gro%p by na"eB

A+9 Analytic e(a"ple
Select na"e
4 trade:date
4 avgEprice; over Eorder by trade:date rows between 2 preceding; as "v:avg
fro" stoc&s gro%p by na"e4 trade:dateB

Roll%p F%nction
@alculates multiple le(els of subtotals across specified dimensions. +implifies and speeds populating
summary tables by subtotaling a long a hierarchical dimension.

C%be F%nction
%i4e rollup but creates subtotals for all possible combinations of the specified grouping columns 5oth
rollup and cube report null for column(s) being rolled up.

*ipelined table f%nctions
<ipelined table functions are <%N+Q% (or 7a(a or @) programs that ser(e as a table.
RSelect I fro" *!?S'!:F%nctionBR
0lthough you actually write
RSelect I fro" TA#!EE*!?S'!:F%nction;BR

)he <%N+Q%_,unction must return a collection type which corresponds to the rows in the simulated

)he function declaration must include R*I*E!INE)R in its declaration and R*I*E RO.Erecord;BR
)hese allow the output be passed out of the <%N+Q% function as it is created so initial results are
a(ailable without ha(ing to wait for processing complete and without needing a large staging area to
hold the results.

9eneral Interview '%estions
1. @an you delete a column in table with data in &racle'
Ies, we can
2 .@an you delete a column in table without data'
Ies, we can
". @an you delete a column in table with indees in &racle'
We can delete a column with indees. 5ut if there is a <rimary or foreign 4ey present ma4e sure,
foreign 4eys are deleted first and then column with <rimary 4ey.
3. @an we add a 1efault (alue to a column with table ha(ing data and the column ha(ing null and not
null (alues'
Ies. 5ut the 1efault (alue will be applied only to the newly inserted rows.
)he eisting column (alues will not be changed.
5ut there is one eception though. +ee this scenario8
Eg insert into 6D< 99-n the table 6D<, @olumn RcommR is ha(ing a default (alue 122
select / from emp1;
5ut, in this case, the table 6D< will be updated with (alues of comm from 6D<1. i.e 1efault (alue of
comm in 6D< will not be considered
!. -n &racle, can we add a #ot #ull column to a table with data' -f R#oR then how can we do that'
#o, we cannot add a #ot #ull column to a table with data. &racle throws 6rror &.0921=!?.
+ee eample belowP
Eg alter table 6D< add comm2 number not null
6rror8 &.0921=!?8 table must be empty to add mandatory (#&) #$%%) column.
<ro(ide a 1efault (alue to the column being added, along with the #&) #$%% constraint. )hen the
column will get added with the default (alue for all eisting rows.
Eg alter table 6D< add comm2 number not null default 122 99 @omm2 will ha(e 122 for all rows
;. @an we delete a #&) #$%% column from a table in &racle'
Ies, we can.
=. Daimum number of columns in a table or (iew in &racle'
&.0921=C28 maimum number of columns in a table or (iew is 1222
?. While doing an ascending order sort on a column ha(ing #$%% (alues, where does the #$%%s show
up in the result set' 0t the beginning or at the end'
0scending order sort 9 #$%%s come last because &racle treats #$%%s are the largest possible (alues
1escending order sort 9 #$%%s come first
/ How to ma4e #$%%s come last in descending order sort'
0dd #$%%+ %0+) to the order by desc clause
Eg select col1 from table1 order by col1 desc #$%%+ %0+)
C. )ime of eecution of an +Q% +tatement
Eg set timing on select / from 6D<
0fter eecution of each query we get the time ta4e for it.
12. What is the 1atatype of #$%% in &racle'
1atatype of #$%% is Rchar(2)R and si>e is *2*
11. 10)6 ,unctions
9ives date
select trunc(sysdate,*DD*) from dual;
select last_day(trunc(sysdate)) from dual
9ives day
select to_char(trunc(sysdate,*DD*),*10I*) from dual;
select to_char(last_day(trunc(sysdate)),*10I*) from dual;
12. Daimum length of all &racle &b7ects 8
Daimum length of all &racle &b7ects should not eceed "2 characters.
1". Query to find the n#th Highest salary
select min(sal) from (select distinct sal from 6D< order by sal desc) where rownum A n;
13. &racle ,unctions 9 .eplace (ersus )rim
+Q%: select replace(*7ose. antonyZ*,* *, null) as .eplace1 from dual;
99999999999999999999 --Removes all spaces from in-between
+Q%: select trim(*7ose. antonyZ*) as )rim1 from dual;
7ose. antonyZ --Removes spaces from both sides only.
1!. -n &racle can we do any 1D%s in a function which is called from a select statement'
#o. &racle )hrows 6rror
&.0913!!18 cannot perform a 1D% operation inside a query
&.092;!128 at R6D<.,#@_J0@0)-&#_$<10)6R, line 11
1;. -n &racle, what happens if there is no statement inside an 0nonymous bloc4'
For Eg
Ans -t will throw 6rror.
1=. -n &racle, where does #$%%s appear in an ascending order sort' ,irst or %ast' 0nd why'
#$%%s appear !ast in an ascending order sort. &racle treats #$%%s as the largest possible (alues in
the 1atabase. +o, they appear last.
1?. How does #$%%s wor4 with -ndees' What are the wor4arounds'
-ndees wonBt help in gi(ing proper search results if there are #$%% (alues in the indeed columns.
+o, it is always ad(isable to create the #J%() function based indees for such columns.
1C. -n an &uter Soin, what happens to columns that are not matched'
0ll unmatched columns (cell (alues) return #$%%+.
22. What are -nde &rgani>ed )ables (-&))'
-nde organi>ed tables are indees which actually hold the data which is being indeed, unli4e the
indees which are stored somewhere else ans ha(e lin4s to actual data.
21. $ser_+ource table contains code for which all &b7ects'
a. ,unctions
b. <ac4ages 9 both spec and body
c. <rocedures
d. )riggers
22. 6plain .&W-1 in &racle.
.&W-1 is a unique headecimal (alue which &racle inserts to identify each record being inserted. -t is
used for all ,ull )able scans.
&&&&&& 9 ,irst si characters is the &b7ect #umber which identifies the 1ata +egment
,,, 9 #et " characters is the 1atabase ,ile number
555555 9 #et ; characters shows the 1ata5loc4 number
... 9 #et " characters identified the .ow within the bloc4
1) #&@&<I concept in &racle
NO CO*/ )he #&@&<I hint tells the <%N+Q% compiler to pass &$) and -# &$) parameters by
reference, rather than by (alue. 6ttp??"?NOCO*/.6t"l . ,irstly what is
Rcall by refernceR and Rcall by (alueR
)he arguments passed to function can be of two types namely
1. Jalues passed
2. 0ddress passed
)he first type refers to call by (alue and the second type refers to call by reference. #ow one gets the
doubt saying Rwe pass the in parameters as call by (alue not by call by refernce.R
,or eample there is a sample procedure p_factory((_(al -# number);
0nd we call this as p_factory(12); so one may thin4 we are passing the (alue here.......
5ut actually oracle doesnBt pass this 12 as parameter but it pass address of the 12 to the procedure..
Hence in paramters are passed by Rcall by refernceR....Hang on Hang on we are de(iating from the
topic called R#& @&<IR. )o understand the concept we will see how call by refernce will wor4 in
%etBs say we ha(e a procedure as follows
*roced%re sa"ple Ep:a IN n%"ber4 p:o%t O7T Nocopy varc6ar1;B and we are
calling it as follows
(_&ut (archar2 (!2);
sample (12,(_out);
)he compiler manages two distinct (ariables8
J_&ut in the caller program
J_&ut (local) in sample program.
0t the beginning of sample the compiler copies (_out into (_out(local) and at the end of sample it
copies (_out(local) to (_out.
5ut if we use nocopy hint the concept of the (ariable (_out(local) doesnot eist..+o perforamce is you can start reading about NO CO*/ ad( and dis ad(antages from the net.......
2) )ypes of )riggers - &racle triggers
") 1ifferences between <rocedure and ,unction (0ll possible differences)
i) ,unction is mainly used in the case where it must return a (alue. Where as a procedure may or may
not return a (alue or may return more than one (alue using the &$) parameter.
ii) ,unction can be called from +Q% statements where as procedure can not be called from the sql
iii) ,unctions are normally used for computations where as procedures are normally used for eecuting
business logic.
i() Iou can ha(e 1D% (insert,update, delete) statements in a function. 5ut, you cannot call such a
function in a +Q% query.
() ,unction returns 1 (alue only. <rocedure can return multiple (alues (ma 1223).
(i) +tored <rocedure8 supports deferred name resolution. 6ample while writing a stored procedure that
uses table named tabl1 and tabl2 etc..but actually not eists in database is allowed only in during
creation but runtime throws error ,unction wont support deferred name resolution.
(ii) +tored procedure returns always integer (alue by default >ero. where as function return type could
be scalar or table or table (alues
(iii) +tored procedure is precompiled eecution plan where as functions are not.
i) 0 procedure may modify an ob7ect where a function can only return a (alue )he .6)$.#
statement immediately completes the eecution of a subprogram and returns control to the caller.
3) How to Digrate 1isco(erer .eports from &ne -nstance to another
&pen the disco(erer report which you want to migrate and then sa(e it on your system. @onnect to the
target instance of the disco(erer and then open the abo(e sa(ed (which is sa(ed on computer)
disco(erer report, 0nd sa(e this in the current database
!) )ypes of )riggers in .eports
.eport )riggers8 .eport triggers enable eecution of <%N+Q% functions at specific time during
eecution and formatting of report. )here are ! types of )riggers in .eports. )hey are as following.
i; #efore *ara"eter For"
,ires before the .untime <arameter ,orm are displayed. @an access the <%N+Q% global (ariables,
report le(el columns and manipulate accordingly.
ii; After *ara"eter For"
,ires after the .untime <arameter form are displayed. $sed to (alidate the parameter (alues.
iii; #efore Report
,ires before the report is eecuted but after the queries is parsed and data is fetched.
iv; #etween *ages
,ires before each page of the report are formatted, ecept the (ery first page. )his page is used to
customi>e page formatting.
v; After Report
,ires after the report pre(iewer are eited, or after report output is sent to a specified destination.
;) 1ifference between Jiews and Dateriali>ed Jiews
Jiew contains 11% statment...(select 999 from 99tables where 999 conditions) 5ut Dateraili>ed (iew
holds the output..(i.e. it contians data rather than the definition...)