Vous êtes sur la page 1sur 40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Oracle SQL by Example, Fourth Edition

NEXT

PREV

Chapter 12. Create, Alter, and ...

Chapter 14. The Data Dictiona...

Enjoy Safari? Subscribe Today

Chapter 13. Indexes, Sequences, and Views

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

1/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Chapter 13. Indexes, Sequences, and Views

CHA P TE ROB J E CTIV E S


Inthischapter,youwilllearnabout:
Indexes
Sequences
Views

Thischaptercoversthreedifferentyetveryimportantdatabaseobjects:
indexes,sequences,andviews.Indexesarerequiredforgood
performanceofanydatabase.Awellthoughtoutindexingstrategy
entailsthecarefulplacementofindexesonrelevantcolumns.Inthis
chapter,youwillgainanunderstandingabouttheadvantagesandtrade
offswhenusingindexesontables.
Sequencesgenerateuniquevaluesandareusedmainlyforcreating
primarykeyvalues.Inthischapter,youwilllearnhowtocreateanduse
sequences.
Viewsaresignificantinadatabasebecausetheycanproviderowlevel
andcolumnlevelsecuritytothedatatheyallowyoutolookatthedata
differentlyand/ordisplayonlyspecificinformationtotheuser.Views
arealsousefulforsimplifyingthewritingofqueriesforendusers
becausetheycanhidethecomplexitiesofjoinsandconditional
statements.

LAB 13.1 INDEXES

LA B OB J E CTIV E S
Afterthislab,youwillbeableto:
CreateIndexes
UnderstandtheImpactofIndexes

Toachievegoodperformancefordataretrievalanddatamanipulation
statements,youneedtounderstandOraclesuseofindexes.Justasyou
usetheindexinthebackofabooktoquicklyfindinformation,Oracle
usesindexestospeedupdataretrieval.Iftheappropriateindexdoesnot
existonatable,Oracleneedstoexamineeveryrow.Thisiscalledafull
tablescan.
Ifanindexdecreasesquerytime,whynotjustindexeverycolumnina
table?Whenyouretrievealargenumberofrowsinatable,itmightbe
moreefficienttoreadtheentiretableratherthanlookupthevaluesfrom
theindex.Italsotakesasignificantamountoftimeandstoragespaceto
buildandmaintainanindex.ForeachDMLstatementthatchangesa
valueinanindexedcolumn,theindexneedstobemaintained.

The B-Tree Index

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

2/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Inthisbook,youwillperformexercisesrelatedtoOraclesmostpopular
indexstoragestructuretheBtreeindex.Themeritsandusesofanother
typeofindex,thebitmapindex,arediscussedbrieflyattheendofthelab
thistypeofindexcanbecreatedonlyinOraclesEnterpriseServer
Edition.
TheBtree(balancedtree)indexisbyfarthemostcommontypeofindex.
Itprovidesexcellentperformanceincircumstancesinwhichthereare
manydistinctvaluesonacolumnorcolumns.Ifyouhaveseverallow
selectivitycolumns,youcanalsoconsidercombiningthemintoone
compositeindex,alsocalledaconcatenatedindex.Btreeindexesarebest
forexactmatchandrangesearchesagainstbothsmallandverylarge
tables.
Figure13.1showsthestructureofaBtreeindex.Itlookslikeaninverted
treeandconsistsoftwotypesofblocks:root/branchblocksandleaf
blocks.Rootorbranchblocksareusedforstoringthekeytogetherwitha
pointertothechildblockcontainingthekeyleafblocksstorethekey
valuesalongwiththeROWID,whichisthephysicalstoragelocationfor
thedatainthetable.
Figure13.1Btreeindex

Searching for Values in a B-Tree Index

ThefirststepinsearchingforvaluesinaBtreeindexistostartwiththe
rootblockoftheindex.Thesearchedvalueiscomparedwiththeroot
blockkeys.Forexample,ifyouarelookingforastudentwiththelast
nameEssner,youmustgodowntherootblock<L.Thisblockpointsto
thenextleafblocks,whicharegreaterthanDaandlessthanJigoing
downonthisleafblock,youfindthevalueEssnerandtheassociated
ROWID,thephysicaladdressoftherow.Aleafblockalsocontainslinks
tothenextandpreviousleafblocks,whichallowscanningtheindexfor
ranges.
The ROWID Pseudocolumn

Apseudocolumnisnotanactualcolumn,butitactslikeone.Oneofthe
pseudocolumnsyouhavealreadyusedisROWNUM,whichrestrictsthe
numberofrowsaqueryreturns.TheROWIDpseudocolumnisaunique
addresstoaparticularrow,andeveryrowhasaROWID.
IndexesstoretheROWIDtoretrieverowsquicklybecausetheROWID
consistsofseveralcomponents:thedataobjectnumber,thenumberof
thedatablock,thenumberofrowswithinthedatablock,andthedatafile

Enjoy Safari? Subscribe Today

number.Thedatablockandthedatafiledefinethephysicalstorage
characteristicsofdatawithintheindividualOracledatabase.Thisallows

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

3/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

youtoquicklyaccessthephysicalrow.Followingisanexampleofa
ROWIDvalue.

AROWIDisalwaysunique.Itisthefastestwaytoaccessa
row.

RatherthanmakeOraclesearchthroughtheindex,youcanusethe
ROWIDinUPDATEstatementstodirectlyaccesstherow.Forexample,
becausetheROWIDofthestudentnamedRadicolaisalreadyselectedas
partofthequery,asubsequentupdatetothenameofthestudentcanfind
therowinthetableimmediately,withouthavingtoscantheentiretable
oruseanindex.

YoucannotupdatetheROWID,buttheROWIDmaychangeifyoufirst
deletetherowandthenreinserttherowbecauseitcannowbeplacedin
anotherphysicallocation.Ifyourtablemovestoanotherdatabase
instanceoranotherschema,theROWIDwillbedifferent.
AsyoulearnedinChapter11,Insert,Update,andDelete,itisalways
goodpracticetoincludetheoldvaluesintheWHEREclauseofUPDATE
toensurethatanothersessionoruserhasnotchangedthenameinthe
meantime.

Creating an Index
Youcreateanindexbyusingthefollowinggeneralsyntax.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

4/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

ThefollowingstatementcreatesanindexnamedSECT_LOCATION_I
ontheLOCATIONcolumnoftheSECTIONtable.

AsubsequentquerytofindalltheclassesheldinLOCATIONL206can
takeadvantageofthisindex.Oraclelooksupthevalueintheindex.This
retrievestherowfasterthanreadingeveryrow,particularlyifthetable
hasmanyrecords.

Composite Indexes
Sometimes,itisusefultobuildindexesbasedonmultiplecolumnsthis
typeofindexiscalledacompositeindex,orconcatenatedindex.For
example,youcancreateacompositeindexontwocolumnswithalow
selectivity(thatis,notmanydistinctvalues).Thecombinationofthese
lowselectivityvaluesmakesthecompositeindexmoreselective.When
youcomparethequeryaccesstimeofacompositeindextothatoftwo
individualsinglecolumnindexes,youfindthatthecompositeindex
offersbetterperformance.
Thefollowingstatementcreatesacompositeindexonthecolumns
DESCRIPTIONandCOST.Thefirstcolumnoftheindex,alsocalledthe
leadingedgeoftheindex,istheDESCRIPTIONcolumnthesecond
columnoftheindexistheCOSTcolumn.
CREATEINDEXcourse_description_cost_i
ONcourse(description,cost)
ColumnsthatareusedtogetherfrequentlyinaWHEREclauseand
combinedwiththeANDlogicaloperatorareoftengoodcandidatesfora
compositeindex,particularlyiftheircombinedselectivityishigh.The
orderoftheindividualcolumnsintheindexcanaffectquery
performance.ChoosethecolumnyouusemostfrequentlyintheWHERE
clausefirst.Ifbothcolumnsareaccessedwithequalfrequency,then
choosethecolumnwiththehighestselectivity.Inthisexample,theCOST
columnhasveryfewdistinctvaluesandisthereforeconsideredalow
selectivitycolumnaccessagainstanindexwithalowselectivitycolumn
astheleadingedgerequiresmoreindexblockreadsandisthereforeless
desirable.
Therearesomecaveatsaboutcompositeindexesyoumustknowabout
whenwritingqueries.WhenexecutedinOracleversionspriorto9i,a
querysuchasthefollowing,usingtheCOSTcolumnintheWHERE
clause,cannotusetheCOURSE_DESCRIPTION_COST_Iindexbecause
itisnottheleadingedgeoftheindex.

Enjoy Safari? Subscribe Today

However,Oraclecanuseatechniquecalledskipscan,whichmayusethe
indexnonetheless.Asyouworkyourwaythroughthislab,youwilllearn

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

5/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

