Anda di halaman 1dari 19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

GetStarted

Solutions

About

Support

Training

Community

Developer

Partner

Community

Blogs

PerformanceoptimizationofSQL
statementsinABAP
August24,2010

| 190Views |

PhaniKumarPasam
morebythisauthor

Retaggingrequired
phanikumarpasam

share
0

share
0

tweet

share
0

Follow

InthissessionIhaveexplainedtheconceptsofDBoptimizerandhowit
parsesaSQLquerytocreateanevaluationpath.Ihavegivenexamples
ofhowtoimprovetheperformanceofSQLstatementsinABAPby
changingtheWHEREclause.Iamassumingreadersarefamiliar
withtransactionsSE30andST05.
Note:belowSQLtracesarefromDB2databaseandresultsmayvaryfor
otherDatabases.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

1/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

Considersimpleselectstatement:SELECT*fromMARAwhereMATNR
=ACFBAS2.
HereDatabasehas3possiblesearchstrategiestofindtherecordand
whichpathtochooseisdecidedbytheoptimizer.
searchtheentiretable
usethePrimaryindexforsearch
usesecondaryindexofsearch
Optimizer:optimizerisdatabaseprogramthatparsestheSQL
statementandconsiderseachaccesspath(fullscan,primaryindex,
secondaryindex)andformulatesanexecutionplanfortheSQL
statement.Thereare2typesofoptimizers
RuleBasedOptimizer:basedonavailableindexesandthefieldsused
inWHEREclause,RBOcreatesitsexecutionplan.Themostimport
criteriaintheWHEREclausearethefieldsthatarespecifiedwithan
EQUALSconditionandthatappearinanindex.
CostBasedOptimizer:tocreatetheexecutionplanforanSQL
statement,theCBOconsidersthesamecriteriaasRBOplus
TableSize:forsmalltables,theCBOdecidestoavoidindexesinfavor
ofamoreefficientfulltablescan.Largetablesaremorelikelytobe
accessedthroughindex.
Selectivityoftheindexfields:theselectivityofagivenindexfieldis
theaveragesizeoftheportionofthetablethatisreadwhenanSQL
statementsearchesforaparticulardistinctvalueinthatfield.Ex:if
thereare200contracttypesand10,000actualcontractsinVBAKtable,
thentheselectivityofthefielddoctypeis10,000dividedby200which
is50or2%of10,000.Thelargerthenumberofdistinctvaluesinafield
themorelikelytheoptimizerwillusetheindexbasedonthatfield.
PhysicalStorage:theoptimizerconsidershowmanyindexdatablocks
orpagesmustbereadphysicallyontheharddrive.Themorephysical
memorythatneedstoberead,thelesslikelythatanindexisused.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

2/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

Example1:createadatabasetableZKUM_TESTwithfieldsF1,F2,..to
F10.AndF1,F2,F3,F4arekeyfieldsofthetablei.e.primarykeys.Now
considerbelowselects

1.
SELECT*FROMZKUM_TESTINTOTABLEITABWHEREF2=1an
dF3=3:Hereoptimizerwillnotusetheprimaryindexforthesearch
operationbecauseF1ismissinginthewhereclause.soafulltablescan
isperformed.
2.
SELECT*FROMZKUM_TESTINTOTABLEITABWHEREF1=2an
dF2=3:HereifthereisnosecondaryindexonfieldsF1andF2then
optimizerwillchooseprimaryindexastwofieldsoutof4arematched.
3.SELECT*FROMZKUM_TESTINTOTABLEITABWHEREF1<>2
andF2=3andF3=3:hereoptimizerwillnotusetheprimaryindex
astheoperatorNOTisusedforcomparisionforcolumnF1.Ifthereis
anysecondaryindexoncolumnsF2,F3thenoptimizerwilluse
secondaryindex.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

3/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

Tomaketherightdecisiononoptimalaccess,theCBOrequires
statisticsonthesizesoftablesandindexes.Thestatisticsmustbe
periodicallygeneratedtobringthemuptodate.StandardSAPreports
areavailabletogeneratethesestatistics(transactionDB13).The
advantageofCBOisitsflexibility,becauseitconsiderstheselectivityof
specifiedfields.
ex:SELECT*FROMMARAWHEREMANDT=020andBISMT=a1.
HeretheCBOknowsthatMANDTcontainsonlyonedistinctvaluewould
decideonafulltablescan,whereastheRBOwouldchoosetheless
effectiveindexrangescan.

