You are on page 1of 8

Oracle Create Index tips

Oracle Tips by Burleson Consulting

CreatingOracleIndexes
Onceyouhavedecidedyouneedtocreateanindexyouusethecreateindexcommand.
Thecommandisprettystraightforwardasseeninthisexample:
CREATE INDEX
ix_emp_01
ON
emp (deptno)
TABLESPACE
index_tbs;

ThisstatementcreatesanindexcalledIX_EMP_01.ThisindexisbuiltontheDEPTNO
columnoftheEMPtable.Wealsodefinedthetablespacethattheindexshouldbecreated
inusingthetablespacekeyword,inthiscasewecreateditintheINDEX_TBStablespace.
Youcancreateindexesonmultiplecolumnsinatable.Say,forexample,wewantedan
indexontheEMPtablecolumnsEMPNOandDEPTNO.Thisisknownasa
concatenatedindex,anditscreatedthisway:
CREATE INDEX ix_emp_01 ON emp (empno, deptno) TABLESPACE index_tbs;

AlteringOracleIndexes
Ifwecreateindexes,theremaybetimesthatwewillwanttochangesomeattributeof
thatindex,suchaswhereitisstored.Also,sometimesanindexneedstoberebuilttohelp
withperformance.Forcaseslikethese,thealterindexcommandiswhatwewant.
Letslookatanexampleoftheuseofthealterindexcommand:
ALTER INDEX ix_emp_01 REBUILD TABLESPACE new_index;

Inthisexampleweusethealterindexcommandtorebuildanindex.Therebuildkeyword
iswhattellsOracletorebuildtheindex.Whenweusethetablespacekeyword,followed
byatablespacename,wearetellingOraclewhichtablespacetorecreatetherebuiltindex
in.BydefaultOraclewillcreatetherebuiltindexinthesametablespace.
Thealterindexcommandallowsyoutorenameatablespaceusingtherenameto
keywordasseeninthisexample:
ALTER INDEX ix_emp_01 RENAME TO ix_emp_01_old;

Inthiscasewehaverenamedtheix_emp_01indextoix_emp_01_old.Allofthedata
dictionaryentrieswillbechangedbyOracletoreflectthenewname(wewilldiscuss
indexesandthedatadictionaryinamoment)

DroppingOracleIndexes
Sometimeswhatwecreatewemustdestroy.Whenitstimetoremoveanindex,thedrop
indexcommandiswhatisneeded.Thedropindexcommandisprettystraightforwardas
seeninthisexample:
DROP INDEX ix_emp_01_old;

http://stanford.edu/dept/itss/docs/oracle/10g/server.101/b10759/statements_5010.htm

CreatingIndexes
Thissectiondescribeshowtocreateindexes.Tocreateanindexinyourownschema,at
leastoneofthefollowingconditionsmustbetrue:

Thetableorclustertobeindexedisinyourownschema.

YouhaveINDEXprivilegeonthetabletobeindexed.

YouhaveCREATEANYINDEXsystemprivilege.

Tocreateanindexinanotherschema,allofthefollowingconditionsmustbetrue:

YouhaveCREATEANYINDEXsystemprivilege.

Theowneroftheotherschemahasaquotaforthetablespacestocontaintheindex
orindexpartitions,orUNLIMITEDTABLESPACEsystemprivilege.

Thissectioncontainsthefollowingtopics:

CreatinganIndexExplicitly

CreatingaUniqueIndexExplicitly

CreatinganIndexAssociatedwithaConstraint

CollectingIncidentalStatisticswhenCreatinganIndex

CreatingaLargeIndex

CreatinganIndexOnline

CreatingaFunctionBasedIndex

CreatingaKeyCompressedIndex

CreatinganInvisibleIndex

CreatinganIndexExplicitly
Youcancreateindexesexplicitly(outsideofintegrityconstraints)usingtheSQL
statementCREATEINDEX.Thefollowingstatementcreatesanindexnamed
emp_enamefortheenamecolumnoftheemptable:
CREATEINDEXemp_enameONemp(ename)
TABLESPACEusers
STORAGE(INITIAL20K
NEXT20k
PCTINCREASE75);