moreaboutthisfeature.
Tofindoutwhatcolumnsofatableareindexedandtheorderofthe
columnsinanindex,youcanquerythedatadictionaryviews
USER_INDEXESandUSER_IND_COLUMNSorreviewtheIndexestab
inSQLDeveloperfortherespectivetable.

NULLs and Indexes


NULLvaluesarenotstoredinaBtreeindex,unlessitisacomposite
indexwhereatleastthefirstcolumnoftheindexcontainsavalue.The
followingquerydoesnotmakeuseofthesinglecolumnindexonthe
FIRST_NAMEcolumn.

Functions and Indexes


Evenwhenyoucreateanindexononeormultiplecolumnsofatable,
Oraclemaynotbeabletouseit.Inthenextscenario,assumethatthe
LAST_NAMEcolumnoftheSTUDENTtableisindexed.Thefollowing
SQLqueryappliestheUPPERfunctionontheLAST_NAMEcolumn.You
canusethisWHEREclauseexpressionifyoudontknowhowthelast
nameisstoredinthecolumnitmaybestoredwiththefirstinitialin
uppercase,inalluppercase,orperhapsinmixedcase.Thisquerydoes
nottakeadvantageoftheindexbecausethecolumnismodifiedbya
function.

Youcanavoidthisbehaviorbycreatingafunctionbasedindexinstead,
asinthefollowingexample.Thisallowsforcaseinsensitivesearcheson
theLAST_NAMEcolumn.
CREATEINDEXstud_last_name_i
ONstudent(UPPER(last_name))

Indexes and Tablespaces


Tooptimizeperformance,itisimportantthatyouseparateindexesfrom
databyplacingtheminseparatetablespaces,residingondifferent
physicaldevices.Thissignificantlyimprovestheperformanceofyour
queries.Usethefollowingstatementtocreateanindexnamed
SECT_LOCATION_IonatablespacecalledINDEX_TX,withaninitial
sizeof500Kand100Kinsizeforeachsubsequentextent.

Thestorageclauseofindexesissimilartothestorageclausediscussedin
Chapter12,Create,Alter,andDropTableshowever,thePCTUSED
parameterisnotapplicableforindexes.Ifyouwanttoseealistof
tablespacesaccessibletoyou,querythedatadictionaryview
USER_TABLESPACES.

Enjoy Safari? Subscribe Today

Unique Index Versus Unique Constraint

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

6/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Attimesyoumightwanttoenforceauniquecombinationofthevaluesin
atable(forexample,theCOURSE_NOandSECTION_NOcolumnsofthe
SECTIONtable).Youcancreateauniqueconstraintonthetablethat
automaticallycreatesauniqueindex.

OryoucanusetheCREATEUNIQUEINDEXcommand.

Oracleprefersthatyouusetheuniqueconstraintsyntaxforfuture
compatibility.

Indexes and Constraints


Whenyoucreateaprimarykeyconstraintorauniqueconstraint,Oracle
createstheindexautomaticallyunlessasuitableindexalreadyexists.In
Chapter12,youlearnedaboutvarioussyntaxoptionsyoucanuse.
TheindexNEW_TERM_PKiscreatedaspartoftheCREATETABLE
statementandisassociatedwiththeprimarykeyconstraint.

Theadvantageofusingthissyntaxisthatyoucancreateanindexinthe
samestatementoftheCREATETABLEcommand,wherebyyouhave
controloverthestoragecharacteristicsoftheindex.Itdoesntrequire
twoseparatestatements:aCREATETABLEstatementandanALTER
TABLEstatementthataddstheconstraintandtheindexplusstorage
clause.
Ifyoualreadyhaveanexistingindexandyouwanttoassociatea
constraintwithit,youcanuseastatementsimilartothefollowing.It
assumesanexistingindexcalledSEMESTER_SEMESTER_ID_I,based
ontheSEMESTER_IDcolumn.

Thenextstatementshowsanexampleofauniqueconstraintthatis
associatedwithauniqueindex.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

7/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Whendisablingauniqueorprimarykey,youcankeepthe
indexifyouspecifytheKEEPINDEXclauseinanALTER
TABLEstatement(seeChapter12).

Indexes and Foreign Keys


Youshouldalmostalwaysindexforeignkeysbecausetheyarefrequently
usedinjoins.Inaddition,ifyouintendtodeleteorupdateuniqueor
primarykeysontheparenttable,youshouldindextheforeignkeysto
improvethelockingofchildrecords.Foreignkeysthatarenotindexed
requirelockstobeplacedontheentirechildtablewhenaparentrowis
deletedortheprimaryoruniquekeysoftheparenttableareupdated.
Thispreventsanyinsertions,updates,anddeletionsontheentirechild
tableuntiltherowiscommittedorrolledback.Theadvantageofan
indexontheforeignkeycolumnisthatthelocksareplacedonthe
affectedindexedchildrows,thusnotlockinguptheentirechildtable.
Thisismoreefficientandallowsdatamanipulationofchildrowsnot
affectedbytheupdatesanddeletionsoftheparenttable.
Thiskeyissuehascausedheadachesformanyunwittingprogrammers
whospentdaysreviewingtheircodeforperformanceimprovements.The
lackofaforeignindexkeyfrequentlyturnsouttobetheculpritforthe
slowperformanceofupdatesanddeletions.

Dropping an Index
Todropanindex,usetheDROPINDEXcommand.Youmightdropan
indexifqueriesinyourapplicationsdonotutilizetheindex.Youfindout
whichindexesareusedbyqueryingtheV$OBJECT_USAGEdata
dictionaryview.
DROPINDEXsect_location_i
Indexdropped.

Whenyoudropatable,allassociatedindexesaredropped
automatically.

Bitmap Indexes
Oraclesupportsbitmapindexes,whicharetypicallyusedinadata
warehousewheretheprimarygoalisqueryingandanalyzingdata,with
bulkdataloadsoccurringatcertainintervals.Bitmapindexesarenot
suitablefortableswithheavydatamanipulationactivitybymanyusers
becauseanysuchchangesonthistypeofindexmaysignificantlyslow
downthetransactions.Abitmapindexistypicallyusedoncolumnswitha
verylowselectivitythatis,columnswithveryfewdistinctvalues.For
example,acolumnsuchasGENDERwiththefourdistinctvalues

Enjoy Safari? Subscribe Today

female,male,unknown,andnotapplicable(incaseofalegalentitysuch
asacorporation)hasaverylowselectivity.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

8/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Alowselectivityisexpressedasthenumberofdistinctvaluesasatotal
againstalltherowsinthedatabase.Forexample,ifyouhad9,000
distinctvaluesinatablewithonemillionrows,itwouldbeconsidereda
lowselectivitycolumn.Inthisscenario,thenumberofdistinctvalues
representslessthan1percentoftheentirerowsinthetable,andthis
columnmaybeaviablecolumnchoiceforabitmapindex.
Figure13.2illustratestheconceptofabitmapindex.Theexampleshows
ahypotheticalCUSTOMERtablewithabitmapindexontheGENDER
column.ThebitmapindextranslatesthedistinctvaluesfortheGENDER
columnofindividualcustomers.Inthissimplifiedexample,the
customerswiththeIDs1and2haveGENDER=F,whichmakesthebit
turnedonto1.Theothervalues,suchasGENDER=M,GENDER=N/A,
andGENDER=UNKNOWN,havea0,indicatingthatthesevaluesare
nottruefortherow.Thenextcustomer,withtheIDof3,hasthe1bit
turnedonGENDER=M,theothervaluesarezero.
Figure13.2Abitmapindex

ThefollowingstatementcreatesabitmapindexontheGENDERcolumn
ofaCUSTOMERtable.
CREATEBITMAPINDEXcustomer_bm_gender_i
ONcustomer(gender)
Ifyouhavemultiplebitmapindexes,suchasoneforGENDER,
MARITALSTATUS,andZIP,andyouneedtoretrieverowsbasedon
certainANDandORconditions,thenbitmapindexesperformveryfast.
Theyquicklycompareandmergethebitsettingsoftheseconditionsand
arethereforehighlyeffectiveforlargetables.Bitmapindexesrequire
lessstoragespacethantraditionalBtreeindexes,buttheydonot
performaswellforlessthanorgreaterthancomparisons.Bitmap
indexesareavailableonlywithOraclesEnterpriseEdition.

Bitmap Join Indexes


Thebitmapjoinindexisanothertypeofindexthatreducestheamountof
datatobejoinedduringaquery.Essentially,itprecomputesthejoinand
storestheresultinabitmapthistypeofindexisusefulindata
warehousingenvironments.Thefollowingstatementshowsthecreation
ofsuchanindex.

Guidelines for When to Index

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

9/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

