You are on page 1of 11

Application SQL Issues and Tuning

Dan Hotka
Director of Database Field Operations
Quest Software, Inc
This paper and presentation are based SQL, the various tools available for gathering
inforation and understanding various parts of the SQL !"plain #lan, or the path that
Oracle$%$i will use to find the data&

Dan Hotka is a Director of Database Field Operations for Quest Software&
He has over '( )ears in the coputer industr), including over (* )ears e"perience
with Oracle products& He is an acknowledged Oracle e"pert where his Oracle e"perience
dates back to the Oracle +,&- da)s& He has co.authored the popular books
Oracle Unleashed, Oracle8 Server Unleashed, Oracle Developer Unleashed, and Special
Edition Using Oracle8/8i fro S/0S #ublishing and fre1uentl) speaks at Oracle
conferences and user groups around the world&
2I2LIO34/#H56 7hapter ',, Oracle$ Server 8nleashed, S/0S #ublishing
isbn6-.9:'.;('-:.:
<ul) (=== Oracle #rofessional, #innacle #ublications& 4eproduced with
perission fro #innacle #ublishing& /ll rights reserved&
SQL Level Tuning should be the final phase of tuning& /ll too often, the other parts discussed in the
previous parts of this series are overlooked& #eople soeties view SQL tuning as the onl) area that
re1uires tuning& The $-%'- rule applies to SQL level tuning as well& Twent) percent of the SQL stateents
will utili>e over $- percent of the resources& It is this '- percent where we need to concentrate our efforts&
There are a variet) of e"plain.plan tools available fro Oracle 7orporation and various ;
rd
part) vendors&
Oracle !nterprise 0anager has a SQL.onitor tool available& Oracle has alwa)s provided a variet) of
wa)s of capturing perforance inforation in the for of T4/7! files& These trace files are interpreted
b) T?#4OF, a tool not for the novice& This final tuning installent will discuss various features of tuning
at the SQL level, the Oracle optii>er choices, e"isting and new inde"ing features, and the SQL stateents
theselves& 4esource.intensive and long running SQL 1ueries will have the biggest ipact on application
perforance& These SQL stateents need to be identified and tuned first&
There are an) features previousl) discussed in this series aid in the perforance of applications, nael)
procedures, functions, and triggers@ the use of unrecoverable transactions Aunderstanding the application
needsB@ and pinning application code in the shared pool& This article will discuss the need to use better SQL
coding techni1ues&
Oracle has supported the copilation of functions, procedures, and triggers Aprocedural obCectsB since
Oracle:& The resulting interediate code does not need to be parsed or prepared for e"ecution, saving
considerable tie at run.tie& The copiler is autoaticall) invoked when the procedural obCect is created
or altered& 7hanges to the table structures can invalidate procedural obCects, re1uiring the to be copiled
again at run.tie& The procedural obCects can be anuall) re.copiled when the) becoe invalidated&
Listings ( and ' show the SQL s)nta" for anuall) invoking the copiler&
alter procedure D#4O7!D84! E/0!F copile
alter function DF8E7TIOE E/0!F copile
alter trigger DT4I33!4 E/0!F copile
Procedure, Function, and Trigger Compile SQL
Listing 1
If the procedure or function is part of a package, the whole package can be copiled or Cust the bod)&
alter package D#/7?/3! E/0!F copile package
alter package D#/7?/3! E/0!F copile bod)
Package Compile Options
Listing 2
SQL stateents with nested sub1ueries can create an enorous aount of i%o traffic& Listing ; is a
correlated sub1uer) where the outer 1uer) is e"ecuted one tie for each row returned b) the inner 1uer)&
Listing , produces the sae result but at a fraction of the i%o as it 1ueries the look up table Athe sub1uer) of
Listing ;B once, not once per each row&
update !0#
set sal G sal H (-
where e"ists
Aselect I"J fro D!#T
where D!#T&deptno G !0#&deptnoB
Correlated SQL statement
Listing 3
DECL!E
cursor c( is select deptno fro dept@
workKdeptno nuber@
"E#$%
open c(@
loop
fetch c( into workKdeptno@
EXIT when c1%NOTFOUND
update ep
set sal G sal H (-
where deptno G workKdeptno@
end loop@
E%D&
PL'SQL Loop E(ample
Listing )
8sing inde"es greatl) enhances the response tie of ost SQL stateents& The rule of thub here is if
ore than '-L of the rows of a table are going to be returned fro the database then consideration on to
use an inde" or not should be given& This is ver) dependent on the si>e of the table obCect& It is iportant
to understand the various available inde"ing options so that the optial inde"ing ethod is being utili>ed
for a given SQL stateent&
Oracle: introduced several new inde"ing options that iprove on the traditional 2Htree inde"es& Oracle:
introduced bitap inde"es, star 1ueries, histogras, and hash Coins& Oracle$ introduced inde".organi>ed
tables and reverse ke) inde"es& !ach of these new inde"ing options is onl) available to the cost.based
optii>er&
The first new inde"ing option available in Oracle: is bitap inde"es& This inde"ing option is intended for
coluns with low cardinalit) of data such as color, se", etc& / bitap inde" stores all the values of a
particular colun in a series of bits& !ach bit is related to a rowid in the table obCect& Oracle can 1uickl)
find rows in the inde" b) sipl) searching for non>ero values& Figure ( illustrates how the !0# table
obCect ight look in a bitap inde"&
Rows
10
20
40
30
1 2 3 4 5 6 7 8 9 . .
1
0
0
0
0
0
1
0
0 1 0 1 0 0 0 1 1 0 0 0
1 0 0 0 1 0 0 0 0 0 1 0
0 0 1 0 0 1 0 0 0 0 0 1
0 0 0 0 0 0 1 0 0 1 0 0
E*P "itmap $nde(
Figure 1
Listing * is a SQL 1uer) that will help identif) table coluns for possible bitap inde" consideration&