Noticethatseveralstoragesettingsandatablespaceareexplicitlyspecifiedfortheindex.
Ifyoudonotspecifystorageoptions(suchasINITIALandNEXT)foranindex,the
defaultstorageoptionsofthedefaultorspecifiedtablespaceareautomaticallyused.
SeeAlso:
OracleDatabaseSQLLanguageReferenceforsyntaxandrestrictionsontheuseofthe
CREATEINDEXstatement

CreatingaUniqueIndexExplicitly
Indexescanbeuniqueornonunique.Uniqueindexesguaranteethatnotworowsofa
tablehaveduplicatevaluesinthekeycolumn(orcolumns).Nonuniqueindexesdonot
imposethisrestrictiononthecolumnvalues.
UsetheCREATEUNIQUEINDEXstatementtocreateauniqueindex.Thefollowing
examplecreatesauniqueindex:
CREATEUNIQUEINDEXdept_unique_indexONdept(dname)
TABLESPACEindx;

Alternatively,youcandefineUNIQUEintegrityconstraintsonthedesiredcolumns.The
databaseenforcesUNIQUEintegrityconstraintsbyautomaticallydefiningauniqueindex
ontheuniquekey.Thisisdiscussedinthefollowingsection.However,itisadvisable
thatanyindexthatexistsforqueryperformance,includinguniqueindexes,becreated
explicitly.
SeeAlso:
OracleDatabasePerformanceTuningGuideformoreinformationaboutcreatingan
indexforperformance

CreatinganIndexAssociatedwithaConstraint
OracleDatabaseenforcesaUNIQUEkeyorPRIMARYKEYintegrityconstraintona
tablebycreatingauniqueindexontheuniquekeyorprimarykey.Thisindexis

automaticallycreatedbythedatabasewhentheconstraintisenabled.Noactionis
requiredbyyouwhenyouissuetheCREATETABLEorALTERTABLEstatementto
createtheindex,butyoucanoptionallyspecifyaUSINGINDEXclausetoexercise
controloveritscreation.Thisincludesbothwhenaconstraintisdefinedandenabled,and
whenadefinedbutdisabledconstraintisenabled.
ToenableaUNIQUEorPRIMARYKEYconstraint,thuscreatinganassociatedindex,
theownerofthetablemusthaveaquotaforthetablespaceintendedtocontaintheindex,
ortheUNLIMITEDTABLESPACEsystemprivilege.Theindexassociatedwitha
constraintalwaystakesthenameoftheconstraint,unlessyouoptionallyspecify
otherwise.
Note:
Anefficientprocedureforenablingaconstraintthatcanmakeuseofparallelismis
describedin"EfficientUseofIntegrityConstraints:AProcedure".

SpecifyingStorageOptionsforanIndexAssociatedwithaConstraint
YoucansetthestorageoptionsfortheindexesassociatedwithUNIQUEandPRIMARY
KEYconstraintsusingtheUSINGINDEXclause.ThefollowingCREATETABLE
statementenablesaPRIMARYKEYconstraintandspecifiesthestorageoptionsofthe
associatedindex:
CREATETABLEemp(
empnoNUMBER(5)PRIMARYKEY,ageINTEGER)
ENABLEPRIMARYKEYUSINGINDEX
TABLESPACEusers;

SpecifyingtheIndexAssociatedwithaConstraint
IfyourequiremoreexplicitcontrolovertheindexesassociatedwithUNIQUEand
PRIMARYKEYconstraints,thedatabaseletsyou:

Specifyanexistingindexthatthedatabaseistousetoenforcetheconstraint

SpecifyaCREATEINDEXstatementthatthedatabaseistousetocreatetheindex
andenforcetheconstraint

TheseoptionsarespecifiedusingtheUSINGINDEXclause.Thefollowingstatements
presentsomeexamples.
Example1:
CREATETABLEa(
a1INTPRIMARYKEYUSINGINDEX(createindexaiona(a1)));

Example2:
CREATETABLEb(
b1INT,

b2INT,
CONSTRAINTbu1UNIQUE(b1,b2)
USINGINDEX(createuniqueindexbionb(b1,b2)),
CONSTRAINTbu2UNIQUE(b2,b1)USINGINDEXbi);

Example3:
CREATETABLEc(c1INT,c2INT);
CREATEINDEXciONc(c1,c2);
ALTERTABLEcADDCONSTRAINTcpkPRIMARYKEY(c1)USINGINDEXci;