YouwanttoconsiderindexingcolumnsfrequentlyusedintheWHERE
clauseofSQLstatementsandforeignkeycolumns.Oracleautomatically
createsauniqueindextoenforcetheprimarykeyconstraintandthe
uniqueconstraint.Thefollowingaresomegeneralguidelineswhenan
indexistypicallyuseful.
FrequentlyaccessedcolumnscontaininghighlyselectivedataforBtree
indexes.
Columnsfrequentlyaccessedwithasmallrangeofvaluesforbitmap
indexes.
Columnsthatarefrequentlyaccessedandthatcontainmanynull
values,butthequeryislookingfortheNOTNULLvalues.
Frequentqueriesagainstlargetablesretrievinglessthan5to15
percentoftherows.Thepercentagemayvary,dependingonanumberof
factors,includingthesizeofthetable.
Buildinganindexisoftenuselessif:
Thetableissmall,butyoushouldneverthelesscreateuniqueand
primaryconstraintstoenforcebusinessrules.
Thequeryretrievesmorethan5to15percentoftherows.
Theindexedcolumnispartofanexpression.Inthiscase,consider
creatingafunctionbasedindexinstead.
InChapter18,SQLOptimization,youlllearntoverifythatSQL
statementsissuedactuallyuseanindex.
Althoughaddingindexesmayimproveperformanceofcertainqueries,
youmustrealizethatOraclemayusethisnewindexforotherqueriesthat
previouslyusedadifferentindex.Thisrarelyhasanadverseeffect,but
youmustneverthelessmakecertainthatyouroverallapplication
performancedoesnotsufferbecauseofthischange.
Keepinmindthataddingindexesmayincreasethetimerequiredfor
datamanipulationoperations,suchasINSERT,UPDATE,andDELETE.
Ifyouprimarilyquerythetable,thencreatingtheindexmayoffsetthe
disadvantageofadditionaltimerequiredforDMLstatements.

Altering an Index
Anumberofsyntaxoptionsletyouchangevariouscharacteristicsofan
index,suchasrenamingorrebuildingtheindexoralteringthestorage
clause.Thefollowingaresomeofthegeneralsyntaxoptions.

ThefollowingSQLstatementshowstherebuildofanindex.Periodically,
youneedtorebuildanindextocompactthedataandbalancetheindex
tree.Thisisparticularlyimportantafterdataissubjecttoalargenumber
ofDMLchangestherebuildoperationwillimprovetheperformanceof
thequeries.UsingtheindexREBUILDoptionisfasterthandroppingand
recreatingtheindexfurthermore,theindexcontinuestobeavailable

Enjoy Safari? Subscribe Today

forquerieswhiletheREBUILDoperationisinprogress.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

10/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

ALTERINDEXstu_zip_fk_iREBUILD
Indexaltered.
BecauseaDDLcommandrequiresexclusiveaccesstothetableorindex,
othersessionsissuinganyDMLcommandspreventsuchchanges.
Therefore,datastructurechangesareusuallyperformedduringtimes
whenusersarenotaccessingthesystem.However,youcancreateor
rebuildindexeswiththeONLINEoptionwhileusersareperforming
DMLcommands.
ALTERINDEXstu_zip_fk_iREBUILDONLINE

Invisible Indexes
Oracle11gaddedtheabilitytomakeanindexinvisible.TheOracle
optimizer,whichevaluatesthebestandmostefficientaccesspathfora
SQLstatement,ignorestheindex.Thisfeaturemaycomeinhandyifyou
considerremovingapossiblyunusedindexwithoutdroppingittoensure
thatthereisnotanadverseimpactonyourapplication.Ifitturnsoutthat
theindexisrequiredafterall,itiseasytomaketheindexvisibleagain
withouthavingtospendtimeandcomputingresourcestorecreateit.
Anotherpossibleuseofthisfeatureiswhenyouwanttousetheindex
onlyforcertainapplicationsthatfindthisindexuseful.These
applicationscanexecuteanALTERSESSIONcommandandmakethe
indexvisible.
ALTERSESSION
SETOPTIMIZER_USE_INVISIBLE_INDEXES=TRUE
Althoughtheindexmaybeinvisibletousers,DMLoperationsstillhave
tomaintaintheinvisibleindex.Theindexstillremainshowever,the
indexisnolongerusedbyOraclesoptimizer.
Tochangethevisibilityonanindex,usethefollowingsyntax.
ALTERINDEXindexnameINVISIBLE
ALTERINDEXindexnameVISIBLE
Youcanalsocreateanindexasinvisible.
CREATEINDEXindexname
ONtablename(columnname)INVISIBLE

Loading Large Amounts of Data


Whenyouinsertorupdatelargeamountsofdata,youmightwantto
considerdroppingcertainindexesnotusedfortheDMLoperations
WHEREclausetoimproveperformance.Aftertheoperationiscomplete,
youcanrecreatetheappropriateindexes.
OnefastwaytorecreateindexesisbyusingtheNOLOGGINGoption.It
avoidswritingtotheredolog,whichkeepstrackofallthedatabase
changes.Ifyouincurafataldatabaseerrorandyouneedtorecoverfrom
theredolog,theindexwillnotberecovered.Thismaybefinebecausean
indexcanalwaysberecreated.
YoucanalsocreateanindexbyusingthePARALLELoption.Thisallows
parallelscansofthetabletocreatetheindexandcanmakeindex
creationmuchfaster,providedthatyouhavetheappropriatehardware
configuration,suchasmultipleCPUs.

Enjoy Safari? Subscribe Today

Indexes and SQL Developer

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

11/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

SQLDeveloperallowsyoutoeasilydeterminetheexistingindexesand
theirindexedcolumnsonagiventable.Whenyoudoubleclickoneofthe
tablesandreviewtheIndexestab,youseealistsimilartotheoneshown
inFigure13.3.Thisexampleshowsalistofindexesforthe
ENROLLMENTtable.Thetabledisplaystheprimarykeyindex
consistingofthetwocolumns.ThesecondindexisontheSECTION_ID
column,whichisaforeignkeycolumn.
Figure13.3ListofindexesfortheENROLLMENTtable

AnotherwaytoaccessindexinformationinSQLDeveloperistousethe
IndexesnodeintheConnectionspane.Tocreateanewindexyouright
clickontheIndexesnodeandselecttheNewIndexmenuchoice.This
willbringupascreensimilartoFigure13.4.Youchoosetheindexed
columnsatthebottomofthescreen.TheOrderdropdownboxonthe
rightofthecolumnnameorexpressionallowsforASCorDESCordering
ofthecolumnswithintheindex.Thiscanbeusefulwhenyouexpectto
retrievetheresultcolumnsinthisorder.
Figure13.4CreateIndexscreeninSQLDeveloper

YoucanfindanumberofdifferentindexoptionsbyusingSQL
Developersmenuscreenswhenyourightclickonaspecificindex(see
Figure13.5).
Figure13.5Menuoptionsforanindex

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

12/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Table13.1highlightsthefunctionalityandpurposeofeachmenuoption.
Table13.1OverviewofSQLDeveloperIndexRelatedMenu
Choices

Indexes and Statistics


TheOracleoptimizermakesadeterminationonhowtoexecuteyourSQL
statement.Ifanindexexists,theoptimizerevaluateswhethertheindex
isusefulinachievinggoodperformance.Becausetherearesomany
variableswhendetermininghowtobestprocessaSQLstatement,the
Oracleoptimizerreliesonstatisticsaboutthetablesandindexes,suchas
thenumberofrowsandthenumberofdistinctcolumnvalues,among
othervariables.
Thesestatisticsneedtobeupdatedperiodicallytoensuregoodjudgment
bytheoptimizer.WithOracleversion10gandabove,whenyoucreatean
index,Oracleautomaticallycollectsthestatistics.Youcanseethe
informationintheStatisticstabofthegivenindexwithinSQLDeveloper
(seeFigure13.6).
Figure13.6TheStatisticstabfortheSECT_LOCATION_Iindex
inSQLDeveloper

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

13/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

TheIndexDetailstabismuchliketheDetailstabforatable.Onit,you
findinformationsuchasthestorageparameters,thedatecreated,and
thedatetheindexwaslastanalyzedthistabprimarilyreflectsdatafrom
thedatadictionaryviewALL_INDEXES.
ThePartitionstabshowswhethertheindexissplitintomultiple
partitionsthatcanbemanagedindependently.Indexandtable
partitioningareusefulforlargescaledatabases.

Lab 13.1 Exercises


a )CreateanindexonthePHONEcolumnoftheSTUDENTtable.
DroptheindexafteryousuccessfullycreateittoreturntheSTUDENT
schematoitsoriginalstate.

b )CreateacompositeindexontheFIRST_NAMEandLAST_NAME
columnsoftheSTUDENTtable.Droptheindexwhenyouhavefinished.

c )CreateanindexontheDESCRIPTIONcolumnoftheCOURSE
table.NotethatqueriesagainstthetableoftenusetheUPPERfunction.
Droptheindexafteryousuccessfullycreateit.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