Access

WithIndex

Runtimein

Path

basedonFields

microseconds

Withouttableaccess

Index

MANDT,MATNR

3,500,000

statisticsWithoutsecondary

rangescan

N/A

500,000

BISMT

3000

indexbasedonthefield
BISMT
Withtableaccess

Fulltable

statisticsWithoutsecondary

scan

indexbasedonthefield
BISMT
Withtableaccessstatistics

Index

Withsecondaryindex

rangescan

basedonthefieldBISMT

RulesforefficientSQLprogramming:
1.SQLstatementsmusthaveaWHEREclausethattransfersonlya
minimalamountofdata.AvoidusingNOTconditionsinthe
WHEREclause.Thesecannotbeprocessedthroughanindex.
Avoidusingidenticalselects,youcanidentifythisinST05
2.UseSELECTcolumn1column2.insteadofSELCT*
3.TheWHEREclausesmustbesimpleotherwisetheoptimizermay
decideonthewrongindexornotuseanindexatall.Awhere
clauseissimpleifitspecifieseachfieldoftheindexusingAND
andanequalscondition
4.UseFORALLENTRIESinsteadofSELCTSinsideLOOPS.When
usingFAEmakesureinternaltableisnotemptyandmustnot
https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

4/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

containduplicates.Dependingonthedatabasesystem,the
databaseinterfacetranslatesaFAEintovariousSQLstatements,
itcantranslateintoSQLstatementsusinganINorUNION
operator

Ifyouarepullinglargevolumesofdatafrommultipletables,thenbetter
tocreateadatabaseviewratherthanusingFORALLENTRIES.
Example2:
RunSQLtraceforbelowselectstatements.
SELECTmandtvbelnposnrFROMvbapINTO
TABLEitabWHEREerdatins_erdat.
IFitab[]ISNOTINITIAL.
selectmandtvbelnposnrfromvbapintotableitab
forALLENTRIESINitab
wherevbeln=itabvbelnandposnr=itabposnr.
ENDIF.

FirstSelect:
ForthefirstSELECT,wholetableisscannedasthereisnomatching
indexfound(becausethecolumnsmentionedintheWHEREclauseare
notpartofeitherprimarykeyorsecondaykey).Toknowtheno.ofhitsto
Database,clickonSummarizeTracebySQLstatementsfrommenu
pathTraceList,thiswillgrouptheidenticalselects.
ForthefirstselectonlyonehittoDBwhereasforsecondselect3210
hitstoDB,seebelowfordetails.columnExecutionsgivesyouno.ofhits
toDB.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

5/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

ClickonExplainbuttonforfirstselecttoknowtheaccesspathi.e.which
indexisused.herenomatchingindexfound,soentiretablewillbe
scanned.
Inbelowscreenshotyoucanseeonlyonecolumni.e.MANDTis
matchedoutof3columnsoftheprimayindex.sowholetableis
scanned.

SecondSelect:internaltableITAB[]ishavingaround32Krecords.
inSQLtraceclickondisplayforsecondSQL,youwillnoticetheFOR
ALLENTRIESINTABLEconstructischangedtoUNIONALLanda
https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

6/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

subquerybytheDBoptimizer.
No.ofhitstoDBis3210

UNION:TheUNIONcommandisusedtoselectrelatedinformation
fromtwotables,muchliketheJOINcommand.TheUNIONALL
commandisequaltotheUNIONcommand,exceptthatUNIONALL
selectsallvalues.
IntheaboveexampleasingleSELECTstatementissplitintomultiple
selectsbytheDBoptimizedandwithasubquery(i.eUNIONALL)and
passedtothedatabase.
InthisexampleITABishavingaround32Krecordsand10recordsare
passedwitheachselectresultingin3210hitstodatabase.

TotaldurationforfirstSELECT:2,167,664microseconds
TotaldurationforsecondSELECT:6,739,983microseconds.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

7/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

Nowchangethesecondselectsuchawaythatoptimizerwillnotuse
subquerywithUNIONALLconstruct.POSNRiscommentedout.
Modifiedcode:
SORTITABBYVBELN.
DELETEADJACENTDUPLICATESFROMITABCOMPARINGVBELN
.
SELECTmandtvbelnposnrFROMvbapINTOTABLEitab
forALLENTRIESINitab
wherevbeln=itabvbeln.andposnr=itabposnr.

No.ofhitstoDBcamedownto189andtotaldurationcamedown
to453,742microseconds.