Ifasinglestatementcreatesanindexwithoneconstraintandalsousesthatindexfor
anotherconstraint,thesystemwillattempttorearrangetheclausestocreatetheindex
beforereusingit.
SeeAlso:
"ManagingIntegrityConstraints"

CollectingIncidentalStatisticswhenCreatinganIndex
OracleDatabaseprovidesyouwiththeopportunitytocollectstatisticsatverylittle
resourcecostduringthecreationorrebuildingofanindex.Thesestatisticsarestoredin
thedatadictionaryforongoingusebytheoptimizerinchoosingaplanfortheexecution
ofSQLstatements.Thefollowingstatementcomputesindex,table,andcolumnstatistics
whilebuildingindexemp_enameoncolumnenameoftableemp:
CREATEINDEXemp_enameONemp(ename)
COMPUTESTATISTICS;

SeeAlso:

OracleDatabasePerformanceTuningGuideforinformationaboutcollecting
statisticsandtheirusebytheoptimizer

"AnalyzingTables,Indexes,andClusters"

CreatingaLargeIndex
Whencreatinganextremelylargeindex,considerallocatingalargertemporary
tablespacefortheindexcreationusingthefollowingprocedure:
1. CreateanewtemporarytablespaceusingtheCREATETABLESPACEor
CREATETEMPORARYTABLESPACEstatement.
2. UsetheTEMPORARYTABLESPACEoptionoftheALTERUSERstatementto
makethisyournewtemporarytablespace.
3. CreatetheindexusingtheCREATEINDEXstatement.
4. DropthistablespaceusingtheDROPTABLESPACEstatement.Thenusethe

ALTERUSERstatementtoresetyourtemporarytablespacetoyouroriginal
temporarytablespace.
Usingthisprocedurecanavoidtheproblemofexpandingyourusual,andusuallyshared,
temporarytablespacetoanunreasonablylargesizethatmightaffectfutureperformance.

CreatinganIndexOnline
Youcancreateandrebuildindexesonline.Thisenablesyoutoupdatebasetablesatthe
sametimeyouarebuildingorrebuildingindexesonthattable.YoucanperformDML
operationswhiletheindexbuildistakingplace,butDDLoperationsarenotallowed.
Parallelexecutionisnotsupportedwhencreatingorrebuildinganindexonline.
Thefollowingstatementsillustrateonlineindexbuildoperations:
CREATEINDEXemp_nameONemp(mgr,emp1,emp2,emp3)ONLINE;

Note:
Keepinmindthatthetimethatittakesononlineindexbuildtocompleteisproportional
tothesizeofthetableandthenumberofconcurrentlyexecutingDMLstatements.
Therefore,itisbesttostartonlineindexbuildswhenDMLactivityislow.
SeeAlso:
"RebuildinganExistingIndex"

CreatingaFunctionBasedIndex
Functionbasedindexesfacilitatequeriesthatqualifyavaluereturnedbyafunctionor
expression.Thevalueofthefunctionorexpressionisprecomputedandstoredinthe
index.
Inadditiontotheprerequisitesforcreatingaconventionalindex,iftheindexisbasedon
userdefinedfunctions,thenthosefunctionsmustbemarkedDETERMINISTIC.Also,
youjusthavetheEXECUTEobjectprivilegeonanyuserdefinedfunction(s)usedinthe
functionbasedindexifthosefunctionsareownedbyanotheruser.
Additionally,touseafunctionbasedindex:

Thetablemustbeanalyzedaftertheindexiscreated.

ThequerymustbeguaranteednottoneedanyNULLvaluesfromtheindexed
expression,sinceNULLvaluesarenotstoredinindexes.
Note:
CREATEINDEXstoresthetimestampofthemostrecentfunctionusedinthe
functionbasedindex.Thistimestampisupdatedwhentheindexisvalidated.
Whenperformingtablespacepointintimerecoveryofafunctionbasedindex,if

thetimestamponthemostrecentfunctionusedintheindexisnewerthanthe
timestampstoredintheindex,thentheindexismarkedinvalid.Youmustusethe
ANALYZEINDEX...VALIDATESTRUCTUREstatementtovalidatethis
index.
Toillustrateafunctionbasedindex,considerthefollowingstatementthatdefinesa
functionbasedindex(area_index)definedonthefunctionarea(geo):
CREATEINDEXarea_indexONrivers(area(geo));