14/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

d )ExecutethefollowingSQLstatements.Explainthereasonforthe
error.

e )WouldaBtreeindexworkonafrequentlyaccessedcolumnwith
fewdistinctvalues?Explain.

f )Listtheadvantagesanddisadvantagesofindexesonperformance.

g )AssumethatanindexexistsonthecolumnENROLL_DATEinthe
ENROLLMENTtable.Changethefollowingquerysoitusesthatindex.

Lab 13.1 Exercise Answers


a )CreateanindexonthePHONEcolumnoftheSTUDENTtable.
DroptheindexafteryousuccessfullycreateittoreturntheSTUDENT
schematoitsoriginalstate.
ANSWER:Tocreatetheindexonthetable,issueaCREATEINDEX
statement.

Includethenameofthetableandtheindexedcolumn(s)intheindex
namethisconventionallowseasieridentificationofindexesandtheir
respectivecolumnsinaparticulartable.Asalways,youcanuseSQL
Developertoreviewtheindexlistingsorquerythedatadictionaryviews
USER_INDEXESandUSER_IND_COLUMNS.Rememberthatno
databaseobjectsname,suchasanindex,cannotbelongerthan30
characters.
Todroptheindex,simplyissuetheDROPINDEXcommand.
DROPINDEXstu_phone_i
Indexdropped.

b )CreateacompositeindexontheFIRST_NAMEandLAST_NAME
columnsoftheSTUDENTtable.Droptheindexwhenyouhavefinished.
ANSWER:Therearetwopossiblesolutionsforcreatingacomposite
indexusingtheFIRST_NAMEandLAST_NAMEcolumns.
Acomposite,orconcatenated,indexisanindexthatconsistsofmore
thanonecolumn.Dependingonhowyouaccessthetable,youneedto
orderthecolumnsintheindexaccordingly.

Enjoy Safari? Subscribe Today

Todeterminethebestcolumnorderintheindex,determinethe

selectivityofeachcolumn.Thismeansdetermininghowmanydistinct

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

15/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

valueseachcolumnhas.Youalsoneedtodeterminewhattypesofqueries
towriteagainstthetable.Allthisinformationhelpsyouchoosethebest
columnorderfortheindex.
Solution 1

TheindexiscreatedintheorderFIRST_NAME,LAST_NAME.
CREATEINDEXstu_first_last_name_i
ONstudent(first_name,last_name)
ThisindexisusedinaSQLstatementifyoureferintheWHEREclause
toeitherbothcolumnsortheFIRST_NAMEcolumn.Oraclecanaccess
theindexiftheWHEREclauseliststheleadingcolumnoftheindex.The
leadingcolumn,alsocalledtheleadingedge,oftheaforementioned
indexistheFIRST_NAMEcolumn.IftheWHEREclauseofaSQL
statementlistsonlytheLAST_NAMEcolumn,theSQLstatementcannot
accesstheindex.Forexample,thenexttwoWHEREclausesdonotuse
theindex.
WHERElast_name='Smith'
WHERElast_nameLIKE'Sm%'
Solution 2

TheindexiscreatedintheorderLAST_NAME,FIRST_NAME.The
LAST_NAMEcolumnistheleadingcolumnoftheindex.
CREATEINDEXstu_last_first_name_i
ONstudent(last_name,first_name)
ThisindexisusedinaSQLstatementifyouquerybothcolumnsorthe
LAST_NAMEcolumn.IfaWHEREclauseinaSQLstatementlistsonly
theFIRST_NAMEcolumn,Oracledoesnotusetheindexbecauseitisnot
theleadingcolumnoftheindex.
Composite Indexes versus Individual Indexes

Analternativetousingacompositeindexistocreatetwoseparate
indexes:onefortheFIRST_NAMEcolumnandonefortheLAST_NAME
column.

ASQLstatementwithoneofthecolumnsintheWHEREclauseusesthe
appropriateindex.InacasewherebothcolumnsareusedintheWHERE
clause,Oracletypicallymergesthetwoindexestogethertoretrievethe
rows.Why,then,haveconcatenatedindexesatall?Acompositeindex
outperformsindividualcolumnindexes,providedthatallthecolumnsare
referencedintheWHEREclause.
Skip Scan

Afeaturecalledskipscanallowstheskippingoftheleadingedgeofan
index.Duringaskipscan,theBtreeindexisprobedforthedistinct
valuesoftheleadingedgecolumn.Ideallyinsuchascenario,thecolumn
hasonlyveryfewdistinctvalues.InthecaseoftheFIRST_NAMEand

Enjoy Safari? Subscribe Today

LAST_NAMEcolumns,therearemanydifferentvalues,whichmeansthe
Oracleoptimizerwillprobablynotusetheskipscanfeature.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

16/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Askipscanisnotasfastasanindexlookupbecauseforeachdistinct
leadingedgevalue,theindexneedstobeprobed.Butifnoleadingedge
indexexists,theskipscanfeaturecanallowqueriestousethecomposite
indexinsteadofreadingtheentiretable.
Asecondbenefitoftheskipscanfeatureisthereducedneedforindexes
fewerindexesrequirelessstoragespaceandthereforeresultinbetter
performanceofDMLstatements.

Skipscanisnotsupportedforbitmapandfunctionbased
indexes.

Thedatabasedesigner,togetherwiththeapplicationdeveloper,decides
howtostructuretheindexestomakethemmostuseful,basedontheSQL
statementsissued.MakesuretoverifythatOracleactuallyusestheindex
inyourstatementyoucandothiswiththehelpofanexplainplan,as
discussedinChapter18.
Assumethatonagiventable,youcreateacompositeindexoncolumnsA,
B,andC,inthisorder.Tomakeuseoftheindex,specifyintheWHERE
clauseeithercolumnAcolumnsAandBcolumnsA,B,andCor
columnsAandC.QuerieslistingcolumnConly,orBonly,orBandC
onlydonotusetheindexbecausetheyarenotleadingedgecolumns.
Todeterminethebestorder,againthinkaboutthetypesofqueriesissued
andtheselectivityofeachcolumn.Thefollowingthreeindexescoverall
thequerypossibilities.Thissolutionrequirestheleastamountofstorage
andoffersthebestoverallperformance.

Yourqueriesmaytakebeabletotakeadvantageoftheskipscanfeature,
andyoumaynotneedtobuildasmanyindexes.Youmusttestyour
statementscarefullytoensureadequateperformance.

c )CreateanindexontheDESCRIPTIONcolumnoftheCOURSE
table.NotethatqueriesagainstthetableoftenusetheUPPERfunction.
Droptheindexafteryousuccessfullycreateit.
ANSWER:AfunctionbasedindexiscreatedontheDESCRIPTION
column.
CREATEINDEXcrse_description_i
ONcourse(UPPER(description))
Afunctionbasedindexstorestheindexedvaluesandusestheindexon
thefollowingSELECTstatement,whichretrievesthecoursenumberfor
thecoursecalledHandsOnWindows.Ifyoudontknowinwhatcasethe
descriptionwasenteredintotheCOURSEtable,youmightwanttoapply
theUPPERfunctiontothecolumn.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

17/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

AnyquerythatmodifiesacolumnwithafunctionintheWHEREclause
doesnotmakeuseofanindexunlessyoucreateafunctionbasedindex.
AnindexlikethefollowingcannotbeusedforthepreviouslyissuedSQL
statement.
CREATEINDEXcrse_description_i
ONcourse(description)
Torestoretheschematoitspreviousstate,droptheindex.
DROPINDEXcrse_description_i
Indexdropped.

d )ExecutethefollowingSQLstatements.Explainthereasonforthe
error.

ANSWER:Droppingatableautomaticallydropsanyassociatedindex.
Thereisnoneedtodroptheindexseparately.

e )WouldaBtreeindexworkonafrequentlyaccessedcolumnwith
fewdistinctvalues?Explain.
ANSWER:ItmaybeadvantageoustocreateaBtreeindexevenona
lowselectivitycolumn.
AssumethatyouhaveanEMPLOYEEtablewithacolumnnamed
GENDERthatyouconsiderindexing.Alsoassumethat90percentofyour
employeesaremaleand10percentarefemale.Youfrequentlyqueryfor
femaleemployees.Inthiscase,theindexishelpfulandimprovesthe
performanceofyourquery.Aqueryformaleemployeeswillprobably
performafulltablescanbecausethisismoreefficientthanlookingupall
thevaluesintheindextheOracleoptimizer(discussedinChapter18)
makesthedecisionregardingthebestaccesspath.

f )Listtheadvantagesanddisadvantagesofindexesonperformance.
ANSWER:Advantages:Addinganindexonatableincreasesthe
performanceofSQLstatementsusingtheindexedcolumn(s)inthe
WHEREclause.Thisassumesthatonlyasmallpercentageoftherows
areaccessed.Ifyouaccessmanyrowsinthetable,accessingtheentire
tableviaafulltablescanprobablyyieldsbetterperformance.Indexeson
theforeignkeycolumnsalsoimprovelocking.