select owner MOwnerM, inde"Knae MInde" EaeM, distinctKke)s MDistinct ?e)sM
fro D2/KIED!N!S
where distinctKke)s D (*
"itmap $nde( Candidates
Listing +
/ star 1uer) involves a single table obCect being Coined with several saller table obCects, where the driving
table obCect has a concatenated inde" ke) and each of the saller table obCects is referenced b) part of that
concatenated ke)& The Oracle cost.based optii>er recogni>es this arrangeent and builds a eor).
based cluster of the saller tables&
/ histogra ight be useful when there is not an even distribution of data throughout a table obCect& #rior
to histogras, the Oracle optii>er assued even distribution of values throughout the obCect&
Figure ' illustrates a histogra as a series of buckets& There are two kinds of histogras, width.balanced
and height.balanced& Oidth.balance is where the values are divided up into an even nuber of buckets and
the optii>er can easil) deterine as to which buckets have a higher count& In height.balanced histogras,
each bucket has the sae nuber of colun values, but a colun value a) span ore than one bucket&
Figure ' illustrates what the !0# table ight look like in either of the t)pes of histogras&
Width-balanced Height-balanced
10 20 30 0 10 10 20 30
E*P ,istogram
Figure 2
Histogras are ipleented via the anal)>e coand b) specif)ing IcolunJ paraeter& Histogras
defaults to :* buckets with a a"iu of '** defined buckets& Histogras can be created for inde"es,
tables, or clusters&
Hash Coins can draaticall) increate perforance of two Coined tables, where one table is significantl)
larger than the other& This inde" option replaces the e"isting Isort.ergeJ Coin algorith& The hash Coin
works b) splitting two tables into partitions and creating a eor) based hash table& This hash table is
then used to ap Coin coluns fro the other table, eliinating the need for a sort.erge& In the hash Coin
ethod, both tables are scanned onl) once& In sort.erge, the saller table can actuall) be read an)
ties& Hash Coins are ipleented b) the init&ora paraeters H/SHK<OIEK!E/2L!D,
H/SHK08LTI2LO7?KIOK7O8ET, and H/SHK/4!/KSIP!&
The reverse.ke) inde" introduced in Oracle$ reverses the order of the b)tes of a nueric ke)& 4everse.ke)
inde"es are reall) useful in keeping the inde" balanced with se1uence.nuber or increenting t)pe ke)s&
The s)nta" in Listing 9 shows how eas) it is to ake regular inde"es reversed and%or change the reverse
ke) back to a regular ke)&
create inde" DIED!N E/0!F on DT/2L! E/0!F AD7OL80E E/0!ASBFB reverse
alter inde" DIED!N E/0!F rebuild noreverse%reverse
!e-erse .e/ $nde( S/nta(
Listing 0
/s far back as Oracle*, if Oracle could resolve a 1uer) fro inforation in the inde", it
would not retrieve an) rows fro the actual table& This trick was utili>ed widel) for
group b) functions or additions on an aount field& / D2/ would sipl) add the
coon data to the end of the concatenated inde" ke)& Inde".organi>ed tables gives this
sae end result as there is no associated table obCect& Inde".organi>ed tables have an
overflow option is where the noninde"ed part of the row will be stored if the row si>e is
over the percentage given& This will create a siilar effect to that of row chaining&
Inde".organi>ed tables a) not be replicated or have additional inde" coluns&
#artitioning will be available in Oracle$&(& Listing : illustrates the s)nta" to create an
inde".organi>ed table& The saller tables of a star 1uer) are an e"cellent use for this
inde" option& To help prevent fragentation of the inde", it is best to avoid tables with
lots of update activit)&
create table DT/2L! E/0!F
Afield descriptions
.
.
DFI!LD E/0!F
priar) ke) AD?!5 FI!LDSFBB
organi>ation inde" tablespace DT/2L!S#/7! E/0!F
pctthreshold '-
overflow tablespace DT/2L!S#/7! E/0!F
$nde(1organi2ed Ta3le S/nta(
Listing 4
Ohen a SQL stateent is presented to the Oracle kernel, it is parsed for proper s)nta" and an e"ecution
plan is developed& Think of this e"ecution plan as a road ap to the actual data& This e"ecution plan can be
visuali>ed with the e"plain.plan 1uer) discussed later in this article&
Oracle$ supports both the rule.based optii>er and the cost.based optii>er& The optii>ers tell Oracle the
best e"ecution path for a particular SQL stateent&
The rule.based optii>er, the original optii>er, uses a series of nineteen rules to decide this path, see
Listing $& The optii>er gives the ore preference the lower the rank& The rule.based optii>er is
controlled b) the order of the tables in the F4O0 clause, how the OH!4! clause is coded, and what
inde"es are available& In a Coin table situation, the driving table will be the last table naed in the F4O0
clause&
!ank 56ere clause predicates
( 4OOID G constant
' uni1ue inde"ed colun G constant
; entire uni1ue concatenated inde" G constant
, entire cluster ke) G cluster ke) of obCect in sae cluster
* entire cluster ke) G constant
9 entire nonuni1ue concatenated inde" G constant
: nonuni1ue inde" G constant
$ entire noncopressed concatenated inde" FG constant
= entire copressed concatenated inde" FG constant
(- partial but leading coluns of noncopressed concatenated inde"
(( partial but leading coluns of copressed concatenated inde"
(' uni1ue inde"ed colun using the SQL stateent 2!TO!!E or LI?! options
(; nonuni1ue inde"ed colun using the SQL stateent 2!TO!!E or LI?! options
(, uni1ue inde"ed colun D or F constant
(* nonuni1ue inde"ed colun D or F constant
(9 sort%erge
(: 0/N or 0IE SQL stateent functions on inde"ed colun
($ O4D!4 25 entire inde"
(= full table scans
!ules 7or !ule1"ased Optimi2er
Listing 8
The cost.based optii>er, introduced first in Oracle9, akes its e"plain.plan decisions based on statistics
gathered b) the /E/L5P! coand and stored in the data dictionar)& Oracle will use the cost based
optii>er if there are statistics collected& The init&ora paraeter, O#TI0P!4K0OD! ust be set to
7HOOS! or 7OST to utili>e the cost.based optii>er&
It is iportant to keep these statistics current when inserting and updating table obCects& /nal)>ing large
table obCects can take a considerable aount of 7#8 and sort resources& Oracle does offer an I!STI0/T!J
clause, however, the percentage given with this estiate option onl) applies fro the beginning of the table
obCect, not a rando selection fro the entire obCect& Listing = illustrates the anal)>e s)nta"&

analyze table <TABLE NAME> estimate
nal/2e Command
Listing 9
Hints are used to ake recoendations to the cost.based optii>er& #lease note that Oracle can decide to
ignore hints& Hints can be used to control the optii>erJs goal, access ethods, Coin conditions, parallel,
and partitioning options& Hints are specified as part of the SQL stateent s)nta"& Listing (- shows an
/LLK4OOS hint in the !0# table obCect&
select %HQ /LLK4OOS H% enae, sal fro !0# where S/L F (---
,int in E*P SQL statement
Listing 1:
The optii>er goal hint controls one of three cost.based optii>er odes6 48L! will force the rule.based
optii>er, FI4STK4OOS Abest responseB and /LLK4OOS Abest throughputB will use the cost.based
optii>er and force the optii>er to the desired goal& 0ost of the access.ethod.controlling hints are
listed in Listing ((&
,int Description
/EDK!Q8/L 8se the /EDK!Q8/L hint when ore than one e1ualit) criterion
e"ists on a single table&
7/7H! 8se the 7/7H! hint to place the entire table in the buffer cache& The table
is placed at the ost recentl) used end of the buffer cache& This hint is
good for sall tables that are accessed often&
7L8ST!4 8se the 7L8ST!4 hint to access a table in a cluster without the use of an
inde"&
F8LL 8se the F8LL hint to perfor a full table scan on a table&
H/SH 8se the H/SH hint to access a table in a hashed cluster without the use of
an inde"&
IED!N 8se an IED!N hint to instruct O4/7L! to use one of the inde"es
specified as a paraeter&
IED!NK7O02IE! The IED!NK7O02IE! forces the use of bitap inde"es&
EO7/7H! 8se the EO7/7H! hint to place the blocks of the table at the beginning
of the buffer cache so as not to age an) blocks out&
EO#/4/LL!L 8se the EO#/4/LL!L hint to not use ultiple.server processes
to service the operations on the specified table&
O4D!4!D 8se the O4D!4!D hint to access the tables in the F4O0 clause in the
order the) appear&
#/4/LL!L 8se the #/4/LL!L hint to re1uest ultiple server processes to
siultaneousl) service the operations on the specified table&
#8SHKS82Q The #8SHKS82Q evaluates sub1ueries earlier, rather than as a filter
operation&
4OOID 8se the 4OOID hint to access the table b) 4OOID&
ST/4 ST/4 hint invokes the ST/4 1uer) feature&
8S!K7OE7/T 8S!K7OE7/T is used when a SQL stateent has ultiple criteria
O4ed together&
8S!KH/SH 8se the 8S!KH/SH hint to perfor a hash Coin rather than a erge Coin
or a nested loop Coin&
8S!K0!4! 8se the 8S!K0!43! hint to perfor a erge Coin rather than a nested
loop Coin or a hash Coin&
ccess *et6od ,ints
Listing 11
SQL stateent tuning re1uires an understanding of e"plan plans& Listing (' displa)s the contents fro a
collection in the Oracle supplied planKtable& Oracle tools include Oracle !nterprise 0anager Top Session,
T?#4OF Ae"aines T4/7! filesB, and the !N#L/IE coand cobined with a SQL stateent to
displa) the results& There are an) third part) tools such as Quest SoftwareJs SQLab that assists the D2/
with SQL e"plain plan tuning, aong other features&
The e"plain plan is a necessit) for tuning SQL stateents for both the rule.based and cost.based
optii>ers& Listing (' shows how to load the plan table and 1uer) the results& This plan table can be set up
for an) user b) running the RO4/7L!KHO0!%rdbs%adin%utl"plan&s1l script fro SQLH#lus&
E;PL$% PL% $%TO PL% <T"LE FO!
select H fro ep@
select 7OST, O#!4/TIOE, O#TIOES, O2<!7TKE/0!
fro #L/EKT/2L!@
COST OPERATION OPTIONS
OBJECT_NAME
------- ----------------------------- ------------- -----
-------0 SELECT STATEMENT
3 TABLE ACCESS FULL EMP
E(plain Plan Ta3le and !esults
Listing 12
!"plain plans can be difficult to interpret& Listing (; describes the ore coon e"plain plan steps&

/ccess 4ule Description
/ED.!Q8/LInde" values will be used to Coin rows&
7OE7/T!E/TIOE SQL stateent 8EIOE coand&
FILT!4 FILT!4s appl) Iother criteriaJ in the 1uer) to further 1ualif) the atching
rows& The Iother criteriaJ include correlated sub1ueries, and H/+IE3
clause&
FI4ST 4OO SQL stateent will be processed via a cursor&
FO4 8#D/T! SQL stateent clause Ifor update ofJ placed row level locks on
affected rows&
IED!N A8EIQ8!B SQL stateent utili>ed a uni1ue inde" to search for a specific
value&
IED!N A4/E3! S7/EB SQL stateent contains a none1ualit) or 2!TO!!E
condition&
H/SH <OIE SQL stateent initiated a hash.Coin operation&
0!43! <OIESQL stateent references two or ore tables, sorting the two result sets
being Coined over the Coin coluns and then erging the results via the
Coin coluns&
E!ST!D LOO#S This operation is one for of Coining tables, as opposed to a erge
Coin& One row is retrieved fro the row source identified b) the first child
operation, and then Coined to all atching rows in the other table,
identified in the second child operation&
EOE8EIQ8! IED!N A4/E3! S7/EB The 4/E3! S7/E option indicates that O4/7L! e"pects to
return ultiple atches A4OOIDsB fro the inde" search
#/4TITIOE A7OE7/TT!E/T!DB SQL stateent will access a partitioned obCect and erge the
retrieved rows fro the accessed partitions&
#/4TITIOE ASIE3L!B SQL stateent will access a single partition&
#/4TITIOE A!0#T5B The SQL stateent akes reference to an ept) partition&
SO4T AO4D!4 25B SQL stateent contains an O4D!4 25 SQL coand&
SO4T A/34!3/T!B SQL stateent initiated a sort to resolve a 0IE or 0/N t)pe
function&
SO4T A34O8# 25B SQL stateent contains a 34O8# 25 SQL coand&
T/2L! /77!SS AF8LLB /ll rows are retrieved fro the table without using an inde"&
T/2L! /77!SS A25 4OOIDB / row was retrieved fro a table based on the 4OOID
of the row&
T/2L! /77!SS A7L8ST!4B / row is retrieved fro a table that is part of an inde"ed
cluster&
8EIOE SQL stateent contains a DISTIE7T SQL coand&
E(plain Plan Steps
Listing 13
Oracle$ has introduced three new coluns6 partitionKstart, partitionKstop, and partitionKid& These three
new fields will aid in the tuning of SQL stateents that access partitioned obCects& The partitionKstart and
partitionKstop show the range of partitions that is affected b) this e"plain step& The partitionKid is
identification nuber for that particular e"plain step&
Finall), there are both good and poor wa)s to code SQL stateents& Here are soe guidelines for SQL
stateent coding that will help both the rule.based and the cost.based optii>ers&
DOEJT use calculations in the where clause on inde"ed coluns& 8nless the intended behavior is to
disable the inde" use, an) function on inde"ed coluns will ignore the inde"&
DO use the IE operator instead of EOT& Tr) to avoid using the EOT coand b) using FG, DG, etc&
DOEJT use an inde" if ore than '- percent of the rows will be returned b) the 1uer)&
DO use arra) processing whenever possible A!"port, and #roH7 applicationsB&
DOEJT use sub1ueries if other solutions e"ist A#L%SQL loop for e"apleB&
DO use hints to insure the desired e"ecution.plan results&
DOEJT write applications that use SQL e"ecution.plan defaults& Oracle 7orp akes no
guarantees that default behavior will be aintained in future releases, or even between
different hardware platfors