clickonExplainbuttontoknowtheaccesspath.HereinthiscaseFOR
ALLENTRIESINTABLEconstructischangedtoINclausebytheDB
optimizer.
Bunchofvalues(around30contractnumbers)arepassedineach
selecttherebyreducingtheno.ofhitstodatabase.Optimizerstillused
theprimayindexastwocolumnsmentionedinWHEREclause
(MANDT,VEBLN)matchedwiththeprimarykeysofthetable.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

8/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

Theruntimeshowninthetraceincludesnotonlythetime
requiredbythedatabasetofurnishtherequesteddata,butalsothetime
requiredtotransferdatabetweendatabaseandtheapplicationserver.If
thereisaperformanceprobleminnetworkcommunication,theruntimes
ofSQLstatementsincrease.Sotakethetrace23timesbeforeyou
cometoanyconclusion.
Asexplainedabove,ifthereisanyperformanceproblemswith
SELECTstatements,firstthingyouneedtocheckisWHERE
caluse,modifytheWHEREclauseandseeiftheoptimizerusesany
availableindexornot.Incaseifnoavailableindexisusedthenbetter
createasecondaryindextoimprovetheperformance.
Pleasenote:whenyouarepullingdatafrommultipletables,itis
bettertojointhesetablesusingINNERJOIN,asINNER
JOINsperformbetterthanFORALLENTRIES.
Example:3
https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

9/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

considerbelowselect:hereIampullingcontractlineitemVC
characteristicdetails.VBAPCUOBJislineitemVCconfignumber

SELECTa~instanceb~in_recnob~symbol_idc~atinnc~atwrtc~atflv
FROM((ibinASaINNERJOINibinvaluesASbONa~in_recno=
b~in_recno)
INNERJOINibsymbolAScONb~symbol_id=c~symbol_id)
INTOTABLEgt_char_val
FORALLENTRIESINl_cabn
WHEREa~instance=it_vbapcuobjANDc~atinn=l_cabnatinn.

Insteadofwriting3individualselectstatementsonIBIN,IBINVALUES
andIBSYMBOLitisbettertouseINNERJOIN.
SQLtraceshowsavailableindexisusedforeachtablei.efortableIBIN
indexCisused,fortableIBINVALUESindexSW0isusedandfor
tableIBSYMBOLindexSELisused,sotheperformanceofthequeryis
good.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

10/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

SowhenyouareusingINNERJOINonmultipletablesbettertotake
SQLtraceandchecktheaccesspathtoseeifavailableindexisusedor
not.
Index:IBIN~CisoncolumnsMANDTandINSTANCE
Index:SWOontableIBINVALUESisoncolumnsMANDT,IN_RECNO,
SYMBOL_ID,ATZISandASSTYP.
Index:SELontableIBSYMBOLisoncolumnsMANDT,ATINN,ATWRT,
ATFLVandSYMBOL_ID.

CreatingSecondayIndex:
Creatingorchangingasecondaryindexcanimproveorworsenthe
performanceofSQLstatements,beforecreatingsecondaryindex
checkifyoucanrewritetheABAPprograminsuchawaythatan
availableindexcanbeused.

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

11/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

NevercreateasecondaryindexonSAPbasistableswithout
recommendationsfromSAP,examplesD010,D020,DD*.

RulesforcreatingSecondaryIndex:

Includeonlyselectivefieldsintheindex:excustomernumber,Material,
Contractnumber
Includefewfieldsintheindex
Positionselectivefieldstotheleftintheindex
IndexshouldbeDisjunct,avoidcreatingtwoormoreindexeswith
largelythesamefields
createfewindexespertable

iftheSQLstatementthatsearchesbymeansofparticularindexfield
wouldcausemorethat5%to10%oftheentireindextoberead,the
costbasedoptimizerdoesnotconsidertheindexisusefulandinstead
choosesthefulltablescanasthemosteffectiveaccessmethod.
Example1:considerbelowselectstatement
SELECTMANDTVBELNposnrFROMVBApintoTABLEITABWHERE
VGBELINs_VGBEL.

VGBEL(referencedocnumber)isnotpartofPRIMARYkeyandalsono
secondaykeyexistforthat.SQLtraceforaboveselectinDB2.

SQLtrace:
https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

12/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