Enjoy Safari? Subscribe Today

Disadvantages:Addingindexesmayincreasethetimerequiredfor
insert,update,anddeleteoperationsbecausetheindexneedstobe

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

18/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

updated.Indexesalsorequireadditionaldiskspace.

g )AssumethatanindexexistsonthecolumnENROLL_DATEinthe
ENROLLMENTtable.Changethefollowingquerysoitusesthatindex.

ANSWER:Whenyoumodifyanindexedcolumnwithafunction,suchas
thefunctionTO_CHARintheWHEREclause,theSQLstatementisnot
abletoaccesstheindex.Theexceptioniswhenyoucreateafunction
basedindexonthecolumn.Inthiscase,youdonotneedafunctionbased
index.TheSQLstatementischangedsoitdoesnotmodifytheindexed
columnwithafunction.Chapter5,DateandConversionFunctions,
discussesthedangersofusingTO_CHARwithaDATEcolumninthe
WHEREclause.

Lab 13.1 Quiz


Inordertotestyourprogress,youshouldbeabletoanswerthefollowing
questions.

1 )Forthefollowingquery,choosewhichindexorindexes,ifany,
probablyyieldthebestperformance.

______a)Indexonemployer
______b)Indexonphone
______c)Indexintheorderemployer,phone
______d)Indexintheorderphone,employer
______e)Noindex

2 )Youshouldalwaysindexasmanycolumnsaspossible.
_______a)True
_______b)False

3 )Frequentlyqueriedcolumnsandforeignkeysshouldalmostalways
beindexed.
_______a)True
_______b)False

Enjoy Safari? Subscribe Today

4 )TheROWIDisthefastestwaytoaccessarow.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

19/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

_______a)True
_______b)False

5 )ThefollowingqueryusesthesinglecolumnBtreeindexontheZIP
columnoftheINSTRUCTORtable.

_______a)True
_______b)False

6 )ThefollowingSQLstatementbenefitsfromanindexonthecolumn
INSTRUCTOR_ID.

_______a)True
_______b)False
ANSWERSAPPEARINAPPENDIXA.

LAB 13.2 SEQUENCES

LA B OB J E CTIV E S
Afterthislab,youwillbeableto:
CreateSequences
UseSequences

SequencesareOracledatabaseobjectsthatallowyoutogenerateunique
integers.RecalltheSTUDENTtablewiththeprimarykeycolumn
STUDENT_ID.ThevalueofSTUDENT_IDisasurrogatekeyoran
artificialkeygeneratedfromasequence.Thiskeyisusefultothesystem
butusuallyhasnomeaningfortheuser,isnotsubjecttochanges,andis
neverNULL.
Assumethatastudentisuniquelyidentifiedbyfirstname,lastname,and
address.Thesecolumnsarecalledthealternatekey.Ifyouchoosethese
columnsastheprimarykey,imagineascenarioinwhichastudents
nameoraddresschanges.Alargenumberofupdatesarerequiredin
manytablesbecausealltheforeignkeycolumnsneedtobechanged
thesechangesinvolvealotofcustomizedprogramming.Instead,youcan
createasurrogatekeycolumnandpopulateditwithasequence.This
surrogatekeyisnotsubjecttochange,andtheusersrarelyseethis
column.
Sequencesensurethatnousergetsthesamevaluefromthesequence,
thusguaranteeinguniquevaluesforprimarykeys.Sequencesare

Enjoy Safari? Subscribe Today

typicallyincrementedby1,butotherincrementscanbespecified.You
canalsostartsequencesataspecificnumber.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

20/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Becauseyoustillneedtoenforceyourusersbusinessrulesandprevent
duplicatestudententries,considercreatingauniqueconstraintonthe
alternatekey.

Creating a Sequence
Thesyntaxforcreatingsequencesisasfollows.

TocreateasequencenamedSTUDENT_ID_SEQ_NEW,issuethe
CREATESEQUENCEcommand.
CREATESEQUENCEstudent_id_seq_newSTARTWITH1NOCACHE
Sequencecreated.
Basingthenameofthesequenceonthenameofthecolumnforwhichyou
wanttouseitishelpfulforidentification,butitdoesnotassociatethe
sequencewithaparticularcolumnortable.TheSTARTWITHclause
startsthesequencewiththenumber1.
TheNOCACHEkeywordindicatesthatsequencenumbersshouldnotbe
keptinmemory,sothatwhenthesystemshutsdown,youdonotloseany
cachednumbers.However,losingnumbersisnotareasonforconcern
becausetherearemanymoreavailablefromthesequence.Itisusefulto
leavethesequencenumbersinthecacheonlyifyouaccessthesequence
frequently.IfyoudontspecifyaCACHEchoice,bydefaultthefirst20
numbersarecached.
TheMAXVALUEandMINVALUEparametersdeterminetheminimum
andmaximumrangevaluesofthesequencethedefaultsare
NOMAXVALUEandNOMINVALUE.TheORDERoption,whichisthe
default,ensuresthatthesequencenumbersaregeneratedinorderof
request.TheCYCLEparameterrecyclesthenumbersafteritreachesthe
maximumorminimumvalue,dependingonwhetheritsanascendingor
descendingsequenceitrestartsattheminimumandmaximumvalues,
respectively.ThedefaultvalueisNOCYCLE.

Using Sequence Numbers


Toincrementthesequenceanddisplaytheuniquenumber,usethe
NEXTVALpseudocolumn.ThefollowingSQLstatementtakesthenext
valuefromthesequence.Becausethesequencewasjustcreatedand
startswiththenumber1,ittakesthenumber1asthefirstavailablevalue.

Typically,youuseNEXTVALinINSERTandUPDATEstatements.To

Enjoy Safari? Subscribe Today

displaythecurrentvalueofthesequenceafteritisincremented,usethe

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

21/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

CURRVALpseudocolumn.

Altering a Sequence
TheALTERSEQUENCEcommandallowsyoutochangethepropertiesof
asequence,suchastheincrementvalue,minandmaxvalues,andcache
option.ThesyntaxoftheALTERSEQUENCEcommandisasfollows.

Torestartasequenceatalowernumber,youcandropandrecreatethe
sequence.AnyGRANTstootherusersofthesequencemustbereissued.
FormoreontheGRANTcommand,seeChapter15,Security.
Alternatively,youcanissueanALTERSEQUENCEcommandtoreduce
MAXVALUEtoanumberclosetothecurrentsequencevalue.Alsomake
surethesequenceissettorestartfromthebeginningbysettingthe
CYCLEvalueand,ifdesired,theappropriateMINVALUE.GetNEXTVAL
fromthesequencetorestartthesequence.Remembertoresetthe
MAXVALUEvaluetoalargernumberwhenyouaredone.

Renaming a Sequence
AswithotherOracleobjects,youcanrenameasequencewiththe
RENAMEcommand.Whenyourenameanobject,dependentobjects
becomeinvalid.Therefore,reviewtheDependenciestabinSQL
DeveloperorquerythedatadictionaryviewUSER_DEPENDENCIESto
determinetheimpactofyourchange.
RENAMEstudent_id_seq_newTOstudent_id_seq_newname

Using Sequence Values


TheNEXTVALandCURRVALpseudocolumnscanbeusedinthe
followingSQLconstructs.
VALUESclauseofanINSERTstatement
SETclauseofanUPDATEstatement
SELECTlist(unlessitispartofasubquery,view,ormaterializedview)
SELECTlistofasubqueryinanINSERTstatement
Sequencevaluesarenotallowedinthefollowingstatements.
SubqueryofaSELECT,UPDATE,orDELETEstatement
SELECTstatementcontainingDISTINCT,GROUPBY,ORDERBY,
UNION,UNIONALL,INTERSECT,orMINUS
WHEREclauseofaSELECTstatement
DEFAULTclauseofacolumninaCREATEorALTERTABLEstatement
CHECKconstraintcondition

Enjoy Safari? Subscribe Today

SQL Developer and Sequences

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

22/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

SQLDeveloperallowsyoutocreate,alter,anddropsequencesusingthe
graphicaluserinterface.Whenyoudoubleclickoneofthesequences,
youseeascreensimilartoFigure13.7.
Figure13.7DetailstabfortheSTUDENT_ID_SEQindexinSQL
Developer

TheDetailstabshowsthecreationdateofthesequence,alongwiththe
lastnumberusedonthesequencemostofthisinformationisfromthe
ALL_SEQUENCESdatadictionaryview.
TheDependenciestabshowswhetheranyobjectreferstothesequence.
Anexampleofareferencetoasequenceisatriggerthatselectsfromthis
sequence.

