WWW.EBOOKWORLD.CO.NR
Expert one-on-one Oracle
2
This page intentionally left blank
Expert one-on-one Oracle
3
Content
Introduction 18
WhatthisBookisAbout 18
WhoShouldUsethisBook? 19
HowThisBookisStructured 20
UnderstandingtheDatabase 21
DatabaseStructuresandUtilities 22
Performance 23
AdvancedSQLFeatures 23
Extensibility 24
Security 25
Appendices 26
Conventions 26
SourceCodeandUpdates 27
SettingUp 28
Overview 28
TheSQL*PLUSEnvironment 28
SettingupAUTOTRACEinSQL*PLUS 30
CCompilers 32
CodingConventions 32
OtherIssues 33
Chapter1:DevelopingSuccessfulOracleApplications 35
Overview 35
MyApproach 36
TheBlackBoxApproach 37
How(andhownot)toDevelopDatabaseApplications 41
UnderstandingOracleArchitecture 41
UnderstandingConcurrencyControl 48
DatabaseIndependence? 57
HowDoIMakeitRunFaster? 71
TheDBA‐DeveloperRelationship 73
Summary 74
Chapter2:Architecture 76
Overview 76
TheServer 76
TheFiles 84
ParameterFiles 84
DataFiles 87
TempFiles 91
ControlFiles 91
RedoLogFiles 92
Expert one-on-one Oracle
4
FilesWrap‐Up 96
TheMemoryStructures 97
PGAandUGA 97
SGA 103
MemoryStructuresWrap‐Up 115
TheProcesses 115
ServerProcesses 116
BackgroundProcesses 122
SlaveProcesses 130
Summary 132
Chapter3:LockingandConcurrency 133
Overview 133
WhatareLocks? 133
LockingIssues 136
LostUpdates 136
Blocking 140
Deadlocks 141
LockEscalation 146
TypesofLock 147
DMLLocks 147
DDLLocks 155
LatchesandInternalLocks(Enqueues) 159
ManualLockingandUser‐DefinedLocks 160
WhatisConcurrencyControl? 161
TransactionIsolationLevels 162
READUNCOMMITTED 163
READCOMMITTED 165
REPEATABLEREAD 167
SERIALIZABLE 170
Read‐OnlyTransactions 172
Summary 173
Chapter4:Transactions 175
Overview 175
TransactionControlStatements 175
IntegrityConstraintsandTransactions 182
BadTransactionHabits 184
DistributedTransactions 191
RedoandRollback 194
Summary 198
Chapter5:RedoandRollback 200
Overview 200
Redo 200
WhatDoesaCOMMITDo? 201
Expert one-on-one Oracle
5
WhatDoesaROLLBACKDo? 208
HowMuchRedoAmIGenerating? 209
CanITurnOffRedoLogGeneration? 221
CannotAllocateaNewLog? 224
BlockCleanout 226
LogContention 230
TemporaryTablesandRedo/Rollback 232
AnalyzingRedo 235
Rollback 236
WhatGeneratestheMost/LeastUndo? 236
SETTRANSACTION 236
ʹORA‐01555:snapshottoooldʹ 237
Summary 250
Chapter6:DatabaseTables 252
Overview 252
TypesofTables 252
Terminology 254
HighWaterMark 254
FREELISTS 255
PCTFREEandPCTUSED 258
INITIAL,NEXT,andPCTINCREASE 265
MINEXTENTSandMAXEXTENTS 265
LOGGINGandNOLOGGING 266
INITRANSandMAXTRANS 266
HeapOrganizedTable 266
IndexOrganizedTables 271
IndexOrganizedTablesWrap‐up 286
IndexClusteredTables 286
IndexClusteredTablesWrap‐up 295
HashClusterTables 295
HashClustersWrap‐up 306
NestedTables 306
NestedTablesSyntax 307
NestedTableStorage 317
NestedTablesWrap‐up 320
TemporaryTables 321
TemporaryTableWrap‐up 329
ObjectTables 330
ObjectTableWrap‐up 339
Summary 339
Chapter7:Indexes 341
Overview 341
AnOverviewofOracleIndexes 342
Expert one-on-one Oracle
6
B*TreeIndexes 343
ReverseKeyIndexes 348
DescendingIndexes 350
WhenshouldyouuseaB*TreeIndex? 351
B*TreesWrap‐up 360
BitmapIndexes 361
WhenShouldyouuseaBitmapIndex? 362
BitmapIndexesWrap‐up 364
Function‐BasedIndexes 364
ImportantImplementationDetails 365
Function‐BasedIndexExample 365
Caveat 375
Function‐BasedIndexWrap‐up 376
ApplicationDomainIndexes 376
ApplicationDomainIndexesWrap‐up 378
FrequentlyAskedQuestionsAboutIndexes 378
DoIndexesWorkOnViews? 378
IndexesandNulls 378
IndexesonForeignKeys 382
WhyisnʹtmyIndexGettingUsed? 383
AremyIndexesBeingUsed? 389
Myth:SpaceisNeverReusedinanIndex 390
Myth:MostDiscriminatingElementsShouldbeFirst 394
Summary 398
Chapter8:ImportandExport 400
Overview 400
AQuickExample 400
WhyYouMightUseIMPandEXP 402
DetectingCorruption 402
ExtractingDDL 403
CloningSchemas 403
TransportingTablespaces 403
RebuildingInstances 403
CopyingDatabetweenPlatforms 404
HowTheyWork 404
TheOptions 404
LargeExports 409
SubsettingData 414
TransportingData 415
GettingtheDDL 421
BackupandRecovery 429
IMP/EXPisnotaReorganizationTool(AnyMore) 429
ImportingintoDifferentStructures 430
Expert one-on-one Oracle
7
DirectPathExports 435
CaveatsandErrors 436
Cloning 436
UsingIMP/EXPAcrossVersions 445
WheredidmyIndexesgo? 446
NamedversusDefault‐NamedConstraints 449
NationalLanguageSupport(NLS)Issues 453
TablesSpanningMultipleTablespaces 455
Summary 461
Chapter9:DataLoading 462
Overview 462
AnIntroductiontoSQL*LOADER 462
Howto 469
LoadDelimitedData 469
LoadFixedFormatData 473
LoadDates 476
LoadDataUsingSequencesandOtherFunctions 477
UpdateExistingRowsandInsertNewRows 483
LoadReport‐StyleInputData 486
LoadaFileintoaLONGRAWorLONGField 489
LoadDatawithEmbeddedNewlines 490
UnloadData 502
LoadLOBs 514
LoadVARRAYS/NestedTableswithSQLLDR 526
CallSQLLDRfromaStoredProcedure 529
Caveats 535
YouCannotPickaRollbackSegmenttoUse 535
TRUNCATEAppearstoWorkDifferently 535
SQLLDRDefaultstoCHAR(255) 535
CommandLineOverridesControlFile 536
Summary 536
Chapter10:TuningStrategiesandTools 537
Overview 537
IdentifyingtheProblem 537
MyApproach 539
TuningisaConstantthing 540
BindVariablesandParsing(Again) 545
AmIUsingBindVariables? 562
BindVariablesandParsingWrap‐Up 565
SQL_TRACE,TIMED_STATISTICS,andTKPROF 565
SettingUpTracing 566
UsingandInterpretingTKPROFOutput 569
UsingandInterpretingRawTraceFiles 580
Expert one-on-one Oracle
8
SQL_TRACE,TIMED_STATISTICS,andTKPROFWrap‐Up 593
DBMS_PROFILER 594
Instrumentation 594
StatsPack 597
SettingupStatsPack 597
StatsPackWrap‐Up 618
V$Tables 619
V$EVENT_NAME 619
V$FILESTATandV$TEMPSTAT 620
V$LOCK 620
V$MYSTAT 620
V$OPEN_CURSOR 622
V$PARAMETER 623
V$SESSION 623
V$SESSION_EVENT 626
V$SESSION_LONGOPS 627
V$SESSION_WAIT 627
V$SESSTAT 627
V$SESS_IO 627
V$SQL,V$SQLAREA 627
V$STATNAME 628
V$SYSSTAT 628
V$SYSTEM_EVENT 628
Summary 628
Chapter11:OptimizerPlanStability 630
Overview 630
AnOverviewoftheFeature 630
UsesofOptimizerPlanStability 634
AMethodtoImplementTuning 634
ADevelopmentTool 640
ToSeetheIndexesUsed 642
ToSeewhatSQLisExecutedbyanApplication 642
HowOptimizerPlanStabilityWorks 643
OUTLINESandOUTLINE_HINTS 643
CreatingStoredOutlines 646
PrivilegesNeededforStoredOutlines 646
UsingDDL 647
UsingALTERSESSION 648
TheOUTLNUser 649
MovingOutlinesfromDatabasetoDatabase 650
GettingJusttheRightOutline 651
ManagingOutlines 654
ViaDDL 654
Expert one-on-one Oracle
9
TheOUTLN_PKGPackage 657
Caveats 661
OutlineNamesandCase 661
ALTERSESSIONIssue 663
DROPUSERdoesnotDropOutlines 663
ʹCURSOR_SHARING=FORCEʹandOutlines 664
OutlinesUseSimpleTextMatching 665
OutlinesbyDefaultareintheSYSTEMTablespace 666
OR‐Expansion 666
Performance 667
TheNamespaceofOutlinesisGlobal 672
ErrorsyouMightEncounter 673
ORA‐18001ʺnooptionsspecifiedforALTEROUTLINEʺ 673
ORA‐18002ʺthespecifiedoutlinedoesnotexistʺ 674
ORA‐18003ʺanoutlinealreadyexistswiththissignatureʺ 674
ORA‐18004ʺoutlinealreadyexistsʺ 674
ORA‐18005‐18007 674
Summary 675
Chapter12:AnalyticFunctions 676
Overview 676
AnExample 676
HowAnalyticFunctionsWork 681
TheSyntax 681
TheFunctions 698
Examples 702
TheTOP‐NQuery 702
PivotQuery 714
AccessingRowsAroundYourCurrentRow 723
Caveats 728
PL/SQLandAnalyticfunctions 728
AnalyticFunctionsintheWhereClause 730
NULLSandSorting 731
Performance 733
Summary 734
Chapter13:MaterializedViews 735
Overview 735
ABriefHistory 735
WhatyouʹllneedtoruntheExamples 737
AnExample 737
UsesofMaterializedViews 745
HowMaterializedViewsWork 745
SettingUp 746
InternalMechanics 747
Expert one-on-one Oracle
10
MakingsureyourViewgetsused 750
Constraints 750
Dimensions 756
DBMS_OLAP 767
EstimatingSize 767
DimensionValidation 769
RecommendingMaterializedViews 772
Caveats 774
MaterializedViewsareNotDesignedforOLTPSystems 774
QueryRewriteIntegrity 774
Summary 775
Chapter14:Partitioning 777
Overview 777
TheUsesofPartitioning 777
IncreasedAvailability 777
ReducedAdministrativeBurden 780
EnhancedDMLandQueryPerformance 781
HowPartitioningWorks 783
TablePartitioningSchemes 784
PartitioningIndexes 789
Summary 813
Chapter15:AutonomousTransactions 814
Overview 814
AnExample 814
WhyUseAutonomousTransactions? 817
AuditingthatCanNotbeRolledBack 817
AMethodtoAvoidaMutatingTable 821
PerformingDDLinTriggers 822
WritingtotheDatabase 828
ToDevelopMoreModularCode 839
HowTheyWork 839
TransactionalControl 840
Scope 842
EndinganAutonomousTransaction 849
Savepoints 850
Caveats 853
NoDistributedTransactions 853
PL/SQLOnly 853
TheEntireTransactionRollsBack 853
Transaction‐LevelTemporaryTables 855
MutatingTables 857
ErrorsYouMightEncounter 860
ORA‐06519ʺactiveautonomoustransactiondetectedandrolledbackʺ 860
Expert one-on-one Oracle
11
ORA‐14450ʺattempttoaccessatransactionaltemptablealreadyinuseʺ 860
ORA‐00060ʺdeadlockdetectedwhilewaitingforresourceʺ 861
Summary 861
Chapter16:DynamicSQL 862
Overview 862
DynamicSQLversusStaticSQL 862
WhyUseDynamicSQL? 865
HowtoUseDynamicSQL 866
DBMS_SQL 866
NativeDynamicSQL 874
DBMS_SQLversusNativeDynamicSQL 880
Caveats 906
ItBreakstheDependencyChain 907
TheCodeisMoreFragile 908
ItisHardertoTune 908
Summary 908
Chapter17:interMedia 910
Overview 910
ABriefHistory 910
UsesofinterMediaText 911
SearchingforText 912
ManagingaVarietyofDocuments 914
IndexingTextfromManyDataSources 915
ItʹsanOracleDatabase,AfterAll 919
GeneratingThemes 920
SearchingXMLApplications 922
HowinterMediaTextWorks 923
interMediaTextIndexing 927
AboutABOUT 931
SectionSearching 932
Caveats 940
ItisNOTDocumentManagement 940
IndexSynchronization 940
IndexingInformationOutsidetheDatabase 941
DocumentServices 942
TheCatalogIndex 943
ErrorsYouMayEncounter 945
IndexOutofDate 946
ExternalProcedureErrors 946
TheRoadAhead 947
Summary 947
Chapter18:C‐BasedExternalProcedures 949
Overview 949
Expert one-on-one Oracle
12
WhenAreTheyUsed? 949
HowAreTheyImplemented? 951
ConfiguringYourServer 953
VerifytheextprocProgram 956
VerifytheDatabaseEnvironment 956
VerifytheListener 958
TheFirstTest 959
Compileextproc.cCode 959
SetUptheSCOTT/TIGERAccount 960
CreatethedemolibLibrary 961
InstallingandRunning 962
OurFirstExternalProcedure 963
TheWrapper 964
TheCCode 976
Buildingtheextproc 1004
InstallingandRunning 1008
LOBtoFileExternalProcedure(LOB_IO) 1009
TheLOB_IOCallSpecification 1010
TheLOB_IOPro*CCode 1012
Buildingtheextproc 1017
InstallingandUsingLOB_IO 1019
ErrorsYouMayEncounter 1025
ORA‐28575ʺunabletoopenRPCconnectiontoexternalprocedureagentʺ 1025
ORA‐28576ʺlostRPCconnectiontoexternalprocedureagentʺ 1026
ORA‐28577ʺargument%sofexternalprocedure%shasunsupporteddatatype
%sʺ 1027
ORA‐28578ʺprotocolerrorduringcallbackfromanexternalprocedureʺ 1027
ORA‐28579ʺnetworkerrorduringcallbackfromexternalprocedureagentʺ . 1028
ORA‐28580ʺrecursiveexternalproceduresarenotsupportedʺ 1028
ORA‐28582ʺadirectconnectiontothisagentisnotallowedʺ 1029
ORA‐06520ʺPL/SQL:Errorloadingexternallibraryʺ 1029
ORA‐06521ʺPL/SQL:Errormappingfunctionʺ 1030
ORA‐06523ʺMaximumnumberofargumentsexceededʺ 1031
ORA‐06525ʺLengthMismatchforCHARorRAWdataʺ 1032
ORA‐06526ʺUnabletoloadPL/SQLlibraryʺ 1032
ORA‐06527ʺExternalprocedureSQLLIBerror:%sʺ 1033
Summary 1033
Chapter19:JavaStoredProcedures 1035
Overview 1035
WhyUseJavaStoredProcedures? 1035
HowTheyWork 1037
PassingData 1042
UsefulExamples 1053
Expert one-on-one Oracle
13
PossibleErrors 1061
ORA‐29549JavaSessionStateCleared 1061
PermissionsErrors 1061
ORA‐29531nomethodXinclassY 1062
Summary 1063
Chapter20:UsingObjectRelationalFeatures 1064
Overview 1064
ReasonsforUsingTheseFeatures 1065
HowObjectRelationalFeaturesWork 1065
AddingDataTypestoyourSystem 1066
AddingDataTypesWrap‐Up 1082
UsingTypestoExtendPL/SQL 1083
CreatingaNewPL/SQLDataType 1083
UniqueUsesforCollections 1095
UsingTypestoExtendPL/SQLWrap‐Up 1101
ObjectRelationalViews 1102
TheTypes 1102
TheO‐RView 1103
Summary 1118
Chapter21:FineGrainedAccessControl 1120
Overview 1120
AnExample 1120
WhyUsethisFeature? 1121
EaseofMaintenance 1121
PerformedintheServer 1122
AvoidsSharedUserAccounts 1124
SupportsSharedUserAccounts 1124
HostinganApplicationasanASP 1124
HowitWorks 1125
Example1:ImplementingaSecurityPolicy 1127
Example2:UsingApplicationContexts 1132
Caveats 1154
ReferentialIntegrity 1154
CursorCaching 1160
Export/Import 1168
Debugging 1172
ErrorsYouMightEncounter 1173
ORA‐28110:policyfunctionorpackage<functionname>haserror. 1173
ORA‐28112:failedtoexecutepolicyfunction. 1175
ORA‐28113:policypredicatehaserror. 1176
ORA‐28106:inputvalueforargument#2isnotvalid. 1178
Summary 1178
Chapter22:n‐TierAuthentication 1180
Expert one-on-one Oracle
14
Overview 1180
WhyUsen‐TierAuthentication? 1180
TheMechanicsofn‐TierAuthentication 1183
GrantingthePrivilege 1194
AuditingProxyAccounts 1195
Caveats 1196
Summary 1198
Chapter23:InvokerandDefinerRights 1199
Overview 1199
AnExample 1199
WhentoUseInvokerRights 1203
DevelopingGenericUtilities 1203
DataDictionaryApplications 1208
GenericObjectTypes 1211
ImplementingyourownAccessControl 1212
WhentoUseDefinerRights 1215
PerformanceandScalability 1215
Security 1216
HowtheyWork 1217
DefinerRights 1217
DefinerRightsandRoles 1221
InvokerRights 1222
Caveats 1235
InvokerRightsandSharedPoolUtilization 1235
Performance 1239
CodemustbemoreRobustinHandlingErrors 1242
SideEffectsofUsingSELECT* 1244
BewareoftheʹHiddenʹColumns 1245
JavaandInvokerRights 1247
ErrorsYouMightEncounter 1254
Summary 1254
AppendixAA:NecessarySuppliedPackages 1256
Overview 1256
WhyUsetheSuppliedPackages? 1257
AboutTheSuppliedPackages 1257
AppendixAB:DBMS_ALERTandDBMS_PIPE 1260
Overview 1260
WhyYouMightUseThem 1260
SetUp 1261
DBMS_ALERT 1261
ConcurrentSignalsbyMorethanOneSession 1264
RepeatedCallstoSignalbyaSession 1266
ManyCallstoSignalbyManySessionsbeforeaWaitRoutineisCalled 1267
Expert one-on-one Oracle
15
Summary 1268
DBMS_PIPE 1268
PipeServersversusExternalRoutines 1271
OnlineExample 1273
Summary 1273
AppendixAC:DBMS_APPLICATION_INFO 1274
Overview 1274
UsingtheClientInfo 1275
UsingV$SESSION_LONGOPS 1278
Summary 1283
AppendixAD:DBMS_JAVA 1284
Overview 1284
LONGNAMEandSHORTNAME 1284
SettingCompilerOptions 1285
SET_OUTPUT 1289
loadjavaanddropjava 1290
PermissionProcedures 1291
Summary 1293
AppendixAE:DBMS_JOB 1294
Overview 1294
RunningaJobOnce 1298
OngoingJobs 1302
CustomScheduling 1305
MonitoringtheJobsandFindingtheErrors 1307
Summary 1310
AppendixAF:DBMS_LOB 1311
Overview 1311
HowdoILoadLOBs? 1312
substr 1312
SELECTFORUPDATEandJava 1313
Conversions 1316
FromBLOBtoVARCHAR2andBackAgain 1316
ConvertingFromLONG/LONGRAWtoaLOB 1321
PerformingaMassOne‐TimeConversionIllustration 1323
PerforminganʹontheflyʹConversion 1327
HowtoWriteaBLOB/CLOBtoDisk 1330
DisplayingaLOBontheWebUsingPL/SQL 1331
Summary 1333
AppendixAG:DBMS_LOCK 1334
Overview 1334
Summary 1338
AppendixAH:DBMS_LOGMNR 1339
Overview 1339
Expert one-on-one Oracle
16
Overview 1341
Step1:CreatingtheDataDictionary 1341
Step2:UsingLogMiner 1345
OptionsandUsage 1352
UsingLogMinertoFindOutWhen 1355
PGAUsage 1357
LogMinerLimits 1359
OracleObjectTypes 1359
ChainedorMigratedRows 1363
Otherlimits 1366
V$LOGMNR_CONTENTS 1367
Summary 1370
AppendixAI:DBMS_OBFUSCATION_TOOLKIT 1372
Overview 1372
TheWrapper 1374
Caveats 1392
KeyManagement 1394
TheClientApplicationManagesandStoresKeys 1394
StoretheKeysintheSameDatabase 1395
StoretheKeysintheFileSystemwiththeDatabase 1396
Summary 1397
AppendixAJ:DBMS_OUTPUT 1398
Overview 1398
HowDBMS_OUTPUTWorks 1399
DBMS_OUTPUTandOtherEnvironments 1404
GettingAroundtheLimits 1409
UsingASmallWrapperFunctionorAnotherPackage 1409
CreatingDBMS_OUTPUTFunctionality 1411
Summary 1418
AppendixAK:DBMS_PROFILER 1419
Overview 1419
Caveats 1431
Summary 1432
AppendixAL:DBMS_UTILITY 1433
Overview 1433
COMPILE_SCHEMA 1433
ANALYZE_SCHEMA 1438
ANALYZE_SCHEMAwithaChangingSchema 1440
ANALYZE_SCHEMAdoesnotAnalyzeEverything 1440
ANALYZE_DATABASE 1442
FORMAT_ERROR_STACK 1442
FORMAT_CALL_STACK 1444
GET_TIME 1448
Expert one-on-one Oracle
17
GET_PARAMETER_VALUE 1449
NAME_RESOLVE 1450
NAME_TOKENIZE 1453
COMMA_TO_TABLE,TABLE_TO_COMMA 1457
DB_VERSIONandPORT_STRING 1459
GET_HASH_VALUE 1460
Summary 1466
AppendixAM:UTL_FILE 1467
Overview 1467
TheUTL_FILE_DIRinit.oraparameter 1467
AccessingMappedWindowsDrives 1469
HandlingExceptions 1471
DumpingaWebPagetoDisk 1472
1023ByteLimit 1473
ReadingADirectory 1474
Summary 1476
AppendixAN:UTL_HTTP 1477
Overview 1477
UTL_HTTPFunctionality 1477
AddingSSLtoUTL_HTTP 1480
ReallyUsingUTL_HTTP 1487
ABetterUTL_HTTP 1490
Summary 1501
AppendixAO:UTL_RAW 1503
Overview 1503
AppendixAP:UTL_SMTPandSendingMail 1506
Overview 1506
UTL_SMTP‐alargerexample 1506
LoadingandusingtheJavaMailAPI 1512
Summary 1521
AppendixAQ:UTL_TCP 1522
Overview 1522
TheSocketType 1523
Summary 1537
AppendixB:Support,Errataandp2p.wrox.com 1539
Overview 1539
TheOnlineForumsatp2p.wrox.com 1539
HowToEnrollForSupport 1539
WhyThisSystemOffersTheBestSupport 1540
CheckingtheErrataOnlineat 1541
FindinganErratumontheWebSite 1541
AddanErratum 1541
HowtoTellUsExactlyWhatYouThink 1543
Expert one-on-one Oracle
18
Introduction
Theinspirationforthematerialcontainedinthisbookcomesfrommyexperiences
developingOraclesoftwareandworkingwithfellowOracledevelopers,helpingthem
buildreliableandrobustapplicationsbasedontheOracledatabase.Thebookisbasicallya
reflectionofwhatIdoeverydayandoftheissuesIseepeopleencounteringeachand
everyday.
IcoveredwhatIfeltwasmostrelevant‐namelytheOracledatabaseanditsarchitecture.I
couldhavewrittenasimilarly‐titledbookexplaininghowtodevelopanapplicationusing
aspecificlanguageandarchitecture‐forexample,oneusingJavaServerPagesthatspeak
toEnterpriseJavaBeans,thatuseJDBCtocommunicatewithOracle.However,attheend
oftheday,youreallydoneedtounderstandthetopicscoveredhereinordertobuildsuch
anapplicationsuccessfully.ThisbookdealswithwhatIbelieveneedstobeuniversally
knowntodevelopsuccessfullywithOracle,whetheryouareaVisualBasicprogrammer
usingODBC,aJavaprogrammerusingEJBsandJDBC,oraPerlprogrammerusingDBI
Perl.Thisbookdoesnotpromoteanyspecificapplicationarchitecture;itdoesnotcompare
3‐tiertoclient‐server.Rather,itcoverswhatthedatabasecandoandwhatyoumust
understandaboutthewayitworks.Sincethedatabaseisattheheartofanyapplication
architecture,thebookshouldhaveabroadaudience.
WhatthisBookisAbout
Oneoftheproblemswithhavingplentyofdevelopmentoptionsisintryingtofigureout
whichonemightbethebestchoiceforyourparticularneeds.Everyonewantsasmuch
flexibilityaspossible(asmanychoicesastheycanpossiblyhave)buttheyalsowant
thingstobeverycutanddry;inotherwords,easy.Oraclepresentsthedeveloperwith
almostunlimitedchoice.NooneeversaysʹyoucanʹtdothatinOra cleʹ‐theysayʹhow
manydifferentwayswouldyouliketodothatinOracle?ʹIhopethatthisbookwillhelp
youmakethecorrect
choice.
Itisabookforthosepeoplewhoappreciatethechoicebutwouldalsolikesomeguidelines
andpracticalimplementationdetailsonOraclefeaturesandfunctions.Forexample,
Oraclehasareallyneatfeaturecalledthevirtualprivatedatabase.Oracledocumentation
tellsyouhowtousethisfeatureand
whatitdoes.Oracledocumentationdoesnot,
however,tellyouwhenyoushouldusethisfeatureand,perhapsevenmoreimportantly,
whenyoushouldnotusethisfeature.Itdoesnotalwaystellyoutheimplementationdetails
ofthisfeature,andifyouʹrenotawareofthem,thiscanreallycomebacktohauntyou(Iʹm
notreferringtobugs,butreallythewayitissupposedtoworkandwhatthefeaturewas
reallydesignedtodo).
Expert one-on-one Oracle
19
WhoShouldUsethisBook?
ThetargetaudienceforthisbookisanyonewhodevelopsapplicationswithOracleasthe
databasebackend.ItisabookforprofessionalOracledeveloperswhoneedtoknowhow
togetthingsdoneinthedatabase.Thepracticalnatureofthebookmeansthatmany
sectionsshouldalsobeveryinterestingtotheDBA.Mostoftheexamplesinthebookuse
SQL*PLUStodemonstratethekeyfeatures,soyouwonʹtfindouthowtodevelopareally
coolGUI‐butyouwillfindouthowtheOracledatabaseworks,whatitskeyfeaturescan
doandwhenthey
should(andshouldnot)beused.
ItisabookforanyonewhowantstogetmoreoutofOraclewithlesswork.Itisforanyone
whowantstoseenewwaystouseexistingfeatures.Itisforanyonewhowantstoseehow
thesefeaturescanbeapplied
intherealworld(notjustexamplesofhowtousethefeature
butwhythefeatureisrelevantinthefirstplace).Anothercategoryofpeoplethatwould
findthisbookofinterestwouldbethetechnicalmanagerinchargeofthedeveloperswho
workonOracleprojects.Insomerespects,itisjustasimportantthattheyunderstandwhy
knowingthedatabaseiscrucialtosuccess.Thisbookcanprovideammunitionforthe
managerwhowouldliketogettheirpersonneltrainedinthecorrecttechnologies,orin
ensuringthattheyalreadyknowwhattheyneedtoknow.
Inordertogetthemostoutofthisbook,thereadershouldhave:
• KnowledgeofSQL.YoudonʹthavetobethebestSQLcoderever,butagood
workingknowledgewouldhelp.
• AnunderstandingofPL/SQL.Thisisnotapre‐requisitebutwillhelpyouto
ʹabsorbʹtheexamples.Thisbookwillnot,forexample,teachyouhowtoprograma
FORloopordeclarearecordtype‐theOracledocumentationandnumerousbooks
coverthiswell.However,thatʹsnottosaythatyouwonʹtlearnalotaboutPL/SQL
byreadingthisbook.Youwill.Youʹllbecomeveryintimatewithmanyfeaturesof
PL/SQLandyouʹllseenewwaystodothings,becomeawareofpackages/features
thatperhapsyoudidnotknowexisted.
• Exposuretosome3GLlanguagesuchasCorJava.Ibelievethatanyonewhocan
readandwritecodeina3GLlanguagewillbeabletosuccessfullyreadand
understandtheexamplesinthisbook.
• FamiliaritywiththeOracleServerConceptsManual.
Afewwordsonthatlastpoint:duetoitsvastsize,manypeoplefindtheOracle
documentationsettobesomewhatintimidating.Ifyouarejuststartingoutorhavenʹtread
anyofitasyet,IcantellyouthattheOracle8iConceptsmanualisexactlytherightplaceto
start.Itisabout800pageslongandtouchesonmanyofthemajorOracleconceptsthat
youneedtoknowabout.Itmaynotgiveyoueach,andeverytechnicaldetail(thisiswhat
theother10,000to20,000pagesofdocumentationarefor)butitwilleducateyouonallof
theimportantconcepts.Thismanualtouchesthefollowingtopics(tonameafew):
Expert one-on-one Oracle
20
• Thestructuresinthedatabase,howdataisorganizedandstored.
• Distributedprocessing.
• Oracleʹsmemoryarchitecture.
• Oracleʹsprocessarchitecture.
• Schemaobjectsyouwillbeusing(tables,indexes,clusters,andsoon).
• Built‐indatatypesanduser‐defineddatatypes.
• SQL‐storedprocedures.
• Howtransactionswork.
• Theoptimizer.
• Dataintegrity.
• Concurrencycontrol.
Iwillcomebacktothesetopicsmyselftimeandtimeagain.Thesearethefundamentals‐
withoutknowledgeofthem,yourOracleapplicationswillbepronetofailure.Iencourage
youtoreadthroughthemanualandgetanunderstandingofsomeofthesetopics.
HowThisBookisStructured
Tohelpyouusethisbook,itisorganizedintosixdiscretesections(describedbelow).
Thesearenotrigiddivisions,buttheywillhelpyounavigatequicklytotheare ayouneed
most.Thisbookhas23chaptersandeachislikeaʹmini‐bookʹ‐avirtuallystandalone
component.Occasionally,Irefertoexamplesorfeaturesinotherchapters(theSecurity
section,inparticular,reliesalittlemoreonexamplesandconceptsthatarebuiltupover
severalchapters)butyoucouldprettymuchpickachapteroutofthebookandreadit
standalone.YouwillnothavetoreadChapter10tounderstandormakeuseofChapter14,
forexample.
Theformatandstyleofeachchapterisvirtuallyidentical:
• Anintroductiontothefeatureorcapability.
• Whyyoumightwanttouseit(ornot).Ioutlinethetimesyouwouldconsiderusing
thisfeatureandwhenyouwouldnotwanttouseit.
• Howtousethisfeature.NotjustacopyoftheSQLreferenceherebutratherstepby
step‐hereiswhatyouneed,hereiswhatyouhavetodo,thesearetheswitches
youneedtogothroughtogetstarted.Thingscoveredinthissectionwillbe:
Howtoimplementit
Examples,examples,andexamples
Debuggingthisfeature
Caveatsofusingthisfeature
Expert one-on-one Oracle
21
Handlingerrors(proactively)
• Asummarytobringitalltogether.
Therewillbelotsofexamples,andlotsofcode,allofwhichwillbeavailablefordownload
at />section:
UnderstandingtheDatabase
• Chapter1,DevelopingSuccessfulOracleApplications.Thischaptersetsoutmy
essentialapproachtodatabaseprogramming.Alldatabasesarenotcreatedequal
andinordertodevelopdatabase‐drivenapplicationssuccessfullyandontime,you
needtounderstandexactlywhatyourparticulardatabasecandoandhowitdoesit.
Ifyoudonotknowwhatyourdatabasecando,youruntheriskofcontinuallyʹre‐
inventingthewheelʹ‐developingfunctionalitythatthedatabasealreadyprovides.
Ifyoudonotknowhowyourdatabaseworksyouarelikelytodevelopapplications
thatperformpoorlyanddonotbehaveinapredictablemanner.
Thechaptertakesanempiricallookatsomeapplicationswherealackofbasic
understandingofthedatabasehasleadtoprojectfailure.Withthisexample‐driven
approach,thechapterdiscussesthebasicfeaturesandfunctionsofthedatabasethat
you,thedeveloper,needtounderstand.Thebottomlineisthatyoucannotaffordto
treatthedatabaseasablackboxthatwillsimplyʹchurnouttheanswersʹandtake
careofscalabilityandperformancebyitself.
• Chapter2,Architecture.TheOracledatabaseisahighlycomplextool.Everytime
youconnecttoadatabaseorissueanUPDATEcommand,awholehostof
processesoccurinthebackgroundtomakesurethatyouʹreapplicationruns
smoothlyandthatdataintegrityismaintained.Forexample,thedatabaseensures
thatithasenoughinformationtorestorethedatatoitsoriginalstateshoulditneed
to.Itwillcacheprogramdataandautomaticallyre‐useitwhereappropriate.And
soon.Mostofthetimeallofthisisoccurstransparently(tothedeveloper,atleast)
butwhen
problemsoccur,halfthebattleisknowingwheretolooktofixthem.
ThischaptercoversthethreemajorcomponentsoftheOraclearchitecture‐its
memorystructures(specifically,theSystemGlobalArea),itsphysicalprocesses,
anditssetoffiles(parameterfiles,redologfiles ).UnderstandingtheOracle
architectureis
fundamentaltounderstandingtheuniquewayinwhichOracle
implementscertainfeaturesandhowthiswillaffectyourapplication.
• Chapter3,LockingandConcurrency.Differentdatabaseshavedifferentwaysof
doingthings(whatworkswellinSQLServermaynotworkaswellinOracle)and
Expert one-on-one Oracle
22
understandinghowOracleimplementslockingandconcurrencycontrolis
absolutelyvitaltothesuccessofyourapplication.
ThischapterdiscussedOracleʹsbasicapproachtotheseissues,thetypesoflocks
thatcanbeapplied(DML,DDL,latches )andtheproblemsthatcanariseiflocking
isnotimplementedcarefully(deadlocking,blockingandescalation).The
concurrencycontrolsectiondiscussesthefunctionsprovidedbyOraclethatallow
ustocontrolhowuserscanaccessandmodifythedatabase.
• Chapter4,Transactions.Transactionsareafundamentalfeatureofalldatabases‐
theyarepartofwhatdistinguishesadatabasefromafilesystem.Andyet,theyare
oftenmisunderstoodandmanydevelopersdonotevenknowthattheyare
accidentallynotusingthem.Thischapterexamineshowtransactionsshouldbe
usedinOracleandalsoexposessomeʹbadhabitsʹthathavebeenpickedupwhen
developingwithotherdatabases.Inparticular,welookattheimplicationsof
atomicityandhowitaffectsstatementsinOracle.Wethenmoveontodiscuss
transactioncontrolstatements(COMMIT,SAVEPOINT,ROLLBACK),integrity
constraintsanddistributed
transactions(thetwo‐phasecommit).Finally,welookat
somerealworldissuessurroundinguseoftransactions‐howtheyarelogged,and
theroleofredoandundo.
DatabaseStructuresandUtilities
• Chapter5,RedoandRollback.Itcanbesaidthatthedeveloperdoesnotneedto
understandthedetailofredoandrollbackasmuchastheDBA,butdevelopersdo
needtoknowtherolestheyplayinthedatabase. After firstdefiningredo,we
examinewhatexactlyaCOMMITdoes.Wealsoconsiderissuessuchashowmuch
redoisbeinggenerated,turningoffloggingandalsoanalyzingredo.
Intherollbacksectionofthechapterwefirstlookwhatgeneratesthemostandleast
undo,beforelookingatthesettransactionSQLstatement.Thisisgenerallyusedto
pickalargerollbacksectionforsomeverylargeoperation.Thenwefocusonthe
infamousʹORA‐01555snapshottoooldʹerror,lookingatcausesandsolutions.
• Chapter6,Tables.Oraclenowsupportsnumeroustypesoftable.Thischapter
looksateachdifferenttype‐heaporganized(thedefault,ʹnormalʹtable),index
organized,indexclustered,hashclustered,nested,temporary,andobject‐and
discusseswhen,how,andwhyyoushouldusethem.Mostoftimetheheap‐
organizedtableissufficient,butyoushouldbeabletorecognizewhenoneofthe
othertypesmightbemoreappropriate.
• Chapter7,Indexes.Indexesareacrucialaspectofyourapplicationdesign.Correct
implementationrequiresanin‐depthknowledgeofthedata,howitisdistributed,
Expert one-on-one Oracle
23
howitwillbeused.Toooften,indexesaretreatedasanafterthoughtinapplication
development,andperformancesuffersasaconsequence.
Thischapterwelookindetailatthedifferenttypesofindexes,includingB*Tree,
bitmap,function‐based,andapplicationdomainindexes,anddiscusswherethey
shouldandshouldnotbeused.Weʹllalsoanswersomeofthosecommonqueriesin
theFrequentlyAnsweredQuestionssection,suchasʹDoindexesworkonviews?ʹand
ʹWhyisnʹtmyindexgettingused?
• Chapter8,ImportandExport.Importandexportaretwooftheoldesttools
suppliedwithOracle,usedtoextracttables,schemasorentiredatabasedefinitions
fromoneOracleinstancetobeimportedintoanotherinstanceorschema,yetmany
developersdonothowtousethemproperly.Wecovertopicssuchaslargeexports,
sub‐settingandtransportingdata,andusingthemasbackuporreorganization
tools.Thechapterfinishesbyhighlightingsomeofthepotentialpitfallsand
problemsintheuseofthesetools.
• Chapter9,DataLoading.ThischapterfocusesonSQLLDRandcoversthevarious
waysinwhichwecanusethistooltoloadandmodifydatainthedatabase.Issues
coveredincludeloadingdelimiteddata,updatingexistingrowsandinsertingnew
ones,unloadingdata,andhowtocallSQLLDRfrom astoredprocedure.Again,
SQLLDRitisawell‐establishedandcrucialtoolbutisthesourceofmanyquestions
withregardtoitspracticaluse.
Performance
• Chapter10,TuningStrategiesandTools.Thisisoneofmyʹspecialisttopicsʹand
hereIdetailmyapproachtotuningOracleapplicationsandthenembarkona
highlypracticalguidetothetoolsandtechniquesthatIuse.Theopeningsection
concentratesonapplicationtuning,coveringtopicssuchasbindvariablesand
parsing,SQL_TRACE,TIMED_STATISTICSandTKPROF,theDBMS_PROFILER,
andtheimportanceoflogginginyourapplications.Withtheapplicationfully
tuned,attentionturnstothedatabaseandspecificallytotheStatsPackgroupof
utilitiesandtheV$tablesyouwilluseintuningefforts.
• Chapter11,OptimizerPlanStability.DevelopersusingOracle8i(andlater)now
havetheabilitytosaveasetofʹhintstotheserverʹ,knownasanoptimizerplan,
detailinghowbesttoexecuteaspecificSQLstatementinthedatabase.Thishas
obviousperformancebenefitsandwetakeadetailedlookathowyoucangenerate
theseoutlinesandhowtomanagethem.
AdvancedSQLFeatures
• Chapter12,AnalyticFunctions.Certainquestionsareaskedofthedatabasevery
regularly,butthequeriesthatcananswerthemaredifficulttowriteinstraightSQL
Expert one-on-one Oracle
24
(andwillnotalwaysperformquickly,anyway).Oracle8.1.6introducedanalytic
functions.ThesefunctionsaddextensionstotheSQLlanguagethatmakesuch
querieseasiertocode,anddramaticallyincreaseperformanceovertheequivalent
straightSQLquery.Thischapterdealswiththewayinwhichanalyticalfunctions
work,lookingatthefullsyntax(includingthefunction,partitionandwindowing
clauses)andthengivesfull,practicalexamplesofhowthesefunctionscanbeused.
• Chapter13,MaterializedViews.Certainʹaggregateʹqueriesmustprocess
potentiallyterabytesofdatatopr oduceananswer.Theperformanceimplications
areclear‐especiallyifitisacommonquery,meaningthatavastamountofdata
hastobeprocessedeachandeverytimethequestionisasked.Withthisfeature,we
simplydosomeoftheworkbeforehand‐wesummarizethedataneededtoanswer
acertainqueryinamaterializedviewandfuturequeriesaredirectedatthis
summarydata.Furthermore,thedatabasecanrecognizesimilarqueriesthatmake
useofthissummarydata,andautomaticallyre‐writesthe
querytoallowthemto
doso.Thischapterdiscusseshowallthisworksandhowtosetupmaterialized
views,includinguseofconstraints,dimensions,andtheDBMS_OLAPpackage.
• Chapter14,Partitioning.Partitioningisdesignedtofacilitatethemanagementof
verylargetablesandindexes,byimplementingaʹdivide‐and‐conquerʹlogic‐
basicallybreakingupatableorindexintomanysmaller,andmoremanageable,
pieces.ItisanareawheretheDBAanddevelopermustworktogethertomaximize
applicationavailabilityandperformance.Thischaptercoversbothtableandindex
partitioning.Welookatpartitioningusinglocalindexes(commonindata
warehouses)andglobalindexes(commoninOLTPsystems).
• Chapter15,AutonomousTransactions.Withthisfeature,wecancreateasub‐
transactionthatcancommitorrollbackchangesindependentlyofitsparent
transaction.Welookatthesituationswhenthismightbedesired,suchaswhen
auditinganʹillegalʹattempttomodifysecureinformation,toavoidmutatingatable
orasawayofperformingDDLintriggers.Thediscussionwillspanissuessuchas
transactionalcontrol,scope,endinganautonomoustransaction,andsavepoints.
• Chapter16,DynamicSQL.Inthischapter,wecomparetwomethodsofusingSQL
statementsinourprograms:ʹnormalʹstaticSQLanddynamicSQL.DynamicSQLis
theSQLexecutedatrun‐time,butwasnotknownatcompiletime.Wewilllookat
twomethodsofusingdynamicSQLinyourprograms,namelywiththesupplied
built‐inpackageDBMS_SQLandnativedynamicSQL,adeclarativemethodforuse
withPL/SQL.Therearevariousreasonswhyyouwouldchooseoneovertheother,
suchaswhetherthebindvariablesareknownatcompiletime,whetheryouknow
theoutputsatcompiletime,andwhetheragivenstatementwillbeexecutedonce,
ormanytimesinasessionandwewillexploretheseissuesindetail.
Extensibility
• Chapter17,interMedia.ThischapterfocusesoninterMediaText.Ratherthana
detailedʹhowtouseinterMediaTextʹ,wewillcoverwhatitisandwhatitprovides,
Expert one-on-one Oracle
25
andthefeaturesofthedatabasethatenablethisfunctionality.Welookathowto
searchfortext,manageavarietyofdocuments,indextextfrommanydatasources,
andsearchXMLapplications.Thechapterfinisheswithalookatsomeofthe
caveatsofinterMedia,includingthesynchronizationofindexesandindexing
informationoutsideofthedatabase.
• Chapter18,C‐BasedExternalProcedures.WithOracle8.0cametheabilityto
implementproceduresinthedatabaseserverthatwerewritteninlanguagesother
thanPL/SQL‐forexample,CorJava.Thesearereferredtoasexternalprocedures.In
thischapter,wewillcoverC‐basedproceduresfromanarchitecturalperspective.
Weseehowtoconfigureyourservertousetheseprocedures,testtheinstallation,
andcreateanexampleprocedureforpassingandmanipulatingvarioustypesof
variables.WealsoexaminetheLOBtoFile(LOB_IO)externalprocedure,which
writestheCLOBs,BLOBs,andBFILEstodisk.
• Chapter19,JavaStoredProcedures.WithjudicioususeofsmallamountsofJava,
wecanachieveagreatdealofusefulfunctionalitythatisbeyondthereachof
PL/SQL.Inthischapter,welookatpracticalexamplesofwherethisabilityisuseful
‐suchaswhengettingadirectorylistingorrunninganoperatingsystemcommand.
Again,weroundoffthechapterwithsomeoftheerrorsthatyoumayencounter
whenyoutrytousethisfeature,andsomepossiblesolutions.
• Chapter20,UsingObjectRelationalFeatures.Theavailabilityofobject‐relational
featuresinthedatabase(withOracle8ionwards)greatlyextendsthesetofdata
typesavailabletothedeveloper‐butwhenshouldtheybeused(and,equally,
whenshouldnʹttheybeused)?Inthischapter,weshowhowtoaddnewdatatypes
toyoursystem(wecreateanewPL/SQLdatatype)andlookattheuniqueusesfor
collections.Finallywelookatobjectrelationalviews,whichareforthoseofyou
whowanttoworkwithobjectrelationalfeaturesbutstillpresentarelationalview
ofthedatatotheapplication.
Security
• Chapter21,FineGrainedAccessControl.Thisfeatureallowsyoutoattacha
predicate,atrun‐time,toallqueriesissuedtoadatabase.Thefactthatthisfeatureis
implementedontheservermeansthatanyapplicationthatcanaccessthedatabase
canusethefeature.Furtherreasonstousethisfeatureincludeeaseofmaintenance
andtheabilitytohostanapplicationasanASP.Youwillalsoseehowitworksby
testingacoupleofexamples,onebasedonimplementingasecuritypolicyandone
usingapplicationcontexts.Thechapterisroundedoffwithasectiononcaveats,
whichincludereferentialintegrity,importandexportissues,andasectionon
errors.
• Chapter22,n‐TierAuthentication.Inthischapterwewilldiscusstheeffectsofthe
Web,whichgivesrisetosituationswhereyourclientpresentstheircredentialstoa
middle‐tierapplicationserver,beforeactuallyaccessingyourdatabase.Wewillsee