InthefollowingSQLstatement,whenarea(geo)isreferencedintheWHEREclause,
theoptimizerconsidersusingtheindexarea_index.
SELECTid,geo,area(geo),desc
FROMrivers
WHEREArea(geo)>5000;

TableownersshouldhaveEXECUTEprivilegesonthefunctionsusedinfunctionbased
indexes.
Becauseafunctionbasedindexdependsuponanyfunctionitisusing,itcanbe
invalidatedwhenafunctionchanges.Ifthefunctionisvalid,youcanuseanALTER
INDEX...ENABLEstatementtoenableafunctionbasedindexthathasbeendisabled.
TheALTERINDEX...DISABLEstatementletsyoudisabletheuseofafunctionbased
index.Considerdoingthisifyouareworkingonthebodyofthefunction.
Note:
Analternativetocreatingafunctionbasedindexistoaddavirtualcolumntothetarget
tableandindexthevirtualcolumn.See"AboutTables"formoreinformation.
SeeAlso:

OracleDatabaseConceptsformoreinformationaboutfunctionbasedindexes

OracleDatabaseAdvancedApplicationDeveloper'sGuideforinformationabout
usingfunctionbasedindexesinapplicationsandexamplesoftheiruse

CreatingaKeyCompressedIndex
Creatinganindexusingkeycompressionenablesyoutoeliminaterepeatedoccurrences
ofkeycolumnprefixvalues.
Keycompressionbreaksanindexkeyintoaprefixandasuffixentry.Compressionis
achievedbysharingtheprefixentriesamongallthesuffixentriesinanindexblock.This
sharingcanleadtohugesavingsinspace,allowingyoutostoremorekeysforeachindex
blockwhileimprovingperformance.
Keycompressioncanbeusefulinthefollowingsituations:

YouhaveanonuniqueindexwhereROWIDisappendedtomakethekeyunique.
Ifyouusekeycompressionhere,theduplicatekeyisstoredasaprefixentryon

theindexblockwithouttheROWID.Theremainingrowsbecomesuffixentries
consistingofonlytheROWID.

Youhaveauniquemulticolumnindex.

YouenablekeycompressionusingtheCOMPRESSclause.Theprefixlength(asthe
numberofkeycolumns)canalsobespecifiedtoidentifyhowthekeycolumnsare
brokenintoaprefixandsuffixentry.Forexample,thefollowingstatementcompresses
duplicateoccurrencesofakeyintheindexleafblock:
CREATEINDEXemp_enameONemp(ename)
TABLESPACEusers
COMPRESS1;

TheCOMPRESSclausecanalsobespecifiedduringrebuild.Forexample,duringrebuild
youcandisablecompressionasfollows:
ALTERINDEXemp_enameREBUILDNOCOMPRESS;

SeeAlso:
OracleDatabaseConceptsforamoredetaileddiscussionofkeycompression

CreatinganInvisibleIndex
BeginningwithRelease11g,youcancreateinvisibleindexes.Aninvisibleindexisan
indexthatisignoredbytheoptimizerunlessyouexplicitlysetthe
OPTIMIZER_USE_INVISIBLE_INDEXESinitializationparametertoTRUEatthe
sessionorsystemlevel.Makinganindexinvisibleisanalternativetomakingitunusable
ordroppingit.Usinginvisibleindexes,youcandothefollowing:

Testtheremovalofanindexbeforedroppingit.

Usetemporaryindexstructuresforcertainoperationsormodulesofanapplication
withoutaffectingtheoverallapplication.

Unlikeunusableindexes,aninvisibleindexismaintainedduringDMLstatements.
Tocreateaninvisibleindex,usetheSQLstatementCREATEINDEXwiththe
INVISIBLEclause.Thefollowingstatementcreatesaninvisibleindexnamed
emp_enamefortheenamecolumnoftheemptable:
CREATEINDEXemp_enameONemp(ename)
TABLESPACEusers
STORAGE(INITIAL20K
NEXT20k
PCTINCREASE75)
INVISIBLE;

You might also like