Lab 13.2 Exercises


a )DescribetheeffectsofthefollowingSQLstatementonthesequence
SECTION_ID_SEQ.

b )WriteaSQLstatementthatincrementsthesequence
STUDENT_ID_SEQ_NEWwithNEXTVALandthenissueaROLLBACK
command.Determinetheeffectonthesequencenumber.

c )DropthesequenceSTUDENT_ID_SEQ_NEW.

Lab 13.2 Exercise Answers


a )DescribetheeffectsofthefollowingSQLstatementonthesequence
SECTION_ID_SEQ.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

23/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

ANSWER:ThesequenceisaccessiblefromwithinanINSERT
statement.Thenextvalueisincremented,andthisvalueisinsertedinto
thetable.
Automating Primary Key Creation with Triggers

Youcanautomaticallyincrementasequenceandinserttheprimarykey
valuewheneveryouinsertanewrowinatable.Thiscanbe
accomplishedwhenyouwriteatrigger.Followingisthecodeforatrigger
associatedwiththeSECTIONtable.ThetriggerfiresuponINSERTtothe
SECTIONtable.ItcheckswhetheravaluefortheSECTION_IDcolumnis
suppliedaspartoftheINSERTstatement.Ifnot,itretrievesthevalue
fromtheSECTION_ID_SEQsequenceandholdsthevalueinthe
correlationvariable:new.SECTION_ID.Thisvalueistheninsertedinto
theSECTION_IDcolumn.

ThenextcommandshowstheprimarykeycolumnSECTION_IDnot
listedaspartoftheINSERTstatement.Thecommandissuccessfulit
doesnotreturnanerrormessageindicatingthattheprimarykeycolumn
SECTION_IDismissing.

AsubsequentSELECTstatementqueriesthenewlyinsertedrowand
displaystheautomaticallycreatedSECTION_IDvalue.

Enjoy Safari? Subscribe Today

SQLDevelopercancreatetriggerstogenerateprimarykeyvaluesfrom
sequences.Whenyourightclickonatablesnodeandthenselect

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

24/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Trigger,youwillseetheCreate(PKfromSequence)menuoption(see
Figure13.8).Oracleletsyouchoosethesequencetogeneratetheprimary
keyvalue.TheDDLtabshowsthedynamicallycreatedtriggerPL/SQL
sourcecode.
Figure13.8SQLDevelopermenuoptionforcreatingaprimary
keysequencetrigger

FormoreinformationontriggersandPL/SQL,refertoOraclePL/SQL
byExample,4thEdition,byBenjaminRosenzweigandElenaSilvestrova
Rakhimov(PrenticeHall,2008)ortheOracleApplicationDevelopers
GuideFundamentalsManual.

b )WriteaSQLstatementthatincrementsthesequence
STUDENT_ID_SEQ_NEWwithNEXTVALandthenissueaROLLBACK
command.Determinetheeffectonthesequencenumber.
ANSWER:Afterasequenceisincremented,theROLLBACKcommand
doesnotrestorethenumber.
Ifyouhaventalreadydoneso,createthesequencewiththeCREATE
SEQUENCEstudent_id_seq_newcommand.Thenretrievethenext
numberfromthesequence.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

25/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Ifthereareanygapsintheprimarykeysequencenumbers,itreally
doesntmatterbecausethenumbershavenomeaningtotheuser,and
therearemanymorenumbersavailablefromthesequence.Oneofthe
uniquepropertiesofsequencesisthatnotwousersreceivethesame
number.
YoucanseeinformationaboutthesequenceintheUSER_SEQUENCES
datadictionaryview.HeretheLAST_NUMBERcolumnindicatesthelast
usednumberofthesequence.Alternatively,youcanseethisinformation
inSQLDevelopersDetailstabforthesequence.

YoucanobtainthecurrentnumberofthesequencebyusingCURRVAL,
providedthatthesequencewasincrementedbytheuserssession.

c )DropthesequenceSTUDENT_ID_SEQ_NEW.
ANSWER:Aswithotherdatabaseobjects,youusetheDROPcommand
todropasequence.
DROPSEQUENCEstudent_id_seq_new
Sequencedropped.

Lab 13.2 Quiz

Enjoy Safari? Subscribe Today

Inordertotestyourprogress,youshouldbeabletoanswerthefollowing
questions.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

26/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

1 )Sequencesareusefulforgeneratinguniquevalues.
_______a)True
_______b)False

2 )AstudentsSocialSecuritynumberisagoodchoiceforaprimary
keyvalueinsteadofasequence.
_______a)True
_______b)False

3 )Thedefaultincrementofasequenceis1.
_______a)True
_______b)False

4 )Whenyoudropatable,theassociatedsequenceisalsodropped.
_______a)True
_______b)False

5 )Thefollowingstatementcreatesasequencenamed
EMPLOYEE_ID_SEQ,whichstartsatthenumber1000.
CREATESEQUENCEemployee_id_seqSTARTWITH1000
_______a)True
_______b)False
ANSWERSAPPEARINAPPENDIXA.

LAB 13.3 VIEWS

LA B OB J E CTIV E S
Afterthislab,youwillbeableto:
Create,Alter,andDropViews
UnderstandtheDataManipulationRulesforViews

Aviewisavirtualtablethatconsistsofcolumnsandrows,butitisonly
theSELECTstatementthatisstored,notaphysicaltablewithdata.A
viewsSELECTquerymayreferenceoneormultipletables,calledbase
tables.Thebasetablesaretypicallyactualtablesorotherviews.

Advantages of Views
Viewssimplifythewritingofqueries.Youcanqueryasingleview
insteadofwritingacomplicatedSQLstatementthatjoinsmanytables.

Enjoy Safari? Subscribe Today

ThecomplexityoftheunderlyingSQLstatementishiddenfromtheuser
andcontainedonlyintheview.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

27/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Viewsareusefulforsecurityreasonsbecausetheycanhidedata.Thedata
retrievedfromaviewcanshowonlycertaincolumnsifyoulistthose
columnsintheSELECTlistofthequery.Youcanalsorestricttheviewto
displayspecificrowswiththeWHEREclauseofthequery.
Inaview,youcangiveacolumnadifferentnamefromtheoneinthe
basetable.Viewsmaybeusedtoisolateanapplicationfromachangein
thedefinitionofthebasetables.Ratherthanchangetheprogram,you
canmakechangestotheview.
Aviewlooksjustlikeanyothertable.Youcandescribeandquerythe
viewandalsoissueINSERT,UPDATE,andDELETEstatementstoa
certainextent,asyouwillseewhenperformingtheexercisesinthislab.

Creating a View
Thesimplifiedsyntaxforcreatingaviewisasfollows.

ThefollowingstatementscreateaviewcalledCOURSE_NO_COSTand
describethenewview.

TheCOURSE_NO_COSTviewhidesanumberofcolumnsthatexistin
theCOURSEtable.YoudonotseetheCOSTcolumnorthe
CREATED_DATE,CREATED_BY,MODIFIED_DATE,and
MODIFIED_BYcolumns.Themainpurposeofthisviewissecurity.You
cangrantaccessjusttotheviewCOURSE_NO_COSTinsteadoftothe
COURSEtableitself.Formoreinformationongrantingaccessprivileges
todatabaseobjects,seeChapter15.

Using Column Aliases


Thefollowingstatementdemonstratesaviewwithcolumnnames
differentfromthecolumnnamesinthebasetables.Heretheview
namedSTUD_ENROLLshowsalistoftheSTUDENT_ID,thelastname
ofthestudentincapitalletters,andthenumberofclassesthestudentis
enrolledin.ThecolumnSTUDENT_IDfromtheSTUDENTtableis
renamedintheviewtoSTUD_ID,usingacolumnalias.Whenacolumn
containsanexpressionsuchasafunction,acolumnaliasisrequired.The
twoexpressionsintheSTUD_ENROLLview,namelythestudentlast
nameincapsandthecountofclassesenrolled,arethereforealiased.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

28/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

TheORREPLACEkeywordisusefuliftheviewalreadyexists.Itallows
youtoreplacetheviewwithadifferentSELECTstatementwithout
havingtodroptheviewfirst.Thisalsomeansyoudonothavetoregrant
privilegestotheviewtherightstotheviewareretainedbythosewho
havealreadybeengrantedaccessprivileges.
ThefollowingexampleshowsanalternateSQLstatementfornaming
columnsinaview,wherebytheviewscolumnsarelistedinparentheses
aftertheviewname.