Ifyoulookataccesspathnomatchingindexfound.Soweneedto
checkifcreatingasecondayindexonMANDTandVGBELisagood
candidateornot.
NowgototransactionDB05andinputtablenameandspecifythefileds
onwhichyouwanttocreateindex,andclickexecute

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

13/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

selectthecheckboxSubmitanalysisinbackgroundiftablesizeis
large.
output:

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

14/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

ouputshowedthatVBAPishaving317,272rowsandtheNo.ofdistinct
VGBELvaluesoutofthese317Krecordsis5644.

outofthese5644distinctvalues
4430ref.documentsarehavinglessthan10entiesinVBAPtable
:meansifyoudocount(*)FROMVBAPandinputanyofthese
4430ref.documentnumberthenlineitemcountwillbebetween1
to10.
1099ref.documentsarehavingentriesbetween10to100
101ref.documentarehavingentriesbetween101to1000
13ref.documentsarehavingentriesbetween1001to10,000
only1ref.documentishavingrecordsmorethat100,000in
VBAP:meansifyoudoacount(*)FROMVBAPandinputthisref.
docnumberyougetlineitemcount>=100,001

DB05analysisshowedthatmostoftheref.documentsarehaving
recordcountbetweenin1to1000meansthisisagoodcandidatefor
secondaryINDEXcreation.
NowcreateasecondayindexonVBAPoncolumnsMANDTandVGBEL
inSE11transactionandthenrunthesamequeryagain.

SQLTraceshowedruntimecamedownfrom2,165,827msto2,026ms
,hugedifference.

Example2:Ifyouwanttocreateindexonmultiplecolumnsofa
table,thenanalyzethetablewithrespecttothoseindexfieldsinDB05.
considerbelowanalysisofTCURRtable.
https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

15/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

IrunDB05onTCURRtableforfieldsMANDT,KURST,FCURR,TCURR
andGDATU
explanation:
KURSTrow:no.ofdistinctexchangeratetypesinTCURRtableis22out
ofwhich2arehavingrecordcountbetween1to10.Threeratetypes
arehavingrecordcountbetween11to100.And14exchangeratetypes
arehavingcountbetween101to100etc
FCURRrow:no.ofdistinctvaluesforcombinationofKURST&FCURRis
1014,outofwhich785combinationsarehavingrecordcountbetween1
to10.And137combinationsofKURST&FCURRarehavingrecord
countbetween11to100.etc
TCURRrow:no.ofdistinctvaluesforcombinationofKURST,FCURR&
TCURRis1019outofwhich790combinationsarehavingrecordcount
between1to10.etc
GDATUrow:no.ofdistinctvaluesforcombinationofKURST,FCURR&
TCURRandGDATUis35Ki.eonlyonerecordpercombinationasthese
arepartofprimaryindex.

ThiswayDB05analysiswillhelpyoudecidewhetherthecolumnsyou
chooseforindexcreationisagoodcandidateornot.IfyouseeinDB05

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

16/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

morerecordsarehavingrecordcount>10,000thenitisnotagood
candidateforindexcreation.
considerbelowanalysisofBKPFtableonTCODEcolumn,definitelythis
isnotagoodcandidate

Someusefultcodes
DB20
ST04,ST05
SE30
DB05
DB02formissingindexes.
SE14forrecreatingindexes

AlertModerator

3Comments
YoumustbeLoggedontocommentorreplytoapost.
https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

17/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

ChitwanjitSingh
September18,2010at3:43am

HiPhani,

quiteanicearticlestoclearvariousaspectsofqueryperformance
enhancement.
canuprovidedetailsoffieldsinindexesincaseofJOINstatementinthelast
partofyourarticle.
Regards,
Chitwanjit

PhaniKumarPasam Postauthor
September21,2010at4:26am

HiChitwanjit,
AsrequestedIhaveupdatedtheblogwiththedetailsofcolumnsused
intheindex.

AlsoaddedanewsectiononcreatingsecondayindexonDBtables,
checkitout.
Thanks
PhaniPasam

GovardhanReddy
December8,2010at10:34pm

InformativeBlogonperformancetuninganditsexplanatorywhilechoosingthe
candidatesforsecondaryindexinatable.

Share & Follow

Privacy

TermsofUse

LegalDisclosure

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

Copyright

Trademark

Sitemap

Newsletter
18/19

11/9/2016

PerformanceoptimizationofSQLstatementsinABAPSAPBlogs

https://blogs.sap.com/2010/08/24/performanceoptimizationofsqlstatementsinabap/

19/19

Anda mungkin juga menyukai