Altering a View
YouusetheALTERVIEWcommandtorecompileaviewifitbecomes
invalid.Thiscanoccurafteryoualteroneofthebasetables.Thesyntax
oftheALTERVIEWstatementisasfollows.
ALTERVIEWviewnameCOMPILE
TheALTERVIEWcommandallowsforadditionalsyntaxoptionsnot
mentioned.Theseoptionsletyoucreateprimaryoruniqueconstraints
onviews.However,theseconstraintsarenotenforcedanddonot
maintaindataintegrity,andanindexisneverbuiltbecausetheycan
onlybecreatedinDISABLENOVALIDATEmode.Theseconstrainttypes
areprimarilyusefulwithmaterializedviews,apopulardatawarehousing
featurethatallowsyoutophysicallystorepreaggregatedresultsand/or
joinsforspeedyaccess.Unliketheviewsdiscussedinthischapter,
materializedviewsresultinphysicaldatastoredintables.

Renaming a View
TheRENAMEcommandallowsyoutochangethenameofaview.
RENAMEstud_enrollTOstud_enroll2
Allunderlyingconstraintsandgrantedprivilegesremainintact.
However,anyobjectsthatusethisview(perhapsanotherviewora
PL/SQLprocedure,package,orfunction)becomeinvalidandneedtobe
compiled.

Dropping a View
Todropaview,youusetheDROPVIEWcommand.Thefollowing
statementdropstheSTUD_ENROLL2view.
DROPVIEWstud_enroll2
Viewdropped.

Lab 13.3 Exercises


a )CreateaviewcalledLONG_DISTANCE_STUDENTwithallthe
columnsintheSTUDENTtableplustheCITYandSTATEcolumnsfrom
theZIPCODEtable.ExcludestudentsfromNewYork,NewJersey,and

Enjoy Safari? Subscribe Today

Connecticut.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

29/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

b )CreateaviewnamedCHEAP_COURSEthatshowsallcolumnsof
theCOURSEtablewherethecoursecostis1095orless.

c )IssuethefollowingINSERTstatement.Whatdoyouobservewhen
youquerytheCHEAP_COURSEview?

d )DroptheviewsnamedLONG_DISTANCE_STUDENTand
CHEAP_COURSE.

e )Usingthefollowingstatement,createatablecalledTEST_TABand
buildaviewoverit.Then,addacolumntothetableanddescribethe
view.Whatdoyouobserve?Dropthetableandviewafteryoucomplete
theexercise.
CREATETABLEtest_tab
(col1NUMBER)

f )CreateaviewcalledBUSY_STUDENT,basedonthefollowing
query.UpdatethenumberofenrollmentsforSTUDENT_ID124tofive
throughtheBUSY_STUDENTview.Recordyourobservation.

g )Createaviewthatliststheaddressesofstudents.Includethe
columnsSTUDENT_ID,FIRST_NAME,LAST_NAME,
STREET_ADDRESS,CITY,STATE,andZIP.Usingtheview,updatethe
lastnameofSTUDENT_ID237fromFrosttoOBrien.Thenupdatethe
stateforthestudentfromNJtoCT.Whatdoyounoticeforthestatements
youissue?

Lab 13.3 Exercise Answers


a )CreateaviewcalledLONG_DISTANCE_STUDENTwithallthe
columnsintheSTUDENTtableplustheCITYandSTATEcolumnsfrom
theZIPCODEtable.ExcludestudentsfromNewYork,NewJersey,and
Connecticut.
ANSWER:ToselectallcolumnsfromtheSTUDENTtable,usethe
wildcardsymbol.ForthecolumnsCITYandSTATEintheview,jointo
theZIPCODEtable.Withthisviewdefinition,youseeonlyrecords
wherethestateisnotequaltoNewYork,Connecticut,orNewJersey.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

30/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Youcanissueaqueryagainsttheviewordescribetheview.Youcan
restrictthecolumnsand/ortherowsoftheview.

Youmightwanttovalidatetheviewbyqueryingforstudentslivingin
NewJersey.

ThequeryfindsnostudentslivinginNewJerseybecausetheviews
definingqueryexcludesthoserecords.

b )CreateaviewnamedCHEAP_COURSEthatshowsallcolumnsof
theCOURSEtablewherethecoursecostis1095orless.
ANSWER:Creatingaviewasfollowsrestrictstherowstocourseswitha
costof1095orless.

c )IssuethefollowingINSERTstatement.Whatdoyouobservewhen
youquerytheCHEAP_COURSEview?

ANSWER:Youcaninsertrecordsthroughtheview,violatingtheviews
definingquerycondition.
Acostof2000issuccessfullyinsertedintotheCOURSEtablethroughthe

Enjoy Safari? Subscribe Today

view,eventhoughthisishigherthan1095,whichisthedefining
conditionoftheview.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

31/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

YoucanqueryCHEAP_VIEWtoseeiftherecordisthere.Thecoursewas
successfullyinsertedintheunderlyingCOURSEbasetable,butitdoes
notsatisfytheviewsdefinitionandisnotdisplayed.

AviewsWHEREclauseworksforanyquery,butnotforDML
statements.Thecoursenumber900isnotvisiblethroughthe
CHEAP_COURSEview,butinsert,update,ordeleteoperationsare
permitteddespitetheconflictingWHEREcondition.Tochangethis
securitydefyingbehavior,createtheviewwiththeWITHCHECK
OPTIONconstraint.ButfirstundotheINSERTstatementwiththe
ROLLBACKcommandbecauseanysubsequentDDLcommand,suchas
thecreationofaview,automaticallycommitstherecord.

Itisagoodhabittonameconstraints.Youunderstandthebenefitofwell
namedconstraintswhenyouquerytheOracledatadictionaryorwhen
youviolateconstraintswithdatamanipulationstatements.
Thefollowingerrormessageappearswheninsertions,updates,and
deletionsissuedagainstaviewviolatetheviewsdefiningquery.The
previousINSERTstatementwouldnowberejected,withtheerrorORA
01402viewWITHCHECKOPTIONwhereclauseviolation.
WhathappensifyouattempttoinsertarecordwithavalueofNULLfor
thecoursecost?Again,Oraclerejectstherowbecausetheconditionisnot
satisfied.TheNULLvalueisnotlessthanorequalto1095.
View Constraints

Youcanenforceconstraintsinavarietyofways:Theunderlyingbase
tablesautomaticallyensuredataintegrity,oryoucanusetheWITH
CHECKOPTION.Youcanalsoavoidanydatamanipulationontheview
byusingtheREADONLYsyntaxoption.Thefollowingstatementcreates
areadonlyviewnamedCOURSE_V.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

32/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

d )DroptheviewsnamedLONG_DISTANCE_STUDENTand
CHEAP_COURSE.
ANSWER:Justlikeotheroperationsondataobjects,theDROP
keywordremovesadatabaseobjectfromthedatabase.

image

RememberthatanyDDLoperation,suchasthecreationof
aview,cannotberolledback,andanypriorDML
operations,suchasinserts,updates,anddeletes,are
automaticallycommitted.

e )Usingthefollowingstatement,createatablecalledTEST_TABand
buildaviewoverit.Thenaddacolumntothetableanddescribethe
view.Whatdoyouobserve?Dropthetableandviewafteryoucomplete
theexercise.
CREATETABLEtest_tab
(col1NUMBER)
ANSWER:Theviewdoesnotshowthenewlyaddedcolumn.

Afterthetablecreation,theviewiscreated.Here,thename
TEST_TAB_VIEWisused.Thenyouaddanadditionalcolumntothe
TEST_TABtablehereitisnamedCOL2.

AsubsequentlyissuedDESCRIBEoftheviewrevealsaninterestingfact.

Whereisthenewcolumnthatwasadded?Wheneveraviewiscreated
withthewildcard(*)character,Oraclestorestheindividualcolumn
namesinthedefinitionoftheview.WhenyoureviewtheDetailstabof
theview(seeFigure13.9)inSQLDeveloper,youseethattheview
consistsonlyofonecolumn.Thisistheviewsdefinitionatthetimeof
viewcreation.Notethecolumnisalsolistedwithenclosedquotation
marks,justincaseofmixedcasecolumnnames.

Enjoy Safari? Subscribe Today

Figure13.9TheTEXTboxshowstheviewsquerydefinition

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

33/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Alternatively,youcanqueryOraclesdatadictionaryview
USER_VIEWS.

Youneedtoreissuethecreationoftheviewstatementfortheviewto
includethenewcolumn.

Now,whenaDESCRIBEisissuedontheview,thenewcolumnis
included.

Compiling a View

YoucanusetheALTERVIEWcommandtodefine,modify,ordropview
constraints.Also,thecommandALTERVIEWviewnameCOMPILE
commandexplicitlycompilestheviewtomakesureitisvalid.Aview
maybecomeinvalidiftheunderlyingtableisalteredordropped.Ifyou
useOracle11g,theviewremainsvalidifyoumodifyacolumninthebase
tablethatsnotbeingusedbythisview.
Dependencies Tab

YoucanseeintheDependenciestabforagiventablewhetherany
objectsaccessthetablethishelpsyouassesstheimpactofchanges.
Figure13.10showsthedependenciesoftheTEST_TABtable.Asyousee,
TEST_TAB_VIEWdependsonthistable,andfyouclickthe
DependenciestabfortheTEST_TAB_VIEW,youfindthattheTEST_TAB
tableisreferencedintheview.
Figure13.10Dependenciestab

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

34/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Accessing an Invalid View

Whenyouaccessaninvalidview,Oracleattemptstorecompileit
automatically.Itisusefultoexplicitlycompiletotheview,asshownin
thenextcommand,toensurethattherearenoproblemswiththeview
afteryoumakedatabasechanges.
ALTERVIEWtest_tab_viewCOMPILE
Viewaltered.
Dropthenolongerneededtableandnoticetheeffectontheview.

FollowingisanattempttoretrievedatafromtheinvalidviewOracle
returnsanerrormessagetotheuser,indicatingthattheviewexists.
However,itiscurrentlyinvalidbecausetheunderlyingobjectswere
alteredordropped.Anysubsequentattempttoaccessthevieworto
compileitreturnsanerror.

DroptheviewtorestoretheSTUDENTschematoitspreviousstate.
DROPVIEWtest_tab_view
Viewdropped.
Forcing the Creation of a View

Ifaviewsbasetablesdonotexistorifthecreatoroftheviewdoesnt
haveprivilegestoaccesstheview,thecreationoftheviewfails.The
followingexampleshowsthecreationoftheviewnamedTEST,basedon
anonexistentSALEStable.

Ifyouwanttocreatetheview,despiteitsbeinginvalid,youcancreateit
withtheFORCEoptionthedefaultintheCREATEVIEWsyntaxis
NOFORCE.ThisFORCEoptionisusefulifyouneedtocreatetheview
andyouaddthereferencedtablelaterorifyouexpecttoobtainthe

Enjoy Safari? Subscribe Today

necessaryprivilegestothereferencedobjectshortly.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

35/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

Theview,thoughinvalid,nowexistsinthedatabase.

f )CreateaviewcalledBUSY_STUDENT,basedonthefollowing
query.UpdatethenumberofenrollmentsforSTUDENT_ID124tofive
throughtheBUSY_STUDENTview.Recordyourobservation.

ANSWER:TheUPDATEoperationfails.Datamanipulationoperations
onaviewimposeanumberofrestrictions.
Tocreatetheview,youneedtogivetheCOUNT(*)expressionacolumn
aliasotherwise,thefollowingerroroccurs.

YoucannowattempttoupdatetheENROLLMENTtableusingtheview
withthefollowingUPDATEstatement.

Data Manipulation Rules on Views

Foraviewtobeupdatable,itneedstoconformtoanumberofrules.The
viewcannotcontainanyofthefollowing.
Anexpression(forexample,TO_DATE(enroll_date))
Anaggregatefunction
Asetoperator,suchasUNION,UNIONALL,INTERSECT,orMINUS
TheDISTINCTkeyword
TheGROUPBYclause
TheORDERBYclause
Specialrulesapplytoviewsthatcontainjoinconditions,asshownin
exerciseg.

g )Createaviewthatliststheaddressesofstudents.Includethe
columnsSTUDENT_ID,FIRST_NAME,LAST_NAME,
STREET_ADDRESS,CITY,STATE,andZIP.Usingtheview,updatethe
lastnameofSTUDENT_ID237fromFrosttoOBrien.Thenupdatethe
stateforthestudentfromNJtoCT.Whatdoyounoticeforthestatements

Enjoy Safari? Subscribe Today

youissue?

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

36/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

ANSWER:Notallupdatestoviewscontainingjoinsareallowed.The
updateofthelastnameissuccessful,buttheupdateoftheSTATEcolumn
isnot.

NowupdatethelastnametoOBrienbyusingthefollowingstatement.
Toindicateasinglequotationmark,prefixitwithanotherquotation
mark.

Becausethetestwassuccessful,rollbacktheupdatetoretainthecurrent
datainthetable.
ROLLBACK
Rollbackcomplete.
YoucanupdatethedataintheunderlyingbasetableSTUDENT.Now
updatethecolumnSTATEinthebasetableZIPCODEthroughthe
STUDENT_ADDRESSview.

Join Views and Data Manipulation

Understandingtheconceptofkeypreservedtablesisessentialto
understandingtherestrictionsonjoinviews.Atableisconsideredkey
preservedifeverykeyofthetablecanalsobeakeyoftheresultofthe
join.Inthiscase,theSTUDENTtableisthekeypreserved,orchild,
table.
Forajoinviewtobeupdatable,theDMLoperationmayaffectonlythe
keypreservedtable(alsoknownasthechildbasetable),andthechilds
primarykeymustbeincludedintheviewsdefinition.Inthiscase,the
childtableistheSTUDENTtable,andtheprimarykeyisthe
STUDENT_IDcolumn.
Ifyouareindoubtregardingwhichtableisthekeypreservedtable,
querytheOracledatadictionarytableUSER_UPDATABLE_COLUMNS.
Theresultshowsyouwhichcolumnsareupdatable.Also,theSTUDENT
tablesZIPcolumnisupdatable,buttheZIPcolumnfromtheZIPCODE
tableisnot.OnlytheSTUDENTtablesZIPcolumn(aliasedasSZIP)is
consideredkeypreserved.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

37/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

ThedatadictionaryiscoveredingreaterdetailinChapter14,TheData
Dictionary,Scripting,andReporting.Ifyouneedtomanipulatekey
preserveddatathroughaview,youovercomethislimitationbyusingan
INSTEADOFtrigger.Thistriggerworksonlyagainstviewsandallows
youtomanipulatedatabasedonthecodewithinthetrigger.The
INSTEADOFtriggerfiresinplaceofyourissuedINSERT,UPDATE,or
DELETEcommandagainsttheview.Forexample,ifyouexecutean
INSERTcommandagainsttheview,thestatementmayactuallyperform
anUPDATEinstead.TheviewsassociatedINSTEADOFtriggercodecan
performanytypeofdatamanipulationagainstoneormultipletables.
YoucreatethesepowerfulINSTEADOFtriggersbyusingOracle
PL/SQL,ascoveredingreatdetailinOraclePL/SQLbyExample,4th
Edition,byBenjaminRosenzweigandElenaSilvestrovaRakhimov
(PrenticeHall,2008).

Lab 13.3 Quiz


Inordertotestyourprogress,youshouldbeabletoanswerthefollowing
questions.

1 )Viewsareusefulforsecurity,forsimplifyingthewritingofqueries,
andforhidingdatacomplexity.
_______a)True
_______b)False

2 )Underwhatcircumstancescanviewsbecomeinvalid?Selectallthat
apply.
_______a)Thedatatypeofacolumnreferencedintheviewchanges.
_______b)Oneoftheunderlyingbasetablesisdropped.
_______c)Viewsneverbecomeinvalidtheyautomaticallyrecompile.

3 )Identifytheerrorinthefollowingviewdefinition.

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

38/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

______a)Line1
______b)Line2
______c)Line4
______d)Lines1,2,and4
______e)Noerror

4 )AnUPDATEtotheSTATEcolumnintheZIPCODEtableis
permittedusingthefollowingview.

_______a)True
_______b)False

5 )Viewsprovidesecuritybyrestrictingaccesstospecificrowsand/or
columnsofatable.
_______a)True
_______b)False

6 )Acolumninaviewmayhaveadifferentnamethaninthebase
table.
_______a)True
_______b)False
ANSWERSAPPEARINAPPENDIXA.

Workshop
Theprojectsinthissectionaremeanttopromptyoutoutilizealltheskills
youhaveacquiredthroughoutthischapter.Theanswerstotheseprojects
canbefoundatthecompanionWebsitetothisbook,locatedat
www.oraclesqlbyexample.com(http://www.oraclesqlbyexample.com) .
1)WhocanupdatetheSALARYcolumnthroughtheMY_EMPLOYEE
view?Hint:TheUSERfunctionreturnsthenameoftheuserwhois
currentlyloggedin.

2)Whichcolumnsinatableshouldyouconsiderindexing?
3)ExplainthepurposeofthefollowingOracleSQLcommand.
ALTERINDEXcrse_crse_fk_iREBUILD

Enjoy Safari? Subscribe Today

4)Arenullvaluesstoredinanindex?Explain.

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

39/40

1/2/2017

Chapter13.Indexes,Sequences,andViewsOracleSQLbyExample,FourthEdition

NEXT

PREV

Recommended
/ Queue
/ History
/ Tutorials
14./The
Settings
Data /Dictiona...
Blog /
Chapter 12. Create,
Alter,
and .../ TopicsChapter
Get the App / Sign Out
2017 Safari. Terms of Service / Privacy Policy

Enjoy Safari? Subscribe Today

https://www.safaribooksonline.com/library/view/oraclesqlby/9780137047345/ch13.html

40/40