Você está na página 1de 491

1

CourseObjectives InthiscourseyouwillinstalltheOracleDatabase10g EnterpriseEditionsoftware, createanewdatabase,andlearnhowtoadministerthedatabase. Youwillalsoconfigurethedatabasetosupportanapplication,performingtasks suchascreatingusers,definingstoragestructures,andsettingupsecurity.This courseusesafictionalapplication.Howeveryouwillbeperformingallthecore tasksnecessaryforarealapplication. Databaseadministrationdoesn doesnt tendafterthedatabaseisconfigured configured,soyouwill alsolearnhowtoprotectyourdatabasebydesigningabackupandrecovery strategy,andhowtomonitorthedatabasetoensureitoperatessmoothly.

OracleProducts OracleDatabase:OracleDatabaseisthefirstdatabasedesignedfor enterprisegridcomputing,themostflexibleandcosteffectivewayto manageinformationandapplications.OracleDatabaseisavailableinthree editions Enterprise,Standard,andPersonal. OracleApplicationServer:OraclesJava2EnterpriseEdition(J2EE)certified server,integratingeverythingneededtodevelopanddeployWebbased applications Theapplicationserverdeploysebusinessportals applications. portals,Web services,andtransactionalapplicationsincludingPL/SQL,OracleForms,and J2EEbasedapplications. OracleApplications:OracleEBusinessSuiteisacompletesetofbusiness applicationsformanagingandautomatingprocessesacrossyour organization. OracleCollaborationSuite:OracleCollaborationSuiteisasingle,integrated systemforallyourorganizationscommunicationsdata:voice,email,fax, wireless,calendarinformation,andfiles. OracleDevelopmentSuite:OracleDeveloperSuiteisacomplete,integrated environmentthatcombinesapplicationdevelopmentandbusiness intelligencetools. OracleServices:ServiceslikeOracleConsultingandOracleUniversity providetheexpertiseyouneedtokeepyourOracleprojectontrackand runningsmoothly.

RelationalDatabaseSystems Dr.E.F.Coddpublished,ARelationalModelofDataforLargeSharedDataBanks, inJune,1970,intheAssociationofComputerMachinery(ACM)journal, CommunicationsoftheACM.Codd'smodelisnowacceptedasthedefinitivemodel forrelationaldatabasemanagementsystems(RDBMS).Thelanguage,called structuredEnglishquerylanguage(SEQUEL),wasdevelopedbyIBMCorporation, Inc.,touseCodd'smodel.SEQUELlaterbecameSQL(stillpronouncedsequel).In 1979 RelationalSoftware, 1979, Software Inc. Inc (nowOracleCorporation)introducedthefirst commerciallyavailableimplementationofSQL.Today,SQLisacceptedasthe standardRDBMSlanguage. Thebasicelementofarelationaldatabasesystemisatwodimensionaltable.A tableconsistsofzeroormorerowsofdata.Eachrowhasoneormorecolumns.A singlecolumnofasinglerowisreferredtoasafieldorcellofdata. Eachrowofdataisacollectionofdataitemsrelatingtoagivensubject.For example,youmighthaveatabletoholdinformationaboutemployeesinyour company.Eachrowrepresentsoneemployeeinthecompany,andthecolumnsmay bethingssuchas,firstandlastname,email,phonenumber,hiredate,andsoon. Eachcolumnhasanameandadatatypeassociatedwithit.Thedatatypedefines whatkindofdataisallowedinthecolumn,forexamplenumbersorcharacters.

HowtheDataIsOrganized Arelationaldatabasehasmanytables,whichcanbeusedindependentlyorjoined togetherbyusingacommoncolumn(orcolumns)betweenthetables.WithOracle Database10g youmayrequirethatthecolumnusedtoestablishtherelationship withanothertablecontainvaluesthatalreadyexistinthattable.Thismandatory relationshipisknownasreferentialintegrity.Usingtheexampleofemployees,each employeeinyourcompanyisassignedtoaparticulardepartment.Becausea departmentmayhavemanyemployees employees,itwouldberedundanttohavethe departmentinformationstoredwitheachrowintheemployeestable.Instead,each rowintheemployeestablehasacolumnwhichisanidentifierpointingtothe departmentstable.Thisallowsyoutojointheemployeestablewiththe departmenttableandseewhichdepartmentanemployeeisassignedto. Thisidentifierisakeyfield.Intheemployeestablethedepartmentsfieldiscalleda foreignkey,becauseitpointstoarowinadifferent(foreign)table.Inthe departmenttablethefieldreferencedbyaforeignkeyintheemployeestableis typicallytheprimarykey,orsometimesanalternatekey.Thisprimarykeyfieldmust havecertainpropertiesinthedepartmenttable.Thefieldmustbeuniqueandmust alwayshaveavalue.Thiswayeachrowintheemployeestablewillpointtooneand onlyonerowinthedepartmenttable.

IntegrityConstraints Youcanuseintegrityconstraintstodefinebusinessrulesinyourrelational database.Thediagramshowsanentityrelationshipdiagram(ERD)ofaHuman Resources(HR)application.TheERDshowsthetablesandrelationsbetweenthem. TheERDisusedtodefineconstraintsthatareusedtoensurevaliddataisstoredin yourdatabasetables. Integrityconstraintsaredefinedaspartofatablesdefinitioninthedatadictionary, sothatallapplicationsaccessingthetablemustadheretotherulesdefinedbythe constraints.Whenyouneedtochangearule,youneedtochangeitonlyonceat thedatabaselevelandnotineachapplicationthataccessesthetable. OracleDatabase10g supportsthefollowingtypesofconstraints: NOT NULL:Disallowsnulls(emptyentries)inatablescolumn UNIQUE:Disallowsduplicatevaluesinacolumnorsetofcolumns PRIMARY KEY:Disallowsduplicatevaluesandnullsinacolumnorsetof columns FOREIGN KEY:Requireseachvalueinacolumnorsetofcolumnsto matchavalueinarelatedtablesUNIQUE orPRIMARY KEY.FOREIGN KEY integrityconstraintsalsodefinereferentialintegrityactionsthatdictate whatOracleshoulddowithdependentdataifthedataitreferencesis altered. CHECK:Disallowsvaluesthatdonotsatisfythelogicalexpressionofthe constraint.

StructuredQueryLanguage StructuredQueryLanguage(SQL)isthesetofstatementswithwhichallprograms andusersaccessdatainanOracledatabase.ApplicationprogramsandOracletools oftenallowusersaccesstothedatabasewithoutusingSQLdirectly,butthese applicationsinturnmustuseSQLwhenexecutingtheusersrequest. SQLenablesyoutoworkwithdataatthelogicallevel.Forexample,toretrieveaset ofrowsfromatable,youdefineaconditionthatisusedtofiltertherows.Allrows satisfyingtheconditionareretrievedinasinglestepandcanbepassedasaunitto anapplicationortoanotherSQLstatement.Youdonotneedtoknowhowtherows arephysicallystoredorretrieved.AllSQLstatementsusetheOracleDatabase optimizertodeterminethemostefficientmeansofaccessingthespecifieddata. SQLwillbecoveredinmoredetailinLesson4,DatabaseInterfaces.Alsoreferto theOracleDatabaseSQLReferenceforadditionalinformation.

TasksofanOracleDatabaseAdministrator AnOracledatabaseadministrator(DBA)istypicallyresponsibleforinstallingthe Oraclesoftwareandcreatingthedatabase.Youmayberesponsibleforcreatingthe databasestoragestructuressuchastablespaces.Inaddition,youmaycreatethe schemaorsetofobjectstoholdapplicationdata. Youneedtoensurethatthedatabaseisavailableforusers.Youcanaccomplishthis bystartingupthedatabase,backingupthedatabaseonaregularbasis,and monitoringtheperformanceofthedatabase database. Asyouproceedthroughthelessonsinthiscourse,youwilllearnhowtoperform eachofthesetasks.YoucanalsorefertotheOracleDatabaseAdministratorsGuide foradditionalinformationabouteachofthetasksoutlinedintheslide.

OracleDatabase10g:Administration WorkshopI213

SystemRequirements Thehardwarerequirementslistedintheslideareminimalrequirementsacrossall platforms.Yourinstallationmayrequiremore,especiallydiskspace.Also,asa generalrule,themoreRAMyouhaveavailablethebetter. Note: Onsystemswith2GBormoreofRAM,theswapspacecanbebetweenone andtwotimesthesizeofRAM. Becauseeachoperatingsystemhasdifferentrequirements,youmustrefertothe operatingsystem systemspecific specificOracledocumentationforinformationaboutoperating systemrequirements.Thesewilllistthereleasesoftheoperatingsystemthatare supported,alongwithhowtosetupanyoperatingsystemgroupsorusers,and otherstepsthatareneededfortheinstallation. Forthiscourseallthenecessaryoperatingsystemrequirementstepshavebeen completed.

OracleDatabase10g:Administration WorkshopI214

OptimalFlexibleArchitecture(OFA) OFAisamethodforconfiguringtheOracledatabaseandotherdatabases.OFA takesadvantageoftheOSanddisksubsystemscapabilitiestocreateaneasyto administerconfigurationthatallowsmaximumflexibilityforgrowingandhigh performancedatabases.ThemethodsdescribedherearethebasicsofOFA. OFAisdesignedto: Organizelargeamountsofcomplicatedsoftwareanddataondisk,toavoid devicebottlenecksandpoorperformance Facilitateroutineadministrativetaskssuchassoftwareanddatabackup, whichareoftenvulnerabletodatacorruption FacilitateswitchingbetweenmultipleOracledatabases Adequatelymanageandadministerdatabasegrowth Helpeliminatefragmentationoffreespaceinthedatadictionary,isolate otherfragmentation,andminimizeresourcecontention FordetailsonthegoalsandimplementationofOFA,refertoOracleInstallation GuideforUNIXSystems, AppendixD.

OracleDatabase10g:Administration WorkshopI215

UsingOptimalFlexibleArchitecture AtthecoreofOFAisanamingscheme,whichgivesyouastandardtoapplytoyour mountpoints(whichareoftenthephysicaldisks),directoriesandsubdirectorieson thosemountpoints,andfinallythefilesthemselves. Mountpointsyntax: Nameallmountpointsusingthesyntax/pm,where p isa stringconstantand m isauniquefixedlengthkey(typicallyatwodigitnumber) usedtodistinguisheachmountpoint.Examplemountpointsare/u01,and/u02. Homedirectoriessyntax: Nameallhomedirectoriesusingthesyntax/pm/h/u. Wherepm isamountpointname, h isa standarddirectorynameand u isthe nameoftheownerofthedirectory.ExamplesofOFAcomplianthomedirectories are: /u01/app/oracle /u01/home/oracle Softwaredirectoriessyntax: TohelpfulfilltheOFAfeatureofsimultaneously executingmultipleversionsofapplicationsoftware,storeeachversionoftheOracle softwareinadirectorymatchingthepattern/pm/h/u/product/v.Here product isaliteralandthevariable v isusedfortheversionnumber.SoanOFA compliantinstallationoftheOracleDatabase10g version10.1.0wouldlooklike: /u01/app/oracle/product/10.1.0

OracleDatabase10g:Administration WorkshopI216

UsingOptimalFlexibleArchitecture(continued) Namingsubdirectoriessyntax: Tofacilitatetheorganizationofadministrativedata, youshouldstoredatabasespecificadministrationfilesinsubdirectoriesmatching thepattern /h/admin/d/a/,where h istheOraclesoftwareownershome directory, admin isaliteral, d isthedatabasename,and a isasubdirectory foreachofthedatabaseadministrationfiles.Followingisalistofthese administrationfilesubdirectories: adhoc:AdhocSQLscriptsforaparticulardatabase arch:Archivedredologfiles adump :Auditfiles(SettheAUDIT_FILE_DEST AUDIT FILE DEST initializationparameter totheadump directory.Cleanoutthissubdirectoryperiodically.) Bdump:Backgroundprocesstracefiles Cdump:Coredumpfiles Create:Programsusedtocreatethedatabase Exp:Databaseexportfiles Logbook:Filesrecordingthestatusandhistoryofthedatabase Pfile i :Instance I parameterfiles fil udump:UserSQLtracefiles Filenamingsyntax: Thefollowingnamingconventionfordatabasefilesensures thattheyareeasilyidentifiable: Controlfiles:/pm/q/d/control.ctl Redologfiles:/pm/q/d/redon.log pm/q/d/tn.dbf Datafiles:/p Thevariablesusedinthesefilenamesare: Pm:Amountpointnameasdescribedpreviously q:AstringdistinguishingOracledatafromallotherfiles(commonlynamed ORACLEororadata) d: ThevalueoftheinitializationparameterDB_NAME (thedatabasename) t: AnOracletablespacename n: Atwo t digit di itstring ti Note: Donotstorefilesotherthancontrolfiles,redologfiles,ordatafiles associatedwithdatabased inthepath/pm/q/d/.

OracleDatabase10g:Administration WorkshopI217

SettingEnvironmentVariables TherearemanyOracleenvironmentvariables,andtheonesmentionedhereare veryimportanttoasuccessfulinstallationanduseofanOracledatabase.Noneof thesearerequiredtobeset,butbysettingthempriortotheinstallationyoumay avoidfutureproblems. ORACLE_BASE:SpecifiesthebaseoftheOracledirectorystructurefor OFA.Useofthisisoptional,butifusedthiscanfacilitatefutureinstallations andupgrades. upgrades Itisadirectorypathforexample: /u01/app/oracle ORACLE_HOME:SpecifiesthedirectorycontainingtheOraclesoftware.Itis adirectorypath,forexample: $ORACLE_BASE/product/10.1.0 ORACLE_SID:Theinitialinstancename(ORCL bydefault).Itisastringof numbersandlettersthatmustbeginwithaletter.OracleCorporation suggeststhatamaximumofeightcharactersbeusedforsystemidentifiers.

OracleDatabase10g:Administration WorkshopI218

SettingEnvironmentVariables(continued) NLS_LANG:SpecifiestheinitialNLSsettingsforasessionontheform language_territory.character set.Forexample,asettingof: AMERICAN DENMARK WE8MSWIN1252 AMERICAN_DENMARK.WE8MSWIN1252 ThissetsthesessiontousethelanguageAMERICAN forOracle messages,sorting,daynames,andmonthnames.Theterritoryis DENMARK,whichsetsthetimeformat,dateformat,andnumericand monetaryconventions.ThecharactersetofWE8MSWIN1252 instructs OracleNettoconvertcharacterinformationtothischaracterset.Thisisan environmentvariableinUNIXandaregistrysettinginWindows.Youcan querythe h actual lNLSsettingsof fyourcurrentsessionby: b select*fromnls_session_parameters; RefertotheGlobalizationSupportGuide forvalidlanguages,territories, charactersets,andmoreinformationaboutlanguagesupport. Note:AWindowsinstallationdefaultstheNLS_LANG valuesinthe registrywherethelanguage partoriginatesfromthekeyboardlanguage. ThishastheeffectthatdefaultinstallationonWindowswithnonAmerican keyboardswillgetthenonAmericanvalueintheNLS_LANG setting.This inturnwilldefaulttheNLS_SORT sessionvariabletobedifferentfrom binary,whichmakesitdifficultfortheoptimizertousecharacterbased indexesforsessionsfromthisnode.

OracleDatabase10g:Administration WorkshopI219

PreinstallationChecks BeforetheOracleUniversalInstallerGUIinterfaceislaunched,thereareanumber ofchecksthatareperformedtoverifythatminimalrequirementsaremet.Inthe eventthatyoursystemdoesntmeetoneormoreoftherequirements,youcan choosetocontinuetheinstallationbyusingtheignoreSysPrereqs flagwhen runningtheinstaller.However,thelikelihoodofasuccessfulinstallationisgreatly reducediftherequirementsarenotmet.Forexample: $sh hrunInstaller I t ll ignoreSysPrereqs i S P Note: Youcanusethehelp flagtoseemoreoptionsfortheOracleUniversal Installer.

OracleDatabase10g:Administration WorkshopI220

OracleUniversalInstaller OracleUniversalInstallerisaJavaapplicationthatperformscomponentbased installationsandenablesdifferentlevelsofintegratedbundle,suite,andWebbased installations,aswellascomplexlogicinasinglepackage.Theinstallationengineis easilyportableacrossallJavaenabledplatforms,andplatformspecificissuescan beencapsulatedfromtheoverallinstallationprocess.TheOracleUniversalInstaller providesthefollowingcapabilitiesforaddressingsoftwaremanagementand distribution: Automaticdependencyresolutionandcomplexlogichandling InstallationfromtheWeb Componentandsuiteinstallations Implicitdeinstallation SupportformultipleOraclehomes Nationallanguagesupport(NLS)/globalizationsupport Supportfordistributedinstallations Unattendedsilentinstallationsusingresponsefiles

OracleDatabase10g:Administration WorkshopI221

InventoryandUNIXGroupName Theinventorydirectoryisanareathatisusedduringtheinstallationofthe software.Thefilesinthisdirectoryshouldnotbedeleted.TheOracleUniversal InstallerinventoryisthelocationfortheOracleUniversalInstallersbookkeeping. Theinventorystoresinformationabout: AllOraclesoftwareproductsinstalledinallOraclehomesonamachine OthernonOracleproductsincludedwithOraclesoftware,suchastheJava RuntimeEnvironment(JRE) Youshouldexpectthesefilestotakeupabout4MBofspace. IfyouareinstallingaproductonaUNIXsystem,theInstallerwillalsopromptyouto providethenameofthegroupthatshouldownthebasedirectory.Youmust chooseaUNIXgroupnamethatwillhavepermissionstoupdate,install,and deinstallOraclesoftware.Membersofthisgroupmusthavewritepermissionsto thebasedirectorythatischosen.Onlyuserswhobelongtothisgroupareableto installordeinstallsoftwareonthismachine.

OracleDatabase10g:Administration WorkshopI222

orainstRoot.sh WheninstallingonaUNIXplatform,youmustruntheorainstRoot.sh scriptas root.Thisscriptcreatestheinventorypointerfile(onLinuxthisfileis /etc/oraInst.loc).TheinventorypointerfileisusedbytheOracleUniversal Installeratstartuptofindtheinventorylocation.Anexampleofthefileis: inventory_loc=/oracle/oraInventory inst_group=oinstall WithaMicrosoftWindowsinstallationtheinventorylocationiscontainedwithin theregistry.

OracleDatabase10g:Administration WorkshopI223

orainstRoot.sh (continued) TheoraintRoot.sh scriptlookslikethefollowing: #!/bin/sh INVPTR=/etc/oraInst INVPTR /etc/oraInst.loc loc INVLOC=/oracle/oraInventory GRP=oinstall PTRDIR="`dirname$INVPTR`"; #Createthesoftwareinventorylocationpointerfile if[!d"$PTRDIR"];then mkdirp$PTRDIR; fi echo"CreatingtheOracleinventorypointerfile($INVPTR)"; echoinventory_loc=$INVLOC>$INVPTR echoinst_group=$GRP>>$INVPTR chmod644$INVPTR #Createtheinventorydirectoryifitdoesn'texist if[!d"$INVLOC" $ ]; ];then echo"CreatingtheOracleinventorydirectory($INVLOC)"; mkdirp$INVLOC; chmod775$INVLOC; fi echo"Changinggroupnameof$INVLOCtooinstall."; chgrpoinstall$INVLOC; if[$?! !=0]; ] then th echo"WARNING:chgrpof$INVLOCtooinstallfailed!"; fi

OracleDatabase10g:Administration WorkshopI224

FileLocations The h Universal i lInstaller ll provides id ad default f l value l onthe h Specify S if File il Locations i page thatpointstothelocationoftheproductsinstallationkitorstage. Oraclehomesareidentifiedbyname.TheOraclehomenameidentifiesthe programgroupassociatedwithaparticularOraclehomeandtheOracleservices installedontheassociatedhome.TheOraclehomenamemustbe1to16 characterslongandcanincludeonlyalphanumericcharactersandunderscores,and mustnotincludespaces. OracleUniversalInstallermaintainsthefollowingOraclehomesonWindows platforms: AllOraclehomesthatarealreadycreatedusingtheOracleUniversalInstaller AllhomescreatedusingthepreviousOracleUniversalInstaller(ORCA based) ThehomesavedintheORACLE_HOME registryentry. OracleUniversalInstallermaintainsthefollowingOraclehomesonUNIX: AllOraclehomesthatarealreadycreatedusingtheOracleUniversalInstaller Allhomesasdefinedinthe/var/opt/oratab file(InLinux, /etc/oratab) ThehomesavedintheORACLE_HOME environmentvariable Ifnoneofthesehomesexists,adefaulthomeiscalculatedbasedonthedisk volumewiththelargestamountoffreespace.

OracleDatabase10g:Administration WorkshopI225

InstallType OracleDatabaseEnterpriseEditionoffersindustryleadingscalabilityandreliability inbothclusteredandsinglesystemconfigurations.Itprovidesthemost comprehensivefeaturesforonlinetransactionprocessingandbusinessintelligence. OracleStandardEditionisforsmallandmediumbusiness,ordepartmental applicationsthatdemandallthepower,reliability,andsecurityofOraclewithoutall theEnterpriseoptions. Thefollowingenterpriselevelfeaturesaresomeoftheoptionsnotavailablewith theOracleStandardEdition: OracleDataGuard:Acomprehensivesetofservicesthatcreate,manage, andmonitoroneormorestandbydatabases. OracleAdvancedSecurity,OracleLabelSecurity,EnterpriseUserSecurity, VirtualPrivateDatabase,Ntierauthentication,andFineGrainedAuditing: TheseoptionsextendthesecurityfeaturesoftheOracleDatabase10g. OraclePartitioning,OracleOLAP,ExportTransportableTablespace,andother featuresthatsupportEnterpriseDataWarehouses. Thecustominstallallowsyoutopickindividualcomponentstoinstall.

OracleDatabase10g:Administration WorkshopI226

PrerequisiteChecks Beforeinstallation,theOracleUniversalInstallercheckstheenvironmentfor requirementsnecessaryforasuccessfulinstallation.Thispageshowthename,type andstatusforallprerequisitechecks.Automaticchecksarerunfirst,ifthereare optionalchecksyoucanrunthemoncetheautomaticchecksarecompete. Onceallchecksarecomplete,therewillbeasummaryofthechecksdoneonthe lowerpartofthepage.Acheckmayrequireverificationifawarningwasproduced duringtheexecutionoramanualcheckwasnotconfirmed confirmed.Toverifyawarningor manualcheck,clickthecheckboxforthecheckthatproducedawarningorisa manualcheck.

OracleDatabase10g:Administration WorkshopI227

StarterDatabase Therearethreetemplatedatabasefromwhichyoucanchoose,oryoucansetupa customstarterdatabase.Thetemplatedatabasesusepreconfiguredfilesand createadatabasequickly,althoughwiththeseyoucancustomizethedatabase.The advancedoptionallowsyoutotalflexibilityinthecreationofthestarteddatabase, butdoestakelongertobuild. Note: Ifyouchoosenottocreateastarterdatabase,thesummarypageappears next. next

OracleDatabase10g:Administration WorkshopI228

ConfigurationandManagement Ifyouselecttocreateastarterdatabaseaspartofyourinstall,youwillgothrougha seriesofpagesaskingyouforinformationtoconfigurethestarterdatabase. DatabaseNaming:Hereyounamethedatabase;thedefaultisorcl. DatabaseCharacterSet:Thisisthecharactersetusedinthedatabaseto storeyourdata.Youshouldtakesometimetodeterminewhatisthebase charactersetforyourdata.Althoughitispossibletochangeacharacterset later itcanbeaverytimeconsumingtask, later, task andwillrequiresomedowntime foryourdatabase.Ifunsureaboutwhichcharactersettouseandyouknow youwillbeusingmultiplelanguages,theUnicodeStandardUFT8AL32UTF8 isagoodchoice.TheWE8ISO8859P1charactersetdoesnthavesupportfor theeurosymbol(),butWE8ISO8859P15does.Formoredetailson selectingtheappropriatecharacterset,seetheOracleDatabase GlobalizationSupportGuide. SampleSchemas:Thesampleschemasareasetofschemasusedfor demonstrationsandtraining. DatabaseManagement:Gridcontrolisusedtomanagemanydatabases eitherononemachineorseveralmachines.Databasecontrolisusedto manageasingledatabase.

OracleDatabase10g:Administration WorkshopI229

FileStorageandBackupRecovery Filestorageoptions: FileSystem:ThisspecifieswheretostorefilesinyourOSconfiguredfile system. AutomaticStorageManagement(ASM):AutomaticStorageManagement filesarecreatedandmanagedautomatically,andyougettheadditional benefitsoffeaturessuchasmirroringandstriping.Fordetailsonhowtoset upASM, ASM seetheOracleDatabaseAdministrators Administrator sGuide. RawDevices(Partitions):Thesearediskpartitionswithoutafilesystemon them.Generallyyoushouldusetheseonlyifyouareveryfamiliarwiththe useofrawpartitionsalready.CheckyourOSdocumentationfordetailson settingupandmaintainingrawpartitions. BackupandRecoveryOptions: DonotenableAutomatedbackups:Eventuallyyouwillneedtosetupa backupplan.Ifyouselectnottosetitupnowyoucandosolater. EnableAutomatedBackups:WhenyouenableAutomatedBackups,you needtospecifywherethebackupswillbestored,andinformationaboutthe backupjobusedforthebackups.

OracleDatabase10g:Administration WorkshopI230

PasswordsandSummary DatabaseSchemaPasswords:Providepasswordsfortheadministrativeusers SYS,SYSTEM,SYSMAN,andDBSNMP.Youcanprovideapasswordfor eachoneseparatelyorprovideonepasswordforall. Summary:Hereyouseealltheproductsandsettingsyouselectedforthe installation.Thenextstepistoinitiatetheinstallation.Checkthesummary thenclickInstalltostarttheactualinstallation.

OracleDatabase10g:Administration WorkshopI231

Installation Duringtheinstallationyoucanwatchtheprogressionoftheinstallation.

OracleDatabase10g:Administration WorkshopI232

ConfigurationAssistants Ifyouhaveselectedtocreateastarterdatabasewiththeinstall,theconfiguration assistantspagewillbedisplayedatthecompletionofthesoftwareinstall. iSQLPlusConfigurationAssistant:ThisconfigurestheOC4J(Oracle ContainersforJava)instancewhichisusedbyiSQLPlusandothertoolsto connecttotheOracledatabase. OracleNetConfigurationAssistant:Thisconfiguresbasicnetwork componentsduringinstallation, installation including(thesecomponentsarecoveredin detailinlaterlessons): Listenernamesandprotocoladdresses Namingmethodstheclientwillusetoresolveconnectidentifiersto connectdescriptors Netservicenamesinatnsnames.orafile Directoryserverusage OracleDatabaseConfigurationAssistant:Thiscreatesthestarterdatabase youselected.Itusestheselectionyoumadetocreatethedatabase.Inthe nextlessonyouwilllearnmoreaboutOracleDatabaseConfiguration Assistant.Whenthisconfigurationassistantfinishesyouwillhavethe opportunitytounlockaccountsandchangepasswords.

OracleDatabase10g:Administration WorkshopI233

ConfigurationAssistants(continued) WheninstallingonaUNIX(orLinux)OS,oryoudidnotchosetocreateastarted database,youwillbepromptedtorunonemorescriptasroot.Thescriptisnamed root.sh.Thisscriptupdatesorcreatesafilethatcontainsinformationabout ORACLE_HOME locationsanddatabases.InaLinuxinstallationthefileisnamed /etc/oratab. WithaninstallationonMicrosoftWindowsOS,thereisnoroot.sh script becausetheinformationaboutORACLE_HOME anddatabasesisstoredinthe registry.Theoratab fileisthefilewheretheuserplacesreferencestoall databasestobediscoveredbytheAgentandcontrolledbyOracleEnterprise Manager.

OracleDatabase10g:Administration WorkshopI234

OracleDatabase10g:Administration WorkshopI235

OracleDatabase10g:Administration WorkshopI236

Practice2 InstalltheOracleSoftware DuringthepracticesofthiscourseyouwillassumetheroleofanewDBAwhowillbe supportingadatabasewhichisusedforaHumanResourcesapplication.Youworkfor anITmanager;yourcoworkerisanOracleCertifiedProfessional. Professional TheOSaccountsonyourmachineare: Theoracle userwithapasswordoforacle. Theroot userwithapasswordoforacle. ThesystemadministratorhassetuptheOSsothatitisreadyfortheinstallandthe installmediaisstagedat/stage/Disk1.Installthesoftwareastheuseroracle. Settheglobalnametoorcl.oracle.com andtheSIDtoorcl U AL32UTF8 Use 32 8 for f the h database d b character h set Createthedatabasewithsampleschemas Makesureoinstall istheselectedgroupnameontheUnixGroupName screen AcceptthedefaultsontheSpecifyFileLocationspage CreateadatabaseusingtheGeneralPurposetemplate Useoracle asthep passwordforalltheadministrationaccounts(sys y , system,sysman anddbsnmp) UnlocktheHRschema

OracleDatabase10g:Administration WorkshopI237

OracleDatabase10g:Administration WorkshopI339

DatabaseArchitecture ThefilesthatconstituteanOracledatabaseareorganizedintothefollowing: Controlfiles:Containdataaboutthedatabaseitself,calledthemetadata. Thesefilesarecriticaltothedatabase.Withoutthemyoucannotopenthe datafilestoaccessthedatawithinthedatabase. Datafiles:Containthedataofthedatabase Onlineredologfiles:Allowforinstancerecoveryofthedatabase.Ifthe databasecrashesanddoesnotloseanydatafiles, files theinstancecanrecover thedatabasewiththeinformationinthesefiles. Thereareotherfileswhicharenotofficiallypartofthedatabasebutareimportant tothesuccessfulrunningofthedatabase.Theseare: Parameterfile:Usedtodefinehowtheinstancewillbeconfiguredwhenit startsup Passwordfile:Allowsuserstoconnectremotelytothedatabaseand performadministrativetasks Archivelogfiles:Containanongoinghistoryoftheredogeneratedbythe instance.Thesefilesallowfordatabaserecovery;usingthesefilesanda backupofthedatabase,youcanrecoveralostdatafile.

OracleDatabase10g:Administration WorkshopI340

ExploringtheStorageStructure Logicaldatastructuresarestoredinthephysicalfilesofthedatabase.Youcaneasily viewthelogicalstructuresofyourdatabasethroughEnterpriseManager.Detailed informationoneachstructurecanbeobtainedbyclickingthelinksintheStorage regionoftheAdministrationpage.

OracleDatabase10g:Administration WorkshopI341

ControlFiles Whenyoustarttheinstanceandmountthedatabase,thecontrolfileisread.The entriesinthecontrolfilespecifythephysicalfilesthatthedatabasecomprises. Whenyouaddadditionalfilestoyourdatabase,thecontrolfileisautomatically updated. Thelocationofthecontrolfilesisspecifiedinaninitializationparameter. Toprotectagainstfailureofthedatabaseduetothelossofthecontrolfile,you shouldmultiplexthecontrolfileonatleastthreedifferentphysicaldevices. devices By specifyingmultiplefilesthroughtheinitializationparameteryouenabletheOracle databaseservertomaintainmultiplecopiesofthecontrolfile. Youcanaccessinformationaboutthecontrolfilesinyourdatabasebyclickingthe ControlfileslinkintheStorageregionoftheAdministrationpageinEnterprise Manager.TheControlfilesGeneralpagedisplaysthenameandlocationofthe controlfilesinyourdatabase.TheAdvancedpageprovidesinformationaboutthe creationofthecontrolfileanddatabaseidentification.TheRecordSectionpage displaysinformationabouttheentriesinthecontrolfile.

OracleDatabase10g:Administration WorkshopI342

RedoLogFiles Youuseredologfilestorecordchangestothedatabaseasaresultoftransactions andinternalOracledatabaseserveractions.Theyprotectthedatabasefromlossof integrityduetosystemfailurescausedbypoweroutages,diskfailures,andsoon. Redologfilesshouldbemultiplexedtoensurethattheinformationstoredinthem isnotlostintheeventofadiskfailure. Theredologconsistsofgroupsofredologfiles.Agroupconsistsofaredologfile anditsmultiplexedcopies. copies Eachidenticalcopyissaidtobeamemberofthatgroup andeachgroupisidentifiedbyanumber.Thelogwriter(LGWR)processwritesredo recordsfromtheredologbuffertoaredologgroupuntilthefileisfilledoralog switchoperationisrequested.Thenitswitchesandwritestothefilesinthenext group.Theredologgroupsareusedinacircularfashion. Youcanaccessinformationabouttheredologfilesinyourdatabasebyclickingthe RedoLogGroupslinkintheStorageregionoftheAdministrationpage.Youcanview detailedinformation,includingthenamesoftheredologfiles,byselectingagroup andclickingView.

OracleDatabase10g:Administration WorkshopI343

TablespacesandDatafiles Adatabaseisdividedintologicalstorageunitscalledtablespaces,whichcanbe usedtogrouprelatedlogicalstructurestogether.Eachdatabaseislogicallydivided intooneormoretablespaces.Oneormoredatafilesareexplicitlycreatedforeach tablespacetophysicallystorethedataofalllogicalstructuresinatablespace. Note: Youcanalsocreatebigfile tablespaces,whicharetablespaceswitha single,butverylarge(upto4Gblocks)datafile.Traditionalsmallfile tablespaces(whicharethedefault), default) cancontainmultipledatafiles, files butthefiles cannotbeaslarge.Formoreinformationaboutbigfile tablespacesseethe DatabaseAdministratorsGuide.

OracleDatabase10g:Administration WorkshopI344

Segments,Extents,andBlocks Databaseobjectssuchastablesandindexesarestoredintablespacesassegments. Eachsegmentcontainsoneormoreextents.Anextentconsistsofcontiguousdata blocks,whichmeansthateachextentcanexistonlyinonedatafile.Datablocksare thesmallestunitofI/Ointhedatabase. WhenthedatabaserequestsasetofdatablocksfromtheOS,theOSmapsthisto anactualOSblockonthestoragedevice.Becauseofthis,youneednotbeawareof thephysicaladdressofanyofthedatainyourdatabase. database Thisalsomeansthatadata filecanbestripedandormirroredonseveraldisks. Thesizeofthedatablockcanbesetatdatabasecreationtime.Thedefaultsizeof8 Kisadequateformostdatabases.Ifyourdatabasesupportsadatawarehouse applicationthathaslargetablesandindexes,thenalargerblockmaybebeneficial. Ifyourdatabasesupportsatransactionalapplicationwherereadsandwritearevery random,thenspecifyingasmallerblocksizemaybebeneficial.Themaximumblock sizedependsonyourOS.Theminimumblocksizeis2Kandshouldrarely(ifever) beused. Youcanhavetablespaceswithdifferentblocksizes.Generallythisshouldbeused onlyforsupportoftransportabletablespaces.FordetailsseetheDatabase AdministratorsGuide.

OracleDatabase10g:Administration WorkshopI345

OracleInstanceManagement AnOracledatabaseserverconsistsofanOracledatabaseandanOracleinstance. AnOracleinstanceismadeupofmemorybuffersknownastheSystemGlobalArea (SGA)andbackgroundprocessesthathandlemuchofthebehindthesceneswork involvedinrunninganinstance. Theinstanceisidle(nonexistent)untilitisstarted.Whentheinstanceisstarted,an initializationparameterfileisreadandtheinstanceisconfiguredaccordingto instructionscontainedwithintheparameterfile. file Aftertheinstanceisstartedandthedatabaseisopened,userscanaccessthe database.

OracleDatabase10g:Administration WorkshopI346

OracleMemoryStructures ThebasicmemorystructuresassociatedwithanOracleinstanceinclude: SystemGlobalArea(SGA):Sharedbyallserverandbackgroundprocesses ProgramGlobalArea(PGA):Privatetoeachserverandbackgroundprocess; thereisonePGAforeachprocess. TheSystemGlobalArea(SGA)isasharedmemoryareathatcontainsdataand controlinformationfortheinstance. TheSGAincludesthefollowingdatastructures: Databasebuffercache:Cachesblocksofdataretrievedfromthedatabase Redologbuffer:Cachesredoinformation(usedforinstancerecovery)untilit canbewrittentothephysicalredologfilesstoredondisk Sharedpool:Cachesvariousconstructsthatcanbesharedamongusers Largepool:OptionalareausedforbufferinglargeI/Orequests Javapool:UsedforallsessionspecificJavacodeanddatawithintheJava VirtualMachine(JVM) Streamspool:UsedbyOracleStreams WhenyoustarttheinstanceusingEnterpriseManagerorSQL*Plus,thememory allocatedfortheSGAisdisplayed.

OracleDatabase10g:Administration WorkshopI347

OracleMemoryStructures(continued) WiththedynamicSGAinfrastructure,thesizeofthedatabasebuffercache,the sharedpool,thelargepool,theJavapool,andtheStreamspoolchangeswithout shuttingdowntheinstance instance. Thepreconfigureddatabasehasbeenpretunedwithadequatesettingsforthe memoryparameters.However,asyourdatabaseusageexpandsyoumayfindit necessarytoalterthesettingsofthememoryparameters. Oracleprovidesalertsandadvisorstoidentifymemorysizingproblemsandtohelp youdetermineappropriatevaluesformemoryparameters. AProgramGlobalArea(PGA)isamemoryregionwhichcontainsdataandcontrol information f f foreach hserverprocess.Aserverprocessisaprocessthat h servicesa clientsrequests.EachserverprocesshasitsownprivatePGAareathatiscreated whentheserverprocessisstarted.Accesstoitisexclusivetothatserverprocess, andisreadandwrittenonlybyOraclecodeactingonbehalfofit. TheamountofPGAmemoryusedanditscontentdependsonwhethertheinstance isconfiguredinsharedservermode(sharedserverwillbediscussedinlesson13). Generally, y,thePGAcontainsthefollowing: g PrivateSQLarea:Containsdatasuchasbindinformationandruntime memorystructures.EachsessionthatissuesaSQLstatementhasaprivate SQLarea. Sessionmemory:Memoryallocatedtoholdsessionvariablesandother informationrelatedtothesession.

OracleDatabase10g:Administration WorkshopI348

OracleProcesses When h youinvoke i k anapplication li i programoranO Oracle l tool lsuch hasEnterprise i Manager,theOracleservercreatesaserverprocesstoexecutecommandsissued bytheapplication. Oraclealsocreatesasetofbackgroundprocessesforaninstancethatinteractwith eachotherandwiththeoperatingsystemtomanagethememorystructures, asynchronouslyperformI/Otowritedatatodisk,anddogeneralhousekeeping. Whichbackgroundprocessesarepresentdependsuponthefeaturesthatarebeing usedinthedatabase database.Themostcommonbackgroundprocessesarethefollowing: Systemmonitor(SMON):Performscrashrecoverywhentheinstanceis startedfollowingafailure Processmonitor(PMON):Performsprocesscleanupwhenauserprocess fails. Databasewriter(DBWn):Writesmodifiedblocksfromthedatabasebuffer cachetothefilesondisk Checkpoint(CKPT):SignalsDBWn atcheckpointsandupdatesallofthedata filesandcontrolfilesofthedatabasetoindicatethemostrecentcheckpoint Logwriter(LGWR):Writesredologentriestodisk Archiver(ARCn):Copiestheredologfilestoarchivalstoragewhenthelog filesarefulloralogswitchoccurs

OracleDatabase10g:Administration WorkshopI349

DataDictionary Thedatadictionaryisthecentralsetoftablesandviewsthatareusedasaread onlyreferenceaboutaparticulardatabase.Adatadictionarystoresinformation suchas: Thelogicalandphysicalstructureofthedatabase Validusersofthedatabase Informationaboutintegrityconstraints Howmuchspaceisallocatedforaschemaobjectandhowmuchofitisin use Adatadictionaryiscreatedwhenadatabaseiscreatedandisautomatically updatedwhenthestructureofthedatabaseisupdated. ThedatadictionaryiswhereEnterpriseManagerretrievesinformationabout objectsinthedatabase.Youcanalsoselectinformationfromthedatadictionary tables.EnterpriseManagerdoesthisforyouandpresentstheinformationinavery easytouseformat.TheDICTIONARY viewcontainsdescriptionsofdata dictionarytablesandviews.Thesetablesandviewsgenerallyhaveoneofthree prefixes: USER:Informationpertainingtotheobjectsownedbythecurrentuser. ALL:Informationpertainingtotheobjectsaccessibletothecurrentuser. DBA:Informationpertainingtoeveryobjectinthedatabase.

OracleDatabase10g:Administration WorkshopI350

DatabaseControl OracleDatabase10g shipswithOracleEnterpriseManagersDatabaseControl. DatabaseControlisawebenabledcontrolconsolethatthedatabaseadministrator canusefor: Performancemonitoring Managingproactivealerts Controllingmaintenancewizardsandadvisors Useranddatabaseobjectadministration Databasebackupandrecovery Storagemanagement andmuchmore. EachOracleDatabase10g youcreatewillhaveitsownDatabaseControl.Youwillbe usingEnterpriseManagerDatabaseControlinthiscoursetomanagethedatabase onyourclassroomPC.

OracleDatabase10g:Administration WorkshopI351

GridControl DatabaseControlscapabilitiescanbeextendedandintegratedwiththerestofyour systemsusingOracleEnterpriseManagersGridControl.Thearchitectureofthe GridControlframeworkprovidesahighlevelofflexibilityandfunctionality.Youcan easilycustomizeEnterpriseManagertosuitthemonitoringandadministrative needsofyourenvironment. ThetypicalEnterpriseManagerframeworkconfigurationconsistsofthefollowing functionalareas: Managedtargets Managementservices Webbasedgridcontrol Databasecontrol Applicationservercontrol

OracleDatabase10g:Administration WorkshopI352

DatabaseConfigurationAssistantOverview(DBCA) DatabaseConfigurationAssistant(DBCA)enablesyoutocreate,changethe configurationof,ordeleteadatabase.Youcanalsocreateadatabasefromalistof predefinedtemplatesoruseanexistingdatabaseasasampletocreateanew databaseortemplate.Atemplateisapredefineddatabasethatyouuseasa startingpointforanewdatabase. Createadatabase:Ifyouselectthisoption,youcancreateanewdatabase ortemplate template. Configureoptionsinadatabase:IfyouselecttheChangedatabase configurationoption,youcanconfigureinstalledoptionsthathavenot previouslybeenconfiguredforusewithyourdatabase.Youcanalsoenable ordisablesharedserversupport. Note: TheChangedatabaseconfigurationoptionisnotavailableforOracle RealApplicationClusters. Deleteadatabase:Ifyouselectthisoption,youcandeleteallthedatabase files. ManageTemplates:Ifyouselectthisoption,youhavethreewaystocreatea template: Fromanexistingtemplate Fromanexistingdatabase(structureonly) Fromanexistingdatabase(structureaswellasdata)

OracleDatabase10g:Administration WorkshopI353

CreatingaDatabase WhencreatingadatabasewithDBCA,youcanselectoneofthreepredefined databases,orcreateacustomdatabase.OracleCorporationshipspredefined templates.Therearetemplatesfordatawarehouse,generalpurpose,and transactionprocessingdatabases.Thetemplatescontainsettingsoptimizedfor workload.ClickShowDetailstoseetheconfigurationforeachtypeofdatabase. Choosethetemplatesuitedtothetypeofworkloadyourdatabasewillsupport.If youarenotsure, sure selectthedefaultGeneralPurposetemplate. template Formorecomplexenvironments,youmaywanttoselecttheCustomDatabase option.Thisresultsinamoreextensiveinterviewandtakeslongertocreateyour database,becauseadatabasecreationscriptmustberun.

OracleDatabase10g:Administration WorkshopI354

DatabaseIdentification EntertheGlobalDatabaseName,intheformdatabase_name.domain_name andSID(Oraclesystemidentifier).TheSIDdefaultstothedatabasenameand uniquelyidentifiestheinstancethatrunsthedatabase.Itisimportantto understandthattheSIDisthenameoftheinstancethatwillconnecttoadatabase andnotnecessarilythenameofthedatabase.Aninstanceandthedatabasethe instanceconnectstoneednothavethesamename,althoughitisconvenient.With RealApplicationClusters Clusters,multipleinstancesopenthesamedatabaseandtheSIDs foreachinstancewillbedifferent.

OracleDatabase10g:Administration WorkshopI355

ManagementOptions UsethispagetosetupyourdatabasesoitcanbemanagedwithOracleEnterprise Manager,whichprovideswebbasedmanagementtoolsforindividualdatabases,as wellascentralmanagementtoolsformanagingyourentireOracleenvironment.To useEnterpriseManager,selectConfiguretheDatabasewithEnterpriseManager. IftheOracleManagementAgenthasbeeninstalledonyourhostcomputer,then youaregiventheoptionofselectingcentralmanagementbyselectingUseGrid ControlforDatabaseManagement. Management Ifyouselectthistypeofmanagement, management youmust alsoindicatewhichmanagementservicetouseinthedropdownmenu.Otherwise, selectUseDatabaseControlforDatabaseManagementtomanageyourdatabase individually.Ifyouchoosethisoption,youcanadditionallyenableEmail NotificationsandEnableDailyBackup.ClickHelpformoreinformationaboutthese options.

OracleDatabase10g:Administration WorkshopI356

PasswordsandStorage Databaseschemapasswords:Providepasswordsfortheadministrativeusers,SYS, SYSTEM,SYSMAN andDBSNMP.Youcanprovideapasswordforeachone separatelyorprovideonepasswordforall. FileStorageOptions FileSystem:ThisstoresfilesinyourOSconfiguredfilesystem. AutomaticStorageManagement(ASM):AutomaticStorageManagement filesarecreatedandmanagedautomatically, automatically andyougettheadditional benefitsoffeaturessuchasmirroringandstriping.Fordetailsonhowtoset upASM,seetheOracleDatabaseAdministratorsGuide. RawDevices(partitions):Thesearediskpartitionswithoutafilesystemon them.Generallyyoushouldusetheseonlyifyouareveryfamiliarwiththe useofrawpartitionsalready.CheckyourOSdocumentationfordetailson settingupandmaintainingrawpartitions.

OracleDatabase10g:Administration WorkshopI357

FileLocationsandBackupRecovery File il Locations i UseDatabaseFileLocationsfromTemplate:Selectingthisoptioninstructs theDBCAtousethedirectoryinformationasspecifiedinthetemplate.You willhaveanopportunitylatertomakemodificationstodatabasefilenames andlocations. UseCommonLocationforAllDatabaseFiles:Thisoptionrequiresyouto specifyanewcommonareaforallyourdatabasefiles.Youwillhavean opportunitylatertomakemodificationstodatabasefilenamesand locationsontheStoragepage. UseOracleManagedFiles:Selectthisoptiontoeliminatetheneedforyou, theDBA,todirectlymanageoperatingsystemfilesthatanOracledatabase comprises.Youmustprovidethepathtothedatabasearea.Formoredetails onOracleManagedFilesseetheDatabaseAdministratorsGuide. BackupandRecoveryOptions AflashrecoveryareaisalocationinwhichOraclecanstoreandmanagefiles relatedtobackupandrecovery.Fordetailsonsettingupandsizingtheflash recoveryarea,seetheOracleDatabaseBackupandRecoveryBasicsguide. Enablingarchivingputsthedatabaseinarchivelogmodeatcreationtime. ArchivingwillbecoveredmoredetailinthelessontitledBackupand RecoveryConcepts.

OracleDatabase10g:Administration WorkshopI358

FileLocationVariables OnseveralpagesyoucanclickFileLocationVariablestoopenapagethatshows youthedefinitionofdefinedvariables.Thesevariablesareusedinthepath definitionforfilesofthedatabase.YoucannotchangethevalueswhileinDBCA.If youneedthesevaluesmodified,youmustexitDBCA,changethemintheOS environment,andthenrestartDBCA.

OracleDatabase10g:Administration WorkshopI359

ContentandInitializationParameters Sampleschemas:Thesampleschemasareasetofschemasusedfor demonstrationsandtraining. Customscripts:Hereyoucanspecifyanyscriptsyouwantrunatcreationtime. Initializationparameters:Thefourtabscanbeusedtosetthemostcommon parameters,andbyclickingAllInitializationParametersyoucanviewandsetallthe parameters. Memory:ThisallocatesthememoryusedbytheSGAandeachPGAofthe userprocesses. Sizing:Hereyoucansettheblocksize,butifusingatemplatetheblocksize cannotbechanged.YoucanalsosetthemaximumnumberofOSprocesses thatareallowedtoconnecttotheinstance. Charactersets:Hereyousetthedefaultcharactersetforthedatabaseand thenationalcharacterset.Thedefaultcharactersetisusedformostdata typesinthedatabase.TheNCHAR,NVARCHAR2,andNCLOB datatypes supportUnicodedataonly,whichisthenationalcharactersetoption.You canuseeithertheAL32UTF8 ortheAL16UTF16 characterset.Formore informationonchoosingacharactersetrefertoGlobalizationSupport Guide.

OracleDatabase10g:Administration WorkshopI360

ContentandInitializationParameters(continued) Connectionmode:OracleDatabasecreatesserverprocessestohandletherequestsof userprocessesconnectedtoaninstance.Aserverprocesscanbeeitherofthe following: Adedicatedserverprocess,whereoneserverprocessservicesonlyoneuser process Asharedserverprocess,whereaserverprocesscanservicemultipleuser processes Yourdatabaseisalwaysenabledtoallowdedicatedserverprocesses,butyoumust specificallyconfigureandenablesharedserverbysettingoneormoreinitialization parameters.UsingOracle l Shared h dServerswill llbe b discussed d dinal laterl lesson.Youcanalso l refertotheDatabaseAdministratorsGuide.

OracleDatabase10g:Administration WorkshopI361

DatabaseStorage Onthispageyoucanseethestoragesettingsforthecontrolfiles,datafiles,and onlineredologfiles.Whenusingatemplateyoucannotaddanydatafilestothe database,butyoucanaddmorecontrolfilesandonlineredologfiles. Multiplecontrolfilesareallmaintainedsuchthateachisanexactcopyofthe others.DBCAautomaticallymultiplexesthecontrolfileacrossthreefiles.Youcan addmoreifyouwant. Redologsworkingroupsandshouldalsobemultiplexed. multiplexed DBCAdoesn doesnt t automaticallymultiplextheonlineredologfiles.Eachfileinaloggroupisanexact copyoftheothermembersinthegroup.Youcanaddinmorememberspergroup noworaddthematanytimeaftercreationofthedatabase.

OracleDatabase10g:Administration WorkshopI362

CreationOptionsandCreate Youhavetheoptionofsavingthedatabasethatyouhavedefinedasatemplate. Thistemplatecanbeusedlatertocreatedatabaseswithalltheoptionsyouhave defined. AfteryouclickNextontheCreationOptionspage,aConfirmationpageappears whereyoucanreviewalltheoptionstaken.Thisisthelastchancetomakeachange beforethecreationprocessstarts.YoucanalsosavetheConfirmationpageasan HTMLfiletoreviewlater later.AfteryouclickOKontheConfirmationpage, page thedatabase creationstarts. Attheendoftheinstallationyouwillseeapagepresentingyoutheopportunityto unlockaccountscreatedandchangepasswordsifyoudesire.ClickPassword Managementtounlockaccountsandchangepassword.ClickOkwhendont managingtheaccounts,thenclickExittoDBCA.

OracleDatabase10g:Administration WorkshopI363

OtherActionswithDBCA Configuredatabaseoptionsinadatabase:Thisallowsyoutoaddinoptionstoan existingdatabase. Deleteadatabase:Thispermanentlyremovesadatabasefromyoursystem. ManageTemplates:Thisallowsyoutoperformthefollowingwithtemplates. CreateaTemplate: FromanexistingTemplate:Usesandexistingtemplateasastarting pointtobuildanewtemplate. template Manyofthepagesarethesameas thoseinthecreatedatabaseprocess. Fromanexistingdatabase(structureonly):Thisrequireslogginginto anexistingdatabaseandusesitsstructureasastartingpoint. Fromanexistingdatabase(structureaswellasdata):Thisrequires loggingintoanexistingdatabaseandusesitsstructureasabase line;howeveritcapturesthedatafilesaswell. Deleteadatabasetemplate:Thispermanentlyremovesadatabasetemplate fromyoursystem

OracleDatabase10g:Administration WorkshopI364

OracleDatabase10g:Administration WorkshopI365

OracleDatabase10g:Administration WorkshopI366

Practice3:CreateanOracleDatabase YourITmanagerreturnsfromameetingwithafewoftheusersthatwillbeusingthe newsystemyouaregoingtosupport.Theywantaseconddatabaseforstorageof historicaldata. data UsingDBCAyouwillcreateadatabaseusingtheGeneralPurposetemplatewiththe followinginformation: Settheglobaldatabasenamehist.oracle.com andtheSIDtohist. Setthepasswordstooracle. ForthestorageoptionsuseFileSystem. UseFlashRecoveryarea,acceptthedefaultsizeandlocation,disablethe b k backups. Afteryoucreatethedatabasetheusersdecidedthattheydontneedtotrackthe historicaldata.Dropthehist database

OracleDatabase10g:Administration WorkshopI367

Objectives SQListhelanguagethatisusedtoworkwiththedatabase.Thislessonprovidesan overviewofthislanguage.Inlaterlessons,individualcommandswillbeintroducedand discussedinmoredetail. PL/SQLisanextensionofSQL.Lesson10willcoverPL/SQLinmoredetail. JavaandOCIarementionedonlytofamiliarizeyouwiththeabilitytouseotherlanguages toaccessanOracledatabase.

OracleDatabase10g:Administration WorkshopI469

WhatIsSQL? Structuredquerylanguage(SQL)isthesetofstatementswithwhichallprogramsand usersaccessdatainanOracledatabase.SQLstatementsaredividedintothefollowing categories: Datadefinitionlanguage(DDL)statements Datamanipulationlanguage(DML)statements Transactioncontrolstatements Sessioncontrolstatements Systemcontrolstatements EmbeddedSQLstatements Withtheadventofgraphicaluserinterface(GUI)tools,youdonthavetowritethese statementsyourself.Formanytasks,thetoolswritesthestatementsforyou.However,if youneedtoruntheSQLwithinascript,thenyoumustwritetheSQLstatements. Note: ThissectionprovidesyouanoverviewofthebasicSQLstatementsavailable.These statementshavemanyoptionswhicharenotdiscussedhere,andtherearemany statementsnotcovered.Forfullsyntaxandothercommands,seetheOracleDatabase SQLReference documentation.

OracleDatabase10g:Administration WorkshopI470

UsingSQL SQLisarichlanguagewhosesyntaxallowsstatementsassimpleasafewwords,and statementssocomplextheyfillpageswiththeirsyntax.Thereareseveralwaystosend SQLcommandstothedatabase. database OracleSQL*PlusandOracleiSQL*Plus:Bothofthesetoolsprovideasimple, commandlineinterfacewiththedatabase. OracleForms:MaskstheSQLfromusersbyprovidingagraphicalbased environmentfromwhichtheycanmanipulatedata. OracleReportsandOracleDiscoverer:Thesereportingtoolsallowcomplex databasequeriestobeexecutedwithasinglemouseclick.OracleReportsis generallyusedforstandard, standard fixedreports. reports OracleDiscovererisadataminingtool thatallowsuserstobrowsedatawithoutknowingtheunderlyingstructureand relationshipofthatdata. OracleEnterpriseManager:Agraphicaltoolthatmanipulatesdatabaseobjects andstructures.ByusingEnterpriseManager,theadministratorcanconcentrateon accomplishingthetaskathandratherthanrememberingsyntax. Thirdpartytools.SQLisastandardsbasedlanguageusedbymostmajordatabase vendors.Therearehundredsoftoolsforinterfacing gwithdatabasesusing gSQL.

OracleDatabase10g:Administration WorkshopI471

EnterpriseManager:SeeingtheSQL UsingtheEnterpriseManagerDatabaseControlyoudonotneedtowritetheSQL statementsusedtoadministeryourdatabase.EnterpriseManagercreatestheSQLfor you.IfyouwanttoseetheSQLthatisbeinggenerated,clickShowSQLatanytimetosee itdisplayed.YoucancopyandpastetheSQLfromheretoatextfileifyouwanttocreate ascriptfilethatwillberuninbatchmodewithascript,orifyoujustwanttokeepitfor historicalpurposes.

OracleDatabase10g:Administration WorkshopI472

WhatIsSQL*Plus? YoucanusethecommandlineinterfacetoSQL*PlustowriteSQL*Plus,SQLand PL/SQLcommandsto: Enter,edit,runstore,retrieve,andsaveSQLcommandsandPL/SQLblocks Format,calculate,store,andprintqueryresults Listcolumndefinitionsforanytable Sendmessagestoandacceptresponsesfromanenduser Performdatabaseadministration PerformthefollowingstepstostartSQL*Plus: 1. Openaterminalwindow. 2. Atthecommandlineprompt,entertheSQL*Pluscommand intheform: $sqlplus/nolog 3. Enterconnect followedbytheuseryouwanttoconnectas. 4. Whenprompted,entertheuserspassword. 5. SQL*Plusstartsandconnectstothedefaultdatabase.

OracleDatabase10g:Administration WorkshopI473

WhatIsiSQL*Plus? iSQL*PlusisabrowserbasedinterfacetoanOracledatabase.Itisacomponentofthe SQL*Plusproduct.iSQL*Plushasaserversidelistenerprocessthatmustbestarted beforeyoucanconnectwithabrowser.Tostartthisserverprocessuse: isqlplusctlstart Aftertheserverprocessisstarted,performthefollowingstepstoconnecttoiSQL*Plus: 1. ConnecttotheInternetoryourintranet,andstartyourWeb browser. 2. Enteryour theiSQL*PlusURL.The iSQL*PlusURLlookslikethe following: http://hostname:port/isqlplus. TheportnumberusedbyiSQL*Plusisusually5560unlesstheOracleUniversalInstaller (OUI)detectssomethingalreadyusingthatport.Check $ORACLE_HOME/install/portlist.ini tofindtheportusedbyiSQL*Plus.

OracleDatabase10g:Administration WorkshopI474

WhatIsiSQL*Plus?(continued) 3. PressEntertogototheURL.TheiSQL*PlusLoginpageisdisplayed inyourWebbrowser. 4. Entery yourOracleusernameandpassword p intheUsernameand Passwordfields.IfyoudonotknowyourOracleusernameandpassword,askyour databaseadministrator. 5. LeavetheConnectionIdentifierfieldblanktoconnecttothe defaultdatabase.EntertheOracleNetdatabasealiastoconnecttoadatabase otherthanthedefault. 6. ClickLogintoconnecttothedatabase.TheiSQL*PlusWorkspaceis di l din displayed i yourWeb W bbrowser. b

OracleDatabase10g:Administration WorkshopI475

UsingiSQL*Plus IntheWorkspacetabbedpageyoucanenteroneormoreSQLandSQL*Pluscommands. WhenyouclickExecuteallthecommandsareexecutedinordertoptobottom.The outputisdisplayedbelowthecommandpanel.Ifyouhavemorethanonecommand,SQL commandsmustbeterminatedbyasemicolon(;)orslash(/). TheHistorytabbedpageshowsthepriorcommandsusedwithinthesession.Youcanload ordeletepriorcommands.Bydefaultthelast10commandsaresaved. YoucanclickPreferencestochangeboththelookoftheiSQL*Pluswindowaswellasits functionality.Forexampleyoucansetthenumberofcommandstobesaved(Rangeis0 to100), 100) howtheoutputisformatted, formatted andexecutionoptions. options

OracleDatabase10g:Administration WorkshopI476

DescribingData TheDESCRIBE commandisusedtoseethedescriptionofadatabaseobject.This commandisnotpartoftheSQLstandard,butisoneofseveralSQL*Pluscommand uniquetoOracletools.UnlikeSQLcommands,theSQL*Pluscommandscanbe abbreviatedtoitsfirstfourletters. Theexampleshowsthestructureoftheemployees table.Fromtheoutputyoucansee thenameofeachcolumn,whetherthecolumnismandatory,andthedatatype associatedwiththatcolumn.Forexample,thecolumnwiththenameofLAST_NAME is mandatorybecauseNOT NULL meansthatrowsmustcontainavalueinthiscolumn. AlsothedescriptionshowsthiscolumntobeoftypeVARCHAR2(25),whichmeansit cancontaincharacterdataandhaveamaximumlengthof25characters. FormoreinformationaboutSQL*PlusanditscommandsseetheSQL*PlusReference Guide.

OracleDatabase10g:Administration WorkshopI477

QueryingData ThemostbasicSELECT statementhasthreeparts: TheSELECT lististhelistofcolumnsyouwanttoretrievefromthetableor tables.Thisismandatory. TheFROM clauseiswhereyouspecifythetableortablesfromwhichyouare retrievingdata.Thisismandatory. TheWHERE conditionlimitstherowsretrievedfromthetablesintheFROM clause.Thispartisoptional;ifnotincludedyouwillretrievealltherows. SQLisalsonotacasesensitivelanguage.Intheexample,thecaseismixedrather unusuallyonlyasanexampletodemonstratethis. this Manyorganizationshavecase standardsthatfacilitatereadability.Bydefault,theonlytimecaseisimportantisina quotedstring.Forexample,ifyouwanttoretrieveonlytherowthathasthelastnameof DeHaan,thentheWHERE conditionlookslikethefollowing: WHERElast_name='DeHaan'

OracleDatabase10g:Administration WorkshopI478

SortingtheData UsetheORDER BY clauseonaselectstatementtosorttheoutput.Thedefaultorderis ascending,togetthedataindescendingorderuseDESC afterthecolumnnameyouare sortingon.Forexample: ORDERBYlast_namedesc Youcansortonmorethenonecolumn.Forexample,thiswillsortdescendingbythelast nameandthenascendingbydepartmentid: ORDERBYlast_namedesc,department_ID

OracleDatabase10g:Administration WorkshopI479

JoiningTables Sometimesyouneedtousedatafrommorethanonetable.Intheslideexample,the reportdisplaysdatafromtwoseparatetables.Toproducethereport,youneedtolinkthe employees l anddepartments d t t tablesandaccessdatafrombothofthem. them Whendatafrommorethanonetableinthedatabaseisrequired,ajoinconditionisused. Rowsinonetablecanbejoinedtorowsinanothertableaccordingtocommonvalues thatexistincorrespondingcolumns;theseareusuallyprimaryandforeignkeycolumns. Todisplaydatafromtwoormorerelatedtables,writeajoinconditionintheWHERE clause.Theexampleintheslideis: SELECTlast_name,department_name FROMemployees, employees departments WHEREemployees.department_id=departments.department_id Notethatthecolumnusedtojointhetables(department_id)neednotbeinthe SELECT listofthestatement.Also,becausethedepartment_id columnhasthe samenameineachtable,thecolumnmustbequalifiedwiththetablenameinfrontofit intheWHERE clause.

OracleDatabase10g:Administration WorkshopI480

JoiningTables(continued) Anequijoinhasajoinconditionthatcontainsanequalityoperator.Anequijoincombines rowsthathaveequivalentvaluesforthespecifiedcolumns.Theexampleintheslideisan equijoin. equijoin Aselfjoinisajoinofatabletoitself.ThistablenameappearstwiceintheFROM clause andisfollowedbytablealiasesthatqualifycolumnnamesinthejoincondition.For example: SELECTe1.last_name||worksfor||e2.last_name "EmployeesandTheirManagers" FROMemployeese1,employeese2 WHEREe1.manager_id d=e2.employee_id l d ANDe1.last_nameLIKER%; EmployeesandTheirManagers RajsworksforMourgos Raphaely p yworksforKing g RogersworksforKaufling RussellworksforKing Aninnerjoin(sometimescalledasimplejoin)isajoinoftwoormoretablesthatreturns onlythoserowsthatsatisfythejoincondition.Theexampleintheslideisaninnerjoin. Anouterjoinextendstheresultofasimplejoin.Anouterjoinreturnsallrowsthatsatisfy thejoinconditionandalsoreturnssomeorallofthoserowsfromonetableforwhichno rowsfrom f th theother th satisfy ti f th thejoin j i condition. diti For F example, l the th following f ll i queryreturns t alldepartmentnumberseveniftherearenoemployeesassignedtothedepartment: SELECTd.department_id,e.last_name FROMdepartmentsdLEFTOUTERJOINemployeese ONd.department_id=e.department_id ORDERBYd.department_id; ACartesianp productisg generatedifaj joinconditionisomitted.Thismeansy youwill retrieveallrowsfromonetablejoinedwithalltherowsofanyothertableortablesinthe SELECT list. OraclealsosupportANSIjoinsyntax.Forexampletheslideexamplecanberewrittenas: SELECTfirst_name,department_name FROMemployeesJOINdepartmentsUSING(department_id); FormoreinformationonjointypesseetheSQLReference documentation.

OracleDatabase10g:Administration WorkshopI481

ManipulatingData Thestatementsthatmakeupthedatamanipulationlanguage(DML)areusedto changedatainthedatabase. INSERT putsnewrowsofdataintoatableinthedatabase.Usedinthe formshownintheslide,onerowofdataiscreatedinthetableatatime. UPDATE modifiesanexistingrow(orsetofrows)inatable.Thenumberof rowsmodifiediscontrolledbytheWHERE condition.Ifyoudonthavea WHERE conditionontheUPDATE,thenallrowsinthetablearemodified modified. DELETE removesrowsfromatable.LikeUPDATE thenumberofrows removediscontrolledbyaWHERE condition.WithoutaWHERE condition, allrowsareremovedfromthetable. Onmostsystemsitisnotcommontousethesestatementsregularly.Insteadof issuingDMLstatementsuchasintheslide,youwillmostlikelyuseanapplication. TheapplicationwillthengeneratetheneededDMLstatementstochangethedata asyouneed. Note: TheNULL keywordinsertsnovalueforthecolumn.Thisisnotablanknora zero;itisrathernovalueatall.TheSYSDATE keywordinsertsthecurrentdateand timeintoaDATE datatypecolumn.

OracleDatabase10g:Administration WorkshopI482

DefiningData Thestatementsthatmakeupthedatadefinitionlanguage(DDL)areusedtoworkwith databaseobjects. TheCREATE statementdefinesnewobjectsinthedatabase.Youcancreatemany differentobjectsinthedatabase,includingtables,indexes,sequences,views,and others. TheALTER statementmodifiesexistingobjectsinthedatabase.Afteranobjectis defined,youmayneedtomodifythatobject.Dependingontheobject,thereare differentthingsthatcanbemodified.Forexample,youcanaddacolumntoa table butyoucannotaddacolumntoanindex. table, index TheDROP commandremovesobjectsinthedatabase.Afteranobjectisdropped itcannolongerbereferenced.Itispossibletoreinstateadroppedatable.

OracleDatabase10g:Administration WorkshopI483

OverviewofTransactions WhenanexecutableSQLstatementisexecutedatransactionbegins.Oracleassignsthe transactiontoanavailableundosegmentinanundotablespacetorecordtheundo entriesforthenewtransaction transaction.Theentriesintheundotablespaceareusedwhena rollbackcommandisissuedtogetthedatabacktoitslastcommittedstatepriortothe currenttransaction.Atransactionendswhenanyofthefollowingoccurs: AuserissuesaCOMMIT orROLLBACK statementwithoutaSAVEPOINT clause. AuserrunsaDDLstatementsuchasCREATE,DROP,RENAME,orGRANT.Ifthe currenttransactioncontainsanyDMLstatements,Oraclefirstcommitsthe transaction,andthenrunsandcommitstheDDLstatementasanew,single statementtransaction. transaction AuserdisconnectsfromOracle.Thecurrenttransactioniscommitted. Auserprocessterminatesabnormally.Thecurrenttransactionisrolledback. Afteronetransactionends,thenextexecutableSQLstatementautomaticallystartsthe nexttransaction. Note: AsetofSELECT commandsthataccessesdatainthesamedatabasetheuseris connectedtodoesnotconstituteatransaction.

OracleDatabase10g:Administration WorkshopI484

TransactionControlStatements Therearethreetransactioncontrolstatements,COMMIT,ROLLBACK,andSAVEPOINT. Committingatransactionmeansmakingpermanentthechangesperformedby theSQLstatementswithinthetransaction. transaction RollingbackmeansundoinganychangestodatathathavebeenperformedbySQL statementswithinanuncommittedtransaction.Oracleusesundotablespacesor rollbacksegmentstostoreoldvalues.Theredologcontainsarecordofchanges. Youcandeclareintermediatemarkers,calledsavepoints,withinthecontextofa transaction.Savepointsdividealongtransactionintosmallerparts.Whenyouset upasavepoint,youcanthenlaterrollbacktothatparticularsavepoint.Each savepointmusthaveaname, name whichyoucanusetorollbacktothatnamed savepoint.Forexample: SQL>SAVEPOINTbefore_insert; Savepointcreated. SQL>INSERTINTOlocal_tempVALUES(SYSDATE,76,58); 1rowcreated. SQL>ROLLBACKTObefore_insert; Rollbackcomplete. p

OracleDatabase10g:Administration WorkshopI485

LockingData Oracleprovidesdataconcurrencyandintegritybetweentransactionsusingitslocking mechanisms.Thismechanismpreventsmultipleusersfromtryingtoupdatethesame dataatthesametime. OracleDatabase10g usesafinegrainedlockingmechanismtoensurethatusersdont unnecessarilyblockotherusers.Someonereadingdata(usingselectstatements)does notblocksomeonefromupdatingdata.Someoneupdatingdatadoesnotblockanother userunlessthatusertriestoupdatethesamerowofdata. Oracleslockingmechanismwillbediscussedinmoredetailinalaterlesson.

OracleDatabase10g:Administration WorkshopI486

OtherStatementCategories Sessioncontrolstatements:Sessioncontrolstatementsdynamicallymanagethe propertiesofausersession.Thesestatementsdonotimplicitlycommitthe currenttransaction.PL/SQLdoesnotsupportsessioncontrolstatements.The sessioncontrolstatementsare: -ALTER SESSION -SET ROLE Systemcontrolstatement:Thesinglesystemcontrolstatement,ALTER SYSTEM, dynamicallymanagesthepropertiesofanOracleinstance.Thisstatementdoes notimplicitlycommitthecurrenttransactionandisnotsupportedinPL/SQL. PL/SQL EmbeddedSQLstatements:EmbeddedSQLstatementsplaceDDL,DML,and transactioncontrolstatementswithinaprocedurallanguageprogram.Embedded SQLissupportedbytheOracleprecompilersandisdocumentedinthefollowing: Pro*COBOLProgrammer'sGuide Pro*C/C++Programmer'sGuide SQL*ModuleforAdaProgrammer'sGuide

OracleDatabase10g:Administration WorkshopI487

WhatIsPL/SQL? PL/SQLisablockstructuredlanguage.Thatis,thebasicunits(procedures,functions,and anonymousblocks)thatmakeupaPL/SQLprogramarelogicalblocks,whichcancontain anynumberofnestedsubblocks.Typically,youcreateeachlogicalblocktosolvea problemorsubproblem.OnewaytolookatitisthatPL/SQLaddsstructured programmingtechniquestotheSQLlanguage. AblockofPL/SQLcodehastheseparts: DECLARE:Thisoptionalpartiswhereyoudefineconstantsandvariables,then usetheminSQLandproceduralstatementsanywhereanexpressioncanbeused. Youmustdeclareaconstantorvariablebeforereferencingitinotherstatements statements, includingotherdeclarativestatements. BEGIN:Thisisthebeginningofthecodeoftheblock.Thecodewillbemadeup ofbothSQLandPL/SQLcommands.Thisismandatory. EXCEPTION:Thisoptionalpartiswhereyoudefineanylocalexceptions. Generallyexceptionsareraisedbecauseofanerrorcondition. END:thisendstheblock.Thisismandatory.

OracleDatabase10g:Administration WorkshopI488

ExamplePL/SQLBlock Theanonymousblockintheslidestartsoffwithdefiningalocalvariabletoholda number.ThecodeoftheblockstartswiththeBEGIN statement.Thefirstactionisto selecttheamountofavailableinventoryfortennisracketsintothelocalvariable.Next followssomeconditionalcontrolinthefromofanIF THEN ELSE statement. Iftherearemorethanzerotennisrackets,thenthequantityisreducedbyoneanda messagewrittentothepurchase_record table.Iftherearezerotennisrackets,then onlyamessageiswrittentothepurchase_record table. LastinthecodeoftheblockisaCOMMIT whichmakesanychangesdoneintheblock permanent TheblockisclosedwithanEND statement. permanent. statement FormoredetailsonPL/SQL,refertoPL/SQLUsersGuideandReference documentation.

OracleDatabase10g:Administration WorkshopI489

UsesofPL/SQL YouusePL/SQLinthefollowingstructures: Anonymousblocks:TheseareunnamedblocksofPL/SQL.Ananonymousblockis generallyfoundinsideanamedblock(afunctionorprocedureforexample), example) itis thenestingoftheseanonymousblocksthatprovidesgreatercontroloverthe executionofthecode. Functions:AfunctionisaPL/SQLblockthatreturnsasinglevaluebyusingthe RETURNPL/SQLcommand Procedures:AprocedureisisaPL/SQLblockthatperformsaspecificaction Packages:Apackageisacollectionofprocedures,functions,andanonymous blocksthatarelogicallyrelated. related Triggers:AtriggerisaPL/SQLblockthatisexecutedwhenaparticularevent happensinthedatabase.Theseeventscanbebasedonatable,suchaswhena rowisinsertedintothetable.Theycanalsobedatabaseevents,suchaswhena userlogsintothedatabase. Objecttypes:Anobjecttypeisakindofdatatype.FordetailsseetheApplication Developer'sGuide ObjectRelationalFeaturesdocumentation. Thesestructures( (except p object j types) yp )willbediscussedinmoredetailinalaterlesson.

OracleDatabase10g:Administration WorkshopI490

WhatIsJava? Java,anobjectorientedprogramminglanguagereleasedbySunMicrosystemsin1995, hashadaprofoundeffectononlineapplications.Javaprogramscanberunonany computerthathasaJavainterpreter(calledaJavaVirtualMachine),whichisincludedin mostWebbrowsers.ProgrammersuseJavatoprovidedynamiccontent,suchasgraphics, motion,andsound.JavaenhancedWebpagesenableinteractiveapplicationssuchas simulationsandcomputerbasedtraining.Javaiscompliedandstoredinthedatabaseas bytecode,acodeformbetweenmachinecodeandsourcecode.Javabytecodeisplatform independent,whichmakeiteasytotransferbetweenoperatingsystems.TheJVM convertsbytecodeintomachinereadableinstructions. instructions TheOracleinstancehasabuiltinJVM.

OracleDatabase10g:Administration WorkshopI491

OracleandJava YoucancallJavastoredproceduresfromanyPL/SQLblock,subprogram,orpackage. Similarly,JDBC(JavaDatabaseConnectivity)allowsyoutocallPL/SQLstoredfunctions andprocedures. TolearnmoreaboutJavasusagesinanOracleDatabase,seetheJavaDevelopersGuide documentation.TolearnmoreaboutJDBC,seetheOracleDatabaseJDBCDeveloper's GuideandReferencedocumentation.

OracleDatabase10g:Administration WorkshopI492

WhatIsOCI? TheOracleCallInterface(OCI)isanapplicationprogramminginterface(API)thatallows applicationswritteninCtointeractwithoneormoreOracleDatabaseservers.OCIisa complexandpowerfullowlevelAPI.Itprovidesimprovedperformanceandscalability throughtheefficientuseofsystemmemoryandnetworkconnections.OCIallows dynamicsessionandtransactionmanagementinatwotierclient/serverormultitier environmentandprovidesforNtierauthentication.Newdatabasecapabilitiesand featuresarefirstexposedtoapplicationdevelopersthroughOCI.OtherAPIsarelayered overOCI.

OracleDatabase10g:Administration WorkshopI493

OtherAPIs ThiscoursewillnotcovertheseAPIsinanydetail.Theintenthereistoinformyouofthe optionsthatareavailable. JavaDatabaseConnectivity(JDBC):JDBCisthestandardAPIforaccessingrelational databasesfromprogramswritteninJava.StandaloneJavaapplications,appletsrunning inabrowser,andJava2Platform,EnterpriseEdition(J2EE)middletiercomponents,such asservletsandEnterpriseJavaBeans,canalluseJDBCtoaccessanOracleDatabase.In addition,JavaclassescanbeloadedintoanOracleDatabaseandpublishedasstored procedures,wheretheyalsouseJDBCfordatabaseaccess.JavaprogramscanuseJDBCto callbothJavaandPL/SQLstoredprocedures procedures.OracleprovidestwodifferentkindsofJDBC drivers.Thindriversarea100%JavaimplementationoftheJDBCspecification.OCI driversinterfacewiththesamenativeOCIclientlibrariesasallotherAPIs.Formore informationseetheJDBCDevelopersGuideandReferenceguide.

OracleDatabase10g:Administration WorkshopI494

OtherAPIs(continued) Pro*C/C++andPro*COBOL:FromtheearliestversionsoftheOracleDatabase programmershaveembeddedSQLstatementsinsideprogramswritteninthird generationprogramminglanguagessuchasCandCOBOL. COBOL Pro Pro*C/C++ C/C++andPro Pro*COBOL COBOLare precompilersthattranslatethisembeddedSQLintoOracleruntimelibrarycallsfor databaseaccess.FormoreinformationseethePro*C/C++PrecompilerProgrammer's Guide andthePro*COBOLPrecompilerProgrammersGuide. OracleC++Interface(OCCI):OCCIprovidesobjectorientedaccesstoanOracledatabase throughaninterfacethat,forC++programmers,issimplerthanOCIandmorenatural thanPro*C/C++.Atthesametimeitexposesmostoftheadvancedfeaturesofthemore l level low l lOCI. OpenDatabaseConnectivity(ODBC):ODBCprovidesastandardinterfacethatallowsone applicationtoaccessmanydifferentdatasources.Adatabasedriverlinkstheapplication toaspecificdatasource.TheOracleODBCdriverenablesWindowsapplicationstoaccess OracledatabasesthroughtheODBCinterfaceusingnativeOCIclientlibraries. OracleDataProviderfor.NET(ODP.NET):ODP.NETallowsfastandreliableaccessto databasefeaturesanddatafromany y.NETapplication. pp Italsousesandinheritsfrom classesandinterfacesavailableintheMicrosoft.NETFrameworkClassLibrary.Formore informationseetheOracleDataProviderfor.NETDevelopersGuide. OracleObjectsforOLE(OO4O):OracleObjectsforOLE(OO4O)allowseasyaccesstodata storedinanOracleDatabasefromanyprogrammingorscriptinglanguagethatsupports theMicrosoftCOMAutomationandActiveXtechnology.ThisincludesVisualBasic,Visual C++,VisualBasicForApplications(VBA),IISActiveServerPages(VBScriptandJavaScript), and dothers. th OtherAccessProtocols WhentheOracleXMLDBisenabled,standardInternetprotocolssuchasFTP,HTTP,and WebDistributedAuthoringandVersioning(WebDAV)canbeusedtoaccessdatainan Oracledatabase.FormoreinformationseetheXMLDBDevelopersGuide.

OracleDatabase10g:Administration WorkshopI495

OracleDatabase10g:Administration WorkshopI496

OracleDatabase10g:Administration WorkshopI497

Practice4:UsingSQL Background:InthispracticesessionyouareactingasaclerkintheHumanResources department.YouwillneedtoconnecttothedatabaseastheHRuser.Onceconnected youwillviewandmanipulatedata data. Tasks: StartiSQL*Plus ConnecttothedatabaseusingiSQL*Plus ConnecttothedatabaseusingSQL*Plus Describedatabaseobjects Querydatastoredwithinthedatabase. Updateexistingdatastoredwithinthedatabase. Rollbackanupdatetorestoredatatoitsoriginalvalue. TofamiliarizeyourselfwiththedatainthedatabaseyoudecidetouseiSQL*Plustoseethe tabledataintheHRschema. 1. ConnecttothedatabaseasuserHR usingiSQL*Plus. 2. DescribetheEMPLOYEES,DEPARTMENTSandLOCATIONStables. 3 Writeaquerythatshowyouthelastname, 3. name phonenumberanddepartmentidof everyoneintheEMPLOYEEStable. 4. Rewritethequerysothatthedepartmentnameisshowninsteadofthedepartment_id. 5. Rewritethequerytoshowthelastname,departmentname,andcityofeveryoneinthe EMPLOYEEStable. 6. Noticethattheresultsarenotreturnedinanyparticularorder.Rewritethequerysothat resultsarereturnedinalphabeticalordersortedfirstbycity,thenbydepartmentname, thenbylastname. 7. WriteandexecuteanSQLstatementthatgiveseveryoneindepartment80a10%raise. 8. The10%raiseyougaveinstep(7)hasbeenrescindedbyuppermanagement.Reverse thetransaction. 9. ConnecttothedatabaseasuserHRusingSQL*Plus. 10. Writeaquerythatshowyouthelastname,departmentnameandstateofeveryonein department30. 30

OracleDatabase10g:Administration WorkshopI498

OracleDatabase10g:Administration WorkshopI5101

StartingandStoppingiSQL*Plus TheiSQL*PlusApplicationServermustberunningbeforeyoucanstartaniSQL*Plus session.AcommandlineutilityandaWindowsServicearesuppliedtostartand stopiSQL*PlusonWindows.TheiSQL*PlusApplicationServerisstartedbydefault duringOracleDatabaseinstallation. TostartorstoptheiSQL*PlusApplicationServeronUnix(Linux). Startaterminalsession. Enterthefollowingtostart:isqlplusctl start Enterthefollowingtostop:isqlplusctl stop Note: Youmayneedtonavigateintoyour$ORACLE_HOME/bin directoryifthis directoryisnotinyourOSpath. TostartortheiSQL*PlusApplicationServeronWindows SelectServicesfromtheStart>Programs>AdministrativeToolsmenu. LocatetheiSQL*PlusWindowsService,OracleOracleHomeNameiSQL*Plus. StarttheWindowsServicetostarttheiSQL*PlusApplicationServer,orstop theservicetostoptheiSQL*PlusApplicationServer. Alternatively,youcanstartiSQL*Plusfromacommandprompt.Usethe samecommandasinUnix(Linux).

OracleDatabase10g:Administration WorkshopI5102

ManagementFramework TherearethreemajorcomponentsoftheOracleDatabase10g managementframework: Thedatabaseandinstancebeingmanaged Alistenerthatallowsconnectionstothedatabase Themanagementinterface.Thismaybeeitheramanagementagentconnecting thisservertoOracleEnterpriseManagerGridControl,orthestandaloneOracle EnterpriseManagerDatabaseControl. Eachofthesecomponentsmustbeexplicitlystartedbeforeyoucanusetheservicesof thecomponentandshouldbeshutdowncleanlywhenshuttingdowntheserverhosting OracleDatabase10g. Thefirstcomponenttobestartedisthemanagementinterface.Afterthisisupand running,themanagementinterfacecanbeusedtostarttheothercomponents.

OracleDatabase10g:Administration WorkshopI5103

StartingandStoppingDatabaseControl FordatabasesnotconnectedtotheGridControlframework,Oracleprovidesastand alonemanagementconsolecalledDatabaseControl.Eachdatabasemanagedwith DatabaseControlhasaseparateDatabaseControlinstallation,andfromanyone DatabaseControlyoucanmanageonlyonedatabase.DatabaseControlrequiresthata dbconsole processbestartedpriortouse.Tostartthedbconsoleprocess: emctlstartdbconsole Tostopthedbconsole process: emctlstopdbconsole Toviewthestatusofthedbconsole process: emctlstatusdbconsole Note: Youmayneedtonavigateintoyour$ORACLE_HOME/bin directoryifthis directoryisnotinyourOSpath. DatabaseControlusesaserversideagentprocess.Thisagentprocessautomaticallystarts andstopswhenthedbconsole processisstartedorstopped.

OracleDatabase10g:Administration WorkshopI5104

AccessingDatabaseControl OpenyourWebbrowserandenterthefollowingURL(thedefaultportis5500): http://hostname:portnumber/em Ifthedatabaseisup,EnterpriseManagerdisplaystheDatabaseControlLoginpage.Login tothedatabaseusingausernamethatisauthorizedtoaccessDatabaseControl.This initiallywillbeSYS,SYSMAN orSYSTEM.Usethepasswordyouspecifiedforthe accountduringthedatabaseinstallation. Ifthedatabaseisdownandneedstobestarted,EnterpriseManagerdisplaysthe Startup/ShutdownandPerformRecoverypage.Ifthisisthecase,clickthe Startup/Shutdownbutton button.Youarethenpromptedforthehostandtargetdatabaselogin usernamesandpasswords,whichyoumustenter.Forthedatabaseuserandpassword, useSYS andthepasswordyouspecifiedduringinstallation.ClickOKtostartthe database.IntheConfirmationpage,clickYEStostartthedatabaseinopenmode.

OracleDatabase10g:Administration WorkshopI5105

SYSOPER andSYSDBA SYSOPER:Isaspecialdatabaseadministrationrolethatpermitsadatabase administratortoperformSTARTUP,SHUTDOWN,ALTER DATABASE OPEN/MOUNT, ALTER DATABASE BACKUP,ARCHIVE LOG,andRECOVER,andincludes RESTRICTED SESSION privileges.WhenyouconnectwithSYSDBA privileges,you areintheschemaownedbySYS. SYSDBA:Isaspecialdatabaseadministrationrolethatcontainseverysystemprivilege withADMIN OPTION andSYSOPER systemprivileges.SYSDBA alsopermitsCREATE DATABASE actionsandincompleterecovery.WhenyouconnectasSYSOPER,youarein thepublicschema schema. MoredetailsonusermanagementwillbecoveredinthelessontitledAdministering Users.

OracleDatabase10g:Administration WorkshopI5106

DatabaseHomePage ThepropertypagesacrossthetopoftheDatabasehomepageenableyoutoaccess performance,administration,andmaintenancepagesformanagingyourdatabase.The varioussectionsoftheDatabasehomepage,andrelatedlinks,provideawealthof informationaboutthedatabasesenvironmentandhealth. Tograntmanagementaccesstootherdatabaseusers,usethefollowingprocedure: 1.StartyourWebbrowserandlogintoDatabaseControlastheSYS orSYSTEM databaseuser. 2.ClickSetupatthetopoftheDatabasehomepage. 3 ClickAdministratorsintheleftnavigationbar. 3. bar 4.ClickCreatetocreateanewEnterpriseManageruserbyassigningthe managementprivilegestoanexistingdatabaseuser. 5.ClicktheflashlighticonnexttotheNamefieldandselectanexistingdatabase userfromthepopupwindow. 6.EnterthepasswordfortheselecteduserandclickFinish.

OracleDatabase10g:Administration WorkshopI5107

ChangingtheListenerStatus FromtheDatabasehomepageclickthelistenernametoopentheListenerhomepage. ClickStoptostopthelistenerifitisrunningorStarttostartthelistenerifitisnot running.YoumustlogontothehostasanOSuserifyouhavenotdonesoalready.This willbetheOSuserthatstartsorstopsthelistener. Thecommandlinemethodforstarting,stopping,andseeingthestatusofthelisteneris: lsnrctlSTART[listener_name] lsnrctlSTOP[listener_name] lsnrctlSTATUS[listener_name] Wherelistener_name listener name isthenameofthelistenerdefinedinthelistener.ora listener ora file.Itisnotnecessarytoidentifythelistenerifyouareusingthedefaultlistener,named LISTENER. TheSTATUS commandprovidesbasicstatusinformationaboutalistener,includinga summaryoflistenerconfigurationsettings,thelisteningprotocoladdresses,anda summaryofservicesregisteredwiththelistener.

OracleDatabase10g:Administration WorkshopI5108

StartupandShutdown Whenyouclickeitherstartuporshutdownyoumaybepromptedforcredentialsthatwill beusedforloggingintoboththehost(thecomputerthedatabaseresideson)andthe databaseitself. YoucanthenclickAdvancedOptionstochangeanystartupoptionsortheshutdown modeasneeded.AlsoyoucanclickShowSQLtoseetheSQLstatementthatwillbeused forthestartuporshutdown.

OracleDatabase10g:Administration WorkshopI5109

StartingUpaDatabase Whenstartingthedatabase,youselectthestateinwhichitstarts.Thefollowing scenariosdescribedifferentstagesofstartingupaninstance. StartingtheInstance(NOMOUNT) Aninstanceisstartedinthe NOMOUNT stageonlyduringdatabasecreationorthere creationofcontrolfiles. Startinganinstanceincludesthefollowingtasks: Readingtheinitializationfilefrom$ORACLE_HOME/dbs inthefollowingorder: FirstspfileSID.ora Ifnotfoundthen, then spfile.ora spfile ora Ifnotfoundthen,initSID.ora SpecifyingthePFILE parameterwithSTARTUP overridesthedefault behavior. AllocatingtheSGA Startingthebackgroundprocesses OpeningthealertSID.log fileandthetracefiles

OracleDatabase10g:Administration WorkshopI5110

StartingUpaDatabase(continued) MountingtheDatabase(MOUNT) Toperformspecificmaintenanceoperations,youstartaninstanceandmountadatabase butdonotopenthedatabase. Forexample,thedatabasemustbemountedbutnotopenduringthefollowingtasks: Renamingdatafiles(datafilesforanofflinetablespacecanberenamedwhenthe databaseisopen) Enablinganddisablingonlineredologfilearchivingoptions Performingfulldatabaserecovery Mountingadatabaseincludesthefollowingtasks: Associatingadatabasewithapreviouslystartedinstance Locatingandopeningthecontrolfilesspecifiedintheparameterfile Readingthecontrolfilestoobtainthenamesandstatusofthedatafilesand onlineredologfiles.However,nochecksareperformedtoverifytheexistenceof thedatafilesandonlineredologfilesatthistime.

OracleDatabase10g:Administration WorkshopI5111

StartingUpaDatabase(continued) OpeningtheDatabase(OPEN) Normaldatabaseoperationmeansthataninstanceisstartedandthedatabaseis mountedandopen.Withnormaldatabaseoperation,anyvalidusercanconnecttothe databaseandperformtypicaldataaccessoperations. Openingthedatabaseincludesthefollowingtasks: Openingtheonlinedatafiles Openingtheonlineredologfiles Ifanyofthedatafilesoronlineredologfilesarenotpresentwhenyouattempttoopen thedatabase, database theOracleserverreturnsanerror. error Duringthisfinalstage,theOracleserververifiesthatallthedatafilesandonlineredolog filescanbeopenedandcheckstheconsistencyofthedatabase.Ifnecessary,theSMON backgroundprocessinitiatesinstancerecovery.

OracleDatabase10g:Administration WorkshopI5112

ShuttingDowntheDatabase Shutdownthedatabasetomakeoperatingsystemofflinebackupsofallphysical structuresandtohavemodifiedstaticinitializationparameterstakeeffectwhen restarted. ToshutdownaninstanceyoumustconnectasSYSOPER orSYSDBA andusethe followingcommand: SHUTDOWN[NORMAL |TRANSACTIONAL|IMMEDIATE|ABORT] ThisisthecommandthatgetsgeneratedwhenyouclickShutdownandconfirmyour intentiononthesubsequentpage.

OracleDatabase10g:Administration WorkshopI5113

SHUTDOWN Options SHUTDOWN NORMAL Normalisthedefaultshutdownmode.Normaldatabaseshutdownproceedswiththefollowing conditions: di i Nonewconnectionscanbemade. TheOracleserverwaitsforalluserstodisconnectbeforecompletingtheshutdown. Databaseandredobuffersarewrittentodisk. Backgroundprocessesareterminated,andtheSGAisremovedfrommemory. Oracleclosesanddismountsthedatabasebeforeshuttingdowntheinstance. Thenextstartupdoesnotrequireaninstancerecovery. SHUTDOWN TRANSACTIONAL Atransactionalshutdownpreventsclientsfromlosingwork.Atransactionaldatabaseshutdown proceedswiththefollowingconditions: Noclientcanstartanewtransactiononthisparticularinstance. Aclientisdisconnectedwhentheclientendsthetransactionthatisinprogress. Whenalltransactionshavefinished,ashutdownoccursimmediately. Thenextstartupdoesnotrequireaninstancerecovery.

OracleDatabase10g:Administration WorkshopI5114

SHUTDOWN Options(continued) SHUTDOWN IMMEDIATE Immediatedatabaseshutdownproceedswiththefollowingconditions: CurrentSQLstatementsbeingprocessedbyOraclearenotcompleted. completed TheOracleserverdoesnotwaitfortheusers,whoarecurrentlyconnectedtothe database,todisconnect. Oraclerollsbackactivetransactionsanddisconnectsallconnectedusers. Oracleclosesanddismountsthedatabasebeforeshuttingdowntheinstance. Thenextstartupdoesnotrequireaninstancerecovery.

OracleDatabase10g:Administration WorkshopI5115

SHUTDOWN Options(continued) SHUTDOWN ABORT IftheNORMAL andIMMEDIATE shutdownoptionsdonotwork,youcanabortthe currentdatabaseinstance.Abortinganinstanceproceedswiththefollowingconditions: CurrentSQLstatementsbeingprocessedbytheOracleserverareimmediately terminated. Oracledoesnotwaitforuserscurrentlyconnectedtothedatabasetodisconnect. Databaseandredobuffersarenotwrittentodisk. Uncommittedtransactionsarenotrolledback. Theinstanceisterminatedwithoutclosingthefiles. files Thedatabaseisnotclosedordismounted. Thenextstartuprequiresinstancerecovery,whichoccursautomatically. Note: Itisnotadvisabletobackupadatabasethatisinaninconsistentstate.

OracleDatabase10g:Administration WorkshopI5116

InitializationParameterFiles Tostartaninstance,Oraclemustreadeitheraninitializationparameterfileoraserver parameterfile.Thesefilescontainalistofconfigurationparametersforthatinstanceand database.Oracletraditionallystoresinitializationparametersinatextinitialization parameterfile.Youcanalsochoosetomaintaininitializationparametersinabinary serverparameterfile(SPFILE). Initializationparametersstoredinaserverparameterfilearepersistent,inthatany changesmadetotheparameterswhileaninstanceisrunningcanpersistacrossinstance shutdownandstartup.Initializationparametersaredividedintotwogroups:basicand advanced Inthemajorityofcases, advanced. cases itisnecessarytosetandtuneonlythebasic parameterstogetreasonableperformance.Inraresituations,modificationtothe advancedparametersmaybeneededforoptimalperformance. Oraclesuggeststhatyoucreateaserverparameterfile(SPFILE)asadynamicmeansof maintaininginitializationparameters.Byusingaserverparameterfileyoucanstoreand manageyourinitializationparameterspersistentlyinaserversidediskfile.

OracleDatabase10g:Administration WorkshopI5117

ViewingInitializationParameters TheOracleDatabaseprovidesanumberofinitializationparameterstooptimizeits operationindiverseenvironments.Onlyafewoftheseparametersmustbeexplicitlyset becausethedefaultvaluesareadequateinthemajorityofcases.Thereare28basic parameters. TheadvancedparametersarepreservedtoallowexpertDBAstoadaptthebehaviorof theOracleDatabasetomeetuniquerequirementswithoutoverwhelmingthosewho havenosuchrequirements.

OracleDatabase10g:Administration WorkshopI5118

ViewingtheAlertLog Eachdatabasealsohasanalert_sid.log.Thefileisontheserverwiththedatabase andisstoredinthedirectoryspecifiedwiththeinitializationparameter b k background_dump_dest d d d t.Thealertfileofadatabaseisachronologicallogof messagesanderrors,includingthefollowing: Allinternalerrors(ORA-600),blockcorruptionerrors(ORA-1578),and deadlockerrors(ORA-60)thatoccur Administrativeoperations,suchastheSQLstatementsCREATE,ALTER,DROP DATABASE,TABLESPACE,ROLLBACK SEGMENT andtheEnterpriseManager orSQL*PlusstatementsSTARTUP,SHUTDOWN,ARCHIVE LOG,andRECOVER Severalmessagesanderrorsrelatingtothefunctionsofsharedserverand dispatcherprocesses Errorsduringtheautomaticrefreshofamaterializedview EMmonitorsthealertlogfileandnotifiesyouofcriticalerrors.Youcanalsoviewthelog toseenoncriticalerrorandinformativemessages.Alsothefilecangrowtoan unmanageablesizeifleftalone.Youshouldmakeabackupofthealertfileoccasionally anddeletethecurrentalertfile.Whenthedatabaseattemptstowritetothealertfile again, g thedatabasewillthenrecreateanewalertfile.

OracleDatabase10g:Administration WorkshopI5119

OracleDatabase10g:Administration WorkshopI5120

OracleDatabase10g:Administration WorkshopI5121

Practice5:ControllingtheDatabase Background:YoursystemadministratorasksthatyoustopallOracleservicesin preparationforsystemmaintenance.Aftermaintenanceiscompleted,restartallOracle services.. services Tasks: StartandstoptheOracleListener StartandstopOracleDatabase10g instance Startandstop iSQL*Plus StartandstoptheOracleEnterpriseManagerDatabaseControl 1.ConnecttoDatabaseControl. 2.Stopthe h Oracle l ListenerusingDatabase b Contol. l 3.ShutdownthedatabaseinstanceusingDatabaseControl. 4.StopiSQL*Plus. 5.StopDatabaseControl. 6.StarttheOracleListenerusingcommandlinetools. 7.StartDatabaseControl. 8.StartiSQL*Plus. Q 9.StarttheOracleDatabase10g instance. 10.Viewinformationintheinstancesalertlog. 11.Viewinitializationparameters.

OracleDatabase10g:Administration WorkshopI5122

OracleDatabase10g:Administration WorkshopI6125

TablespacesandDataFiles Databases,tablespaces,anddatafilesarecloselyrelated,buttheyhaveimportant differences: AnOracledatabaseconsistsofoneormorelogicalstorageunitscalled tablespaces,whichcollectivelystoreallofthedatabasesdata. EachtablespaceinanOracledatabaseconsistsofoneormorefilescalled datafiles,whicharephysicalstructuresthatconformwiththeoperating systemonwhichOracleisrunning running. Adatabasesdataiscollectivelystoredinthedatafilesthatconstituteeach tablespaceofthedatabase.Forexample,thesimplestOracledatabase wouldhaveonetablespaceandonedatafile.Anotherdatabasecanhave threetablespaces,eachconsistingoftwodatafiles(foratotalofsixdata files).Asingledatabasecouldpotentiallyhaveasmanyas65,535datafiles.

OracleDatabase10g:Administration WorkshopI6126

SpaceManagementinTablespaces Tablespacesallocatespaceinextents.Tablespacescanbecreatedtouseoneofthe followingtwodifferentmethodsofkeepingtrackoffreeandusedspace: Locallymanagedtablespaces:Theextentsaremanagedwithinthetablespacevia bitmaps.Eachbitinthebitmapcorrespondstoablockoragroupofblocks.Whenan extentisallocatedorfreedforreuse,theOracleserverchangesthebitmapvaluesto showthenewstatusoftheblocks. Dictionarymanagedtablespaces:Theextentsaremanagedbythedatadictionary.The Oracleserverupdatestheappropriatetablesinthedatadictionarywheneveranextentis allocatedordeallocated. deallocated Thisisforbackwardcompatibly;youshoulduselocallymanaged foralltablespaces.

OracleDatabase10g:Administration WorkshopI6127

CreatingaNewTablespace Tocreateatablespace,performthefollowingsteps: 1. NavigatetotheTablespacespage.GototheAdministrationtab,then clickTablespacesundertheStorageheading heading. 2. ClicktheCreatebutton. Note: Ifyouwanttocreateatablespacethatislikeanexisting tablespace,selectanexistingtablespaceandselectCreateLikefromtheActionsmenu. ClickGo. TheCreateTablespaceGeneralpageappears. 3. Enteranameforthetablespace. 4. UndertheExtentManagementheading,selectLocallyManaged.The extentsofalocallymanagedtablespacearemanagedefficientlywithinthetablespaceby theOracledatabaseserver.Foradictionarymanagedtablespaceyoumustmoreactively manageextentsanddatadictionaryaccessisrequiredfortrackingthem.Dictionary managedtablespacesarebeingdeprecated.Oracledoesnotsuggesttheiruse. 5. UndertheTypeheading,selectPermanent.Permanenttablespacesstore permanentdatabaseobjectscreatedbythesystemorusers. 6. UndertheStatusheading,selectReadWrite.Read/writestatusmeans userscanreadandwritetothetablespaceafteritiscreated.Thisisthedefault.

OracleDatabase10g:Administration WorkshopI6128

CreatingaNewTablespace(continued) 7. IntheDatafilesregionofthepageclickAddtoadddatafilestothe tablespace,atablespacemusthaveatleastonefile.Bigfiletablespacesareused withultralargedatabaseswhereOracles Oracle sAutomaticStorageManagementor otherlogicalvolumemanagerssupportstripingorRAID,anddynamically extensiblelogicalvolumes. 8.IntheAddDatafilespage,enterafilename.AcceptthedefaultsfortheFile DirectoryandFileSize. 9.UndertheStorageregion,selectAutomaticallyextenddatafilewhenfull (AUTOEXTEND)andspecifyanamountintheIncrementfieldbywhichyouwant toextend dthe h data d file f l each htimeitfills. f ll Leavethe h MaximumFile l Sizesetto Unlimited.ClickOK.YouarereturnedtotheCreateTablespaceGeneralpage. 10. ClicktheStoragetab.TheCreateTablespaceStoragepageappears. 11. AcceptallofthedefaultsontheStoragepage. 12. ClicktheThresholdstabtoopentheThresholdspage.Thispage enablesyoutosetmonitoredthresholdsforspaceusage.Youreceiveadviceand anoption p foractionwhenthethresholdisreached. 13. AfterspecifyingthresholdsclickOKtoaddthetablespace.Youare returnedtotheTablespacespagewhereyoureceiveaconfirmationofthe creationofthetablespace.YoucanviewyournewtablespaceintheResults section. Note: Thesestepsareintendedtoshowyouhowtoquicklycreateatablespaceformost situations.Youmayneedtochangesomeoptionsdependonyourparticularsystem requirements. i t

OracleDatabase10g:Administration WorkshopI6129

StorageforLocallyManagedTablespaces Extentswithinalocallymanagedtablespacecanbeallocatedinoneoftwoways: Automatic:Alsocalledautoallocate,specifiesthatthesizeoftheextentswithin thetablespacearesystemmanaged.Youcannotspecifyanextentsize.Youcannot specifyautomaticforatemporarytablespace. Uniform:Specifiesthatthetablespaceismanagedwithuniformextentsofasize youspecify.Thedefaultsizeis1megabyte.Allextentsoftemporarytablespaces areofuniformsize,sothisisoptionalforatemporarytablespace.Youcannot specifyuniformforanundotablespace. Segmentspacemanagementwithinalocallymanagedtablespace: Automatic:Oracleusesbitmapstomanagethefreespacewithinsegments.A bitmap,inthiscase,isamapthatdescribesthestatusofeachdatablockwithina segmentwithrespecttotheamountofspaceintheblockavailableforinserting rows.Asmoreorlessspacebecomesavailableinadatablock,itsnewstateis reflectedinthebitmap.BitmapsallowOracletomanagefreespacemore automatically,andthus,thisformofspacemanagementiscalledautomatic segmentspacemanagement.

OracleDatabase10g:Administration WorkshopI6130

StorageforLocallyManagedTablespaces(continued) Manual:ThistellsOraclethatyouwanttousefreelistsformanagingfreespace withinsegments.Freelistsarelistsofdatablocksthathavespaceavailablefor insertingrows. rows Thisformofmanagingspacewithinsegmentsiscalledmanual segmentspacemanagementbecauseoftheneedtospecifyandtunethe PCTUSED,FREELISTS,andFREELIST GROUPS storageparametersfor schemaobjectscreatedinthetablespace.Thisissupportedforbackward compatibility. AdvantagesofLocallyManagedTablespaces Locallymanagedtablespaceshavethefollowingadvantagesoverdictionarymanaged tablespaces: bl Localmanagementavoidsrecursivespacemanagementoperations.Thiscan occurindictionarymanagedtablespacesifconsumingorreleasingspaceinan extentresultsinanotheroperationthatconsumesorreleasesspaceinanundo segmentordatadictionarytable. Becauselocallymanagedtablespacesdonotrecordfreespaceindatadictionary tables, ,they yreducecontentiononthesetables. Localmanagementofextentsautomaticallytracksadjacentfreespace, eliminatingtheneedtocoalescefreeextents. Thesizesofextentsthataremanagedlocallycanbedeterminedautomatically bythesystem. Changestotheextentbitmapsdonotgenerateundoinformationbecausethey donotupdatetablesinthedatadictionary(exceptforspecialcasessuchas t bl tablespace quota t i information). f ti ) Note: Ifyouaremanagingadatabasethathasdictionarymanagedtablespacesandyou wanttoconvertthemtolocallymanaged,usethe DBMS_SPACE_ADMIN.TABLESPACE_MIGRATE_TO_LOCAL proceduretodothis. FordetailsontheuseofthisprocedureseethePL/SQLPackagesandTypesReference andtheDatabaseAdministratorsGuide. Logging gg g Whenchangesaremadetoobjectsinthetablespace,thechangeisloggedintowhatis calledtheredostream.Thisredostreamstartsinmemory,theiswrittentotheonline redologfilesandmaybewrittentoarchivelogfiles.Youcanturnthisprocessesoff.If youdoturnofflogging,theobjectsinthistablespacewillbeunrecoverableintheevent ofanykindoffailure. Thresholds UsetheTablespaceThresholdstabtosetthespaceusedthresholdsforthecurrent databasetablespace.Youcanchoosetousethedefaultusagethresholdsfor tablespacesforthedatabaseoryoucanspecifythethresholdforthepercentageof spaceusedforthecurrenttablespacebyenteringthevaluesfortheWarningand Criticalfields.Youcanalsodisablespaceusedthresholdsentirelyforthistablespace. Thresholdsarecoveredinmoredetailinlesson15.

OracleDatabase10g:Administration WorkshopI6131

TablespacesinthePreconfiguredDatabase Thefollowingtablespacesarecreatedforyouinthepreconfigureddatabase: SYSTEM:TheSYSTEM tablespaceisusedbytheOracledatabaseserverto managethedatabase. database Itcontainsthedatadictionaryandtablesthatcontain administrativeinformationaboutthedatabase.TheseareallcontainedintheSYS schema,andcanbeaccessedonlybytheuserSYS,orotheradministrativeusers withtherequiredprivilege. SYSAUX:ThisisanauxiliarytablespacetotheSYSTEM tablespace.Some componentsandproductsthatusedtheSYSTEM tablespaceortheirown tablespacesinpriorreleasesofOracle,nowusetheSYSAUX tablespace.Every OracleDatabase10g orhigherleveldatabasemusthaveaSYSAUX tablespace. tablespace TEMP:Thistablespaceisusedtostoretemporarytablesandindexeswhen processingSQLstatements.Itwould,forexample,beusedforsortworkspace. Everydatabaseshouldhaveatemporarytablespacethatisassignedtousersas theirtemporarytablespace.Inthepreconfigureddatabase,theTEMP tablespace isspecifiedasthedefaulttemporarytablespace.Thismeansthatifnotemporary tablespaceisspecifiedwhentheuseraccountiscreated,thenOracleassignsthis tablespace p totheuser.

OracleDatabase10g:Administration WorkshopI6132

TablespacesinthePreconfiguredDatabase(continued) UNDOTBS1:Thisistheundotablespaceusedbythedatabaseservertostore undoinformation.Everydatabasemusthaveanundotablespacethatiscreated duringdatabasecreation. creation USERS:Thistablespaceisusedtostorepermanentuserobjectsanddata.Inthe preconfigureddatabase,theUSERS tablespaceisthedefaulttablespaceforall objectscreatedbynonsystemusers.FortheSYS andSYSTEM users(thesystem users),thedefaultpermanenttablespaceremainsSYSTEM. EXAMPLE:Thistablespacecontainsthesampleschemasthatcanbeinstalled whenyoucreatethedatabase.Thesampleschemasprovideacommonplatform f examples. for l Oracle l documentation d and dcoursewarecontainexamples l b based d uponthesampleschemas.

OracleDatabase10g:Administration WorkshopI6133

AlteringaTablespace Afteryoucreateatablespace,youcanlateralteritinseveralwaysastheneedsofyour systemchange. Renaming:SimplyenteranewnameforthetablespaceandclickApply. ChangingtheStatus:Atablespacecanbeinoneofthreedifferentstatusesorstates. Dependingonthetypeoftablespace,notallstatesmaybeavailable: ReadWrite:Thetablespaceisonlineandcanbereadfromandwrittento. ReadOnly:Specifyreadonlytoplacethetablespaceintransitionreadonlymode. Inthisstate,existingtransactionscancomplete(commitorrollback),butno furtherDMLoperationsareallowedtothetablespaceexceptforrollbackof existingtransactionsthatpreviouslymodifiedblocksinthetablespace.The tablespaceisonlinewhileinthereadonlystate.YoucannotmaketheSYSTEM or SYSAUX tablespacereadonly.

OracleDatabase10g:Administration WorkshopI6134

AlteringaTablespace(continued) Offline:Youcantakeanonlinetablespaceofflinesothatthisportionofthe databaseistemporarilyunavailableforgeneraluse.Therestofthedatabaseis openandavailableforuserstoaccessdata.Whenyoutakeitofflineyouhave choicesofhowtodothis: Normal:Atablespacecanbetakenofflinenormallyifnoerrorconditions existforanyofthedatafilesofthetablespace.Oracletakesacheckpoint foralldatafilesofthetablespaceasittakesthemoffline. Temporary:Atablespacecanbetakenofflinetemporarily,evenifthereare errorconditionsforoneormorefilesofthetablespace.Oracletakes offlinethedatafilesthatarenotalreadyoffline,checkpointingthemasit doesso. so Ifnofilesareoffline, offline butyouusethetemporaryclause, clause media recoveryisnotrequiredtobringthetablespacebackonline.However,if oneormorefilesofthetablespaceisofflinebecauseofwriteerrors,and youtakethetablespaceofflinetemporarily,thetablespacerequires recoverybeforeyoucanbringitbackonline. Immediate:Atablespacecanbetakenofflineimmediately,withoutOracle takingacheckpointonanyofthedatafiles.WhenyouspecifyImmediate, mediarecoveryforthetablespaceisrequiredbeforethetablespacecanbe broughtonline.Youcannottakeatablespaceofflineimmediatelyifthe databaseisrunninginNOARCHIVELOG mode. ForRecover:TheFOR RECOVER settinghasbeendeprecated.Thesyntax issupportedforbackwardcompatibility. ChangetheSize:Youcanaddspacetoanexistingtablespacebyaddingdatafilestothe tablespaceoryoucanchangethesizeofanexistingdatafile. ToaddanewdatafiletothetablespaceclickAdd,andfillintheinformationabout thedatafileontheAddDataFilepage.Notethatthetablespacenameisfixed. Tochangethesizeofanexistingdatafile,selectthedatafileintheDatafiles regionoftheEditTablespacepagebyclickingthenameofthedatafile,orselect thedatafileandclickEdit.ThenontheEditDatafilepageyoucanchangethesize ofthedatafile.Youcanmakethetablespaceeitherlargerorsmaller.Howeveryou cannotmakeadatafilesmallerthantheusedspaceinthefile;ifyoutryyouget thefollowingerror: ORA03297: 03297 file fil contains t i used ddata d t beyond b drequested t dRESIZEvalue l StorageOptions:ClickStoragetochangechangetheloggingbehaviorofthetablespace. Thresholds:ClickThresholdstocanchangethewarningandcriticalusedspacealtersfor thetablespace.Youhavethreeoptions: UseDefaultThresholds:Thisusespresetdefaults,andyouhavetheoptionof settingthesedefaults. SpecifyThresholds:Thisallowsyoutosetthresholdsforthisparticulartablespace. DisableThresholds:Thisturnsoffspaceusagealertsforthistablespace. tablespace

OracleDatabase10g:Administration WorkshopI6135

ActionswithTablespaces WiththeActionsMenuyoucanperformaverityoftaskswithyourtablespaces.Selecta tablespaceandthentheactionyouwanttoperform: AddDatafile:Addsadatafiletothetablespace,whichmakesthetablespace larger. CreateLike:Createanothertablespaceusingthetablespaceasatemplate. GenerateDDL:GeneratetheDDLstatementthatcreatesthetablespace.Thiscan thenbecopiedandpastedintoatextfileforuseasascriptorfordocumentation purposes. MakeLocallyManaged:Ifthetablespaceiscurrentlydictionarymanaged managed,thiswill convertthetablespacetolocallymanaged. MakeReadonly:Stopsallwritestothetablespace.Currenttransactionsare allowedtocompetebutnonewDMLorotherwriteactivitiesareallowedtostart onthetablespace. MakeWritable:AllowsDMLandotherwriteactivitiestobeinitiatedonobjectsin thetablespace.

OracleDatabase10g:Administration WorkshopI6136

ActionswithTablespaces(continued) PlaceOnline:Ifthetablespaceiscurrentlyoffline,thisbringsitbackonline. Reorganize:ThisstartstheReorganizationWizard,whichyoucanusetomove objectsaroundwithinthetablespacetoreclaimspacethatotherwisemightnot beused.Thisisataskthatshouldbedoneduringnonpeakusageoftheobjects inthetablespace. ShowDependencies:Thisshowsobjectsthatthistablespacedependsonor objectsthatdependonthistablespace. RunSegmentAdvisor:TheSegmentAdvisorhelpsyoudeterminewhetheran objecthasspaceavailableforreclamationbasedonthelevelofspace f fragmentation within h the h object. b Atthe h tablespace bl level, l l advice d isgenerated dfor f everysegmentinthetablespace. TakeOffline:Ifthetablespaceiscurrentlyonlinethiswillmakethetablespace unavailable.Thetablespaceisnotdeletedordrop,justunavailable. Note: Notallactionsareavailableforeachtablespace.Dependingonthetypeof tablespaceselected,someactionscannotbeperformed.Forexample,youcannottake theSYSTEM tablespace p offline, ,norcany youmakeanundotablespace p readonly. y

OracleDatabase10g:Administration WorkshopI6137

DroppingTablespaces Youcandropatablespaceanditscontents(thesegmentscontainedinthetablespace) fromthedatabaseifthetablespaceanditscontentsarenolongerrequired.Youmust havetheDROP TABLESPACE systemprivilegetodropatablespace. Whenyoudropatablespace,thefilepointersinthecontrolfileoftheassociated databaseareremoved.YoucanoptionallydirectOracletodeletetheoperatingsystem files(datafiles)thatconstitutedthedroppedtablespace.IfyoudonotdirectOracleto deletethedatafilesatthesametimethatitdeletesthetablespace,youmustlateruse theappropriatecommandsofyouroperatingsystemtodeletethem. Youcannotdropatablespacethatcontainsanyactivesegments. segments Forexample, example ifatablein thetablespaceiscurrentlybeingusedorthetablespacecontainsundodatathatis neededtorollbackuncommittedtransactions,youcannotdropthetablespace.The tablespacecanbeonlineoroffline,butitisbesttotakethetablespaceofflinebefore droppingit.

OracleDatabase10g:Administration WorkshopI6138

ViewingTablespaceInformation ClickViewtoseeinformationabouttheselectedtablespace.IntheViewTablespacepage, youcanalsoclickedittoalterthetablespace. Obtainingtablespaceanddatafileinformationcanalsobeobtainedbyqueryingthe following: Tablespaceinformation: DBA_TABLESPACES V$TABLESPACE Datafileinformation: DBA DATA FILES DBA_DATA_FILES V$DATAFILE Tempfileinformation: DBA_TEMP_FILES V$TEMPFILE

OracleDatabase10g:Administration WorkshopI6139

OracleDatabase10g:Administration WorkshopI6140

OracleDatabase10g:Administration WorkshopI6141

Practice6:WorkingwithTablespaces Background:Youwillbesupportinganewinventoryapplicationwithyourdatabase.The installationinstructionsfortheapplicationinstructyoutocreateatablespacetoholddataforthe newapplication. Tasks: Examinetablespacesanddatafiles Createatablespace Addspacetoanexistingtablespace. 1.UseDatabaseControltoviewalltablespacesinyourdatabase.Foreachtablespace recordthetablespacename,type,size,andpercentused. 2.Viewalldatafilesinyourdatabase.Foreachdatafilerecordthefilename,tablespace name,currentsize,autoextendstatus,andmaximumfilesize(ifautoextendisenabled).

Tablespace Name

Type

Size (MB)

Used %

Fil Name File N

Tablespace T bl Name

Current C Size (MB)

Auto A extend?

Maximum M i Size (MB)

OracleDatabase10g:Administration WorkshopI6142

Practice6:WorkingwithTablespaces (continued) 3. Createanewtablespace toholdinformationfortheinventoryapplication. Characteristicsforthenewtablespace are: Tablespace Name:INVENTORY Filesize:50MB Extentmanagement:Local AUTOEXTEND: disabled Type:Permanent ExtentAllocation: Automatic Status:ReadWrite Segmentspace management:Auto File l name:inventory01.dbf dbf Enable bl Logging:Yes Filedirectory:default Usedefaultthresholds

OracleDatabase10g:Administration WorkshopI6143

OracleDatabase10g:Administration WorkshopI7145

DatabaseUserAccounts Toaccessthedatabaseausermustspecifyavaliddatabaseuseraccountandsuccessfully authenticateasrequiredbythatuseraccount. Insomesystems, systems eachdatabaseuserhashisorherowndatabaseaccount. account Inothers, others manyusersshareacommondatabaseaccount.Regardlessofwhichmodelyourdatabase follows,eachuseraccountwillhave: Auniqueusername.Usernamescannotexceed30characters,cannotcontain specialcharacters,andmuststartwithaletter. Anauthenticationmethod.Themostcommonauthenticationmethodisa password,butOracleDatabase10g supportsseveralotherauthentication gbiometric, ,certificate, ,andtokenauthentication. methodsincluding Adefaulttablespace.Aplacewheretheuserwillcreateobjectsiftheuserdoes notspecifysomeothertablespace.Notethathavingadefaulttablespacedoesnot implytheuserhastheprivilege ofcreatingobjectsinthattablespacenoraquota ofspacewithinthattablespaceinwhichtocreateobjects.Boththesearegranted separately. Atemporarytablespace.Aplacewheretheusercancreatetemporaryobjects suchassortsandtemporarytables. Auserprofile. profile Asetofresourceandpasswordrestrictionsassignedtotheuser user.

OracleDatabase10g:Administration WorkshopI7146

CreatingaUser InOracleEnterpriseManageryoucanmanagethelistofdatabaseusersthatare allowedtoaccessthecurrentdatabasethroughtheUserspropertysheet.Youcan usethepropertysheettocreate,delete,andmodifythesettingsofauser. TheUserspropertysheetconsistsofseveralpages.Youcancreateoreditthe securitysettingsforadatabaseuserbymovingtotheotherpagesassociatedwith theUserspropertysheet.ClickHelpformoreinformationaboutaspecificpage. Tocreateadatabaseuser: 1.NavigatetotheDatabasehomepage. 2 OntheAdministrationpropertiespageunderSecurity, 2.On Security clickUsers. Users TheUsers Searchpageappearscontainingaresultstablethatlistsallcurrentusersforthe database. 3.ClickCreatetocreateanewuser.

OracleDatabase10g:Administration WorkshopI7147

ProfilesandUsers Profilesimposeanamedsetofresourcelimitsondatabaseusageandinstanceresources. Profilesalsoplacelimitationsonuserspasswords(length,expirationtime,andsoon.) Everyuserisassignedtoaprofileandmaybelongtoonlyoneprofileatanygiventime. time Thedefaultprofileservesasthebasisforallotherprofiles.Asyoucanseeintheslide, limitationsforaprofilecanbeeitherimplicitlyspecified(asinCPU/Session),unlimited(as inCPU/Call)orreferencewhateversettingisinthedefaultprofile(asinConnectTime). ProfilescannotimposeresourcelimitationsonusersunlesstheRESOURCE_LIMIT initializationparameterissettoTRUE.WithRESOURCE_LIMIT atitsdefaultvalueof FALSE,profilelimitationsareignored. Profilesallowtheadministratortocontrolthefollowingsystemresources: CPU.CPUresourcesmaybelimitedonapersessionorpercallbasis.A CPU/sessionlimitationof1000meansthatifanyindividualsessionusingthis profileconsumesmorethan10secondsofCPUtime(CPUtimelimitationsarein 100thsofasecond),thenthatsessionreceivesanerrorandisloggedoff: ORA02392:exceededsessionlimitonCPUusage,youarebeing loggedoff

OracleDatabase10g:Administration WorkshopI7148

ProfilesandUsers(continued) Apercalllimitationdoesthesamething,butinsteadoflimitingtheusersoverall session,itpreventsanysinglecommandfromconsumingtoomuchCPU.IfCPU/Callis limitedandtheuserexceedsthelimitation limitation,thecommandabortsandtheusergetsan errormessagesuchasthefollowing: ORA02393:exceededcalllimitonCPUusage Network/Memory:Eachdatabasesessionconsumessystemmemoryresources and(ifthesessionisfromausernotlocaltotheserver)networkresources. ConnectTime:Howmanyminutesauserscanbeconnectedbefore beingautomaticallyloggedoff. Idle dl Time:Howmanyminutesausers sessioncanremainidle dl before b f beingautomaticallyloggedoff.Idletimeiscalculatedfortheserver processonly.Itdoesnottakeintoaccountapplicationactivity.The IDLE_TIME limitisnotaffectedbylongrunningqueriesandother operations. ConcurrentSessions:Howmanyconcurrentsessionscanbecreated using gadatabaseuseraccount. PrivateSGA:LimitstheamountofspaceconsumedwithintheSGAfor sorting,mergingbitmaps,andsoon.Thisrestrictiontakeseffectonlyif thesessionusesasharedserver(sharedserversarediscussedinalater lesson) DiskI/O:Limitstheamountofdataausercanreadeitheratthepersessionor percalllevel.Reads/SessionandReads/Callplacealimitationonthetotal number b of freads d from f both b thmemoryand ddisk. di k This Thi canbe b done d to t ensurethat th t noI/Ointensivestatementshoardmemoryandtieupthedisk. Profilesalsoallowacompositelimit.Compositelimitsarebasedonaweighted combinationofCPU/session,reads/session,connecttime,andprivateSGA.Composite limitsarediscussedinmoredetailintheOracleDatabaseSecurityGuide. Usingprofilestomanageuserpasswordswillbediscussedinalaterlesson.

OracleDatabase10g:Administration WorkshopI7149

AuthenticatingUsers Authenticationmeansverifyingtheidentityofsomeone(auser,device,orotherentity) whowantstousedata,resources,orapplications.Validatingthatidentityestablishesa trustrelationshipforfurtherinteractions.Authenticationalsoenablesaccountabilityby makingitpossibletolinkaccessandactionstospecificidentities.Afterauthentication, authorizationprocessescanalloworlimitthelevelsofaccessandactionpermittedto thatentity. Whenyoucreateauseryoumustdecideontheauthenticationtechniquetouse,which canbemodifiedlater. Password: AlsoreferredtoasauthenticationbytheOracledatabase, database createeachuser withanassociatedpasswordthatmustbesuppliedwhentheuserattemptstoestablisha connection.Whensettingupapasswordyoucanexpirethepasswordimmediately,which forcestheusertochangethepasswordafterfirstloggingin.Ifyouplanonexpiringuser passwords,makesuretheusershavetheabilitytochangethepassword.Some applicationsdonothavethisfunctionality.

OracleDatabase10g:Administration WorkshopI7150

AuthenticatingUsers(continued) External: Alsoreferredtoasauthenticationbytheoperatingsystem,userscanconnect toOraclemoreconveniently,withoutspecifyingausernameorpassword.Withexternal authentication yourdatabasereliesontheunderlyingoperatingsystemornetwork authentication, authenticationservicetorestrictaccesstodatabaseaccounts.Adatabasepasswordis notusedforthistypeoflogin.Ifyouroperatingsystemornetworkservicepermits,you canhaveitauthenticateusers.Ifyoudoso,settheOS_AUTHENT_PREFIX initializationparameterandusethisprefixinOracleusernames.The OS_AUTHENT_PREFIX parameterdefinesaprefixthatOracleaddstothebeginning ofeveryusersoperatingsystemaccountname.Thedefaultvalueofthisparameteris OPS$ $ for f backward b k dcompatibility ibili with i hprevious i versions i of fOracle. O l O Oracle l comparesthe h prefixedusernamewiththeOracleusernamesinthedatabasewhenauserattemptsto connect.Forexample,assumethatOS_AUTHENT_PREFIX issetasfollows: OS_AUTHENT_PREFIX=OPS$ Ifauserwithanoperatingsystemaccountnamedtsmith istoconnecttoanOracle databaseandbeauthenticatedbytheoperatingsystem,Oraclechecksthatthereisa corresponding p gdatabaseuserOPS$tsmith $ and, ,ifso, ,allowstheusertoconnect.All referencestoauserauthenticatedbytheoperatingsystemmustincludetheprefix,as seeninOPS$tsmith. Note: ThetextoftheOS_AUTHENT_PREFIX initializationparameteriscasesensitive onsomeoperatingsystems.SeeyouroperatingsystemspecificOracledocumentation formoreinformationaboutthisinitializationparameter. Global: StrongauthenticationthroughtheOracleAdvancedSecurityoption,global authentication th ti ti allows ll userst tobe b identified id tifi dthrough th hthe th useof fbiometrics, bi t i x509 509 certificates,tokendevices,andtheOracleInternetDirectory.Formoreinformationon advancedauthenticationmethodsrefertotheOracleEnterpriseIdentityManagement course.

OracleDatabase10g:Administration WorkshopI7151

DefaultandTemporaryTablespacesandLocking Adefaulttablespaceisthetablespacewhereobjectsarecreatedifatablespaceisnot specifiedinthecreationoftheobject.Ifyoudonotchooseadefaulttablespace,thenthe systemdefineddefaultpermanenttablespaceisused. Thetemporarytablespaceisthetablespacewhereanysortingactionhappens.Thereare severalwaysthatasortcantakeplace,forexamplewhencreatinganindexorusingan ORDER BY clauseonaSELECT statement.Ifyoudonotspecifyone,thensystem definedtemporarytablespaceisused. Whenauseriscreated,thatusercanhaveastatusoflockedorunlocked.Ifauseris locked thatmeansthatnoonecanloginasthisuser. locked, user Newusers usersaccountsareunlocked bydefault. Note: Itispossibletodefineadefaultandtemporarytablespaceatthedatabaselevel.If youdefinethematthedatabaselevel,thenanyusernotassignedaspecifictablespace fordefaultandtemporarywhencreated,isassignedthedatabasedefaultandtemporary tablespaces.

OracleDatabase10g:Administration WorkshopI7152

DatabaseUsersandSchemas Aschemaisthecollectionofdatabaseobjectsownedbyadatabaseuser.Aschemahas thesamenameastheuserthatownsit.Schemaobjectsincludestructuressuchas tables,views,indexes,andJavaandPL/SQLstoredcode.Thereisnorelationshipbetween atablespaceandaschema.Objectsinthesameschemacanbeindifferenttablespaces, andatablespacecanholdobjectsfromdifferentschemas.Whenadatabaseuseris created,acorrespondingschemawiththesamenameiscreatedforthatuser.Ausercan beassociatedonlywithaschemaofthesamename,andthereforeusernameand schemaareoftenusedinterchangeably. Schemaobjectsthatoccupyspacewithinthedatabase(suchastablesandindexes)are createdintheusersdefaulttablespaceunlessspecificallyplacedsomewhereelse. Schemaownershavefullcontrolovertheirownschemaobjectsandcangrantpermission tootheruserstousethoseobjects. Someuseraccountsarecreatedspecificallytoprovideaschemaandarentintendedto allowuserstologintothedatabase.Theseaccountsshouldbelocked,whichmeansthat noonecanlogintotheaccount.Tolockanaccount,selectLockedinthestatussectionof theCreateorEditUserpage.

OracleDatabase10g:Administration WorkshopI7153

ChecklistforCreatingUsers Tocreateauser,theadministratormustassignaprofile,chooseanauthentication technique,andassigntablespaces.Bydefaultawhenauseriscreatedtheyarenotgiven anyprivileges,whichmeanstheywillnotbeabletodoanyactionsinthedatabase. DatabaseControlautomaticallygrantsafewprivilegeswhichallowstheusertoconnect tothedatabaseandcreatesomeobjectsinthedatabase.Howeveriftheuserdoesnt havequotainanytablespace,theuserwillstillbeunabletocreateobjects.

OracleDatabase10g:Administration WorkshopI7154

Privileges AprivilegeisarighttoexecuteaparticulartypeofSQLstatementortoaccessanother usersobject.Oracleallowsveryfinegrainedcontroloverwhatuserscanorcannotdo withinthedatabase.Privilegesaredividedintotwocategories: Systemprivileges.Eachsystemprivilegeallowsausertoperformaparticular databaseoperationorclassofdatabaseoperations;forexample,theprivilegeto createtablespacesisasystemprivilege.Systemprivilegescanbegrantedbythe administratororbysomeonewhoexplicitlygivespermissiontoadministerthe privilege.Thereareover100distinctsystemprivileges. Objectprivileges. privileges Objectprivilegesallowausertoperformaparticularactionona specificobject,suchasatable,view,sequence,procedure,function,orpackage. Withoutspecificpermission,userscanaccessonlytheirownobjects.Object privilegescanbegrantedbytheownerofanobject,bytheadministrator,orby someonewhowasexplicitlygivenpermissiontograntprivilegesontheobject.

OracleDatabase10g:Administration WorkshopI7155

SystemPrivileges Tograntsystemprivileges,clicktheSystemsPrivilegeslink,selectappropriateprivileges fromthelistofavailableprivileges,andmovethemtotheSelectedSystemPrivilegeslist boxbyclickingtheMovearrow. GrantingaprivilegewiththeANY clausemeanstheprivilegecrossesschemalines.For example,theCREATE TABLE privilegeallowstheusertocreateatable,butonlywithin theirownschema.TheSELECT ANY TABLE privilegeallowsausertoselectfrom tablesownedbyotherusers. SelectingtheAdminOptioncheckboxallowsthisusertoadministertheprivilegeand grantthesystemprivilegetootherusers. users Carefullyconsidersecurityrequirementsbeforegrantingsystempermissions.Some systemprivilegesareusuallygrantedonlytoadministrators: RESTRICTED SESSION:Thisprivilegeallowstheusertologinevenifthe databasehasbeenopenedinrestrictedmode.

OracleDatabase10g:Administration WorkshopI7156

SystemPrivileges(continued) SYSDBA andSYSOPER:Theseprivilegesallowtheusertoshutdown,startup, performrecovery,andotheradministrativetasksinthedatabase. DROP ANY object:TheDROP ANY privilegeallowsuserstodeleteobjects theydonotown. CREATE,MANAGE,DROP,ALTER TABLESPACE:Nonadministratorsshouldnot usuallybeabletocontroltablespaces. CREATE ANY DIRECTORY:Oracleallowsdeveloperstocallexternalcode(for example,aClibrary)fromwithinPL/SQL.Asasecuritymeasure,theoperating systemdirectorywherethecoderesidesmustbelinkedtoavirtualOracle di directory object. bj With Wi hthe h CREATE ANY DIRECTORY privilege, i il ausercan potentiallycallinsecurecodeobjects. EXEMPT ACCESS POLICY:Thisprivilegeallowsausertobypasssecurity functionsplacedontablesorviews. GRANT ANY OBJECT PRIVILEGE:Thisprivilegeallowsuserstograntobject permissionsonobjectstheydonotown. ALTER DATABASE andALTER SYSTEM:Nonadministratorsshouldnotusually y beallowedtochangethedatabaseorinstance.

OracleDatabase10g:Administration WorkshopI7157

ObjectPrivileges Tograntobjectprivileges,clicktheObjectPrivilegeslink,selectthetypeofobjectyou wanttograntprivilegeson,andclicktheAddbutton.Choosetheobjectsyouwantto grantprivilegesonbyeitherenteringintheusername.objectname orbyselectingthem fromthelist. Next,selecttheappropriateprivilegesfromtheAvailablePrivilegeslistboxandclickthe Movebutton. SelecttheGrantcheckboxfromthelistofobjectprivilegestoallowthisusertogrant otherusersthesameaccess.

OracleDatabase10g:Administration WorkshopI7158

AssigningQuotatoUsers Quotaisaspaceallowanceinagiventablespace.Bydefaultauserhasnoquotaonanyof thetablespaces.Youhavethreeoptionsforprovidingauserquotaonatablespace. Unlimited:Thisallowstheusertouseasmuchspaceasisavailableinthe tablespace. Value:Thisisanumberofkilobytesormegabytesthattheusercanuse.This doesn'tguaranteethatthespaceissetasidefortheuser.Thisvaluecanbelarger orsmallerthanthecurrentspaceavailableinthetablespace. UNLIMITED TABLESPACE systemprivilege:Thissystemprivilegeoverridesall individualtablespacequotasandgivestheuserunlimitedquotaonall tablespaces,includingSYSTEM andSYSAUX.Thisprivilegeshouldbegranted withcaution. YoushouldnotgivequotatousersontheSYSTEM orSYSAUX tablespace.Typically,only theusersSYS andSYSTEM shouldbeabletocreateobjectsintheSYSTEM orSYSAUX tablespace. Usersdonotneedquotaontheirassignedtemporarytablespacesoranyundo tablespaces.

OracleDatabase10g:Administration WorkshopI7159

AssigningRolestoUsers Aroleisasetofprivilegesthatcanbegrantedtousersortootherroles.Youcanuseroles toadministerdatabaseprivileges.Youcanaddprivilegestoaroleandthengranttherole toauser.Theusercanthenenabletheroleandexercisetheprivilegesgrantedbythe role.Arolecontainsallprivilegesgrantedtothatroleandallprivilegesofotherroles grantedtoit. Bydefault,EnterpriseManagerautomaticallygrantstheconnectroletonewusers.This allowsuserstoconnecttothedatabaseandcreatedatabaseobjectsintheirownschema.

OracleDatabase10g:Administration WorkshopI7160

Roles Inmostsystemsitistootimeconsumingtograntnecessaryprivilegestoeachuser individually,andthereistoogreatachanceoferror.Oracleprovidesforeasyand controlledprivilegemanagementthroughroles. roles Rolesarenamedgroupsofrelated privilegesthataregrantedtousersortootherroles.Theyaredesignedtoeasethe administrationofprivilegesinthedatabase,andhenceimprovesecurity. RoleCharacteristics Privilegesaregrantedtoandrevokedfromrolesasiftherolewereauser. Rolescanbegrantedtoandrevokedfromusersorotherrolesasiftheywere systemprivileges. Arolecanconsistofbothsystemandobjectprivileges. privileges Arolecanbeenabledordisabledforeachuserwhoisgrantedtherole. Arolecanrequireapasswordtobeenabled. Rolesarenotownedbyanyone;andtheyarenotinanyschema. Intheexampleabove,theHR_CLERK roleisgrantedSELECT andUPDATE privilegeson theemployees table.TheHR_MGR roleisgrantedtheDELETE andINSERTprivileges ontheemployees tableand theHR_CLERK role.ThemanagerisgrantedtheHR_MGR roleandcannowselect,delete,insert,andupdate p theemployees p y table.

OracleDatabase10g:Administration WorkshopI7161

BenefitsofRoles EasierPrivilegeManagement Userolestosimplifyprivilegemanagement.Ratherthangrantingthesamesetof privilegestoseveralusers,youcangranttheprivilegestoarole,andthengrantthatrole toeachuser. DynamicPrivilegeManagement Iftheprivilegesassociatedwitharolearemodified,alltheuserswhoaregrantedtherole acquirethemodifiedprivilegesautomaticallyandimmediately. SelectiveAvailabilityofPrivileges Rolescanbeenabledanddisabledtoturnprivilegesonandofftemporarily. temporarily Enablinga rolecanalsobeusedtoverifythatauserhasbeengrantedthatrole. GrantingThroughtheOperatingSystem Operatingsystemcommandsorutilitiescanbeusedtoassignrolestousersinthe database.

OracleDatabase10g:Administration WorkshopI7162

PredefinedRoles ThereareseveralrolesdefinedautomaticallyforOracledatabaseswhenyourun databasecreationscripts.CONNECT isgrantedautomaticallytoanyusercreatedwith EnterpriseManager.SELECT_CATALOG_ROLE isprovidedforaccessingdatadictionary viewsandpackages(thisroleisdeprecatedinfavoroftheSELECT_ANY_DICTIONARY systemprivilege).TheDBA roleincludesnearlyallprivilegesandshouldnotbegrantedto nonadministrators. FunctionalRoles Otherrolesthatauthorizeyoutoadministerspecialfunctionsarecreatedwhenthat functionalityisinstalled. installed Forexample example,XDBADMIN containstheprivilegesrequiredto administertheXMLdatabaseifthatfeatureisinstalled.The AQ_ADMINISTRATOR_ROLE providesprivilegestoadministeradvancedqueuing.The HS_ADMIN_ROLE includestheprivilegesneededtoadministerheterogeneousservices. Youshouldnotaltertheprivilegesgrantedtothesefunctionalroleswithoutthe assistanceofOracleSupportbecauseyoumayinadvertentlydisableneededfunctionality.

OracleDatabase10g:Administration WorkshopI7163

SecureRoles Rolesareusuallyenabledbydefault,whichmeansthatifaroleisgrantedtoauser,that usercanexercisetheprivilegesgiventothatrole.Itispossibleto: Makearolenondefault.Whentheroleisgrantedtoauser,cleartheDEFAULT checkbox.Nowtheusermustexplicitlyenabletherolebeforetherolesprivileges canbeexercised. Havearolerequireadditionalauthentication.Thedefaultauthenticationforarole isNONEbutitispossibletohavetherolerequireadditionalauthenticationbefore itcanbeset. CreatesecureapplicationrolesthatcanbeenabledonlybyexecutingaPL/SQL proceduresuccessfully.ThePL/SQLprocedurecancheckthingssuchastheusers networkaddress,whichprogramtheuserisrunning,timeofday,oranythingelse thatisneededtoproperlysecureagroupofpermissions.

OracleDatabase10g:Administration WorkshopI7164

OracleDatabase10g:Administration WorkshopI7165

OracleDatabase10g:Administration WorkshopI7166

Practice7:AdministeringUsers Background:YouneedtocreateauseraccountforJennyGoodman,thenewhuman resourcesdepartmentmanager.Therearealsotwonewclerksinthehumanresources department DavidHambyandRachelPandya. department, Pandya Allthreeofthemshouldbeabletologin tothedatabase,selectfromthehr.employees table,andupdaterecordsinthattable. Themanageralsoneedstobeabletoinsertanddeletenewemployeerecords.Ensure thatifthenewusersforgettologoutattheendoftheday,theywillautomaticallybe loggedoffafterfifteenminutes. Tasks: Createaprofilewithresourcelimitations Createroles l with happropriatepermissions Createusersandassignthemthecorrectroles 1.CreateaprofilenamedHRPROFILE thatlimitsidletimeto15minutes.Leave allotherfieldssettoDefault. 2.Createroleswithappropriatepermissions. a) )CreatearolenameHRCLERK withSELECT andUPDATE p permissions onthehr.employees table. b)CreatearolenameHRMANAGER withINSERT andDELETE permissionsonthehr.employees table.GranttheHRCLERK roleto theHRMANAGER role. 3.Createthreenewusers. a)CreateanaccountforDavidHamby,anewHRclerk. b)Create C t anaccount tfor f Rachel R h lPandya, P d another th newHRclerk. l k c)CreateanaccountforJennyGoodman,thenewHRmanager. 4.Testthenewusers. a)ConnecttothedatabaseasuserDHAMBY.Attempttoselectfromthe hr.employees table. b)Nowattempttodeletearecordfromthehr.employees table. c)ConnecttothedatabaseasJGOODMAN andattempttoselectandthen deletefromthehr.employees table. d)Rollbackthedeleteoperationbecausethiswasonlyatest. 5.Whenyoucreatedthenewusersyoudidnotselectadefaultortemporary tablespace.Whatdetermineswhichtablespacesthenewuserswilluse? 6.YoudidnotgranttheCREATE SESSION systemprivilegetoeitherofthe newusers,buttheycanallconnecttothedatabase.Why? 7 Createanewuseraccounttoowndatabaseobjectsforanewinventory 7. application.Theusernameshouldbeinventorywithapasswordofverysecure. Maketheusersdefaulttablespacetheinventorytablespace.Granttheuserthe connectandresourceroles. 8.Leaveoneofthenewusersconnectedtothedatabaseduringthenextlesson orattheendoftheday.Verifythattheuserisautomaticallyloggedoutafter fifteenminutes.

OracleDatabase10g:Administration WorkshopI7167

OracleDatabase10g:Administration WorkshopI8169

WhatIsaSchema? Aschemaisacollectionofdatabaseobjectsownedbyaparticularuser.Aschemahasthe samenameastheuserthatownstheschema.Schemaobjectsarethelogicalstructures thatdirectlyrefertothedatabasesdata.Schemaobjectsincludestructuressuchas tables,views,andindexes. Note: Thereisnorelationshipbetweenatablespaceandaschema.Objectsinthesame schemacanbeindifferenttablespaces,andatablespacecanholdobjectsfromdifferent schemas. YoucancreateandmanipulateschemaobjectsusingSQLorEnterpriseManager.When youuseEnterpriseManager Manager,theunderlyingSQLisgeneratedforyou. you

OracleDatabase10g:Administration WorkshopI8170

Schemas Whenyoucreatethedatabase,anumberofschemasarecreatedforyou.Twoof particularimportanceare: SYS schema:Allofthebasetablesandviewsthatconstitutethedatabase'sdata dictionaryarecreatedintheSYS schema.Thedatadictionaryisacollectionof tablesthatdescribetheOracledatabase.Thedatadictionaryiscreatedinthe SYSTEM tablespacewhenthedatabaseiscreatedandisupdatedbytheOracle databaseserverwhenadatadefinitionlanguage(DDL)statementisexecuted.The datadictionarycontainsinformationaboutusers,schemaobjects,andstorage structures. structures Youcanusethedatadictionaryasareadonlyreferencefor informationaboutthedatabase.WhenyouuseEnterpriseManageryouaccess thedatadictionarytablesthroughviews. ObjectsintheSYS schemashouldneverbemodifiedbyanyuser ordatabaseadministrator,andnooneshouldcreateanytablesintheschemaof userSYS. SYSTEM schema:Containsadditionaltablesandviewsthatstoreadministrative information,andinternaltablesandviewsusedbyvariousOracleoptionsand tools.YoushouldnotcreateanyadditionalobjectsintheSYSTEM schema.

OracleDatabase10g:Administration WorkshopI8171

Schemas(continued) DuringacompleteinstallationofanOracledatabase,thesampleschemasareinstalled automaticallywiththeseeddatabase.Thesampleschemasservethepurposeof providingacommonplatformforexamplesinOracledocumentationandcurriculum. curriculum Theyareasetofinterlinkedschemasaimedatprovidingalayeredapproachto complexityandincludethefollowing: HR:TheHumanResourcesschemaisasimpleschemaforintroducingbasictopics. AnextensiontothisschemasupportsOracleInternetDirectorydemonstrations. OE:TheOrderEntryschemaisfordealingwithmattersofintermediate complexity.AmultitudeofdatatypesisavailableintheOE schema.TheOC ( l Catalog) (Online l )subschema b h isacollection ll of fobject b relational l ldatabase d b objects b builtinsidetheOE schema. PM:TheProductMediaschemaisdedicatedtomultimediadatatypes. QS:TheQueuedShippingschemacontainsasetofschemasthatareusedto demonstrateOracleAdvancedQueuingcapabilities. SH:TheSalesHistoryschemaisdesignedtoallowdemonstrationswithlarger amountsofdata.Anextensiontothisschemap providessupport pp foradvanced analyticprocessing.

OracleDatabase10g:Administration WorkshopI8172

AccessingSchemaObjects YoucanquicklyaccessmanytypesofschemaobjectsfromtheSchemaregionofthe DatabaseAdministrationpage. Afterclickingoneofthelinks,theResultspageisdisplayed.IntheSearchregionofthe pageyoucanenteraschemanameandobjectnametosearchforaspecificobject.In addition,youcansearchforothertypesofobjectsfromtheSearchregionbyselecting theobjecttypefromthedropdownmenu.Thedropdownmenuincludesadditional objecttypesthatarenotshownaslinksontheDatabaseAdministrationpage.

OracleDatabase10g:Administration WorkshopI8173

NamingDatabaseObjects Whenyounameanobjectinthedatabaseyouhavetheoptionofenclosingnamesin doublequotationmarks(").Ifyoudothisthenyoucanbreakseveralofthenamingrules mentionedintheslide.Howeverthisisnotrecommended,becauseifyounameanobject thiswayyoumustalwaysrefertoitwiththequotesaroundthename.Forexample,ifyou nameatable"LocalTemp"youmustdothefollowing: SQL>select*from"LocalTemp"; TEMP_DATELO_TEMPHI_TEMP 01DEC033041 Ifyoumistypethecaseyouwillget: SQL>select*from"localtemp"; select*from"localtemp" * ERRORatline1: ORA00942:tableorviewdoesnotexist Nonquotednamesarestoredinuppercaseandarenotcasesensitive.WhenaSQL statementisprocessed,nonquotednamesareconvertedtoalluppercase.

OracleDatabase10g:Administration WorkshopI8174

NamingDatabaseObjects(continued) Nonquotedidentifierscancontainonlyalphanumericcharactersfromyourdatabase charactersetandtheunderscore(_),thedollarsign($),andthepoundsign(#).Database linkscanalsocontainperiods(.)andtheatsign(@).Youarestronglydiscouragedfrom using$and#innonquotedidentifiers. Quotedidentifierscancontainanycharactersandpunctuationsmarksaswellasspaces. However,neitherquotednornonquotedidentifierscancontaindoublequotationmarks.

OracleDatabase10g:Administration WorkshopI8175

SchemaObjectNamespaces TheOracledatabaseusesnamespacestoresolveschemaobjectreferences.Whenyou refertoanobjectinaSQLstatement,OracleconsidersthecontextoftheSQLstatement andlocatestheobjectintheappropriatenamespace.Afterlocatingtheobject,Oracle performstheoperationspecifiedbythestatementontheobject.Ifthenamedobject cannotbefoundintheappropriatenamespace,thenOraclereturnsanerror. Becausetablesandviewsareinthesamenamespace,atableandaviewinthesame schemacannothavethesamename.However,tablesandindexesareindifferent namespaces.Therefore,atableandanindexinthesameschemacanhavethesame name. name Eachschemainthedatabasehasitsownnamespacesfortheobjectsitcontains.This means,forexample,thattwotablesindifferentschemasareindifferentnamespacesand canhavethesamename.

OracleDatabase10g:Administration WorkshopI8176

SpecifyingDataTypesinTables Whenyoucreateatable,youmustspecifyadatatypeforeachofitscolumns.Whenyou createaprocedureorfunction,youmustspecifyadatatypeforeachofitsarguments. Thesedatatypesdefinethedomainofvaluesthateachcolumncancontainoreach argumentcanhave. OracleDatabasebuiltindatatypesincludethefollowing: CHAR:Fixedlengthcharacterdataoflengthsizebytes.Maximumsizeis2000 bytes.Defaultandminimumsizeis1byte. VARCHAR2:Variablelengthcharacterstringhavingmaximumlengthsizebytesor characters Maximumsizeis4000bytes. characters. bytes YoumustspecifysizeforVARCHAR2. DATE:ValiddaterangefromJanuary1,4712BCtoDecember31,9999AD;also storesthetimedowntothesecond. NUMBER:Numberhavingprecisionp andscales.Theprecisioncanrangefrom1 to38.Thescalecanrangefrom84to127. RefertotheOracleDatabaseSQLReferenceforacompletelistofbuiltindatatypesand userdefinedtypes.

OracleDatabase10g:Administration WorkshopI8177

OtherDataTypes FLOAT(p):ThisisanANSIdatatype.TheFLOAT datatypeisafloatingpoint numberwithabinaryprecision p.Thedefaultprecisionforthisdatatypeis126 binary,or38decimal. INTEGER:ThisisequivalenttoNUMBER(p,0). NCHAR(length):TheNCHAR datatypeisaUnicodeonlydatatype.Whenyou createatablewithanNCHAR column,youdefinethecolumnlengthincharacters. Youdefinethenationalcharactersetwhenyoucreateyourdatabase.The maximumlengthofacolumnisdeterminedbythenationalcharacterset definition WidthspecificationsofcharacterdatatypeNCHAR refertothenumber definition. ofcharacters.Themaximumcolumnsizeallowedis2000bytes.Ifyouinserta valuethatisshorterthanthecolumnlength,thenOracleblankpadsthevalueto columnlength.YoucannotinsertaCHAR valueintoanNCHAR column,norcan youinsertanNCHAR valueintoaCHAR column. NVARCHAR2(length):TheNVARCHAR2 datatypeisaUnicodeonlydatatype. ItislikeNCHAR expectthatitsmaximumlengthis4000bytesanditisnotblank paddedtothelengthspecified.

OracleDatabase10g:Administration WorkshopI8178

OtherDataTypes(continued) LONG:Characterdataofvariablelengthupto2gigabytes,or231 1bytes. LONG RAW:Rawbinarydataofvariablelengthupto2gigabytes. RAW(size):Rawbinarydataoflengthsizebytes.Maximumsizeis2000bytes. YoumustspecifysizeforaRAWvalue. ROWID:Base64stringrepresentingtheuniqueaddressofarowinitstable.This datatypeisprimarilyforvaluesreturnedbytheROWID pseudocolumn. UROWID:Base64stringrepresentingthelogicaladdressofarowofanindex organizedtable.TheoptionalsizeisthesizeofacolumnoftypeUROWID.The maximumsizeanddefaultis4000bytes. BLOB:Abinary ylarge g object. j CLOB:Acharacterlargeobjectcontainingsinglebyteormultibytecharacters. Bothfixedwidthandvariablewidthcharactersetsaresupported,andbothuse theCHAR databasecharacterset. NCLOB:AcharacterlargeobjectcontainingUnicodecharacters.Bothfixedwidth andvariablewidthcharactersetsaresupported,andbothusetheNCHAR databasecharacterset.Storesnationalcharactersetdata. Note: ThemaximumsizeforallLOBdatatypes(BLOB,CLOB and NCLOB)is:(4 gigabytes - 1) * (the value of CHUNK).A CHUNKisanoptionalattributewhichyoucansetwhendefiningaLOB.The CHUNKspecifiesthenumberofbytestobeallocatedforLOB manipulation.Ifsizeisnotamultipleofthedatabaseblocksize,thenthe databaseroundsupinbytestothenextmultiple.Forexample,ifthe databaseblocksizeis2048andCHUNKsizeis2050,thenthedatabase allocates4096bytes(2blocks).Themaximumvalueis32768(32K),which isthelargestOracleDatabaseblocksizeallowed. allowed ThedefaultCHUNKsizeis oneOracleDatabaseblock. BFILE:Containsalocatortoalargebinaryfilestoredoutsidethedatabase. EnablesbytestreamI/OaccesstoexternalLOBsresidingonthedatabaseserver. Maximumsizeis4gigabytes. TIMESTAMP(fractional_seconds_precision):Year,month,andday valuesofdate,aswellashour,minute,andsecondvaluesoftime,where fractional seconds precision isthenumberofdigitsinthefractional fractional_seconds_precision partoftheSECOND datetimefield(asinfractionsofasecond).Acceptedvalues offractional_seconds_precision are0to9.Thedefaultis6.

OracleDatabase10g:Administration WorkshopI8179

CreatingandModifyingTables TablesarethebasicunitofdatastorageinanOracledatabase.Theyholdalluser accessibledata.Eachtablehascolumnsandrows. CreatingaTable YoucancreateatableusingEnterpriseManagerasfollows: 1. ClickTablesintheSchemaregionoftheAdministrationpage. TheTablespageappears. 2 2. Ifyouknowtheschemaname name,enterallorpartofitinthe SchemafieldintheSearchregion.Ifyoudonotknowtheschemaname, clicktheflashlighticonnexttotheSchemafield.TheSearchandSelect: Schemawindowappears.Youcanpagethroughtheschemanamesand selecttheoneyouarelookingfor. 3. ClickCreate.TheCreateTable:TableOrganizationpage appears. 4. AcceptthedefaultofStandard,HeapOrganizedbyclicking Continue.TheCreateTablepageappears. 5. EnterthetablenameintheNamefield. 6. EntertheschemanameintheSchemafieldorclickthe flashlighticontoinvokethesearchfunction.

OracleDatabase10g:Administration WorkshopI8180

CreatingandModifyingTables (continued) 7. EnterthetablespacenameintheTablespacefieldorclickthe flashlighticontoinvokethesearchfunction. 8 8. IntheColumnssection, section enterthecolumnnameanddatatypes. types 9.ClickOK.Anupdatemessageappearsindicatingthetablehasbeensuccessfully created. ModifyingaTable YoucanmodifyatableusingEnterpriseManagerasdescribedinthefollowingsteps.In thisexample,anadditionalcolumnisaddedtoatable. 1. IntheTablespage,selectthetableintheresultslistandclickEdit. 2. Inthe h Edit d Table bl page,click l kthe h Add dd5Table bl Columns l b button.An editablecolumnslistappears. 3. Enterthenewcolumnname,datatype,andsize.ClickApply. 4. Anupdatemessageappearsindicatingthatthetablehasbeen modifiedsuccessfully.

OracleDatabase10g:Administration WorkshopI8181

UnderstandingDataIntegrity Youcanusethefollowingintegrityconstraintstoimposerestrictionsontheinputof columnvalues: NOT NULL:Bydefault,allcolumnsinatableallownullvalues.Nullmeansthe absenceofavalue.ANOT NULL constraintrequiresthatacolumnofatable containnonullvalues.Forexample,youcandefineaNOT NULL constraintto requirethatavaluebeinputinthelast_name columnforeveryrowofthe employees table. UNIQUE Key:AUNIQUE keyintegrityconstraintrequiresthateveryvalueina columnorsetofcolumns(key)beuniquethatis, is notworowsofatablehave duplicatevaluesinaspecifiedcolumnorsetofcolumns.Forexample,aUNIQUE keyconstraintisdefinedonthedepartment_name columnofthe departments tabletodisallowrowswithduplicatedepartmentnames. PRIMARY KEY:EachtableinthedatabasecanhaveatmostonePRIMARY KEY constraint.Thevaluesinthegroupofoneormorecolumnssubjecttothis constraintconstitutetheuniqueidentifieroftherow.Ineffect,eachrowisnamed byitsprimarykeyvalues.

OracleDatabase10g:Administration WorkshopI8182

UnderstandingDataIntegrity(continued) TheOracleimplementationofthePRIMARY KEY integrity constraintguaranteesthatbothofthefollowingaretrue: Notworowsofatablehaveduplicatevaluesinthespecifiedcolumnorset ofcolumns. Theprimarykeycolumnsdonotallownulls.Thatis,avaluemustexistfor theprimarykeycolumnsineachrow. OracleenforcesallPRIMARY KEY constraintsusingindexes.The primarykeyconstraintcreatedforthedepartment_id columninthe departments tableisenforcedbytheimplicitcreationof: Auniqueindex d onthat h column l ANOT NULL constraintforthatcolumn Referentialintegrityconstraints:Differenttablesinarelationaldatabasecanbe relatedbycommoncolumns,andtherulesthatgoverntherelationshipofthe columnsmustbemaintained.Referentialintegrityrulesguaranteethatthese relationshipsarepreserved. Areferentialintegrity g yconstraintrequires q thatforeachrowofa table,thevalueintheforeignkeymatchesavalueinaparentkey. Asanexample,aforeignkeydefinedisdefinedonthe department_id columnoftheemployees table.Itguaranteesthatevery valueinthiscolumnmustmatchavalueintheprimarykeyofthedepartments table(alsothedepartment_id column).Therefore,noerroneousdepartment numberscanexistinthedepartment_id columnofthedepartments table. A th type Another t of freferential f ti lintegrity i t it constraint t i tis i called ll daself lf referentialintegrityconstraint.Thistypeofforeignkeyreferencesaparentkeyin thesametable. Checkconstraints:ACHECK integrityconstraintonacolumnorsetofcolumns requiresthataspecifiedconditionbetrueorunknownforeveryrowofthetable. IfaDMLstatementresultsintheconditionoftheCHECK constraintevaluatingto false,thenthestatementisrolledback.

OracleDatabase10g:Administration WorkshopI8183

DefiningConstraints Youcanaddaconstrainttoatableasfollows: 1.SelectthetableontheTablespageandclickEdit. 2.ClickConstraints.TheConstraintspageisdisplayedshowingallconstraintsthat havebeendefinedonthetable. 3.Selectthetypeofconstraintyouwanttoaddfromthedropdownmenuand clickAdd. 4.Entertheappropriateinformationforthetypeofconstraintyouaredefining. ClickOK.

OracleDatabase10g:Administration WorkshopI8184

ViewingtheAttributesofaTable YoucanuseEnterpriseManagertoviewtheattributesofatableasfollows: 1. ClicktheTableslinkintheSchemasectionoftheDatabase Administrationpage. 2. SelectatablefromtheResultslistandclicktheViewbuttontosee theattributesofthetable.

OracleDatabase10g:Administration WorkshopI8185

ViewingtheContentsofaTable YoucaneasilyviewtherowsinatableusingEnterpriseManagerasfollows: 1.SelectthetableontheTablespage. 2.SelectViewDatafromtheActionsmenuandclickGo. TheViewDataForTablepageappears.TherowdataforthetableisshownintheResults section.TheQueryboxdisplaystheSQLquerythatwasexecutedtoproducetheresults. Onthispageyoucanclickanycolumnnameandsortthedatainthecolumnineither ascendingordescendingorder.Ifyouwanttochangethequery,clicktheRefineQuery button.OntheRefineQueryforTablepage,youcanselectthecolumnsthatyouwantto displayandspecifyaWHERE clausefortheSQLstatementtolimittheresults. results RefertotheOracleDatabaseSQLReferenceformoreinformationonWHERE clausesin SQLstatements.

OracleDatabase10g:Administration WorkshopI8186

ActionswithTables Youcanselectatableandthenperformactionsonthattable. CreateLike:Withthisyoucancreateatablethathasthesamestructureasthe selectedtable.Youmustchangethetablenameandtheconstraintnames.You canalsoaddordeletecolumnsandmakeotherchangestothetablestructure. Whencreated,thetablewillbeempty. CreateIndex:Usethisoptiontocreateindexesonatable.Indexesshouldbe createdonlyoncolumnsthatareusedinWHERE conditionsofselectandDML statements. CreateSynonym:Asynonymisanameusedinplaceofthefulltablename. name A synonymcanbeprivateorpublic. CreateTrigger:AtableleveltriggerisaPL/SQLblockthatisexecutedbecauseof aneventhappeningonthetable.Forexampleyoumaywanttokeepacopyof datainanothertableasitgetsdeletedfromtheemployees table.Youwould thencreateabeforedeletetriggerthatwouldinsertthedataabouttobe deletedfromtheemployees tableintoanothertable.Formoreinformation abouttriggersrefertotheApplicationDeveloper'sGuide Fundamentals andthe PL/SQLUsersGuideandReference.

OracleDatabase10g:Administration WorkshopI8187

ActionswithTables (continued) GatherStatistics:TheGatherStatisticsWizardguidesyouthroughtheprocessof generatingandmodifyingoptimizerstatistics.Thestatisticsarestoredinthedata dictionaryandusedbythecostbasedoptimizer. optimizer Uptodatestatisticscangreatly improvetheperformanceofSQLqueriesagainstyourobjects.Oraclesuggests thatyouuseautomatedtaskstogeneratestatisticsregularlywithinmaintenance windows. GenerateDDL:ThisgeneratestheDDLcommandtocreatethetableselected.This canthenbecopypastedintoatextfileforuseasascriptorfordocumentation purposes. GrantPrivileges: l Byd default f l when h atable bl iscreated donly l the h ownercando d anythingwithit.Theownermustgrantoutprivilegestootheruserstobeableto performDMLandsomeDDLonthetable. Reorganize:YoucanusetheReorgWizardtorebuildfragmentedindexesortables, moveobjectstoadifferenttablespace,oroptimizethestorageattributesof specifiedobjects. RunSegment g Advisor:Thesegment g advisordetermineswhetherobjects j have unusedspacethatcanbereleased,takingestimatedfuturespacerequirements intoconsideration.Theestimatedfuturespacecalculationisbasedonhistorical trends. ShrinkSegment:Theshrinkoperationcompactsfragmentedspaceand,optionally, freesthespace. ShowDependencies:Thisshowobjectsthatthistabledependsonorobjectsthat d depend donthis thi table. t bl ViewData:Runsaselectstatementonthetable,yourefinetheselectstatement. Youcannotchangethedata. FlashbackTable:TheFlashbackTablesfacilityallowsyoutorecoveratabletoa previouspointintime.Itprovidesamethodofrecoveringatablethathasbeen accidentallymodifiedordeletedbyauserorapplication.Youcanrestoretable dataalong gwithallitsassociatedattributes,suchasindexes,triggers, gg andsoon. Thisisdonewhilethedatabaseisonlinebyrollingbackonlythechangestothe giventables.Youcanrevertatableanditscontentstoacertaintimeoruser specifiedsystemchangenumber(SCN).Useflashbacktablewithflashbackquery androwversionstofindatimetowhichthetableshouldberestored.Formore informationaboutusingtheFlashbackTablesfeature,seetheOracleDatabase AdministratorsGuide. FlashbackbyRowVersions:FlashbackVersionsQueryallowsyoutoquery metadataandhistoricaldatawithinatimeinterval.Youcanperformquerieson thetableasofacertainwallclocktime.Selectthefilterconditionsthatallowyou toretrievethedifferentversionsofrowsinatablethatexistedinaspecifictime interval.

OracleDatabase10g:Administration WorkshopI8188

CreatingIndexes Indexesareoptionalstructuresassociatedwithtables.Theycanbecreatedtoincrease theperformanceofdataretrieval.AnOracleindexprovidesadirectaccesspathtotable data. Indexescanbecreatedononeormorecolumnsofatable.Afteranindexiscreated,itis automaticallymaintainedandusedbytheOracleserver.Updatestoatablesdata,such asaddingnewrows,updatingrows,ordeletingrows,areautomaticallypropagatedtoall relevantindexeswithcompletetransparencytotheusermakingthechange. YoucanclicktheIndexeslinkundertheSchemaheadingoftheAdministrationpageto viewtheIndexespage. page Youcanviewindexattributes, attributes orusetheActionsmenutoView Dependenciesforanindex. Indexescanbecreatedexplicitly,orimplicitlythroughconstraintsthatareplacedona table.

OracleDatabase10g:Administration WorkshopI8189

WhatIsaView? Viewsarecustomizedrepresentationsofdatainoneormoretablesorotherviews.They canbethoughtofasstoredqueries.Viewsdonotactuallycontaindata,butinsteadthey derivetheirdatafromthetablesuponwhichtheyarebased.Thesetablesarereferredto asthebasetablesoftheview.

OracleDatabase10g:Administration WorkshopI8190

CreatingViews Liketables,viewscanbequeried,updated,insertedinto,anddeletedfrom,withsome restrictions.Alloperationsperformedonaviewactuallyaffectthebasetablesofthe view.Viewsprovideanadditionallevelofsecuritybyrestrictingaccesstoa predeterminedsetofrowsandcolumnsofatable.Theyalsohidedatacomplexityand storecomplexqueries. YoucanclicktheViewslinkundertheSchemaheadingontheAdministrationpagetosee theviewsdefinedinthedatabase.

OracleDatabase10g:Administration WorkshopI8191

WhatIsaSequence? Asequenceisadatabaseobjectfromwhichmultipleuserscangenerateuniqueintegers. Yougenerallyusesequencestogenerateprimarykeyvalues. Name:Usethenamingrulescoveredearliertonameasequence. Schema:Thisistheownerofthesequence. Type:Asequencecaneitherbeascendingordescending MaximumValue:Specifythemaximumvaluethesequencecangenerate.This integervaluecanhave28orfewerdigits.ItmustbegreaterthanMinimumValue andInitial.UsingUnlimitedindicateamaximumvalueof1027 foranascending sequenceor 1foradescendingsequence. sequence ThedefaultisUnlimited. Unlimited MinimumValue:Specifytheminimumvalueofthesequence.Thisintegervalue canhave28orfewerdigits.ItmustbelessthenorequaltoInitialandlessthen MaximumValue.UsingUnlimitedindicatesaminimumvalueof1foranascending sequenceor1026 foradescendingsequence.ThedefaultisUnlimited.

OracleDatabase10g:Administration WorkshopI8192

WhatIsaSequence? (continued) Interval:Specifytheintervalbetweensequencenumbers.Thisintegervaluecan beanypositiveornegativeinteger,butitcannotbezero.Thisvaluecanhave28or fewerdigits. digits Thedefaultisone. one Initial:Specifythefirstsequencenumbertobegenerated.Usethisclausetostart anascendingsequenceatavaluegreaterthanitsminimumortostarta descendingsequenceatavaluelessthanitsmaximum. CycleValues:Afteranascendingsequencereachesitsmaximumvalue,it generatesitsminimumvalue.Afteradescendingsequencereachesitsminimum, itgeneratesitsmaximumvalue.Ifyoudonotchoosethisoption,anerrorwillbe returned dif fyouattempttoretrieveavalue l after f the h sequencehas h been b exhausted. OrderValues:Thisguaranteesthatsequencenumbersaregeneratedinorderof request.Thisclauseisusefulifyouareusingthesequencenumbersas timestamps.Guaranteeingorderisusuallynotimportantforsequencesusedto generateprimarykeys.Thisoptionisnecessaryonlytoguaranteeordered generationify g youareusing gOraclewithRealApplication pp Clusters. CacheOptions:SpecifyhowmanyvaluesofthesequenceOraclepreallocatesand keepsinmemoryforfasteraccess.Thisintegervaluecanhave28orfewerdigits. Theminimumvalueforthisparameteris2.Forsequencesthatcycle,thisvalue mustbelessthanthenumberofvaluesinthecycle.Youcannotcachemore valuesthanwillfitinagivencycleofsequencenumbers.

OracleDatabase10g:Administration WorkshopI8193

UsingaSequence YourefertosequencevaluesinSQLstatementswiththefollowingpseudocolumns: CURRVAL:Returnsthecurrentvalueofasequence NEXTVAL:Incrementsthesequenceandreturnsthenextvalue YoumustqualifyCURRVAL andNEXTVAL withthenameofthesequence: sequence.CURRVAL sequence.NEXTVAL ThefirstreferencetoNEXTVAL returnstheinitialvalueofthesequence.Subsequent referencestoNEXTVAL incrementthesequencevaluebythedefinedincrementand returnthenewvalue. value AnyreferencetoCURRVAL alwaysreturnsthecurrentvalueofthe sequence,whichisthevaluereturnedbythelastreferencetoNEXTVAL.

OracleDatabase10g:Administration WorkshopI8194

OracleDatabase10g:Administration WorkshopI8195

OracleDatabase10g:Administration WorkshopI8196

Practice8:ManagingSchemaObjects Background: You need to create a schema objects for the new inventory application. Tasks: Createtablestostoredata Ensurereferentialintegritythroughtheuseofconstraints Createindexestoimproveaccesstodata Modifyexistingtables Createviewsthatsimplifyuseraccesstodata 1.IntheINVENTORYtablespace,createthePRODUCT_MASTERtableintheINVENTORY schema.Thespecificationsofthetableare: PRODUCT_ID number(5).Thisistheprimarykeyfield. PRODUCT_NAME varchar2(50) withaNotNullconstraint. CODE varchar2(20) withaNotNullconstraint. REORDER_THRESHOLD number(5) withacheckconstraintensuringthatthe numberis alwaysgreaterthanzero. COST number(5,2) number(5 2) PRICE number(5,2) 2.IntheINVENTORYtablespacecreatethePRODUCT_ON_HANDtableintheINVENTORY schema.Thespecificationsofthetableare: ON_HAND_ID number(5).Thisistheprimarykeyfield. PRODUCT_ID number(5).Thisfieldshouldhaveaforeignkeyconstraint linkingittothe product_idfieldintheproduct_mastertable. QUANTITY number(5) WAREHOUSE_CITY varchar2(30) 3.IntheINVENTORYtablespacecreatetheOBSOLETE_PRODUCTStableinthe INVENTORY schema.Thespecificationsofthetableare: PRODUCT ID number(5).Thisistheprimarykeyfield. PRODUCT_ID PRODUCT_NAME varchar2(50) withaNotNullconstraint. CODE varchar2(20) withaNotNullconstraint. COST number(5,2) PRICE number(5,2) 4.IntheINVENTORYtablespace,createanindexonthePRODUCT_NAMEcolumnofthe OBSOLETE_PRODUCTStableintheINVENTORYschema. 5.Inthe h INVENTORYtablespace, bl createanindex d onthe h PRODUCT_NAMEand dCODE columns ofthePRODUCT_MASTERtableintheINVENTORYschema. 6.IntheINVENTORYtablespace,createanindexthePRODUCT_IDandQUANTITYcolumn of thePRODUCT_ON_HANDtableintheINVENTORYschema. 7.Youreceiveanupdate p fortheinventory yapplication pp thatrequires q y youtoaddtwo columnstothe PRODUCT_MASTERtable.AddacolumnnamedPRIMARY_SOURCEofdatatype varchar2 withsize50.AddanothercolumnnamedSECONDARY_SOURCEofdatatypevarchar2 OracleDatabasewith 10g:Administration size50. WorkshopI8197

Practice8:ManagingSchemaObjects(continued) 8.Theupdatefortheinventoryapplicationalsorequiresyoutoaddacolumntothe PRODUCT_ON_HANDtable.AddacolumnnamedLAST_UPDATEofdatatypedate. 9 Theupdatefortheinventoryapplicationalsorequiresyoutoaddacolumntothe 9. OBSOLETE_PRODUCTStable.AddacolumnnamedOBSOLETEDofdatatypedate. 10.Youreceiveanotherupdatefortheinventoryapplication.Thisupdateinstructsyouto dropthe OBSOLETE_PRODUCTStableandaddacolumnOBSOLETEDtothe PRODUCT_MASTERtablewithdatatypedate. 11.Thesecondupdatetotheinventoryapplicationalsoinstructsyoutocreateaview named d WAREHOUSE_VWintheINVENTORYschemathattheshows(inorder): Thenameoftheproduct Theamountoftheproductonhand Thewarehousecityname.

OracleDatabase10g:Administration WorkshopI8198

OracleDatabase10g:Administration WorkshopI9201

ManipulatingDataThroughSQL ThebasicDMLstatementsarethewaydataismanipulatedinthedatabase. AlthoughthesestatementswerebrieflymentionedinthelessontitledDatabase Interfaces,inthislessontheywillbecoveredinmoredetail.

OracleDatabase10g:Administration WorkshopI9202

TheINSERT Command ThebasicINSERT statementcreatesonerowatatime.Usingwhatiscalledasubselect, youcancausetheinserttocopyrowsfromonetabletoanother.Thismethodisalso referredtoasanINSERT selectstatement.Theexampleontheslideisthefollowing INSERT command: insertintodept_80(select*fromemployees wheredepartment_id=80); Inthiscasethedept_80 tablehastheexactsamestructureastheemployees table.If thisisnotthecaseyoucannamethecolumnsineachtable.Thecolumnvalueswill matchintheorderasnamedintheINSERT andSELECT statements. statements Allthatisrequired isthatthedatatypesmatch.Forexample: insertintojust_names(first,last) (selectfirst_name,last_namefromemployees); Herethejust_names tablehasonlytwocolumnsthathavethesamedatatypeasthe first_name andlast_name columnsintheemployees table. Usingtheinsertselectmethodisawaytobulkloaddatafromoneormoretablesinto anothertable.

OracleDatabase10g:Administration WorkshopI9203

TheUPDATE Command TheUPDATE commandisusedtomodifyexistingrowsinatable.Thenumberorrows modifiedbytheupdatewilldependontheWHERE condition.IftheWHERE clauseis omitted,thenallrowswillbechanged.IfnorowssatisfytheWHERE condition,thenno rowswillbemodified.

OracleDatabase10g:Administration WorkshopI9204

TheDELETE Command TheDELETE commandisusedtoremoveexistingrowsfromatable.Thenumberor rowsmodifiedbythedeletedependsontheWHERE condition.IftheWHERE clauseis omitted,thenallrowswillberemoved.IfnorowssatisfytheWHERE conditionthenno rowswillberemoved.Noteintheexample,whennorowsaredeleteditisnotanerror; themessagereturnedonlystatesthatzerorowshavebeenremovedfromthetable.

OracleDatabase10g:Administration WorkshopI9205

TheCOMMIT andROLLBACK Commands BydefaulteachDMLcommandenteredisnotcommitted.Severaltools(including iSQL*Plus)haveoptionsthatcanbesettocommitoneachcommandoragroupof commands. BeforeaCOMMIT orROLLBACK isissued,thechangesareinapendingstate.Onlythe userwhomadethechangeisallowedtoseethechangeddata.Otheruserscanselectthe samedata,butwillseethedataasitwasbeforeanychangeismade.Otheruserscannot issueDMLonthesamedatathatanotheruserhaschanged. Bydefaultausertryingtomakeachangeonthesamerowasanotheruserwillwaituntil thefirstusereithercommitsorrollsbackthechange. change Thisiscontrolledautomaticallyby Oracleslockingmechanism.Becausethelockingmechanismisbuiltintotherowitself, thereisnowaythedatabasewillrunoutoflocks.

OracleDatabase10g:Administration WorkshopI9206

IntegrityConstraintsandDML AllintegrityconstraintsareenforcedwheneverDMLstatementsareexecuted. FOREIGN KEY columns INSERT andUPDATE:Thevaluemustexistintheparenttable. DELETE:Arowintheparenttablethathasatleastonerowstillreferringtoit cannotbedeleted. NOT NULL columns INSERT:Cannotinsertwithoutavalue UPDATE:CannotmodifythevaluetoNULL UNIQUE keycolumns: INSERT andUPDATE:Cannothavethesamevalueasanyothercolumninthe table,exceptfornull.Eachnullisconsideredunique,soallrowscouldhaveanull valueinacolumnwithaUNIQUE keyconstraint. PRIMARY KEY columns: ApplytherulesforUNIQUE keyandNOT NULL columns. CHECK columns: INSERT andUPDATE:Valuesmustmeettheconditionoftheconstraint.

OracleDatabase10g:Administration WorkshopI9207

DataPumpExport OraclesDataPumputilityenableshighspeedtransferofdatafromonedatabaseto another.Forexample,youmaywanttoexportatableanditsassociatedindexesfromone databaseandimportitintoanotherdatabase.FormoreinformationaboutDataPump seetheOracleDatabaseUtilitiesGuide. OnthemaintenancepageclickExporttoFilestouseDataPumptowritedataouttoa file. 1.Onthefirstpage,youselectwhatyouwanttoexport,andenterinthehost logincredentialsintheUsernameandPasswordfields: Database:Thisexportstheentiredatabase, database andisalsocalledafullexport. export Thefollowingsystemschemasarenotexportedaspartofafullexport becausethemetadatatheycontainisexportedaspartofotherobjectsin thedumpfileset:SYS,ORDSYS,ORDPLUGINS,CTXSYS,MDSYS, LBACSYS,andXDB.Thismoderequiresthatyouhavethe EXP_FULL_DATABASE role.

OracleDatabase10g:Administration WorkshopI9208

DataPumpExport(continued) Schemas:Thisexportsallobjectsofoneormoreschemas.Ifyoudonot havetheEXP_FULL_DATABASE role,thenyoucanspecifyonlyyour ownschema.Crossschemareferencesarenotexportedunlessthe referencedschemaisalsospecifiedinthelistofschemastobeexported. Tables:Intablemode,onlyaspecifiedsetoftables,partitions,andtheir dependentobjectsareunloaded.Youmusthavethe EXP_FULL_DATABASE roletospecifytablesthatarenotinyourown schema,andonlyoneschemacanbespecified.Notethattypedefinitions forcolumnsarenotexportedintablemode.Itisexpectedthatthetype d fi iti already definitions l d exist i tin i the th target t ti instance t at timport i ttime. ti Also, Al asin i schemaexports,crossschemareferencesarenotexported. 2.IfyouselectSchemasorTablesfortheexporttype,thenextpagewillallow youtoselectthesetofSchemasorTablesthatyouwanttoexport.ClickAddto selecttheSchemasorTablesyouwanttoexport. 3.TheOptionspageisthenextstep,ifyouselectedaDatabaseexportyouwill godirectly g ytothisp page g afterselecting gthetype yp ofexport. p TheMaximumNumber ofThreadsinExportJobisthedegreeofparallelismtobeused.Hereyoucansee andestimateofhowbigtheexportwillbe,selectblocksforaquickestimate,and statisticsforamorepreciseestimate.ClickEstimateDiskSpaceNowtoseethe results.Youalsocanspecifyinformationabouttheoptionallogfilehere.Click ShowAdvancedOptionsforthefollowing: Content:Youcanexportjustthemetadataorthedata,orboth.Youcan alsosetupaconditiontofilteroutbyobjectname. name Flashback:Getaconsistentexporttoaparticulartime. Query:GetonlydatathatmatchesaWHERE clausethatyouprovide. 4.ThenextpageisFiles.YouusetheFilespagetospecifythedirectorynameand filename,andthemaximumsizefortheexportfiles.The%Uisasubstitution variablethatbeginswith01forthefirstfileandthengoesto02,03,andsoon. Enoughdumpfilesarecreatedtoallowallprocessesspecifiedbythecurrent settingofthePARALLEL parametertobeactive.Forexample,ifexpa%U, expb%U,andexpc%U wereallspecifiedforajobhavingaparallelismof6,the initialdumpfilescreatedwouldbeexpa01.dmp,expb01.dmp, expc01.dmp,expa02.dmp,expb02.dmp,andexpc02.dmp. 5.ThenextpageistheSchedule.YouusetheSchedulepagetoschedulethe exportjob. 6 ThelastpageisReview. 6. Review YouusetheReviewpagetodisplaythePL/SQLcode fortheexportcommandgeneratedbytheselectionsyoumadeintheprevious pagesofthewizard.Youcannotchangethecodegenerated.Youcancopyoutfor creationofascriptfileifneeded.ClickSubmitJobtobegintheexportprocess. Afterthejobissubmitted,clickViewJobtomonitorthejobprogress.

OracleDatabase10g:Administration WorkshopI9209

DataPumpImport UseDataPumpImporttoloaddataextractedbyDataPumpExport.OntheMaintenance pageclickImportfromFilestouseDataPumpImporttoreadfileswrittenbyDataPump Exportbackintoadatabase. 1.Files:UsetheFilespagetodesignatethepathandnameoftheimportfileson thedatabaseserver.Thenyoumustselectoneofthreepossibleimportchoices whethertoimportentirefiles,specificschemas,orspecifictables.Youcanalso choosetogeneratealogfileandthenentercredentialsinthehostUsernameand HostPasswordfields. 2 SelectObjects:Thispageisdisplayedonlywhenyouchoosetheoptiononthe 2. Filespagetoselectspecificobjectstoimport.Usethispagetoselecttheusers youwanttoimportfromtheAvailableUserslistandmovethemtotheSelected Userslist.

OracleDatabase10g:Administration WorkshopI9210

DataPumpImport(continued) 3.ReMapping:Thispageisdisplayedonlyifyoupreviouslyselectedobjectsin theSelectObjectspage.Usethispagetodesignatewhethertoimporteachusers dataintothesameuser users sschema,ortoimportintodifferentuser users sschemaas designatedintheSourceUserandDestinationUserfields. 4.Options:UsetheOptionspagetosetoptionsfordatafilereuse,object creationerror,andunusableindexes. 5.Schedule:UsetheSchedulepagetoscheduletheimportprocedureasajobin theJobsystem. 6.Review:UsetheReviewpagetodisplaythePL/SQLcodefortheimport command dgenerated t dby b the th selections l ti youmade d in i the th previous i pagesof fthe th wizard.YoucaneditthePL/SQLcodemanuallyorclickImporttobegintheimport process. Afterthejobissubmitted,clickViewJobtomonitorthejobprogress.

OracleDatabase10g:Administration WorkshopI9211

DIRECTORY Objects BecauseDataPumpisserverbased(ratherthanclientbased),dumpfiles,logfiles,and SQLfilesareaccessedrelativetoserverbaseddirectorypaths.DataPumprequiresthat youspecifydirectorypathsasdirectoryobjects.Adirectoryobjectmapsanametoa directorypathonthefilesystem. UsetheCREATE DIRECTORY statementtocreateadirectoryobject,orclickCreate DirectoryObject.Adirectoryobjectspecifiesanaliasforadirectoryontheserversfile system.YoumusthaveCREATE ANY DIRECTORY systemprivilegestocreate directories. Whenyoucreateadirectory, directory youareautomaticallygrantedthereadandwriteobject privilegesonthedirectory,andyoucangranttheseprivilegestootherusersandroles. ToviewthedefinitionofdirectoryobjectusetheDBA_DIRECTORIES view. Note: Oracledoesnotverifythatthedirectoryyouspecifyactuallyexists.Therefore,take carethatyouspecifyavaliddirectoryinyouroperatingsystem.Inaddition,ifyour operatingsystemusescasesensitivepathnames,besureyouspecifythedirectoryinthe correctformat.(However,youneednotincludeatrailingslashattheendofthepath name).Rememberthattheoperatingsystemwillcontrolsecurityforfilesinthedirectory.

OracleDatabase10g:Administration WorkshopI9212

SQL*Loader SQL*LoaderloadsdatafromexternalfilesintotablesofanOracledatabase.Ithasa powerfuldataparsingenginethatputslittlelimitationontheformatofthedatainthe datafile.ThefilesusedbySQL*Loaderareasfollows: InputDataFiles: SQL*Loaderreadsdatafromoneormorefiles(oroperatingsystem equivalentsoffiles)specifiedinthecontrolfile.FromSQL*Loader'sperspective,thedata inthedatafileisorganizedasrecords.Aparticulardatafilecanbeinfixedrecordformat, variablerecordformat,orstreamrecordformat.Therecordformatcanbespecifiedinthe controlfilewiththeINFILE parameter.Ifnorecordformatisspecified,thedefaultis streamrecordformat format. ControlFile: ThecontrolfileisatextfilewritteninalanguagethatSQL*Loader understands.ThecontrolfiletellsSQL*Loaderwheretofindthedata,howtoparseand interpretthedata,wheretoinsertthedata,andmore.Althoughnotpreciselydefined,a controlfilecanbesaidtohavethreesections. Thefirstsectioncontainssessionwideinformation,forexample: Globaloptionssuchasbindsize,rows,recordstoskip,andsoon INFILE clausestospecifywheretheinputdataislocated Datatobeloaded

OracleDatabase10g:Administration WorkshopI9213

SQL*Loader(continued) ThesecondsectionconsistsofoneormoreINTO TABLE blocks.Eachofthese blockscontainsinformationaboutthetableintowhichthedataistobeloaded, suchasthetablenameandthecolumnsofthetable. Thethirdsectionisoptionaland,ifpresent,containsinputdata. LogFile: WhenSQL*Loaderbeginsexecution,itcreatesalogfile.Ifitcannotcreatealog file,executionterminates.Thelogfilecontainsadetailedsummaryoftheload,including adescriptionofanyerrorsthatoccurredduringtheload. BadFile: Thebadfilecontainsrecordsthatwererejected,eitherbySQL*Loaderorbythe Oracledatabase.DatafilerecordsarerejectedbySQL*Loaderwhentheinputformatis i lid Aft invalid. Afterad data t file fil record dis i accepted t dfor f processing i by b SQL*Loader, SQL*L d itis i sent t t tothe th Oracledatabaseforinsertionintoatableasarow.IftheOracledatabasedeterminesthat therowisvalid,thentherowisinsertedintothetable.Iftherowisdeterminedtobe invalid,thentherecordisrejectedandSQL*Loaderputsitinthebadfile. DiscardFile: Thisfileiscreatedonlywhenitisneeded,andonlyifyouhavespecifiedthat adiscardfileshouldbeenabled.Thediscardfilecontainsrecordsthatwerefilteredoutof theloadbecausethey ydidnotmatchany yrecordselectioncriteriaspecified p inthecontrol file. FormoreinformationonSQL*LoaderrefertotheOracleDatabaseUtilities documentation.

OracleDatabase10g:Administration WorkshopI9214

TheSQL*LoaderControlFile TheSQL*Loadercontrolfileisatextfilethatcontainsdatadefinitionlanguage(DDL) instructions.DDLisusedtocontrolthefollowingaspectsofaSQL*Loadersession: WhereSQL*Loaderfindsthedatatoload HowSQL*Loaderexpectsthatdatatobeformatted HowSQL*Loaderconfigures(memorymanagement,rejectingrecords,interrupted loadhandling,andsoon)asitloadsthedata HowSQL*Loadermanipulatesthedatabeingloaded

OracleDatabase10g:Administration WorkshopI9215

TheSQL*LoaderControlFile(continued) TheexamplebelowillustratesatypicalSQL*Loadercontrolfile. 1 -- This is a sample control file 2 LOAD DATA 3 INFILE SAMPLE.DAT 4 BADFILE sample.bad 5 DISCARDFILE sample.dsc 6 APPEND 7 INTO TABLE emp 8 WHEN (57) = . 9 TRAILING NULLCOLS 10 (hiredate SYSDATE, deptno POSITION(1:2) INTEGER EXTERNAL(3) NULLIF deptno=BLANKS, job POSITION(7:14) CHAR TERMINATED BY WHITESPACE NULLIF job=BLANKS job BLANKS "UPPER(:job)", mgr POSITION(28:31) INTEGER EXTERNAL TERMINATED BY WHITESPACE, NULLIF mgr=BLANKS, ename POSITION(34:41) CHAR TERMINATED BY WHITESPACE "UPPER(:ename)", empno POSITION(45) INTEGER EXTERNAL TERMINATED BY WHITESPACE, sal POSITION(51) CHAR TERMINATED BY WHITESPACE "TO_NUMBER(:sal,$99,999.99)", comm INTEGER EXTERNAL ENCLOSED BY ( AND % ":comm * 100" ) Samplecontrolfileexplanation,bylinenumbers: 1. Commentscanappearanywhereinthecommandsectionofthe file,buttheyshouldnotappearwithinthedata.Precedeanycommentwithtwo hyphens.Alltexttotherightofthedoublehyphenisignored,untiltheendofthe line. line 2. TheLOAD DATA statementtellsSQL*Loaderthatthisisthe beginningofanewdataload.Ifyouarecontinuingaloadthatwasbeen interruptedinprogress,thenusetheCONTINUE LOAD DATA statement. 3. TheINFILE keywordspecifiesthenameofadatafilecontaining datathatyouwanttoload.

OracleDatabase10g:Administration WorkshopI9216

TheSQL*LoaderControlFile(continued) 4. TheBADFILE keywordspecifiesthenameofafileintowhich rejectedrecordsareplaced. 5 5. TheDISCARDFILE keywordspecifiesthenameofafileinto whichdiscardedrecordsareplaced. 6. TheAPPEND keywordisoneoftheoptionsyoucanusewhen loadingdataintoatablethatisnotempty.Toloaddataintoatablethatisempty, youusetheINSERT keyword. 7. TheINTO TABLE keywordenablesyoutoidentifytables,fields, anddatatypes.Itdefinestherelationshipbetweenrecordsinthedatafileand tablesinthedatabase. 8. TheWHEN clausespecifiesoneormorefieldconditionsthateach recordmustmatchbeforeSQL*Loaderwillloadthedata.Inthisexample SQL*Loaderwillonlyloadtherecordifthe57th characterisadecimalpoint.That decimalpointdelimitsdollarsandcentsinthefieldandcausesrecordstobe rejectedifSAL hasnovalue. 9 9. TheTRAILING NULLCOLS clausetellsSQL SQL*Loader Loadertotreatany relativelypositionedcolumnsthatarenotpresentintherecordasnullcolumns. 10. Theremainderofthecontrolfilecontainsthefieldlist,which providesinformationaboutcolumnformatsinthetablethatisbeingloaded.

OracleDatabase10g:Administration WorkshopI9217

ControlFileSyntaxConsiderations Thesyntaxisfreeformat.(Statementscanextendovermultiplelines.) Itiscaseinsensitive;however,stringsenclosedinsingleordoublequotation marksaretakenliterally,includingcase. Incontrolfilesyntax,commentsextendfromthetwohyphens()thatmarkthe beginningofthecommenttotheendoftheline.Theoptionalthirdsectionofthe controlfileisinterpretedasdataratherthanascontrolfilesyntax;consequently, commentsinthissectionarenotsupported. TheCONSTANT keywordhasspecialmeaningtoSQL*Loaderandistherefore reserved Toavoidpotentialconflicts, reserved. conflicts donotusethewordCONSTANT asaname foranytablesorcolumns.

OracleDatabase10g:Administration WorkshopI9218

InputDataandDataFiles FixedRecordFormat Afileisinfixedrecordformatwhenallrecordsinadatafilearethesamebyte y length. g Althoughthisformatistheleastflexible,itresultsinbetterperformancethanvariableor streamformat.Fixedrecordformatisalsosimpletospecify.Forexample: INFILE <datafile_name> "fix n" ThisexamplespecifiesthatSQL*Loadershouldinterprettheparticulardatafileasbeing infixedrecordformatwhereeveryrecordisn byteslong. Thefollowingexampleshowsacontrolfilethatspecifiesafixedrecordformatdatafile. Thedatafilecontainsfour fo rph physical sicalrecords records.Thefirstrecordis[0001, [0001 abcd] b d], which hichis exactlyninebyteslong(usingasinglebytecharacterset)andthecarriagereturnisthe tenthbyte. load data infile example.dat "fix 10" into table example e ds te terminated ated by , , fields (col1, col2) example.dat:

OracleDatabase10g:Administration WorkshopI9219

InputDataandDataFiles(continued) 0001,abcd 0002,fghi 0003,klmn VariableRecordFormat Afileisinvariablerecordformatwhenthelengthofeachrecordinacharacterfieldis includedatthebeginningofeachrecordinthedatafile.Thisformatprovidessomeadded flexibilityoverthefixedrecordformatandaperformanceadvantageoverthestream recordformat.Forexample,youcanspecifyadatafilethatistobeinterpretedasbeingin variablerecordformatasfollows: INFILE "datafile_name d t fil " "var n" Inthisexample,n specifiesthenumberofbytesintherecordlengthfield.Ifn isnot specified,SQL*Loaderassumesalengthof5.Specifyingn largerthan40resultsinan error.ThefollowingexampleshowsacontrolfilespecificationthattellsSQL*Loaderto lookfordataintheexample.dat datafileandtoexpectvariablerecordformatwhere therecordlengthfieldsare3byteslong.Theexample.dat datafileconsistsofthree physical p y records.Thefirstisspecified p tobe009( (thatis, ,nine) )bytes y long, g,thesecondis 010byteslong(includingaonecharacternewline),andthethirdis012byteslong.This examplealsoassumesasinglebytecharactersetforthedatafile. load data infile example.dat "var 3 into table example fields terminated by , optionally enclosed by " (col1 char(5),col2 char(7)) example.dat: 009hello,cd, 010world,im, 012my,name is, StreamRecordFormat Afileisinstreamrecordformatwhentherecordsarenotspecifiedbysize;instead SQL*Loaderformsrecordsbyscanningfortherecordterminator.Streamrecordformatis themostflexibleformat,buttherecanbeanegativeeffectonperformance.The specificationofadatafilethatistobeinterpretedasbeinginstreamrecordformatlooks similartothefollowing: INFILE <datafile_name> ["str terminator_string"] The ete terminator ato _st string g is sspec specified edase either t e c char a st string g o orXhex e st string g where: char_string isastringofcharactersenclosedinsingleordoublequotation marks Xhex_string isabytestringinhexadecimalformat

OracleDatabase10g:Administration WorkshopI9220

InputDataandDataFiles(continued) Whentheterminator_string containsspecial(nonprintable)characters,itshould bespecifiedasaXhex_string.However,somenonprintablecharacterscanbe specifiedas(char char string) byusingabackslash.Forexample: \n linefeed(newline) \t horizontaltab \f formfeed \v verticaltab \r carriagereturn IfthecharactersetspecifiedwiththeNLS_LANG parameterforyoursessionisdifferent f from the th character h t set tof fth thed data t fil file,character h t strings t i areconverted t dto t the th character h t set t ofthedatafile. Hexadecimalstringsareassumedtobeinthecharactersetofthedatafile,sono conversionisperformed.Ifnoterminator_string isspecified,itdefaultstothe newline(endofline)character(linefeedinUNIXbasedplatforms,carriagereturn followedbyalinefeedonMicrosoftplatforms,andsoon).Thenewlinecharacteris connectedtothecharactersetofthedatafile. Thefollowingexample illustratesloadingdatainstreamrecordformatwherethe terminatorstringisspecifiedusingacharacterstring,|\n.Theuseofthebackslash characterallowsthecharacterstringtospecifythenonprintablelinefeedcharacter. load data infile example.dat "str |\n into table example fields terminated by , optionally enclosed by " (col1 char(5), col2 char(7)) example.dat: hello,world,| james,bond,|

OracleDatabase10g:Administration WorkshopI9221

LoadingMethods SQL*Loaderprovidestwomethodsforloadingdata: Conventionalpath Directpath ConventionalPathLoad ConventionalpathloadbuildsanarrayofrowstobeinsertedandusestheSQLINSERT statementtoloadthedata.Duringconventionalpathloads,inputrecordsareparsed basedonfieldspecifications,andanarrayofrecordsisbuiltandinsertedintothetable specifiedinthecontrolfile.Recordsthatdonotconformtothefieldspecificationsare rejectedandthoserecordsthatdonotsatisfytheselectioncriteriaarediscarded discarded. Conventionalpathloadscanbeusedtoloaddataintoboththeclusteredandunclustered tables.Redogenerationiscontrolledbytheloggingattributeforthetablethatisbeing loaded.

OracleDatabase10g:Administration WorkshopI9222

LoadingMethods(continued) DirectPathLoad Adirectpathloadbuildsblocksofdatainmemoryandsavestheseblocksdirectlyintothe extentsallocatedforthetablebeingloaded.Onlineredologfileentriesarenotgenerated unlessthedatabaseisinARCHIVELOG mode.Directpathloadsusethefield specificationstobuildwholeOracleblocksofdata,andwritetheblocksdirectlytoOracle datafilesabovethehighwatermark.Thehighwatermarkisthehighestpointtowhich datahasbeenwrittenintothetablesofar.Directpathloadbypassesthedatabasebuffer cacheandaccessestheSGAonlyforextentmanagementandadjustmentofthehigh watermark.

OracleDatabase10g:Administration WorkshopI9223

ComparingDirectandConventionalPathLoads MethodofSavingData ConventionalpathloadsuseSQLprocessingandadatabaseCOMMIT forsavingdata.The insertionofanarrayofrecordsisfollowedbyacommitoperation.Eachdataloadmight involveseveraltransactions. Directpathloadsusedatasaves towriteblocksofdatatoOracledatafiles.Thefollowing featuresdifferentiateadatasavefromaCOMMIT: Duringadatasave,onlyfulldatabaseblocksarewrittentothedatabase. Theblocksarewrittenafterthehighwatermarkofthetable. Afteradatasave, save thehighwatermarkismoved moved. Internalresourcesarenotreleasedafteradatasave. Adatasavedoesnotendthetransaction. Indexesarenotupdatedateachdatasave.

OracleDatabase10g:Administration WorkshopI9224

ComparingDirectandConventionalPathLoads(continued) LoggingChanges ConventionalpathloadinggeneratesredoentriessimilartoanyDMLstatement.When usingadirectpathload,redoentriesarenotgeneratedif: ThedatabaseisinNOARCHIVELOG mode ThedatabaseisinARCHIVELOG mode,butloggingisdisabled.Loggingcanbe disabledbysettingtheNOLOGGING attributeforthetableorbyusingthe UNRECOVERABLE clauseinthecontrolfile. EnforcingConstraints Duringaconventionalpathload,allenabledconstraintsareenforcedinthesameway th tthey that th areduring d i anyDMLoperation. ti Duringdirectpathloads,theconstraintsarehandledasfollows: NOT NULL constraintsarecheckedwhenarraysarebuilt. FOREIGN KEY andCHECK constraintsaredisabled,andcanbeenabledatthe endoftherunbyusingtheappropriatecommandsinthecontrolfile.FOREIGN KEY constraintsaredisabledbecausetheyreferenceotherrowsortables,and CHECK constraintsaredisabledbecausethey ymay yuseSQLfunctions.Ifonly ya smallnumberofrowsaretobeinsertedintoalargetable,useconventionalloads. PRIMARY KEY andUNIQUE constraintsarecheckedduringandattheendof therun,andmaybedisablediftheyareviolated. FiringINSERT Triggers WHILE INSERT triggersarefiredduringconventionalloads;theyaredisabledbeforea directpathloadandreenabledattheendoftherun.Theymayremaindisabledifa referencedobjectisnotaccessibleattheendoftherun. run Considerusingconventional pathloadstoloaddataintotableswithINSERT triggers. LoadingintoClusteredTables Directloadscannotbeusedtoloadrowsintoclusteredtables.Clusteredtablescanbe loadedusingconventionalpathloadsonly. Locking Whileadirectpathloadisinprogress,othertransactionscannotmakechangestothe tablesthatarebeingloaded.Theonlyexceptiontothisruleiswhenseveralparalleldirect loadsessionsareusedconcurrently.

OracleDatabase10g:Administration WorkshopI9225

LoadingDatawithSQL*Loader UsetheLoadDatafromFileWizardtoloaddatafromanonOracledatabaseintoan Oracledatabase.Todisplaythewizard,selectLoadDatafromFileontheUtilitiessection oftheDatabasehomepageMaintenancesubtab. Youcanloaddataasfollows: 1. LogintoEnterpriseManagerasSYS oranotheruserwith administratorprivileges. 2. ClickLoadDatafromFileunderUtilitiesontheMaintenancepage toinvokeasixsteploadingwizard. 3 3. Enterthefullpathofyourcontrolfileonthedatabaseserver machineontheLoadData:ControlFilepage.Alsoentertheusernameand passwordforthehostmachine.ClickNext. 4. SelectProvidethefullpathandnameonthedatabaseserver machineontheLoadData:DataFilepageandenterthepath.ClickNext. 5.ThedefaultisConventionalPathfortheloadingmethodontheLoadData: LoadMethodpage.YoumaychooseDirectPathifneeded.

OracleDatabase10g:Administration WorkshopI9226

LoadingDatawithSQL*Loader(continued) 6. SelectGeneratelogfilewherelogginginformationistobestored underOptionalFilesontheLoadData:Optionspage.Youcanacceptthedefault filenameandpathorenteradifferentone.Notethatthispagegivesyouthe optionoflimitingthenumberofrowsloaded.ClickNext 7. EnteraJobNameandDescriptionontheLoadData:Schedule page.SelectImmediatelytorunthejobnow.ClickNext. 8. TheLoadData:Reviewpageallowsyoutoreviewyourfilenames andloadingmethods.Ifyouwanttochangesomething,youcanclickBack. Otherwise,clickSubmitJobtostarttheloading. 9 9. Th Status The St t pageappearswith iththe th Load L dData D t Submit S b itS Successful f l message.ClickViewJobtoviewthejobsummary.TheSummarypageshould indicatethatthejobhassucceeded.Youcanviewthelogfilebyclickingyourjob undertheLogsheadingorbyviewingthelogfiledirectly. 10.YoucanconfirmtheloadeddatabynavigatingtotheTablespage,selecting thetable,andchoosingViewDataastheaction.

OracleDatabase10g:Administration WorkshopI9227

OracleDatabase10g:Administration WorkshopI9228

OracleDatabase10g:Administration WorkshopI9229

Practice9:ManagingData Background:Youneedtocreateadditionaltablesforthenewinventoryapplicationand loaddataintoyourexistingtables. Tasks: UseDataPumptoexportdatafromthedatabase. UseDataPumptoimportdataintothedatabase. UseDataPumptomoveobjectsanddatabetweenschemas. UseSQLLoadertoloaddatafromatextfileintothedatabase. 1.ExporttheHRschematoafilenamedhrexport.dmp.Allthefilesforthe exportneedtogointothehomedirectoryoftheoperatingsystemuser oracle. 2.ImportEMPLOYEES,DEPARTMENTSandLOCATIONStablesintoINVENTORY schemaandtheINVENTORYtablespace usingthehrexport.dmp youcreatedin step1. 3.UseDatabaseControltoverifythatyouhavesuccessfullycopieddatafromthe HRschematotheINVENTORYschemausingexport/import. export/import 4.UseSQLLoadertoloaddatafromtextfilesintotheproduct_master and product_on_hand tables. a)Usethecontrolfile/home/oracle/labs/lab09_04_a.ctl toloaddatafrom thetextfile/home/oracle/labs/lab09_04_a.dat intothe product_master table. b)Usethecontrolfile/home/oracle/labs/lab09_04_f.ctl toloaddatafrom the h textfile f l /home/oracle/labs/lab09_04_f.dat / / / / intothe h product_on_hand table.

OracleDatabase10g:Administration WorkshopI9230

PL/SQL PL/SQLisanOracleproprietaryfourthgenerationprogramminglanguagethat providesproceduralextensionstotheSQLlanguage.PL/SQLprovidesacommon programmingenvironmentforOracledatabasesandapplicationsregardlessofthe operatingsystemorhardwareplatform. WithPL/SQL,youcanmanipulatedatawithSQLstatementsandcontrolprogram flowwithproceduralconstructssuchasIFTHEN,CASE,andLOOP.Youcanalso declareconstantsandvariables, variables defineproceduresandfunctions, functions usecollections andobjecttypes,andtrapruntimeerrors.PL/SQLprogramcanalsocallprograms writteninotherlanguagessuchasC,C++,andJava. Becauseitrunsinsidethedatabase,PL/SQLcodeisveryefficientfordataintensive operations,andminimizesnetworktrafficinapplications. FormoredetailsonproceduralconstructsandusesofPL/SQL,refertoPL/SQL UsersGuideandReference documentation.

AdministeringPL/SQLObjects AstheDBA,youarenotusuallyresponsibleforloadingPL/SQLcodeintothedatabase andforassistingdevelopersintroubleshooting.Youarealsonotusuallyexpectedtowrite applicationsusingPL/SQL,butyoushouldbefamiliarwiththedifferentPL/SQLobjects sufficientlytomakerecommendationstoapplicationdevelopersandidentifyproblem objects. InDatabaseControlyoucanaccessPL/SQLobjectsintheAdministrationtab,under Schema.Whenyouclicktheobjecttypeyoucanview,modify,andcreatethetypeof PL/SQLobjectselected.

PL/SQLObjects Packages:Apackageisacollectionofprocedures,andfunctionsthatarelogically related.Thispartofapackageisalsocalledthespecification(orspec),andisthe interfacetoyourapplications;itdeclaresthetypes,variables,constants, exceptions,cursors,andsubprogramsavailableforuse. Packagebody:Thebodyfullydefinescursorsandsubprograms,andso implementsthespec.Thebodyholdsimplementationdetailsandprivate declarations,whicharehiddenfromyourapplication. Typebody:Acollectionofmethods(proceduresandfunctions)associatedwith userdefineddatatypes. types Formoreinformationonuserdefineddatatypes types,referto OracleDatabaseApplicationDevelopersGuide ObjectRelationalFeatures Procedures:AprocedureisaPL/SQLblockthatperformsaspecificaction. Functions:AfunctionisaPL/SQLblockthatreturnsasinglevaluebyusingthe RETURN PL/SQLcommand. Triggers:AtriggerisaPL/SQLblockthatisexecutedwhenaparticularevent happensinthedatabase.Theseeventscanbebasedonatable,suchaswhena rowisinsertedintothetable.Theycanalsobedatabaseevents,suchaswhena userlogsintothedatabase.

Functions PL/SQLfunctionsaretypicallyusedtocomputeavalue.Therearemanybuiltinfunctions suchasSYSDATE,SUM,AVG,andTO_DATE.Developersalsocreatetheirownfunctions whenwritingapplications.ThecodeforaPL/SQLfunctionmust containaRETURN statement.PL/SQLfunctionsareinvokedbyselectingfromthemasshowabove. Thecomputetax functionshownintheslideiscreatedwiththeSQLcommand: CREATEORREPLACEFUNCTIONcomputetax(salaryNUMBER) RETURNNUMBER AS BEGIN IFsalary<5000THEN RETURNsalary*.15; ELSE RETURNsalary*.33; ENDIF; END; /

Procedures PL/SQLproceduresperformaspecificaction.Theprocedureshownintheslideproduces thefollowingresults: SQL>SELECTsum(salary)FROMhr.employees; SUM(SALARY) 691400 SQL>callgiveraise(); Callcompleted. completed SQL>SELECTsum(salary)FROMhr.employees; SUM(SALARY) 725970 Likefunctions,procedurescanacceptinputvaluesandperformconditionalstatements suchasIFTHEN,CASE,andLOOP.

Packages Packagesaregroupingsoffunctionsandprocedures.Thereareperformanceand maintainabilityadvantagesingroupingfunctionsandproceduresintoasinglepackage. Eachpackageshouldbemadeupoftwoseparatelycompileddatabaseobjects: Packagespecification,sometimesknownasthepackageheader.Thisobjecthas anobjecttypeofPACKAGEandonlycontainsthedefinitionoftheprocedures functions,andvariablesforthepackage. Packagebody.ThisobjecthasanobjecttypeofPACKAGE BODY andcontains theactualcodeforthesubprogramsdefinedinthepackagespecification. Proceduresandfunctionscalledfromwithinapackagearecalledusingdotnotation: package_name.procedureorfunctionname Inthepackageshownabovethesubprogramsareexecutedasfollows: SQL>SELECTmoney.computetax(salary)FROMhr.employees WHEREemployee_id=107; SQL>EXECUTEmoney.giveraise;

PackageBody Packagebodies: Areseparatefromthepackagespecifications.Becauseofthis,thecodeofthe bodycanbechangedandrecompiled,andotherobjectsthataredependanton thespecificationarenotmarkedinvalid. Containthecodeforsubprogramsdefinedinthepackagespecification.Thisis wheretheworkisdone.Thespecificationshowshowtocallsubprogramswithin thepackage;thebodyisthecodesection. Cannotbecompiledunlessthepackagespecificationhasalreadybeencompiled. Youcancreateaspecificationwithoutabody, body butyoucannotcreateabody withoutaspecification. Maybewrappedtohidedetailsofthecode.Wrapisastandaloneprogramthat obfuscatesPL/SQLsourcecodesothatyoucandeliverPL/SQLapplications withoutexposingyoursourcecode.Formoreinformationontheuseofwrapsee thePL/SQLUsersGuideandReference.

PackageBody(continued) Thecodeforthemoneypackagebodyisasfollows: CREATEORREPLACEPACKAGEBODYmoneyAS FUNCTIONcomputetax(salaryNUMBER)RETURNNUMBERIS BEGIN IFsalary<5000THEN RETURNsalary*.15; ELSE RETURNsalary*.33; ENDIF; ENDcomputetax; PROCEDUREgiveraiseAS BEGIN EXECUTEIMMEDIATE'UPDATEhr.employees SET salary=salary*1.05'; ENDgiveraise; g ; ENDmoney; /

BuiltInPackages ThebuiltinPL/SQLpackagessuppliedwiththeOracleDatabase10g provideaccess toextendeddatabasefunctionalitysuchasadvancedqueuing,encryption,and heterogeneousservices.Theyalsoincludemanyadministrationandmaintenance utilities. Whichpackagesanadministratorusesdependsonthetypeofapplicationsthe databaseserves.Afewofthemorecommonadministrationandmaintenance packagesare: DBMS_STATS:Gather,view,andmodifyoptimizerstatistics DBMS_TTS:Validatetransportabletablespaces DBMS_WORKLOAD_REPOSITORY:ManagetheADDMrepository DBMS_SESSION:PL/SQLaccesstoALTER SESSION andSET ROLE statements DBMS_RLS:AdministertheVirtualPrivateDatabase DBMS_RESOURCE_MANAGER:Maintainresourcemanagerobjects DBMS_OBFUSCATION_TOOLKIT:Encrypt,decrypt,andcompute checksums DBMS_SCHEDULER:Schedulingfunctionsandproceduresthatarecallable fromanyPL/SQLprogram Fordetailsontheseandotherbuiltinpackages,seethePL/SQLPackagesandTypes Reference manual.

Triggers TriggersarePL/SQLcodeobjectsstoredinthedatabasethatautomaticallyrunorfire whensomethinghappens.OracleDatabase10g allowsmanyactionstoserveras triggeringevents,includinganinsertintoatable,auserloggingintothedatabase, someonetryingtodropatableorchangeauditsettings. Triggersmaycallotherproceduresorfunctions(anexperienceddeveloperusuallykeeps thetriggerscodeveryshortandplacesanythingthatrequireslengthycodeinaseparate package). DBAsusetriggerstoassistinvaluebasedauditing(discussedinalaterlesson),toenforce complexconstraints, constraints andtoautomatemanytasks. tasks Forexample, example the SECURE_EMPLOYEES triggerthatisshownabove,logsallDDLstatementstoaholding table. Therearemanydifferenteventsthatcanbeusedtofireatrigger.Mostcanfirethetrigger eitherbeforetheeventisallowedtooccurorafter(exceptionsarenotedinthefollowing table).FortheDMLtriggers(INSERT,UPDATE,DELETE),thetriggercanbedesignedto fireonceforthestatement,orwitheachrowthatismodified.

Triggers(continued) Thefollowingeventscanbeusedtofiretriggers:

INSERT STARTUP (AFTER) ALTER ASSOCIATE STATISTICS COMMENT DISASSOCIATE STATISTICS LOGON (AFTER) SUSPEND (AFTER)

UPDATE SHUTDOWN (BEFORE) DROP AUDIT CREATE GRANT RENAME TRUNCATE

DELETE SERVERERROR (AFTER) ANALYZE NOAUDIT DDL LOGOFF (BEFORE) REVOKE

PL/SQLConfigurationOptions AfewofthemoreimportantinitializationparameterscontrollingPL/SQLperformance are: PLSQL_CODE_TYPE:CompiledPL/SQLcanbestoredintwodifferentwaysas interpretedbytecodeorasnativemachinecode.Thedefault,interpreted bytecodeprovidesbetterdebuggingfeaturesfordevelopment.Nativemachine codeprovidesthebestruntimeperformance,uptotwiceasfastasinterpreted bytecode. PLSQL_DEBUG:AsettingofTRUE enablesadditionaldebuggingfeaturesthat arehelpfulinadevelopmentenvironmentandforcescodetobestoredas interpreted,regardlessofthePLSQL_CODE_TYPE setting.Thedefaultsettingof FALSE turnsoffextendeddebuggingfeatures. PLSQL_OPTIMIZE_LEVEL:Thedefaultsettingof1providesoptimumcompiler performance.Incaseswherecodechangesareinfrequentandapplicationsmake heavyuseofstoredPL/SQL,asettingof2providesbetterruntimeperformance butslightlydegradescompilerperformance. PLSQL_WARNINGS:Acceptstwoarguments.Thefirstenablesordisables warningmessagesfromthePL/SQLcompiler.ThesecondappliesthefirsttoALL warningmessages,orlimitsittoSEVERE,INFORMATIONAL,or PERFORMANCE messages.AproductionsettingofDISABLE:ALL providesthe bestperformance. Fordetailsontheseparameters,seetheOracleDatabaseReference manual.

DatabaseSecurity OracleDatabase10g providestheindustrysbestframeworkforasecuresystem, butforthatframeworktobeeffectivethedatabaseadministratorshouldfollow bestpracticesandcontinuallymonitordatabaseactivity. RestrictingAccesstoDataandServices Allusersshouldnothaveaccesstoalldata.Dependingonwhatisstoredinyour database,restrictedaccesscanbemandatedbybusinessrequirements,customer expectations andincreasinglybylegalrestrictions expectations, restrictions.Creditcardinformation, information health caredata,identityinformation,andmoremustbeprotectedfromunauthorized access.Oracleprovidesextremelyfinedgrainedauthorizationcontrolstolimit databaseaccess.Restrictingaccessshouldincludeapplyingtheprincipalofleast privilege.

DatabaseSecurity (continued) AuthenticatingUser toenforceaccesscontrolsonsensitivedata,thesystemmustfirstknowwhoistryingto accessthedata.Compromisedauthenticationcanrenderallothersecurityprecautions useless.Themostbasicformofuserauthenticationisbychallengingtheusertoprovide somethingtheyknowsuchasapassword.Ensuringthatpasswordsfollowsimplerules cangreatlyincreasethesecurityofyoursystem.Strongerauthenticationmethods includerequiringtheusertoprovidesomethingtheyhave,suchasatokenorPublicKey Infrastructure(PKI)certificate.Anevenstrongerformofauthenticationistoidentifythe userthroughauniquebiometriccharacteristicsuchasafingerprint,irisscan,bone structurepatterns,and dsoon.Oracle O l supportsadvanced d dauthentication h i i techniques h i such h astoken,biometric,andcertificatebasedidentificationthroughtheAdvanced SecurityOption.Useraccountsthatarenotinuseshouldbelockedtopreventattempts tocompromiseauthentication. MonitoringforSuspiciousActivity Evenauthorized,authenticateduserscansometimescompromiseyoursystem. Identifying y gunusualdatabaseactivity ysuchasanemployee p y whosuddenly ybegins g queryinglargeamountsofcreditcardinformation,researchresults,orothersensitive information,canbethefirststeptodetectinginformationtheft.Oracleprovidesarich setofauditingtoolstotrackuseractivityandidentifysuspicioustrends.

ApplythePrincipleofLeastPrivilege OracleDatabase10g databaseserverleadstheindustryinsecurity.However,to fullymaximizethesecurityfeaturesofferedbyOracleDatabase10ginanybusiness environment,itisimperativethatOracleDatabase10g itselfbewellprotectedand properlyconfigured. Properuseofembeddedsecurityfeaturesandadherencetobasicsecuritypractices willhelpprotectagainstdatabaserelatedthreatsandattacksandprovideamuch moresecureoperatingenvironmentfortheOracleDatabase10g. PracticethePrincipleofLeastPrivilege Theprincipleofleastprivilegemeansthatausershouldbegivenonlythose privilegesthatarerequiredtoefficientlycompleteatask.Thisreducesthechances thatusers,eitheraccidentallyormaliciously,canmodifyorviewdatathatthey shouldnothavetheprivilegetomodifyorview.

ProtecttheDataDictionary Nonadministratorsdonotneedaccesstothedatadictionary,butmaygainaccessif yougrantoneofthe* ANY TABLE systemprivilegessuchasSELECT ANY TABLE orUPDATE ANY TABLE.Thedatadictionarycontainsinformationthata malicioususercanleveragetopenetrateordamageyoursystem.Toexemptdata dictionarytablesfromthe* ANY TABLE privileges,setthe O7_DICTIONARY_ACCESSIBILITY initializationparametertoFALSE. Iftherearenonadministratoruserswhodo needaccesstothedatadictionary,you cangrantthataccessby: UsingstandardGRANT commandstoallowtheusertoseethespecificdata dictionaryobjectsrequired GrantingtheSELECT ANY DICTIONARY systemprivilegetogiveaccess totheentiredatadictionary InOracleDatabase10gandOracle9i Database,thedefaultvaluefor ,inOracle8iandearlier, , O7_DICTIONARY_ACCESSIBILITY isFALSE;however, itdefaultstoTRUE;thereforewitholderversionyoushouldmanuallysetitto FALSE toenabledatadictionaryprotection. Caution:IfthisparameterissettoTRUE,anyuserwiththeDROP ANY TABLE systemprivilegewillbeabletomaliciouslyoraccidentallydroppartsofthedata dictionary.

RevokeUnnecessaryPrivilegesfromPUBLIC BecauseanydatabaseusercanexerciseprivilegesthataregrantedtoPUBLIC, revokeunnecessaryprivilegesandrolesfromthedatabaseserverusergroup PUBLIC. SuchprivilegesincludeEXECUTE onseveralPL/SQLpackagesthatmaypermita minimallyprivilegedusertoaccessandexecutepackagesthatyoumaynotwant themtoaccess.ManyofthebuiltinDBMS_* andUTL_* packagesareinstalled withtheEXECUTE privilegegrantedtoPUBLIC.Followingtheprincipleofleast privilegeyoushouldusuallyrevokethesepermissionsforafewofthemore sensitivepackages,andthengrantindividualexecutepermissionstouserswho needthem.Restrictingaccesstopublicprivilegesaffectsall users.Youshouldretest relevantsystemcomponents.Ifrestrictingaccessisnotpractical,youmayalso choosetoauditaccessinstead. Themorepowerfulpackagesthatmaypotentiallybemisusedinclude: UTL_SMTP:Permitsarbitrarymailmessagestobesentusingthedatabase asanSMTPmailserver.GrantingthispackagetoPUBLIC maypermit unauthorizedexchangeofmailmessages. UTL_TCP:Permitsoutgoingnetworkconnectionstobeestablishedbythe databaseservertoanyreceivingorwaitingnetworkservice.Thus,arbitrary datacanbesentbetweenthedatabaseserverandanywaitingnetwork service.

RevokeUnnecessaryPrivilegesfromPUBLIC (continued) UTL_HTTP:AllowsthedatabaseservertorequestandretrievedataviaHTTP. GrantingthispackagetoPUBLIC maypermitdatatobesentviaHTMLformsto amaliciousWebsite. UTL_FILE:Ifconfiguredimproperly,allowstextlevelaccesstoanyfileonthe hostoperatingsystem.Evenwhenproperlyconfigured,thispackagedoesnot distinguishbetweenitscallingapplications,withtheresultthatoneapplication withaccesstoUTL_FILE maywritearbitrarydataintothesamelocationthat iswrittentobyanotherapplication. DBMS_OBFUSCATION_TOOLKIT:Encryptsdata.Generally,mostusersshould nothave h the h privilege i il toencryptdata d because b encrypted dd datai isnonrecoverable bl iftheencryptionkeysarenotsecurelystoredandmanaged. Thesepackagesareextremelyusefultoapplicationsthatneedthem,butrequireproper configurationtobeusedsecurely.Thus,unlessabsolutelynecessary,revokethemfrom PUBLIC andgrantthemonlytoindividualusersorroleswhenrequired. ListingObjectsExecutablebyPublic Usethefollowing gq query ytolisttheobjects j ownedby ySYS thathavetheEXECUTE privilegegrantedtoPUBLIC: SQL>SELECTtable_name 2FROMdba_tab_privs 3WHEREowner='SYS' 4ANDprivilege='EXECUTE' 5ANDgrantee='PUBLIC' grantee 'PUBLIC' 6/ TABLE_NAME AGGXMLIMP AGGXMLINPUTTYPE ... XMLTYPEEXTRA XMLTYPEPI 437rowsselected. SQL>

RestricttheOperatingSystemDirectoriesAccessiblebytheUser TheUTL_FILE_DIR configurationparameterdesignateswhichoperatingsystem directoriesPL/SQLcanreadfromandwriteto.Bydefault,nodirectoriescanbe accessed. Operatingsystemprivilegesstillapply.Directoriesthattheuserwhostartedthe databasecouldnotaccessarestillnotaccessibleregardlessofthe UTL_FILE_DIR setting. Tospecifymultipledirectories directories,listallrequireddirectoriesinsinglequotesasa commaseparatedlist(asshownabove).Thisisnotadynamicparametersothe instancemustberestartedforchangestotakeaffect.Remembernottouse environmentvariablesinthedirectorypath.Theinstancedoesnotchecktosee whetherthedirectoriesexist,soyoucanchangetheparameterandcreatethe directorieslater. BecauseallPL/SQLuserscanreadorwritetoallfilesspecifiedbythisparameter,all PL/SQLusersmustbetrustedwiththeinformationinthedirectoriesspecifiedby thisparameter. ThedirectorieslistedmustalsobeaccessiblebytheOracleinstance. Caution:NeversetUTL_FILE_DIR = *,becausethisenablesaccesstoall directoriesaccessiblebytheOracleinstance,includingthedatafileandredolog directories.

LimitUserswithAdministrativePrivileges Donotprovidedatabaseusersmoreprivilegesthannecessary.Toimplementleast privilege,restrictthefollowingtypesofprivileges: Grantsofsystemandobjectprivileges SYSprivilegedconnectionstothedatabase,suchasSYSDBA andSYSOPER OtherDBAtypeprivileges,suchasDROP ANY TABLE UsethequeryshownontheslidetolistallusersthathavetheDBA rolegrantedto them.NonadministratorsshouldnotbegrantedtheDBArole.Instead,determine theactualprivilegestheyneedandgrantonlythoseprivileges. ToseeuserswhohavebeengrantedSYSDBA orSYSOPER privileges(effectively grantingthemtheDBArole),usethefollowingquery: SQL>SELECT*FROMV$PWFILE_USERS; USERNAMESYSDBASYSOPER SYSTRUETRUE ThereisseldomreasonforanyuserotherthanSYS tohaveSYSDBA privileges.

DisableRemoteOperatingSystemAuthentication Thisfeatureisdisabledbydefault.Whenenabled(TRUE),externalauthentication ofdatabaseusersisdelegatedtotheremotesystem.Thismeansthattheinstance implicitlytruststhatusershaveauthenticatedproperlyontheirclientPCanddoes notcheckauthenticationcredentialsagain.Userscanconnecttotheinstance withoutprovidingapasswordaslongastheiroperatingsystemusernamematches thedatabaseusernameandthedatabaseuserisallowedtobeauthenticated externally. externally

Mostremoteoperatingsystems,especiallyforusersconnectingfromPCs,should notbetrustedtoperformoperatingsystemauthenticationproperly.Itisverypoor securitypracticetoturnonthisfeature.

ManageDefaultUserAccounts OracleDatabase10g installswithanumberofdefault,presetdatabaseserveruser accounts.TheseaccountsareintendedtostoredataandownPL/SQLorJavacode objects,nottopermitdatabaseconnections.WhentheDatabaseCreationAssistant (DBCA)isusedtocreateadatabaseitautomaticallylocksandexpiresalldefault databaseuseraccountsexceptforthefollowing: SYS SYSTEM DBSNMP SYSMAN Oraclesupportsscriptedcreationofcustomdatabases.Manyapplicationsexpect theirdatabasetobeconfiguredinacertainwayandautomatethatconfiguration throughtheuseofscripteddatabasecreation.Databasescreatedinthiswaymay notlockthedefaultaccounts.Also,manyapplicationscreateuseraccountsthat shouldbelocked. Validatethatunlockedaccountsarereallybeingusedfordatabaseconnections,and notsimplytostoredata.

ImplementStandardPasswordSecurityFeatures Oraclepasswordmanagementisimplementedwithuserprofiles. Profilescanprovidemanystandardsecurityfeaturesincluding: Accountlocking:Enablesautomaticlockingofaccountsforasetduration whenusersfailtologintothesysteminthespecifiednumberofattempts Passwordagingandexpiration:Enablesuserpasswordstohavealifetime, afterwhichtheyexpireandmustbechanged Passwordhistory:Checksthenewpasswordtoensurethatthepasswordis notreusedforaspecifiedamountoftimeoraspecifiednumberof passwordchanges Passwordcomplexityverification:Makesacomplexitycheckonthe passwordtoverifythatitmeetscertainrules.Thecheckshouldensurethe passwordiscomplexenoughtoprovideprotectionagainstintruderswho mighttrytobreakintothesystembyguessingthepassword. RememberthatwhenusersarecreatedtheyareassignedtheDEFAULTprofile unlessanotherprofileisimplicitlyspecified.

PasswordAccountLocking TheOracleserverautomaticallylocksanaccountaftertheuserfailstologinbefore theFAILED_LOGIN_ATTEMPTS valueisreached.Theaccountiseither automaticallyunlockedafteraspecifiedtimedeterminedby PASSWORD_LOCK_TIME oritmustbeunlockedbythedatabaseadministrator usingtheALTER USER command. ThedatabaseaccountcanbeexplicitlylockedwiththeALTER USER commandor byusingEnterpriseManager. Manager Whenthishappens happens,theaccountisnotautomatically unlockedafterPASSWORD_LOCK_TIME hasexpired,butmustbemanually unlockedbytheDBA. SQL>ALTERUSERhrACCOUNTLOCK; Useraltered. SQL>CONNECThr/hr ERROR:ORA28000:theaccountislocked Warning:YouarenolongerconnectedtoORACLE. SQL>CONNECT/assysdba Connected. SQL>ALTERUSERhrACCOUNTUNLOCK; Useraltered.

PasswordExpirationandAging ThedatabaseadministratorcanspecifyagraceperiodPASSWORD_GRACE_TIME, whichbeginsafterthefirstattempttologintothedatabaseafterpassword expiration.Awarningmessageisgeneratedeverytimetheusertriestologinuntil thegraceperiodisover.Ifauserdoesnotchangetheirpasswordwithinthegrace period,theiraccountislocked. Note: Iftheaccountisanapplicationaccount(notaccessedthroughSQL*Plus), verifythattheapplicationisabletohandlethechangepassworderrorbefore enablingpasswordexpiration.ManyDBAsassignaseparateprofiletoapplication useraccountsandmonitoringtools. Ausersaccountcanbemanuallyexpiredbysettingthepasswordtoexpired. SQL>ALTERUSERhrPASSWORDEXPIRE; Useraltered. SQL>CONNECThr/hr ERROR:ORA28001:thepasswordhasexpired Changingpasswordforhr Newpassword:******** Retypenewpassword:******** Passwordchanged

PasswordHistory Passwordhistorychecksensurethatausercannotreuseapasswordforaspecified timeinterval.Thesecheckscanbeimplementedusingoneofthefollowing: PASSWORD_REUSE_TIME:Specifiesthatausercannotreuseapassword foragivennumberofdays PASSWORD_REUSE_MAX:Specifiesthenumberofpasswordchanges requiredbeforethecurrentpasswordcanbereused. Thesetwoparametersaremutuallyexclusive, exclusive sowhenoneparameterissettoa valueotherthanUNLIMITED (orDEFAULT iftheDEFAULT profilehasthevalue settoUNLIMITED),theotherparametermustbesettoUNLIMITED.

PasswordVerification Beforeassigninganewpasswordtoauser,aPL/SQLfunctioncanbeinvokedto verifythevalidityofthepassword. TheOracleserverprovidesadefaultverificationroutinethatcanbeloadedby runningtheSQLscriptlocatedat $ORACLE_HOME/rdbms/admin/utlpwdmg.sql orthedatabase administratorcanwriteacustomPL/SQLfunctionthatmeetstheirownsecurity requirements. requirements Inadditiontotherestrictionslistedintheslide,custompasswordverification functionsmustusethefollowingspecificationtodeclareinputvariables: function_name(userid_parameter INVARCHAR2, password_parameter INVARCHAR2, old_password_parameter IN VARCHAR2) RETURNBOOLEAN Ifthepasswordfunctionraisesanexceptionorbecomesinvalid,anerrormessageis returnedandtheALTER USER orCREATE USER commandisterminated.

SuppliedPasswordVerificationFunction:VERIFY_FUNCTION TheOracleserverprovidesacomplexityverificationfunctionnamed VERIFY_FUNCTION.Thisfunctioniscreatedwiththescript $ORACLE_HOME/rdbms/admin/utlpwdmg.sql.Thepasswordverification functionmustbecreatedintheSYS schema. InadditiontocreatingtheVERIFY_FUNCTION,theutlpwdmg scriptalso changestheDEFAULT profilewiththefollowingALTER PROFILE command: ALTERPROFILEdefaultLIMIT PASSWORD_LIFE_TIME60 PASSWORD_GRACE_TIME10 PASSWORD_REUSE_TIME1800 PASSWORD_REUSE_MAXUNLIMITED FAILED_LOGIN_ATTEMPTS3 PASSWORD_LOCK_TIME1/1440 PASSWORD_VERIFY_FUNCTIONverify_function;

CreatingaPasswordProfile
Tocreateapasswordprofile,openEnterpriseManagerandnavigatetothe Administrationpage.SelectProfilesandclicktheCreatebutton. Commonvaluesforeachofthesettingscanbechosenfromalistofvalues(click theflashlighticontobrowse)oryoucanenteracustomvalue. Alltimeperiodsareexpressedindays,butcanbeexpressedasfractions.Thereare 1440minutesinaday, y,so5/1440 / isfiveminutes. EnterpriseManagercanalsobeusedtoeditexistingpasswordprofiles. DroppingaPasswordProfile Ifyoudropaprofile,allusersassignedthatprofilewillautomaticallybeassignedto thedefaultprofile.

AssigningUserstoaPasswordProfile Toassignausertoapasswordprofile: 1. OpenEnterpriseManagerandnavigatetotheAdministration page. 2. SelectUsers.Selecttheuseryouwishtoassigntoaprofile andclicktheEditbutton. 3. FromtheProfiledropdownlist,selecttheprofilethatyou wanttoapplytotheuser, user andclicktheApplybutton button. Rememberthatausercanhaveonlyoneprofileineffectatanygiventime.Ifusers havealreadyloggedinwhenyouchangetheirprofile,thechangedoesnottake effectuntiltheirnextlogin. NotethatuseraccountscanbealsobelockedorexpiredfromtheEditUserpage.

MonitoringforSuspiciousActivity OracleDatabase10g providesthreedifferenttypesofauditing.Theadministrator canauditallactionsthattakeplacewithinthedatabase.Itisimportantto rememberthatcapturingandstoringinformationaboutwhatishappeninginthe systemincreasestheamountofworkthesystemmustdo.Auditingshouldbe focusedsothatonlyeventsthatareofinterestarecaptured.Properlyfocused auditinghasminimalimpactonsystemperformance.Improperlyfocusedauditing cansignificantlyaffectperformance. performance Standarddatabaseauditingcapturesseveralpiecesofinformationaboutanaudited eventincludingthattheeventoccurred,whenitoccurred,theuserwhocausedthe auditedevent,andwhichclientmachinetheuserwasonwhentheevent happened. Usevaluebasedauditingtoauditchangestodata(inserts,updates,deletes).Value basedauditingextendsstandarddatabaseauditing,capturingnotonlythatthe auditedeventoccurred,buttheactualvaluesthatwereinserted,updated,or deleted.Valuebasedauditingisimplementedthroughdatabasetriggers. Usefinegrainedauditing(FGA)toauditSQLstatements.FGAextendsstandard databaseauditing,capturingtheactualSQLstatementthatwasissuedratherthan onlythattheactionoccurred.

StandardDatabaseAuditing Tousedatabaseauditingyoumustfirstsetthenondynamicparameter AUDIT_TRAIL topointtoastoragelocationforauditrecords.Thenormalsetting forthisparameterisDB,whichcausesauditrecordstobestoredinthe DBA_AUDIT_TRAIL table. Databaseauditingcancaptureinformationaboutloginevents,theexerciseof systemprivileges,andtheexerciseofobjectprivileges.Auditinformationcanbe focusedbytheusergeneratingtheauditeventorbythestatusoftheevent (successfulornot).Thefollowingauditcommandthatgeneratesinformationis probablynotrequiredbecauseitisnotwellfocused.Thisoptioncapturesany operationthataffectsanytable: SQL>AUDITTABLE; Auditsucceeded. Abetterexampleofanauditcommand(becauseitismorenarrowlyfocused)is: SQL>AUDITDELETEONhr.employeesWHENEVER SUCCESSFUL; Auditsucceeded.

SpecifyingAuditedOptions SQLstatementauditing:ThestatementshownintheslidewillauditanyDDL statementthataffectsatableincludingCREATE TABLE,DROP TABLE, TRUNCATE TABLE,andsoon.SQLStatementauditingcanbefocusedby usernameorbysuccess/failure. SQL>AUDITTABLEBYhrWHENEVERNOTSUCCESSFUL; Systemprivilegeauditingcanbeusedtoaudittheexerciseofanysystemprivilege (suchasDROP ANY TABLE). ) Itcanbefocusedbyusernameorsuccess/failure. success/failure By default,eachtimeanauditedsystemprivilegeisexercisedanauditrecordis generated.Youcanchoosetogroupthoserecordssothatonlyonerecordis generatedpersession(thatwayifauserupdates100,000recordsinatable belongingtoanotheruser,youonlygatheroneauditrecord).IftheBY SESSION clauseisnotspecified,thedefaultisBY ACCESS.ConsiderusingtheBY SESSION clausetolimittheperformanceandstorageimpactofsystemprivilege auditing. Objectprivilegeauditingcanbeusedtoauditactionsontables,views,procedures, sequences,directoriesanduserdefineddatatypes.Thistypeofauditingcanbe focusedbysuccess/failureandgroupedbysessionoraccess.Unlikesystemprivilege auditing,thedefaultgroupingisbysessionsoyoumustimplicitlyspecifyBY ACCESS ifyouwantaseparateaudittrailrecordgeneratedforeachaction.

SpecifyingAuditOptions(continued) TheAUDIT SESSION optionauditsthecreationofusersessions.Itcanbefocusedby usernameorbysuccess/failure.Thisoptionisuniquebecauseitgeneratesasingleaudit recordforeachsessioncreatedbyconnectionstoaninstance.Anauditrecordis insertedintotheaudittrailatconnecttimeandupdatedatdisconnecttime.Cumulative informationaboutasessionsuchasconnectiontime,disconnectiontime,logicaland physicalI/Osprocessed,andmoreisstoredinasingleauditrecordthatcorrespondsto thesession.InmanydatabasesitiscommontousetheAUDIT SESSION (nonfocused)command.InalmostalldatabasesyoushouldAUDIT SESSION WHENEVER NOT SUCCESSFUL becausethisallowsyoutodetectattemptstobreak i yourdatabase into d b Note: Oftenyourauditoptionsstartasnonfocusedbecauseyouarenotsurewhattype ofactivityyouarelookingfor.TheAUDIT ALL optionisaconvenientshortcuttoaudit abroadrangeofactivity.Ifusedwithobjectprivilegeauditing(asshownintheslide),it detects:

Alter Grant Read

Audit Index Rename

Comment Insert Select

Delete Lock Update

If the AUDIT ALL option is used with a username: SQL> AUDIT ALL BY hr; Th user will The ill h have all ll DDL statements t t t audited dit d for f the th following f ll i objects: bj t

Alter System Database Link Materialized View

Cluster Dimension Not Exists

Context y Directory Procedure Role System Audit Trigger

Create Session Index Profile Rollback Segment System Grant Type

Public Database Link Public Synonym Sequence Table User Synonym Tablespace View

ViewingAuditingOptions Toseewhichauditoptionshavebeenselected,usetheviewslistedabove. DBA_STMT_AUDIT_OPTS andDBA_PRIV_AUDIT_OPTS containonlyrecords ofstatementorprivilegeauditoptionsthathavebeenspecified. DBA_OBJ_AUDIT_OPTS containsonerecordperauditableobjectregardlessof whatobjectauditoptionshavebeenspecified.Theviewshowsacolumnforeach auditableoption.Forexample,INSERT auditoptionsareshownintheINS column AuditoptionsaredisplayedasSUCCESSFUL/NOT SUCCESSFUL with column. threepossiblevaluesforeachstatus: Notaudited S Collectauditrecordsbysession A Collectauditrecordsbyaccess SQL>SELECTobject_name,object_type,ins,upd FROMdba_obj_audit_optsWHEREobject_name= 'EMPLOYEES OBJECT_NAMEOBJECT_TYINSUPD EMPLOYEESTABLEA/S/

StandardDatabaseAuditing Aftertheadministratorhasenableddatabaseauditing(withtheAUDIT_TRAIL parameter)andspecifiedauditingoptions(withSQLstatementsasshowonthe previousfewpages),thedatabasebeginscollectingauditinformation. IfAUDIT_TRAIL issettoOS,theauditrecordswillbestoredintheoperating systemsauditsystem.InaWindowsenvironment,thisistheeventlog.InaUNIXor Linuxenvironment,auditrecordsarestoredinafile.Thelocationofthatfileis specifiedwithAUDIT_FILE_DEST AUDIT FILE DEST.AssumingthatAUDIT_TRAIL AUDIT TRAIL issettoDB, auditrecordsarestoredinatablethatispartoftheSYS schema. Maintainingtheaudittrailisanimportantadministrativetask.Dependingonthe focusoftheauditoptions,theaudittrailcangrowverylargeveryquickly.Ifnot properlymaintained,theaudittrailcanconsumesomuchspacethatitaffectsthe performanceofthesystem.

ViewingAuditingResults Accesstoauditrecordsshouldbetightlycontrolledbecausetheymaycontain sensitiveinformation.Usuallythetaskofmanagingtheaudittrailishandledbythe administratorbutifitneedstobedelegatedtheDELETE_CATALOG_ROLE grants permissiontodeletefromtheaudittrail.

ValueBasedAuditing Databaseauditingrecordsthatinserts,updates,anddeleteshaveoccurredon auditedobjects,butdoesnotcapturetheactualvaluesthatwerechanged.Value basedauditingextendsdatabaseauditing,capturingtheactualvaluesthathave beenchanged.Valuebasedauditingleveragesdatabasetriggers(eventdriven PL/SQLconstructs). Whenauserinserts,updates,ordeletesdatafromatablewiththeappropriate triggerattached, attached thetriggerworksinthebackgroundtocopyauditinformationtoa tabledesignedtocontaintheauditinformation.Valuebasedauditingtendsto degradeperformancemorethanstandarddatabaseauditingbecausetheaudit triggercodemustbeexecutedeachtimetheinsert,update,ordeleteoperation occurs.Thedegreeofdegradationdependsontheefficiencyofthetriggercode. Valuebasedauditingshouldbeusedonlyinsituationswheretheinformation capturedbystandarddatabaseauditingisinsufficient.

ValueBasedAuditing(continued) Thekeytovaluebasedauditingistheaudittrigger.Atypicalaudittriggerisshow below. CREATE OR REPLACE TRIGGER system.hrsalary_audit system.hrsalary audit AFTER UPDATE OF salary ON hr.employees REFERENCING NEW AS NEW OLD AS OLD FOR EACH ROW BEGIN IF :old.salary != :new.salary THEN INSERT INTO system.audit_employees t dit l VALUES (sys_context('userenv','os_user'), sysdate, sys_context('userenv','ip_address'), :new.employee_id ||' salary changed from '||:old.salary|| ' to '||:new.salary); || y) END IF; END; / Thistriggerfocusesauditingtocapturechangestothesalarycolumnofthe hr.employees table.Whenarowisupdatedthetriggerchecksthesalarycolumn.If theoldsalaryisnotequaltothenewsalary,thenthetriggerinsertsanauditrecordinto theaudit_employees audit employees table(createdviaaseparateoperationintheSYSTEM schema).Theauditrecordwillincludetheusername,IPaddressfromwhichthechange wasmade,primarykeyidentifyingwhichrecordwaschanged,andtheactualsalary valuesthatwerechanged. Databasetriggerscanalsobeusedtocaptureinformationaboutuserconnectionsin caseswherestandarddatabaseauditingdoesnotgathersufficientdata.Withlogon triggers,theadministratorcancapture: -IPaddressofthepersonloggingin -Thefirst48charactersoftheprogramnameusedtoconnecttotheinstance -Terminalnameusedtoconnecttotheinstance

FineGrainedAuditing(FGA) Databaseauditingrecordsthatanoperationhasoccurred,butdoesnotcapture informationaboutthestatementthatcausedtheoperation.Finegrainedauditing (FGA)extendsthatcapabilitytoallowsthecaptureofactualSQLstatementsthat queryormanipulatedata.FGAalsoallowsauditingtobemorenarrowlyfocused thanstandardorvaluebaseddatabaseauditing. FGAauditoptionscanbefocusedbyindividualcolumnswithinatableorview,and canevenbeconditionalsothatauditsarecapturedonlyifcertainadministrator definedspecificationsaremet. Unlikevaluebasedauditing,FGAdoesnotrequiretheuseofdatabasetriggersand hasaperformanceimpactsimilartostandarddatabaseauditing. TheadministratorusestheDBMS_FGA PL/SQL packagetocreateanauditpolicy onthetargettableorview.Ifanyoftherowsreturnedfromaqueryblockmatches theauditedcolumnandtheauditcondition,thenanauditeventcausesanaudit recordtobecreatedandstoredintheaudittrail.Optionally,theauditeventcan alsoexecuteaprocedure.FGAautomaticallyfocusesauditingatthestatementlevel soaSELECT statementthatreturnsthousandsofrowsgeneratesonlyoneaudit record.

FGAPolicy TheexampleintheslideshowsanFGApolicybeingcreatedwiththe DBMS_FGA.ADD_POLICY procedure.Theprocedureacceptsthefollowing arguments: PolicyName YouassigneachFGApolicyanamewhenyoucreateit.Theexampleintheslide namesthepolicyAUDIT_EMPS_SALARY,usingthefollowingargument: policy name=>'audit policy_name audit_emps_salary emps salary' AuditCondition TheauditconditionisaSQLpredicatethatdefineswhentheauditeventshouldfire. Intheexampleontheslide,allrowsinthesales departmentareaudited,using thefollowingconditionargument: audit_condition=>'department_id=10' StatementType Whichtypeofstatementsshouldbeaudited?ThechoicesareSELECT and(all ( one string)INSERT,UPDATE,DELETE.

FGAPolicy(continued) AuditColumn Theauditcolumndefinesthedatathatisbeingaudited.Anauditeventoccursonlyif thiscolumnisincludedintheSELECTstatement.Theexampleintheslideauditsthe SALARYcolumn,usingthefollowingargument: audit_column=>'salary' Thisargumentisoptional.Ifitisnotspecified,thenonlytheAUDIT_CONDITION argumentdetermineswhetheranauditeventoccurs. Object Theobjectisthetableorviewthatisbeingaudited.Itispassedastwoarguments: Th schema The h that h contains i the h object bj Thenameoftheobject Theexampleontheslideauditsthehr.employeestableusingthefollowingarguments: object_schema=>'hr' object_name=>'employees' Handler Anoptional p eventhandlerisaPL/SQL / Q procedure p thatdefinesany yadditionalactionsthat shouldbetakenduringauditing.Forexample,theeventhandlercouldsendanalert pagetotheadministrator.Ifitisnotdefined,thenanauditevententryisinsertedinto theaudittrail.Ifanauditeventhandlerisdefined,thentheauditentryisinsertedinto theaudittrailandtheauditeventhandlerisexecuted. TheauditevententryincludestheFGApolicythatcausedtheevent,theuserexecuting theSQLstatement,andtheSQLstatementanditsbindvariables. Theeventhandlerispassedastwoarguments: arguments TheschemathatcontainsthePL/SQLprogramunit ThenameofthePL/SQLprogramunit TheexampleontheslideexecutestheSECURE.LOG_EMPS_SALARYprocedureusingthe followingarguments: handler_schema=>'secure' handler_module=>'log_emps_salary' Status ThestatusindicateswhethertheFGApolicyisenabled.Intheexampleontheslide,the followingargumentenablesthepolicy: enable=>TRUE

DBMS_FGA Package TheDBMS_FGA packageistheadministrationtoolforfinegrainedauditfunctions. ExecuteprivilegesonDBMS_FGA areneededtoadministerfinegrainedaudit policies.Becausethefinegrainedaudittrailcancontainsensitiveinformation, executeprivilegesonthispackageshouldbereservedforadministratorsonly.

EnablingandDisablinganFGAPolicy DisablinganFGApolicymeansthatthepolicydoesnotgenerateauditevents.You cancausethepolicytostartgeneratinglogeventsagainbyenablingit.Youcan causethepolicytostartgeneratinglogeventsagainbyenablingit.Bydefault,the policyisenabledwhenitiscreated.Theexampleontheslideshowshowtoenable anddisableapolicy.Forbothprocedures,allargumentsarerequired. Theexampleontheslideshowhowtoenableanddisableapolicy.

DroppinganFGAPolicy IfyounolongerrequireanFGApolicy,youcanremoveitwith DBMS_FGA.DROP_POLICY.Allargumentsarerequired.

TriggeringAuditEvents Ingeneral,finegrainedauditingpolicyisbasedoncolumnsauditedandsimple userdefinedSQLpredicates.Duringparsingwheneverpolicyconditionsaremetfor astatement,thestatementisaudited,andifthereisaneventhandler,itisalso fired. Theauditfunctionisexecutedasanautonomoustransaction.Eachauditpolicyis appliedindividually.Thatis,aslongastherowsbeingreturnedorchangedfitinto anyoftheauditconditiondefinedonthetable, table anauditrecordwillbegenerated, generated andtherewillbeonerecordgeneratedforeachpolicyperSQLstatement. Examples Thefirsttwoexamplesontheslidecauseanauditeventbecausetheyaccessthe salary columnandrowswiththedepartment_id = 10.Oracleserveris awarethatthesecondexampleaccessestherowsindepartment10,eventhough thedepartment_id isnotreferencedintheSQLstatementWHERE clause. Thelastexampledoesnotcauseanauditeventbecausethesalary columnisnot accessed.Ifthesalary columnhadnotbeenspecifiedastheAUDIT_COLUMN whenthepolicywascreated,thenthisSELECT statementwouldcauseanaudit event.

DataDictionaryViews FGAauditentriesareloggedintoaseparatetablefromobjectandprivilegeaudits. TheentriesarerecordedintheDBA_FGA_AUDIT_TRAIL view. Theotherthreeviewslistedontheslidecontainpolicydefinitions.

DBA_FGA_AUDIT_TRAIL Name TIMESTAMP DB_USER executing OS_USER theuserexecuting OBJECT SCHEMA OBJECT_SCHEMA OBJECT_NAME POLICY_NAME SCN SQL_TEXT auditevent SQL_BIND event,formattedas:#n(s):v: bindvariableinthestatement

Description Thedateandtimeofexecution Thedatabasenameoftheuser Theoperatingsystemnameof Theowneroftheauditedobject Thenameoftheauditedobject Thepolicynamethecausedtheauditevent TheSCNofthetransaction TheSQLstatementcausingthe Thebindvariableoftheaudit wheren isthenumberofthe

s isthebindvariablelength,v is thebindvariablevalue COMMENT$TEXT Acomment Note: Thisisapartiallistofcolumnsavailableindba_fga_audit_trail dba fga audit trail.For moreinformationrefertotheOracleDatabaseReference guide.

DBA_FGA_AUDIT_TRAIL (continued) SelectingfromtheFGAAuditTrail Thefollowingexampledisplaysthetwoauditrowscreatedbythevalidexamplesfrom thepreviouspage.Thesql_bind sql bind columninthesecondrowhasavalueof #1(4):1000,whichincludesthefollowingcomponents: #1 indicatesthatthisisthefirstbindvariableinthestatement. (4) Indicatesthatthebindvariablehasalengthof4. 1000 indicatesthatthebindvariablehasavalueof1000. Example Thisexampleissimilartotheoneontheslide,exceptitalsoincludesarowforapolicy without i h anaudit di eventhandler. h dl SQL> COL timestamp FORMAT A10 SQL> COL db_user FORMAT A7 SQL> COL policy_name FORMAT A20 SQL> COL sql_bind FORMAT A20 SQL> COL sql_text FORMAT A60 SQL> SQL> SELECT to_char(timestamp, 'YYMMDDHH24MI') 2 AS timestamp, 3 db_user, 4 policy_name, 5 sql_bind, 6 sql_text 7 FROM dba_fga_audit_trail; dba fga audit trail; TIMESTAMP DB_USER POLICY_NAME SQL_BIND ---------- ------- -------------------- ----------------SQL_TEXT --------------------------------------------------------0201221740 SYSTEM AUDIT_EMPS_SALARY #1(4):1000 SELECT count(*) FROM hr.employees WHERE department_id = 10 AND salary > :b1 0201221741 SYSTEM AUDIT_EMPS_SALARY AUDIT EMPS SALARY SELECT salary FROM hr.employees SQL>

FGAGuidelines AuditCondition WhencreatinganewFGApolicy,theauditconditiondefaultstonull,which meansallstatementswillbeaudited. PolicyNameError Policynamesmustbeuniquewithinthedatabase.Theyhavenoowner.Ifa duplicatenameisused,youreceivethefollowingerrorwhencreatingthepolicy: ORA28101:policyalreadyexists AuditedObjectErrors Theauditedtableorviewmustexistwhenyoucreatethepolicy.Ifitdoesnotyou receivethefollowingerror: ORA00942:tableorviewdoesnotexist

FGAGuidelines(continued) AuditConditionErrors Iftheauditconditionhasinvalidsyntax,thepolicyiscreatedwithoutanerror,butthe followingerrorisraisedwhentheauditedobjectisaccessed: ORA28112:failedtoexecutepolicyfunction Iftheauditconditionhasvalidsyntax,butisincorrect,thenthewrongrowsareaudited. AuditColumnErrors Iftheauditcolumndoesnotexistinthetable,thenthepolicyiscreated;however,no rowsareaudited,becausetheauditcolumnisneveraccessed. Iftheauditcolumnnameisvalid,butincorrect,thenthewrongrowsareaudited. E Event H Handler dl E Error Whenthepolicyreferencesanonexistentorinvalideventhandler,thepolicyiscreated; however,norowsarereturnedwhenanauditeventoccurs.

AuditingSYSDBA andSYSOPER Users SYSDBA andSYSOPER usershaveprivilegestostartandshutdownthedatabase. Becausetheymaymakechangeswhilethedatabaseisclosed,theaudittrailfor theseprivilegesmustbestoredoutsidethedatabase.Oraclecapturesloginevents bySYSDBA andSYSOPER usersautomatically,butdoesnotcaptureanything otherthantheloginunlessauditingisspecificallyenabled. EnableauditingofSYSDBA andSYSOPER usersbysettingtheinitialization parameter: audit_sys_operations=TRUE(the default is FALSE) IfSYS operationsareaudited,theaudit_file_dest initializationparameter controlswheretheauditrecordswillbestored.OnaWindowsplatform,theaudit traildefaultstotheWindowsEventLog.OnUNIXorLinuxplatforms,auditrecords arestoredin$ORACLE_HOME/rdbms/audit.

SecurityUpdates Oraclesecurityalertscontainabriefdescriptionofthevulnerability,anassessment oftheriskanddegreeofexposureassociatedwiththevulnerability,andapplicable workaroundsorpatches.Oraclealsoincludesanacknowledgementoftheindividual ororganizationthatnotifiedusofthevulnerability. SecurityalertsarepostedontheOracleTechnologyNetworkWebsiteandon OracleMetaLink (MetaLink).Althoughsecurityalertsarepubliclyacknowledgedfor anyoneinterestedinthem, them onlycustomerswithacurrentCustomerSupport Identification(CSI)numbercandownloadpatches. Oracleappreciatesyourcooperationinkeepingitsproductssecurethroughprompt, complete,andconfidentialnotificationofpotentialsecurityvulnerabilities.Ifyou discoverasecurityvulnerabilitywithanyOracleproduct,pleasenotifyusby submittingaservicerequestthroughMetaLinkorbyemailing secalert_us@oracle.com.

Practice111Overview:DatabaseSecurity(Part1) Background Whileconductingusertrainingyoudiscoverthatsomeusersareusingverysimple passwords,andsuspectthatsomeonemaybetryingtoguessthepasswordsof privilegeduserssotheycangainaccesstosensitivedata.Configureyourdatabaseto preventtheuseofsimplepasswordsandtodetectattemptstoguesspasswords Tasks Preventtheuseofsimplepasswords Forceaccountstolockfor10minutesafterfourfailedloginattempts Exempttheapplicationserverloginfromforcedpasswordchanges Auditunsuccessfulattemptstoconnecttothedatabase 1.Preventtheuseofsimplepasswords a)Whatprofilesexistwithinthedatabase? b)UseEnterpriseManagertoseewhatpasswordrestrictionsare enforcedbythedefaultprofile? c)UsingSQL SQL*Plus Plus,connecttothedatabaseassysdba andrunthe utlpwdmg.sql scriptlocatedin$ORACLE_HOME/rdbms/admin SQL>connect/assysdba SQL>@?/rdbms/admin/utlpwdmg.sql Functioncreated. Profilealtered. d)UsingEnterpriseManager,viewthechangesmadetothedefault profile f l b bythe h utlpwdmg.sql script.Notethat: h - Passwords now expire every 60 days. - If a user doesnt change his or her password within 10 days of expiration, the account will be locked. - Passwords may not be reused within 1800 days. - After a user fails to provide the correct password within three consecutive login attempts the account will automatically lock for one minute. 2.Editthedefaultprofilesothatuserswhofailtologincorrectlyfourtimesin arowwillhavetheiraccountslockedfor10minutes.

Practice111Overview:DatabaseSecurity(Part1)(continued) 3.ExempttheHRuserfromforcedpasswordchanges. a)CreateanewprofilecalledHRPROFILEusingthedefaultprofileasa template. b)Editthenewprofiletomakepasswordexpirationunlimited. c)AssignuserHRtothenewprofile. d)IfyouweretodroptheHRPROFILEwhatwouldhappentotheHR user? 1. Nothing would happen to the HR user. The drop statement would fail b because the h HRPROFILE cannot be b dropped d d while hil a user is i assigned to it. 2. The HR user would also be dropped. 3. The HRPROFILE would be dropped and the HR user would be unable to log in until the administrator assigned a different profile. 4. The HR user would be automatically y assigned g the DEFAULT profile. 4.Auditunsuccessfulattemptstoconnecttothedatabase a)Enablecollectionofauditinformation.Storetheauditinformationin thedatabase. b)Begincollectingauditrecordsforuserswhounsuccessfullyattempt tologin. c)Verifythatunsuccessfulattemptstoconnecttothedatabaseare captured. d)Whydidyouhavetorestarttheinstanceafterchangingthe AUDIT_TRAIL initializationparameter? e)WhatwouldhavehappenedifyouhadleftAUDIT_TRAIL atits defaultsettingofNONE?

Practice112:DatabaseSecurity(Part2) Background Yoususpectthatsomeonehasbeenviewingandpossiblychangingemployeesalary datawithoutproperpermission.Configureyourdatabasetodetectunauthorizedaccess tosalarydataandcaptureanychangestosalaryinformation. Tasks AuditselectontheSALARY columnoftheEMPLOYEES table AuditchangestotheSALARY columnoftheEMPLOYEES table. Capture oldvalue newvalue which hi husermade d the h change h what h location l i the h change h was madefrom. 1.Auditselectonthesalary columnoftheemployees table.Becausewe onlywanttocaptureauditinformationifsomeoneselectsthesalarycolumnwe mustusefinegrainedauditingratherthanstandarddatabaseauditing. Note:isusedtocontinueastatementonanewlineinPL/SQL / Q a)UsetheDBMS_FGApackagetoaddafinegrainedauditpolicytoHRs employees table.Onlycaptureauditinformationifsomeonereadsthe salary column. b)VerifythatonlySELECT statementsthatincludethesalary columngenerateanaudittrail. 2.Auditchangestothesalary columnoftheemployees table.Because youwanttocapturetheoldandnewvaluesratherthanjustthefactthata changehappened,youmustusevaluebasedauditingratherthanstandard databaseauditing.Rememberthatvaluebasedauditingisimplementedthrough theuseofdatabasetriggers. a)CreateatablecalledAUDIT_EMPLOYEES intheSYSTEM schema toholdinformationcapturedthroughdatabaseauditing.Makethetable astandard,heaporganizedtablewithfourcolumns: who varchar2(10) event_date date ipaddress varchar2(16) what varchar2(2000) b)Createatriggertocapturechangestothesalary column. Connectasusersystem Runthescript$HOME/LABS/hrsalarytrig.sql $HOME/LABS/hrsalarytrig sql SQL>connectsystem/manager@dba10g Connected. SQL>@$HOME/LABS/hrsalarytrig.sql TriggerCreated. c)Verifythatauditinformationaboutchangestothesalary column arenowcaptured.

OracleDatabase10g:Administration WorkshopI12299

OracleNetServices OracleNetservicesenablenetworkconnectionsfromaclientormiddletier applicationtotheOracleDatabaseServer.Afteranetworksessionisestablished, OracleNetactsasthedatacourierforboththeclientapplicationandthedatabase server.Itisresponsibleforestablishingandmaintainingtheconnectionbetween theclientapplicationanddatabaseserver,aswellasexchangingmessagesbetween them.OracleNet,orsomethingthatsimulatesOracleNetsuchasJavaDatabase Connectivity(JDBC),islocatedoneachcomputerthatneedstotalktothedatabase server. Ontheclientmachine,OracleNetisabackgroundcomponentaccessedby whateverapplicationneedstoconnecttothedatabase(SQL*Plus,OracleForms, OracleDiscovererandmanyothers).TheuserneverseesOracleNet,justthe applicationthatisusingit. Onthedatabaseserver,OracleNetincludesanactiveprocesscalledthelistener. p forcoordinating gconnectionsbetweenthe TheOracleNetlistenerisresponsible databaseandexternalapplications.Withoutthelistener,externalconnectionsto thedatabasearenotpossible. WhilethemostcommonuseofOracleNetistoallowincomingdatabase connections,servicesalsocanbeconfiguredtoallowaccesstoexternalcode librariesandprocedures(EXTPROC)andtoconnecttheOracleinstancetonon OracledatasourcessuchasSybase,Informix,DB2,andSQLServerthroughOracle g services. Heterogeneous

OracleDatabase10g:Administration WorkshopI12300

OracleNetListener TheOracleNetlisteneristhegatewaytotheOracleinstanceforallnonlocaluser connections.Asinglelistenercanservicemultipledatabaseinstancesand thousandsofclientconnections. TheOracleNetlisteneriscontrolledbyDatabaseControlorbythelsnrctl commandlineutility.ListenersareconfiguredusingDatabaseControl.Forthe server,DatabaseControlcontrolstheconfigurationoftheactuallisteneraswellas generalparameterssuchaspasswordprotectionandlogfilelocations. locations AdvancedadministratorscanalsoconfigureOracleNetservicesbymanuallyediting theconfigurationfileswithatexteditorsuchasVi,gedit,orNotepadifnecessary.

OracleDatabase10g:Administration WorkshopI12301

MonitoringtheListener SelectingtheListenerlinkfromtheEnterpriseManagerhomepagetakesyoutothe listenerstatuspage. Fromthispageyoucansee: ThelistenerversionandORACLE_HOME Thefirstlisteningaddressforthelistener Thelocationoftheconfigurationfilesusedtostartthelistener Theavailabilityofthelistenerandwhenitwasstarted Thelistenerresponsetime:TNSPing(ms) Averagenumberofconnectionsrefused/establishedperminute Clickingthelinksforavailability,responsetime,orconnectionsperminutetakes youtodetailedinformationaboutthosemetrics.

OracleDatabase10g:Administration WorkshopI12302

CreatingaListener Eachlistenermusthaveatleastonelisteninglocation.Inthedetailpaneclickthe AddAddressbuttontocreatealisteninglocation.Selectthenetworkprotocol. TCP/IPismostcommonlyusedandisthedefault.OtherchoicesareInternalProcess Communication(IPC)normallyusedforconnectingtolocalapplications(resident onthedatabaseserver)orexternalcodelibraries(EXTPROC),NamedPipes(NMP) andTCP/IPwithSSL.EnterthenameorIPaddressoftheserverthelistenerwillbe runningon on,andtheportyouwantthelistenertomonitor. monitor OracleNet Nets sdefaultport is1521.Ifyouchoosetouseaportotherthan1521,additionalconfigurationis requiredforthelistenerorfortheinstance. Allotherconfigurationstepsareoptionalforthelistener.Theonlyrequired configurationisthelisteninglocation.SelectFilethenSaveNetworkConfiguration fromthemenu. TocreateanOracleNetlistener,selectNetServicesAdministrationfromtheRelated Linkssectionofthelistenerpropertiespage. 1. ChooseListenersfromtheAdministerdropdownboxand clickgo. 2. ClickCreate 3. Enteralistenername.Thenamemustbeuniqueforthis server. 4. Addalisteningaddress.

OracleDatabase10g:Administration WorkshopI12303

ListeningAddresses Eachlistenermusthaveatleastonelisteningaddress. 5. Selectthenetworkprotocol.TCP/IPismostcommonlyused andisthedefault. Note: TheNMPandEXTPROCprotocolsareconfiguredusingtheOther Servicestab. 6. EnterthenameorIPaddressoftheserverthelistenerwillbe runningon on,andtheportyouwishthelistenertomonitor monitor.OracleNet Nets s defaultportis1521.Ifyouchoosetouseaportotherthan1521,additional configurationisrequiredforthelistenerorfortheinstance. 7. EnterthenameorIPaddressoftheserverthelistenerwill runon. 8. Allotherconfigurationstepsareoptionalforthelistener.Click OKtosavetheaddress.Theonlyrequiredconfigurationisthelistening addressandname.ClickOKtosaveyourchanges. 9. Tostartthenewlistener,selectStart/StopfromtheActions dropdownlistandclickGo.

OracleDatabase10g:Administration WorkshopI12304

ConfiguringOptionalParameters Althoughonlyanaddressisrequiredforalistener,youcanalsoconfigureoptional parameters: Logging:DoyouwanttokeepalogofOracleNetconnectionsandifso, wheredoyouwantthelogfilestored? Tracing:DoyouwanttokeepdetailedinformationabouteachOracleNet connection?Ifso,howmuchinformationdoyouwanttocollect(Trace Level)andwheredoyouwantthetracefilesstored?

OracleDatabase10g:Administration WorkshopI12305

StaticDatabaseRegistration Foralistenertoforwardclientconnectionstoaninstance,thelistenermustknow thenameoftheinstanceandwheretheinstancesORACLE_HOME islocated.The listenercanfindthisinformationintwoways: Dynamicserviceregistration:Oracle8i,Oracle9i,andOracleDatabase10g instancesautomaticallyregisterwiththedefaultlistenerondatabase startup.Noadditionallistenerconfigurationisrequiredforthedefault listener. Staticserviceregistration:OlderreleasesoftheOracleDatabasedonot automaticallyregisterwiththelistenerandthereforerequirethatthe listenerconfigurationfilecontainalistofalldatabaseservicesthelistener willserve.Youmaystillchoosetousestaticserviceregistrationwithnewer releasesif: Yourlistenerisnotonthedefaultportof1521andyoudonotwish toconfigureyourinstancetoregisterwithanondefaultport. port Yourapplicationrequiresstaticserviceregistration. Toaddastaticdatabaseservice,selectStaticDatabaseRegistrationfromtheEdit ListenerpageandclicktheAddDatabasebutton.Entertheservicename(sameas theglobaldatabasename<DB_NAME>.<DB_DOMAIN>),ORACLE_HOME path, andSID(sameastheinstancename).ClickOK.Youwillhavetorestartyourlistener forthechangestotakeeffect.

OracleDatabase10g:Administration WorkshopI12306

ControllingtheListener Thelistenercontrolutilityenablesyoutocontrolthelistener.Withlsnrctl you can: Startthelistener Stopthelistener Checkthestatusofthelistener Checkthestatusoflistenerservices Reinitializethelistenerfromtheconfigurationfileparameters Dynamicallyconfiguremanylistener Changethelistenerpassword Thebasiccommandsyntaxforthisutilityisasfollows: LSNRCTL>command [listener_name] Whenalsnrctl commandisissued,thecommandactsonthedefaultlistener listenerunlessadifferentlistenernameisspecifiedortheSET LISTENER commandisexecuted.IfthelistenernameisLISTENER,thelistener_name argumentcanbeomitted. Validcommandsforlsnrctl areshownintheslideabove.

OracleDatabase10g:Administration WorkshopI12307

ListenerControlUtilitySyntax lsnrctl commandscanbeissuedfromwithintheutility(promptsyntax)orthe commandline.Thefollowingtwocommandshavetheidenticaleffect.First,using thecommandlinesyntax: #lsnrctlstart Thenusingthepromptsyntax: #lsnrctl LSNRCTLforLinux:Version10.1.0.1.0 10 1 0 1 0on05NOV2003 Copyright(c)1991,2003,Oracle.Allrightsreserved. WelcometoLSNRCTL,type"help"forinformation. LSNRCTL>start Usually,commandlinesyntaxisusedtoexecuteoneofforscriptedcommands.If youplantoexecuteseveralconsecutivelsnrctl commands,thepromptsyntaxis mostefficient.Noticethatthelistener_name argumentwasomitted,sothe stopcommandwouldaffectthelistenernamedLISTENER.Promptsyntaxmustbe usedifyourlistenerispasswordprotected.

OracleDatabase10g:Administration WorkshopI12308

ListenerControlUtilitySyntax(continued) RememberthatifyourlistenerisnamedsomethingotherthanLISTENER,youmust eitherincludethelistenernamewiththecommandorusetheSET CURRENT LISTENER command.SupposeyourlistenerwasnamedBACKUP.Using CURRENT_LISTENER promptsyntax: LSNRCTL>stopbackup Connectingto (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=rhel)(PORT=5 521))) Thecommandcompletedsuccessfully The h above b produces d the h sameresults l asfollows: f ll LSNRCTL>setcurbackup CurrentListenerisbackup LSNRCTL>stop Connectingto (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=rhel)(PORT=5 521))) ))) Thecommandcompletedsuccessfully Note:Intheabovesyntax,thecurrent_listener canbeabbreviatedascur. Youcanalsoachievethesameresultswithcommandlinesyntax: /home/oracle>lsnrctlstopbackup LSNRCTLforLinux:Version10.1.0.1.0on05NOV200315:19:33 Copyright(c)1991,2003,Oracle.Allrightsreserved. C Connecting ti to t (DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=rhel)(PORT=5 521))) Thecommandcompletedsuccessfully Whichsyntaxyouuseispurelyamatterofchoiceandconvenience.

OracleDatabase10g:Administration WorkshopI12309

MonitoringwithListenerControl Thelsnrctl servicescommandprovidesthestatusofeveryOracleNetService thelistenerishandling,bothstaticanddynamic.Outputincludesthe: Nameoftheservice Statusoftheservice(staticserviceswillshowstatusofUNKNOWN) Numberofconnectionsestablishedorrefusedfordedicatedandshared connections(sharedserverconnectionswillbediscussedinalaterlesson)

OracleDatabase10g:Administration WorkshopI12310

MonitoringwithListenerControl(continued) Thelistenercontrolstatuscommandreturnsdetailedinformationaboutthelistenerand summaryinformationaboutallservicesthelistenerishandling. LSNRCTL> SET PASSWORD Password: d The command completed successfully LSNRCTL> STATUS Connecting to (DESCRIPTION=(ADDRESS=(PROTOCOL=IPC)(KEY=EXTPROC))) STATUS of the LISTENER -----------------------Alias LISTENER Version TNSLSNR for Linux: Version 10.1.0.1.0 - Beta Start Date 05-NOV-2003 15:48:08 Uptime 0 days 16 hr. 40 min. 2 sec Trace Level off Security ON: Local OS Authentication SNMP OFF Listener Parameter File /oracle/product/ora10g/network/admin/listener.ora Listener Log File /oracle/product/ora10g/network/log/listener.log Listening Endpoints Summary... (DESCRIPTION=(ADDRESS=(PROTOCOL=ipc)(KEY=EXTPROC))) (DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=rhel)(PORT=1 521))) Services Summary... Service "dba10g" has 2 instance(s). Instance "dba10g", status READY, has 1 handler(s) for this service... Instance "dba10g", status UNKNOWN, has 1 handler(s) for this service... Service "rhel" has 1 instance(s). Instance "dba10g", status READY, has 1 handler(s) for this service... The command completed successfully Statusinformationincludes: Listenernameandversion Whenthelistenerwasstartedandhowlongithasbeenup Locationofconfigurationandlogfiles Tracelevelandsecuritystatus Listeneraddressinformationincludinghost,port,andprotocolsserviced Summaryinformationabouteachservicethelistenerishandling.Statusinformation forstaticallyregisteredserviceswilldisplayasUNKNOWN.Asyoucanseeabove, aninstancecanhavemultipleservicenames(instancedba10g isalso answeringtorhel)

OracleDatabase10g:Administration WorkshopI12311

OracleNetConnections InorderforanapplicationtoconnecttoaservicethroughanOracleNetlistener, theapplicationmustknowinformationaboutthatservice,includingtheaddressor hostwherethelistenerresides,theprotocolthelistenerwillaccept,andwhichport thelistenerismonitoring.Afterthelistenerislocated,thefinalpieceofinformation theapplicationneedsisthenameoftheserviceitwantstoconnectto. TheprocessofdeterminingthisconnectioninformationiscalledNamesResolution.

OracleDatabase10g:Administration WorkshopI12312

NamesResolution EasyConnect,localnaming,anddirectorynamingarediscussedinthefollowing pages.ExternalnamingusesthirdpartynamingservicessuchasNetwork InformationServices(NIS),DistributedComputingEnvironment(DCE),orCell DirectoryServices(CDS).Conceptually,externalnamingisverysimilartodirectory naming.

OracleDatabase10g:Administration WorkshopI12313

EasyConnect WithEasyConnecttheusersuppliesallinformationrequiredfortheOracleNet connectionaspartoftheconnectstring.EasyConnectconnectionstringstakethe formof: <username>/<password>@<hostname>:<listener port>/<service name> Thelistenerportandservicenameareoptional.Ifthelistenerportisnotprovided, thenOracleNetassumesthedefaultportof1521isbeingused used.Iftheservicename isnotprovidedOracleNetassumesthedatabaseservicenameandhostname providedintheconnectstringareidentical. AssumingthelistenerwasusingtheTCPprotocoltolistenonport1521and instanceparametersSERVICE_NAMES=db,DB_DOMAIN=us.oracle.com, theconnectstringshownintheslideabovecouldbeshortenedto: SQL> connect hr/hr@db.us.oracle.com Note: TheSERVICE_NAMES initializationparametercanacceptmultiplecomma separatedvalues.Onlyoneofthosevaluesneedstobedb forthisscenariotowork.

OracleDatabase10g:Administration WorkshopI12314

LocalNaming Withlocalnaming,theusersuppliesanaliasfortheOracleNetservice.OracleNet checksthealiasagainstalocallistofknownservicesandifitfindsamatch,converts thealiasintohost,protocol,port,andservicename. Oneadvantageoflocalnamingisthatthedatabaseusersonlyneedtoremembera shortaliasratherthanthelongconnectstringrequiredbyEasyConnect. Thelocallistofknownservicesisstoredininthetextconfigurationfile $ORACLE HOME/network/admin/tnsnames ora. $ORACLE_HOME/network/admin/tnsnames.ora LocalnamingisappropriatefororganizationswhereOracleNetservice configurationsdonotchangeoften.

OracleDatabase10g:Administration WorkshopI12315

DirectoryNaming Withdirectorynaming,theusersuppliesanaliasfortheOracleNetservice.Oracle Netchecksthealiasagainstanexternallistofknownservicesandifitfindsamatch, convertsthealiasintohost,protocol,port,andservicename. Likelocalnaming,databaseusersonlyneedtorememberashortaliasratherthan thelongconnectstringrequiredbyEasyConnect. Oneadvantageofdirectorynamingisthatassoonasanewservicenameisadded totheLDAPdirectory directory,theservicenameisavailableforuserstoconnectwith. with With localnamingtheDBAmustfirstdistributeupdatedtnsnames.ora files containingthechangedservicenameinformationbeforeuserscanconnecttonew ormodifiedservices. DirectorynamingisappropriatefororganizationswhereOracleNetservice configurationschangefrequently.

OracleDatabase10g:Administration WorkshopI12316

ConfiguringServiceAliases TocreatealocalOracleNetservicealias,selectLocalNamingfromtheAdminister dropdownlistandclickGo,andthenclickCreate. Toconfigureservicealiasesfordirectorynaming,selectDirectoryNaminginsteadof LocalNaming. Note: Ifdirectorynaminghasnotalreadybeenconfigured,thenyoucannotselect theDirectoryNamingoption.DirectoryNamingisdiscussedintheOracleEnterprise IdentityManagement courseaswellastheOracleAdvancedSecurity Administrationmanual. IntheCreateNetServiceNamepage,enterauniquenameintheNetServiceName field(thisisthenameuserswillenterwhentheywanttousethisalias).Enterthe servicenameorSIDofthedatabaseyouwanttoconnectto,andclicktheAdd buttontoentertheaddressfortheservicename. Fortheaddress,entertheprotocol,port,andhostusedbythelistenerforthe serviceyouwanttoconnectto.

OracleDatabase10g:Administration WorkshopI12317

AdvancedConnectionOptions Withadvancedconnectionoptions,OracleNetcantakeadvantageoflistener failoverandloadbalancing,aswellasOracleConnectionManagersourcerouting. Withconnecttimefailoverenabled,thealiashastwoormorelisteneraddresses listed.Ifthefirstaddressisnotavailable,thesecondisthentried.OracleNetwill keeptryingaddressesinorderuntilitreachesalistenerthatisfunctioningoruntil alladdresseshavebeentriedandfailed. Withloadbalancingenabled, enabled OracleNetpicksanaddressatrandomfromthelistof addresses.InaRealApplicationClusterthisbalancestheworkloadacrossmultiple instancesofthesamedatabase. SourceroutingisusedwithOracleConnectionManager.OracleConnection ManagerservesasaproxyserverforOracleNettraffic,enablingOracleNettraffic toberoutedsecurelythroughafirewall.OracleNettreatstheaddressesasalistof relays,connectingtothefirstaddressandthenrequestingtobepassedfromthe firsttotheseconduntilthedestinationisreached.Itdiffersfromfailoverorload balancinginthatalladdressesareusedeachtimeaconnectionismade.Formore informationonOracleConnectionManagerpleaserefertoChapter11oftheOracle NetServicesAdministrator guide.

OracleDatabase10g:Administration WorkshopI12318

AdvancedConnectionOptions(continued) Note that there are five choices for connect-time failover and load balancing. The five options translate to:

Option Try each address, in order, until one succeeds Try each address, randomly, until one succeeds Try one address, selected at random Use each address in order until destination reached Use only the first address

Advanced Functionality Failover Failover Load balancing Load balancing Source routing None

OracleDatabase10g:Administration WorkshopI12319

OracleNetManager EnterpriseManagerDatabaseControlconfigurestheserversideofOracleNet,but doesnothelpwithclientormiddletierconfiguration.TheOracleNetManagerisa graphicaltoolprimarilyusedtoconfigureclientsideOracleNetconnections including: OracleNetservicenames OracleNetprofiles Security Troubleshooting(loggingandtracing) Namesresolutionmethods TheOracleNetManagercanalsobeusedtocreateandconfigureOracleNet listeners,andtoconfigureLightweightDirectoryAccessProtocol(LDAP)service nameresolution. TostartOracleNetManager,runnetmgr fromacommandprompt.Whenyou openOracleNetManager,youwillseeanavigationtreeontheleft,andadetail windowontheright.Youcandrilldownintoeachnodeinthetreestructureusing theexpand/contractsymbol(+/)nexttothenodeyouwanttoconfigure.

OracleDatabase10g:Administration WorkshopI12320

ChoosingNamingMethods Thedefaultnamesresolutionmethodsarelocalnaming(TNSNAMES),Easy Connect(EZCONNECT)andhostnaming(adeprecatedpredecessortoEasy Connect). Withtheconfigurationshownabove,OracleNetfirstexaminesthelocalnames resolutionfile,attemptstouseEasyConnect,checksthedirectoryserver,andfinally attemptstousehostnaminguntiliteitherfindsamatchfortheusersupplied connectstringorfails. fails IfyouwantdirectorynamingtobecheckedbeforeEasy Connect,thenselectLDAPandclickthePromotebutton.

OracleDatabase10g:Administration WorkshopI12321

ConfiguringServiceAliaseswithNetManager YoucanalsouseOracleNetManagertoaddOracleNetServicealiasestothelocal namingordirectorynamingrepository.Forlocalnaming,expandtheLocalnode andselectServiceNamesfromthetreestructure.Thenclicktheplus(+)icon(upper left)orusethemenubyselectingEditandthenCreate.Thisopensaconfiguration wizardwhereyoufirstchoosethealiasname,thentheprotocol,thentheaddress andport,andfinallytheactualservicenamethatthelistenerishandling. Toconfigureservicealiasesfordirectorynaming naming,expandtheDirectorynoderather thantheLocalnode. Afteryouraliashasbeencreatedyoucantesttheconnection.UnlikeDatabase Control,OracleNetManagerattemptstoconnecttotheservicewiththeusername SCOTT usingapasswordofTIGER.YoumustclicktheChangeLoginbuttonand supplythecorrectusernameandpassword.

OracleDatabase10g:Administration WorkshopI12322

AdvancedConnectionOptionsUsingOracleNetManager LikeDatabaseControl,OracleNetManagerallowsyoutoselectadvanced connectionoptionssuchaslistenerfailoverandloadbalancing,aswellasOracle ConnectionManagersourcerouting.

Option Try each address, in order, until one succeeds Try each address, randomly, until one succeeds Try one address, selected at random Use each address in order until d i i reached destination h d Use only the first address
OracleDatabase10g:Administration WorkshopI12323

Advanced Functionality Failover Failover Load balancing Load balancing Source routing None

TestingOracleNetConnectivity tnsping istheOracleNetequivalentoftheTCP/IPpingutility.Itoffersaquick testtoverifythatthenetworkpath(includingportandprotocol)toadestinationis good.


# tnsping db.us.oracle.com:1521/dba10g TNS Ping Utility for Linux: Version 10.1.0.1.0 - Production on 06-NOV-20 Copyright (c) 1997, 2003, Oracle. All rights reserved. Used parameter files: /oracle/prodouct/ora10g/network/admin/sqlnet.ora Used EZCONNECT adapter to resolve the alias Attempting to contact (DESCRIPTION=(CONNECT_DATA=(SERVICE_NAME=dba10g)) (ADDRESS=(PROTOCOL=TCP)(HOST=192.168.2.61)(PORT=1521))) OK (380 msec)

Theutilityvalidatesthatthehostname,port,andprotocolreachalistener.Itdoes notactuallycheckthatthelistenerhandlestheservicename.Oneotheruseful thingthattnsping revealsisthelocationoftheconfigurationfiles.Inasystem withmultipleORACLE_HOME locations,thiscanbehelpful.

OracleDatabase10g:Administration WorkshopI12324

OracleDatabase10g:Administration WorkshopI12325

OracleDatabase10g:Administration WorkshopI12326

Practice12:OracleNetServices Background:Usersneedtoconnecttoyourdatabase.Workwiththemtoallow connectionsusingseveraldifferentmethods.Ensurethatuserscanuseconnecttime failovertotakeadvantageofabackuplistener. listener Tasks: Createabackuplistenertosupportconnecttimefailover Modifyyourlocalnameresolutionfilesoyoucanconnecttoanotherdatabase Modifyyourlocalnameresolutionfilesothatusersfailovertothebackup listeneriftheprimaryisunavailable 1. Createabackuplistenertosupportconnecttimefailover. Namethe h newlistener l BACKUP. UseTCP/IPprotocolonport1561. UsestaticregistrationtoregisteryourORCLdatabasewiththenew listener. Startthenewlistener. 2. Modifyyourlocalnameresolutionfilesothatyoucanconnectto anotherdatabase.Testy yourchanges g tothenetworkconfiguration g using g SQL*PlusoriSQL*Plus. 3. Modifyyourlocalnameresolutionfilesothatyoufailovertothe backuplisteneriftheprimarylistenerisunavailable.Testyourchangesby shuttingdownthedefaultlistenerandverifyingthatyoucannowconnect throughthebackuplistener.

OracleDatabase10g:Administration WorkshopI12327

OracleDatabase10g: Administration WorkshopI13329

EstablishingaConnection AfterOracleNetnamesresolutioniscomplete,aconnectionrequestispassedfromthe userormiddletierapplication(referredtoastheuserprocessfromhereon)tothe OracleNetListener.ThelistenerreceivesaCONNECT packetandcheckstoseewhether thatCONNECT packetisrequestingavalidOracleNetservicename. Iftheservicenameisnotrequested(asinthecaseofaTNSPING request),thelistener acknowledgestheconnectrequestanddoesnothingelse.Ifaninvalidservicenameis requested,thelistenertransmitsanerrorcodetotheuserprocess.

OracleDatabase10g: Administration WorkshopI13330

DedicatedServerProcess IftheCONNECT packetrequestsavalidservicename,thelistenerspawnsanewprocess todealwiththeconnection.Thisnewprocessisknownastheserverprocessandis sometimesalsoreferredtoastheshadowprocess.Aftertheprocesshasbeen spawned,thelistenerconnectstotheprocessandpassesitinitializationinformation, includingtheaddressinformationfortheuserprocess.Atthispointthelistenernolonger dealswiththeconnectionandallworkishandedofftotheserverprocess. TheserverprocessnowtransmitsaRESEND packetbacktotheuserprocess.

OracleDatabase10g: Administration WorkshopI13331

UserSessions After f the h usersessionreceivesthe h RESEND packet, k itretransmitsthe h CONNECT packet.Theserverprocesscheckstheusersauthenticationcredentials(usuallya password)andifthecredentialsarevalid,ausersessioniscreated. Dedicatedserverprocess:Withthesessionestablished,theserverprocessnowacts astheusersagentontheserver.Theserverprocessisresponsiblefor: ParsingandrunninganySQLstatementsissuedthroughtheapplication CheckingthedatabasebuffercachefordatablocksrequiredtoperformSQL statements Readingnecessarydatablocksfromdatafilesondiskintothedatabase buffercacheportionoftheSGA,iftheblocksarenotalreadypresentinthe SGA Managingallsortactivity.AportionoftheserverprocesscalledtheProgram GlobalArea(PGA)containsamemoryareaknownastheSortAreathatis used dto t work kwith ithsorting. ti Returningresultstotheuserprocessinsuchawaythattheapplicationcan processtheinformation Serverprocessesalsoreservememoryforspecializedworksuchasbitmapandhash joins.Theamountofmemoryconsumedbythededicatedserverprocessdepends onseveralinitializationparametersettings.Itcanbeautomaticallycontrolled g theuseofPGA_AGGREGATE_TARGET andWORKAREA_SIZE_POLICY through orfinedtunedifneededforadvanceduse.

OracleDatabase10g: Administration WorkshopI13332

UserSessions:DedicatedServer Withdedicatedserverprocessesthereisaonetooneratiobetweenserverprocesses anduserprocesses.EachserverprocessconsumessystemresourcesincludingCPUcycles andmemory. Inaheavilyloadedsystem,thememoryandCPUresourcesconsumedbydedicated serverprocessescanbeprohibitiveandnegativelyaffectthesystemsscalability.Ifyour systemisbeingnegativelyimpactedbytheresourcedemandsofthededicatedserver architectureyouhavetwooptions: IncreasesystemresourcesbyaddingmorememoryandadditionalCPUcapability. UsetheOracleSharedServerarchitecture. architecture

OracleDatabase10g: Administration WorkshopI13333

UserSessions:SharedServers EachservicethatparticipatesintheSharedServerarchitecturehasatleastone(and usuallymore)dispatcherprocess.Whenaconnectionrequestarrives,thelistenerdoes notspawnadedicatedserverprocess.Instead,thelistenermaintainsalistofdispatchers availableforeachservicename,alongwiththeconnectionload(numberofconcurrent connections)foreachdispatcher. Connectionrequestsareroutedtothelightestloadeddispatcherthatisservicingagiven servicename.Usersremainconnectedtothesamedispatcherforthedurationofa session. Unlikededicatedserverprocesses, processes asingledispatchercanmanagehundredsofuser sessions. Dispatchersdonotactuallyhandletheworkofuserrequests.Insteadtheypassuser requeststoacommonqueuelocatedinthesharedpoolportionoftheSGA. SharedServerprocessestakeovermostoftheworkofdedicatedserverprocesses, pullingrequestsfromthequeueandprocessingthemuntilcomplete. Becauseasingleusersessionmayhaverequestsprocessedbymultiplesharedserver processes,mostofthememorystructuresusuallystoredintheProgramGlobalArea (PGA)mustbeinasharedmemorylocation.InaSharedServerarchitecture,mostof thesememoryareasarestoredinthelargepoolportionoftheSGA.

OracleDatabase10g: Administration WorkshopI13334

ProcessingaRequest WhenauserconnectsthroughtheSharedServerarchitecturesubmitsadatabase request: 1.Theuserprocessforwardstherequesttoitsdispatcher. 2.ThedispatcherplacestherequestintothecommonrequestqueueintheSGA. 3.Thenextavailablesharedserverpicksuptherequestfromtherequestqueue andprocessestherequest. 4.Thesharedserverplacestheresponseonthecallingdispatchersresponse queue.Eachdispatcherhasitsownresponsequeue. 5 Thedispatcherretrievestheresponsefromitsresponsequeue. 5. queue 6.Thedispatcherreturnstheresponsetotheuser. Aftertheusercallhasbeencompleted,thesharedserverprocessisreleasedandis availabletoserviceanotherusercallintherequestqueue. RequestQueue Onerequestqueueissharedbyalldispatchers. Sharedserversmonitortherequestqueuefornewrequests. Requestsareprocessed donafirst f in,first f out(FIFO) ( )basis. b There h isnopriority setting.

OracleDatabase10g: Administration WorkshopI13335

TheSGAandPGA ThecontentsoftheSystemGlobalArea(SGA)andtheProgramGlobalArea(PGA)differ whendedicatedserversorsharedserversareused. TextandparsedformsofallSQLstatementsarestoredintheSGA. ThecursorstatecontainsruntimememoryvaluesfortheSQLstatement,suchas rowsretrieved. Usersessiondataincludessecurityandresourceusageinformation. Thestackspacecontainslocalvariablesfortheprocess. Technical Note ThechangeintheSGAandPGAistransparenttotheuser;however, however ifsupportingmultiple users,youneedtoincreasetheLARGE_POOL_SIZE.Eachsharedserverprocessneeds toaccessthedataspacesofallsessionssothatanyservercanhandlerequestsfromany session.SpaceisallocatedintheSGAforeachsessionsdataspace.Youcanlimitthe amountofspacethatasessioncanallocatebysettingthePRIVATE_SGA resourcelimit intheDatabaseServicesregionoftheGeneralpageoftheusersprofile.

OracleDatabase10g: Administration WorkshopI13336

ConfiguringOracleSharedServer ToconfigureOracleSharedServer,youmustedittheinitializationparametersforyour instance.Mostoftheoptionalparametershavesensibledefaults.Onmanysystems,the onlyparameterthatmustbeconfiguredisDISPATCHERS. Dependingontheoptionsselectedwhenyoucreatedyourdatabase,theDISPATCHERS parametermayalreadybeconfiguredtostartonedispatchertoservicetheXML database.TheDISPATCHERS parameteracceptsmultiplesetsofvaluesintheformat: <parametersforfirstset>,<parametersforsecondset>

OracleDatabase10g: Administration WorkshopI13337

DISPATCHERS TheDISPATCHERS parameterenablesvariousattributesforeachdispatcher. OracleDatabase10g supportsanamevaluesyntax(similartothesyntaxusedbyOracle NetServices)toenablethespecificationofexistingandadditionalattributesinaposition independent,noncasesensitivemanner. Forexample:DISPATCHERS = (PROTOCOL=TCP)(DISPATCHERS=3) Parameter Type Parameter class: String (Specify as a quoted string) Dynamic

Default value: Null (no dispatchers will becan started) Although thenumberof connections adispatcher handlevariesgreatlydependingon thetypeofworkload,agoodmeasuretouseistoallowonedispatcherpereveryfifty concurrentdatabaseconnectionsthatusethesharedserverarchitecture.

OracleDatabase10g: Administration WorkshopI13338

DISPATCHERS (continued) TheonlyrequireddispatcherattributeisPROTCOL.Allothersareoptional.Afewofthe possibleargumentsfortheDISPATCHERS parameteraredescribedbelow.Noticethat argumentsuseathreeletterabbreviationinsteadofthefullargumentname. name Attribute PROTOCOL (PRO or PROT) DISPATCHERS (DIS or DISP) SERVICE (SER or SERV) LISTENER (LIS or LIST) Description Specifies the network protocol for which the dispatcher generates a listening endpoint (usually TCP) The initial number of dispatchers to start (default is 1) The Oracle Net Service name the dispatcher registers with the listener. If not given, the dispatcher registers the values in SERVICE_NAMES.

Specifies S ifi an alias li name f for th the li listeners t with ith which hi h th the PMON process registers dispatcher information. Set the alias to a name which is resolved through a naming method. This attribute need only be specified if the listener is a local listener that uses a nondefault port (not 1521) and is not specified with the LOCAL_LISTENER parameter or the listener is on another node. SESSIONS The maximum number of network sessions for each dispatcher. (SES or SESS) The default is operating systemspecific. Most operating systems have a default of 16 K. Note: TherearemanymorepossibleattributesfortheDISPATCHERS parameter.Further CONNECTIONS Specifies the maximum number connections to detailsontheDISPATCHERS parameter canbe foundof innetwork theInitialization Parameters (CON or CONN) allow for each dispatcher. The default is operating system sectionintheOracleDatabaseReference f Manual. specific. For example, 1024 is the default for Sun Solaris and Windows.

OracleDatabase10g: Administration WorkshopI13339

SHARED_SERVERS SHARED_SERVERS specifiestheminimumnumberofserverprocessesthatthatwillbe retained.Settingthisparameterisnotusuallycriticalbecausetheinstancemonitorsthe CommonRequestQueueandwillstartadditionalsharedserversasneededtoservethe queue,andthendisposeofthemwhennolongerneeded. Parameter type Parameter class Default value Integer Dynamic 0 if DISPATCHERS is NULL NULL, 1 if DISPATCHERS is set

Range of values Operating system dependent Agood measuretouse istoretain oneshared serverforeverytwentyfiveconcurrent databaseconnectionsusingthesharedserverarchitecture.

OracleDatabase10g: Administration WorkshopI13340

MAX_SHARED_SERVERS MAX_SHARED_SERVERS specifiesthemaximumnumberofsharedserverprocesses thatwillbeallowedtorunsimultaneously.Thesettingisimportantbecausetheinstance automaticallycreatesadditionalsharedserverprocessesasneededtoservicethe commonrequestqueue. Parameter type Integer Parameter class Default value Range of values Dynamic None (unlimited) Operating system dependent

Estimating the Maximum Number of Shared Servers Ingeneral,setthisparameterforanappropriatenumberofsharedserverprocessesat timesofhighestactivity.Experimentwiththislimit,andmonitorsharedserversto determineanidealsettingforthisparameter.Tofindthemaximumnumbersofservers started(highwatermark),querytheV$SHARED_SERVER_MONITOR datadictionary view.

OracleDatabase10g: Administration WorkshopI13341

CIRCUITS Virtualcircuitsareuserconnectionstothedatabasethroughdispatchersandservers.The CIRCUITS parameterspecifiesthetotalnumberofvirtualcircuitsthatareavailablefor inboundandoutboundnetworksessions. Parameter type Parameter class Default value Integer Dynamic

g , then the value of If Oracle Shared Server is configured, CIRCUITS will match that of SESSIONS. Otherwise, the value is 0 Setthisparameteronly ifyou wanttolimitthetotalnumberofconnectionsuserscan makeviathesharedserverarchitecture.Thisparameterisofinterestbecauseitisoneof severalparametersthatcontributetothetotalSGArequirementsofaninstance.

OracleDatabase10g: Administration WorkshopI13342

SHARED_SERVER_SESSIONS Thisparametercontrolsthetotalnumberofsharedserversessionsopenconcurrentlyat anypointintime.Theuseofthisparameterallowsresourcesfordedicatedusersessions tobereserved. Parameter type Parameter class Default value Integer Dynamic None (unlimited)

OracleDatabase10g: Administration WorkshopI13343

RelatedParameters OtherparametersaffectedbyOracleSharedServerthatmayrequireadjustment: LARGE_POOL_SIZE specifiesthesizeinbytesofthelargepool.OracleShared Serverusesthelargepooltostoresessioninformationthatusuallyresidesinthe PGAinadedicateserversession. SESSIONS specifiesthemaximumnumberofsessionsthatcanbecreatedinthe system.ThismayneedtobeadjustedforOracleSharedServerbecauseyour systemcannowservicemoresessions. PROCESSES controlsthenumberofserversideprocesses. LOCAL LISTENER definestheportandprotocolusedbythelisteners. LOCAL_LISTENER listeners Ifyour listenerisnotusingTCP/IPonport1521,orifyouhavemultiplelisteners,you mustconfigureLOCAL_LISTENER sothedispatcherscanregisterwiththe listeners. IfyoudonotsetavalueforLARGE_POOL_SIZE,thenOracleusesthesharedpoolfor OracleSharedServerusersessionmemory.Thiscannegativelyimpacttheperformance ofPL/SQL,SQL,andotherservicesthatrelyonthesharedpool. Oracleallocatessomefixedamountofmemory(about10K)perconfiguredsessionfrom thesharedpool,evenifyouhaveconfiguredthelargepool.

OracleDatabase10g: Administration WorkshopI13344

VerifyingSharedServerSetup WhenusingOracleSharedServer,youshouldfirststartthelistener,thenthedatabase,so thatthedispatcherscanimmediatelyregisterwiththelistener.Ifyoulaterrestartthe listener,allowoneminuteforservicestoreregister.Toverifythatregistrationhastaken placeissuethefollowingcommand:


$ lsnrctl services Service "TEST" has 1 instance(s). Instance "TEST", status READY, has 3 handler(s) for this service. Handler(s): "DISPATCHER" established:1 refused:0 curr:0 max:1022 state:ready D001 <machine: db.us.oracle.com, pid: 8705> (ADDRESS=(PROTOCOL=tcp)(HOST=db.us.oracle.com)(PORT=35230)) "DISPATCHER" established:1 refused:0 curr:0 max:1022 state:ready D000 <machine: db.us.oracle.com, pid: 8703> (ADDRESS=(PROTOCOL=tcp)(HOST=db.us.oracle.com)(PORT=35229)) "DEDICATED" established:0 refused:0

OracleDatabase10g: Administration WorkshopI13345

VerifyingSharedServerSetup(continued) Verifythatyourconnectionsareusingsharedserversbymakingconnections,andthenquery theV$CIRCUIT viewtoshowoneentrypersharedserverconnection.Thisalsoverifiesthat thelistenerisperformingloadbalancingforincomingconnections. connections


SQL>select dispatcher, circuit, server, status from v$circuit; DISPATCH -------82890064 8288F9E4 8288FD24 CIRCUIT -------8257BA64 8257BBB0 8257BCFC SERVER -------8288F6A4 00 00 STATUS ---------------NORMAL NORMAL NORMAL

OracleDatabase10g: Administration WorkshopI13346

DataDictionaryViews V$CIRCUIT This view contains information about virtual circuits, which are user ser connections to the database through thro gh dispatchers and servers. Any shared server connection creates an entry in V$CIRCUIT. This view contains information on the shared server processes. This view provides information on the dispatcher processes. This view contains information for tuning the shared server processes. This view contains information on request and response queues. This view lists session information for each current session.

V$SHARED_SERVER V$DISPATCHER V$SHARED_SERVER_ MONITOR V$QUEUE V$SESSION

OracleDatabase10g: Administration WorkshopI13347

ChoosingaConnectionType OracleNetsdefaultconnectiontypeisthesharedserverconnection.Iftheinstancehas beenconfiguredforasharedserverandaconnectrequestdoesnotspecificallyaskfora dedicatedserver,theconnectiontypewillbeshared. TheOracleNetManagerallowstheconnectiontypetobespecifiedforbothlocalnaming anddirectorynaming.SelectthedesiredConnection Type fromdropdownlist.

OracleDatabase10g: Administration WorkshopI13348

WhenNottoUseSharedServer TheOracleSharedServerarchitectureisanefficientprocessandmemoryusemodel,but isnotappropriateforallconnections.Becauseofthecommonrequestqueue,andthe factthatmanyusersmayshareadispatcherresponsequeue,sharedserversdonot performwellwithoperationsthatmustdealwithlargesetsofdatasuchaswarehouse queriesorbatchprocessing. BackupandrecoverysessionsusingOracleRecoveryManager(discussedinlater chapters)alsodealwithverylargedatasetsandshouldmakeuseofdedicated connections. Manyadministrationtaskscannotorshouldnotbeperformedusingsharedserver connections.Theseincludestartupandshutdownoftheinstance,creatingtablespacesor datafiles,indexandtablemaintenance,analyzingstatistics,andmanyothertasks commonlyperformedbytheDBA.AllDBAsessionsshouldchoosededicatedservers.

OracleDatabase10g: Administration WorkshopI13349

OracleDatabase10g: Administration WorkshopI13350

OracleDatabase10g: Administration WorkshopI13351

Practice13:OracleSharedServer Background:Youvenoticedthatduringpeakloadtimes,yoursystemisperforming poorly.Afterinvestigating,youfindthatusersessionsareconsumingsomuchmemory that h yoursystemis i swapping i excessively. i l C Configure fi yoursystemtoreduce d the h amount ofmemoryconsumedbyusersessions. Tasks: Investigatetheimpactofdedicatedserverconnectionsonyoursystem Configureyoursystemtousesharedservers Investigatetheimpactofsharedserverconnectionsonyoursystem 1. Investigate g theimpact p ofdedicatedserverconnectionsony your system. a) Openfourterminalsessionsonyourserver. b) ChecktoseehowmanyOracleprocessesarerunning. c) InyourremainingthreeterminalsessionsstartSQL*Plussessions. VerifythatnoneofyourthreeSQL*Plussessionsisusingsharedservers. d)Yourdefaultservicenameisconfiguredtousededicatedserver processes.Note N t that th twith itheach hSQL*Plus SQL*Pl session i started, t t d t twonew processesarecreated.RememberthateachofyourSQL*Plussessions startstwo resourceconsumingprocesses.OneistheSQL*Plussession itself(whichwillnormallyconsumeresourcesontheclientormiddle tier),theotheristhededicatedserverprocess(whichconsumes resourcesontheserver). 2. Configureyoursystemtousesharedservers.UsetheTCP protocolandyoursystemsservice name. 3. Investigatetheimpactofsharedserverconnectionsonyour system. a) ExityourthreeSQL*Plussessions(leavethefourterminal sessionsopen;youwillneedthemlater). b) Createanewlocalnamingaliasthatusesthedefaultdatabase connection. connection c) OpenthreeSQL*Plussessionsusingthenewservicename. d) Verifythatyouareconnectedusingasharedserver(youwill probablyseeanextraconnectioninV$CIRCUIT becausetheEnterprise Managermonitoringprocessusuallylogsintothenewsharedserver systembeforeyoucan). e) ChecktoseehowmanyOracleprocessesarerunningnow.Note thatyourthreeSQL*Plussessionsstartedonlythreenewprocesses (thesearethethreeSQL*Plusprocesses).Allthreeoftheseareusually locatedontheclientmachineorapplicationserver,whichmeansthat thesethreenewsessionshavenotaddedany newprocessesonthe server.

OracleDatabase10g: Administration WorkshopI13352

OracleDatabase10g:Administration WorkshopI14355

PerformanceMonitoring ToadministerOracleDatabase10gandkeepitrunningsmoothly,thedatabase administratormustregularlymonitorperformancetolocatebottlenecksand correctproblemareas. TherearehundredsofperformancemeasurementstheDBAcanlookat,covering everythingfromnetworkperformancetodiskinput/outputspeedtothetimespent workingonindividualapplicationoperations.Theseperformancemeasurements arecommonlyreferredtoasdatabasemetrics. metrics

OracleDatabase10g:Administration WorkshopI14356

MonitoringMethodologies TheOracleDatabase10g supportsbothproactiveandreactivemonitoring.Reactive monitoringisaresponsetoaknownorreportedproblem.Youmaybegin monitoringperformancemetricsinreactiontousercomplaintsaboutresponse time,instancefailures,orerrorsfoundinthealertlog. Reactivemonitoringisinevitablynecessarysometimes,butyourgoalshouldbeto detectandrepairproblemsbeforetheyaffectsystemoperation.Fixingproblems beforetheyoccur occur,oratleastbeforetheyarewidelynoticed noticed,isaproactiveapproach tosystemmaintenance. OracleDatabase10g includesseveraltoolsthataidinproactivemonitoring.Twoof theseareservergeneratedalertsandtheAutomatedDatabaseDiagnosticMonitor (ADDM).Proactivemonitoringwillbecoveredinthenextlesson.

OracleDatabase10g:Administration WorkshopI14357

DatabaseandInstanceMetrics Therearehundredsofdifferentmeasurementpointsavailabletomonitoryour system. Thedatadictionaryprovidesinformationaboutspaceconsumptionandobject status. Realtimeperformancemetricscoveringmemoryusage,waitevents,input/output devicethroughput,andinstanceactivityareavailablethroughdynamic performanceviews, views alsoknownasv$ views. views OracleDatabasescanbeextremelylarge(terabytedatabasesarebecoming commonandexabytedatabasesarepossible).Withsuchlargedatasetsitiscritical thattheinstancelocatetheparticularpieceofdataauserislookingforinthemost efficientwaypossible.Theportionoftheinstancethatdecideshowtolookfordata isknownastheoptimizer. DatadistributionmetricsareusedtohelptheOracleDatabase10g optimizer choosethemostefficientwaytoretrievedata,andarethereforecommonly referredtoasoptimizerstatistics.

OracleDatabase10g:Administration WorkshopI14358

DatabaseandInstanceMetrics(continued) Optimizerstatisticsshowingdatadistributionforeachtableinclude: Numberofrows Averagerowlength Amountofemptyspacethatisallocatedtothetable Numberofrowsthatarechained(existingintwoormoredatablocksdueto longrowlengthorinefficientdatastoragesettings) Oneexampleofanoptimizerchoiceisbetweenafulltablescan(readingtheentire tabletofindaparticularrow)andanindexscan(lookingfortherowinanindexfirst, thengoingdirectlytothedatablockinthetablethatholdstherow).Forsmalltables,a f lltable full bl scani isusually ll moreefficient ffi i than h looking l ki through h hanindex i d for f data d and dlater l jumpingtothecorrectblock.Foralargetable(rememberthatlargecaneasilybe hundredsofmillionsofrows)anindexscanprobablymakesmuchmoresense.

OracleDatabase10g:Administration WorkshopI14359

DataDictionaryMetrics Oneofthemostimportantdatadictionarymetricsdealswithobjectstatus. DatabaseindexesandstoredproceduresbothneedtobeVALID tobeused. IndexescanbecomeUNUSABLE duetonormalmaintenanceoperationsontables. Indexescontainpointerstothephysicallocationofindividualrowsofdata.Ifthe DBAcausesthoserowstochangelocationthroughmaintenanceoperationssuchas theMOVE command,thepointersarenolongervalidandtheindexwillnotbe usableuntilitisrebuilt. rebuilt PL/SQLcodeobjectshaveanINVALID statusforseveralreasons.Ifthecode containsaprogrammingerror,thePL/SQLobjectwillnotcompilecorrectlyandwill bemarkedinvalid.Avalidprocedurecanbecome invalidifanobjecttheprocedure referenceschanges.Supposeaprocedurereferencesthesalary columnofthe employees table.Ifthecolumnprecisionischanged,orifthecolumnisdropped, thereisnoguaranteethattheprocedurethatworkedcorrectlyontheold table definitionwillstillrunonthenewtabledefinition. UnusableindexesalwaysrequireDBAinterventiontorestorethemtoavalidstate. InvalidPL/SQLobjectswillnormallyrecompileautomaticallythefirsttimetheyare called,butsometimesrequireDBAinterventionincaseswheretheautomatic recompilationfails.

OracleDatabase10g:Administration WorkshopI14360

InvalidandUnusableObjects IfyoufindPL/SQLobjectswithastatusofINVALID,thefirstquestionyouneedto answerishasthisobjectever beenVALID?Often,anapplicationdeveloper neglectstocleanupcodethatdoesnotwork.IfthePL/SQLobjectisinvalidbecause ofacodeerror,thenthereislittlethatcanbedoneuntilthaterrorisfixed.Ifthe procedurewasvalidatsometimeinthepastandhasrecentlybecomeinvalid,you havetwooptionstofixtheproblem: 1 1. Donothing. nothing MostPL/SQLobjectswillautomaticallyrecompile ifneededwhentheyarecalled.Userswillexperienceaslightdelaywhilethe objectsrecompile(inmostcasesthisdelayisnotevennoticeable). 2. Manuallyrecompiletheinvalidobject. InvalidPL/SQLobjectscanbemanuallyrecompiledusingEnterpriseManageror throughSQLcommands: ALTERPROCEDUREHR.updatesalaryCOMPILE; ManuallyrecompilingPL/SQLpackagesrequirestwosteps: ALTERPACKATEHR.maintainempCOMPILE; ALTERPACKATEHR.maintainempCOMPILEBODY;

OracleDatabase10g:Administration WorkshopI14361

InvalidandUnusableObjects(continued)

Unusableindexesaremadevalidbyrebuildingthemtorecalculatethepointers. Rebuildinganunusableindexrecreatestheindexinanewlocation,thendropsthe unusableindex.ThiscaneitherbedoneusingEnterpriseManagerorthroughSQL commands. ALTERINDEXHR.emp_empid_pkREBUILD; ALTERINDEXHR HR.emp_empid_pk emp empid pkREBUILDONLINE; ALTERINDEXHR.emailREBUILDTABLESPACEUSERS; IftheTABLESPACE clauseisleftout,theindexisrebuiltinthesametablespacewhere italreadyexists.TheREBUILD ONLINE clauseallowsuserstocontinueupdatingthe indexstablewhiletherebuildtakesplace(withouttheONLINE keywordusersmust waitfortherebuildtofinishbeforeperformingDMLontheaffectedtable).

EnterpriseManagerusesthereorganizeactiontorepairanUNUSABLE index. Note: Rebuildinganindexrequiresthatfreespacebeavailablefortherebuild.Verify thatthereissufficientspacebeforeattemptingtherebuild.EnterpriseManagerchecks spacerequirementsautomatically. ll

OracleDatabase10g:Administration WorkshopI14362

OptimizerStatistics Optimizerstatisticsfortablesandindexesarestoredinthedatadictionary.These statisticsarenotintendedtoproviderealtimedata.Theyprovidetheoptimizera statistically correctsnapshotofdatastorageanddistributionwhichtheoptimizer usestomakedecisionsonhowtoaccessdata. Metricscollectedinclude: Sizeofthetableorindexindatabaseblocks Numberofrows Averagerowsizeandchaincount(tablesonly) Heightandnumberofdeletedleafrows(indexesonly) Asdataisinserted,deleted,andmodifiedthesevalueschange.Theperformance impactofmaintainingrealtimedatadistributionstatisticswouldbeprohibitive,so thesestatisticsareupdatedbyperiodicallygatheringstatisticsontablesand indexes. IfyourdatabasewascreatedwiththeDatabaseCreationAssistant(DBCA), optimizerstatisticsareautomaticallycollectedonceadaybetween10:00PMand 6:00AM.IfyourdatabasewasnotcreatedwiththeDBCA,orifyourdatabase containstablesandindexesthatareveryvolatile,youmustmanuallycollect optimizerstatistics.

OracleDatabase10g:Administration WorkshopI14363

OptimizerStatistics(continued) Alargetablethatexperiences10percentgrowth(orreduction)withina24hourperiod isusuallyconsideredtoovolatileforstatisticscollectiononceperdaytobesufficient. Fortablesthatexperiencethislevelofchange,Oraclerecommendscollectingstatistics morefrequently,preferablyoftenenoughthatthetableneverchangesbymorethan about10percentbetweencollectionperiods. StatisticscanbemanuallycollectedusingEnterpriseManager,orthroughtheuseofthe DBMS_STATS packageasshownbelow: SQL>EXECdbms_stats.gather_table_stats(HR,EMP); SQL>SELECTnum_rowsFROMdba_tables 2WHEREowner='HR' 'HR'ANDtable_name bl ='EMP'; 'EMP' NUM_ROWS 214 Notethatthenumberofrowsnowcorrectlyreflectswhatwasinthetableasofthe timestatisticsweregathered.DBMS_STATS alsoallowsmanualcollectionofstatistics foranentireschema, ,oreventhewholedatabase.

OracleDatabase10g:Administration WorkshopI14364

GatheringOptimizerStatistics EnterpriseManagersGatherStatisticsWizard(availablefromtheMaintenance page)istherecommendedwaytomanuallycollectorupdateoptimizerstatistics. Thewizardpromptsforinformationandthencreatesajobtocollectstatistics.: 1.DefaultMethod:Offersthechoicetodelete,estimate,orcompute statistics.Computingstatisticsexamineseveryrowinatable;estimating takesastatisticalsample.Forindexesandsmalltablesthecomputemethod shouldbeused. used Forlargetablesanestimateisusuallybest. best Inmostcases thedefaultestimatepercentageshouldbeusedforestimates. Note: Anestimatepercentageof50%orhighertriggersacompute. Whenmanuallychoosinganestimatesize,515%isusuallysufficient. 2.Objectselection:Choosetheobjectstogatherstatisticsfor.Youcan selectindividualtablesorindexesorbroadenthescopetocollectforentire schemasoreventhecompletedatabase. 3.Schedule:Provideshostcredentialsanddetermineswhenthestatistics willbecollected.Choicesincludeimmediately,ascheduledtime,oranamed maintenancewindow. 4.Review:Showsthecodegeneratedbythewizardandallowsyouto submitthejob.

OracleDatabase10g:Administration WorkshopI14365

AutomateOptimizerStatisticsCollection TheOracleSchedulerautomatesrepetitivetaskssuchasstatisticscollection.From theAdministrationpage,clickJobsandcreateanewjob.Ifyouareunfamiliarwith PL/SQL,youcancopythecodegeneratedbymanuallycollectingstatisticsandpaste itinthecommandsection.

OracleDatabase10g:Administration WorkshopI14366

ScheduleOptimizerStatisticsCollection Schedulecollectionofoptimizerstatisticsfrequentlyenoughsothattheoptimizer canmakegooddecisionsonthebestmethodstoaccessdata. Rememberthattheactofcollectingstatisticscausestheinstancetoperformwork. Avoidschedulingstatisticscollectionduringpeakoperatingtimestominimizethe impactonnormaloperations.

OracleDatabase10g:Administration WorkshopI14367

DynamicPerformanceViews Thereareover300dynamicperformanceviewsintheOracleDatabase10g that providedetailedinformationonsessionandsystemstatistics,fileI/O,andinstance activity. Dynamicperformanceviewsprovideasnapshotofrealtimedata.Asyoucansee fromtheexampleabove,eachaccessofadynamicperformanceviewgivesupto dateresults.Forthestatisticshownabove,theactofselectingtheinformationwith theORDER BY clausecausedsorts (memory) toincrement increment. Dynamicperformancedataisalsononpersistent.Aftertheinstanceisshutdown, theviewsresetandbegincountingupagain.Thatmeansthatperformancedata obtainedfromdynamicperformanceviewsshouldnotbeusedtomake configurationdecisionsuntiltheinstancehasbeenoperationalforawhile. Dynamicperformancemetricsareusuallynotmeaningfulasasinglemeasurement. Theyshouldbeconsideredinthecontextofperformancetrends(increasing, decreasing)oragainstbaselinedata. Formoreinformationondynamicperformanceviews,refertoOracleDatabase: Reference.

OracleDatabase10g:Administration WorkshopI14368

ViewingPerformanceInformation EnterpriseManagersAllMetricspagegroupsmetricsbyfunctionalarea. 1.Expandtheareaofinterest. 2.Clickthelinkforthemetricyouwanttoview. Themetricdetailpagedisplays: Lastknownvalue High andlow watermarkvalues Averagereadings Graphicalrepresentationofthemetricplottedoverauserdefinedtime period

OracleDatabase10g:Administration WorkshopI14369

ReactingtoPerformanceIssues EnterpriseManagersPerformancepageisthebestplacetostartifyounoticea degradationinsystemperformance.ThePerformancepageisdividedintothree mainregions: Host:Servermetricsshowingthenumberofwaitingprocessesandthe amountofmemorypaging ActiveSessions:WaitingandWorking:Anoverviewofinstanceperformance showinggroupedmetricsfrommultiplecategories. categories Ifonecategoryis consumingasignificantportionofthewaittimefortheinstance,that categoryiswheretroubleshootingshouldstart. InstanceThroughput:Informationaboutcurrentsessions,redogeneration, anddatafilereadactivity. Eachofthesesectionscanbedrilledintobyclickingthemetricofinterest.Inthe exampleshownintheslide,usersarespendingasignificantportionoftheirtime waitingonaconfigurationissue.ClicktheConfigurationmeasurementtodrilldown andseewheretheproblemis.

OracleDatabase10g:Administration WorkshopI14370

ReactingtoPerformanceIssues(continued) Drillingdownintotheconfigurationwaittimerevealsthatthemajorityofthewait timeisforspaceintheredologbuffer.Inthiscase,theDBAmustdetermine whethertheproblemiswiththelogbufferitself(needingmorememoryallocated) orwiththeredologfiles(filewritetimemaybetoohighforLGWR tokeepupwith demand). DrillingintotheRunQueuegraphintheHostregionofthePerformancepage revealsthatdiskI/Oishighandhasbeensteadilyclimbing. climbing Afterfurther investigationusingoperatingsystemtoolsyoumightfindthattheredologgroups areonthesamedisksasthedatafiles.

Disk I/O contention is often a performance bottleneck. Oracle suggests: Putting redo log files on separate disks Separating index and data tablespace files

OracleDatabase10g:Administration WorkshopI14371

OracleDatabase10g:Administration WorkshopI14372

OracleDatabase10g:Administration WorkshopI14373

Practice14:MonitoringPerformance Background:Userarecomplainingaboutslowerthannormalperformancefor operationsinvolvingthehumanresourcesandorderentryapplications.Upon questioningothermembersoftheDBAstaffyoufindthatmaintenancewasrecently performed f donsomeof fthe h tables bl belonging b l tothe h HR schema. h Troubleshoot bl h and dmake k changesasappropriatetoresolvetheperformanceproblems. Tasks: Viewoverallinstanceperformance. Detectandrepairunusableindexes. ManuallycollectstatisticsontheHR andOE schemas. Automatestatisticscollectionusingthescheduler. 1 1. Simulateaworkingloadonyourinstancebyrunningthescript $HOME/labs/lab14_01.sql.Expectthisscripttotakeabout30minutesto completesorunitinaseparateterminalwindowandcontinueonwiththelab whileitruns. Note: BecausethisscriptgeneratesafairlyheavyloadintermsofCPUand diskI/OyouwillnoticeresponsetimeforDatabaseControlisslower. SQL>connecthr/hr@orcl Connected. SQL>@$HOME/labs/lab14_01.sql 2.Detectandrepairunusableindexes. a)ConnecttothedatabaseasuserHR andrunthescript $HOME/labs/lab14_02_a.sql. SQL>connecthr/hr@dba10g Connected. SQL>@$HOME/labs/lab14_02_a.sql TableAltered. b)AsuserHR ,attempttoaddanewemployeebyrunningthescript $HOME/labs/lab14_02_b.sql. SQL>connecthr/hr@dba10g Connected. SQL>@$HOME/labs/lab14_02_b.sql INSERTINTOhr.employees h l VALUES(301, (301 'John','JONES', 'J h ' 'JONES' ERRORat t line1: ORA01502:index'HR.EMP_EMP_ID_PK'orpartitionofsuch indexisinunusablestate c)UsingEnterpriseManager,checktoseewhetheranyotherindexesin theHR schemaareunusable. d)Reorganizeanyunusableindexes. e)Repeatstepdfortheremainingunusableindexes indexes.Afterallindexes havebeenreorganized,attempttoaddanewemployeeagainbyrunning the$HOME/labs/lab14_02_b.sql script. SQL>@$HOME/labs/lab14_02_b.sql 1rowcreated. SQL>commit; Commitcomplete.

OracleDatabase10g:Administration WorkshopI14374

Practice14:MonitorPerformance(continued) f)Whydidtheoriginalattempttoinsertarowinstep2.bfail? g)WhatimpactwouldanunusableindexhaveonSELECT statements? h)Wereanyobjectsotherthanindexesmadenotvalidwhenthe employees tablewasmoved?Ifso,whatdoyouneedtodoasan administratortocorrectthem? 3.CollectstatisticsontheHR andOE schemas. 4.AutomatestatisticscollectionsothatstatisticsarecollectedfortheOE and HR schemaseachevening.Remembertocheckyourjobtomorrowmorningto verifythatitsucceeded. 5. Viewoverallinstanceperformance. a)InEnterpriseManagernavigatetothePerformancepageand investigatesystemperformance. b)ClicktheRunQueueLengthmetricintheHostregion.Noticethatthe threemajorindicatorsofsystemperformance(CPU,Memory,andDisk I/O)aredisplayedgraphically.ClicktheDiskI/OUtilizationgraph.For howlongdoestheinstanceretainmetricdataonDiskI/Outilization? c)ReturntotheDatabasePerformancepagebyclickingtheDatabase tabatthetoprightofthepageandselectingPerformance.Drilldown intoUserI/ObyclickingtheUserI/OlabeltotherightoftheActive Sessions:WaitingandWorkingregion.NoticethebargraphlabeledTop FilesbyWaitCount%.Whathappensifyoumoveyourcursoroverone ofthebars? d)SelecttheTopObjectspage.LookatthepiechartlabeledTop ObjectsByWaitCount%.Noticethatasyoumovetheshadedboxonthe timeline(topportionofthepage)theobjectsthatcausedwaitevents duringtheselectedtimeperiodchange.Clickoneoftheobjectnumbers inthelegendbox.Whathappens?

OracleDatabase10g:Administration WorkshopI14375

ServerGeneratedAlerts OracleDatabase10g providesalertsaboutproblemstotheadministratorviathe EnterpriseManagerDatabaseConsole.EnterpriseManagercanbeoptionally configuredtoemailtheadministratoraboutproblemconditionsaswellasdisplay alertinformationontheconsole. Youcanalsosetthresholdsonmanyofthepertinentmetricsforyoursystem. OracleDatabase10gwillproactivelynotifyyouifthedatabasedeviatesfrom normalreadingsenoughtoreachthosethresholds. thresholds Earlynotificationofpotential problemsallowsyoutorespondquickly,andoftenresolveissuesbeforeuserseven noticethem. Afewkeymetricsthatcanprovideearlyproblemnotificationare: AverageFileReadTime(centiseconds) DumpAreaUsed(%) ResponseTime(pertransaction) SQLResponseTime(%) TablespaceUsed(%) WaitTime(%)

Thresholds Thresholdsareboundaryvaluesagainstwhichmonitoredmetricvaluesare compared.Youcanspecifywarningandcriticalthresholdssuchthat,whena monitoredmetricvaluecrossesthosethresholds,analertisgenerated.Thisalertin turnnotifiesyouofimpendingproblems,whichyoucanaddressinatimelymanner. Warningthresholdsaregenerallyusedtoprovideadvancenotificationwhen performancetrendsstarttodeviatefromnormalactivity.Noactionisusually requiredforperformancewarnings, warnings theyaremeanttoalerttheDBAtobegin monitoringthesituationmorecarefully. Criticalalertsshouldbeusedtoindicateproblemsthatrequireimmediateattention. Automatedresponseactionscanbeestablishedtoactivatewhencriticalthresholds arereached. Theadministratorsgoalshouldbetosolveproblemsbeforethecriticalthresholds arereached.

SettingThresholds ClicktheEditThresholdbuttonfromtheManageMetricspagetosetwarningor criticalthresholds. Forsomemetricsyoumaychoosetosetmoredetailedtargets.Forexample,you maywanttosetthemetricTablespaceSpaceUsed(%)differentlyfordifferent tablespaces.Perhapsyourtransactiontablespacesshouldalertat70%fullbutyour readonlytablespacesarenotaproblemevenwhen95%full. Detailedthresholdscanbesetbyselectingtheappropriatemetricandclicking ManageMetricIndexes.

BaselineMeasurements Youmaywantthresholdsforperformancemetricstobebasedondeviationsfrom realtargetperformanceinsteadofabsolutenumbers.Forexample,ifthedatabase wasrunningunderanormalworkloadwithacceptableperformanceonagivenhour ingivenday,youmaywanttodefinethresholdssuchthatyouarewarnedif databaseperformancebecomes10%worsethantheperformanceonthatgiven day,andreceiveacriticalalertifperformancedegradesby25%. Th Create The C t Baseline B li Wizard Wi dallows ll youto t capture t averageperformance f statistics t ti ti for f anygivenhouror,ifyoudonotselectanhour,fortheentire24hourperiod indicatedbytheDatefield.Itwillcalculatewarningandcriticaldeviationsfrom averageperformance. Tocaptureabaseline: 1.InvoketheCreateBaselineWizardfromtheManageMetricspage. 2.Specifyadateandoptionalhourwhenperformanceandworkloadwere normal. 3.Providedefaultwarningandcriticalpercentagedeviationsandclickthe Gobutton. 4.Choosethemetricormetricsyouwanttocapture(thedefaultisto captureabaselinemeasurementforallmetrics).Thresholdvalueswill populateautomaticallyusingthedeviationpercentagesenteredinstep3. Youcancustomizetheseifneeded. needed 5.Afteranydesiredchangeshavebeenmadetothecalculatedthresholds, clicktheOKbutton.

UsingBaselines Afteryouhavecreatedabaseline,youapplythatbaselinebyclickingtheCopy ThresholdsFromBaselinebuttonintheEditThresholdspage,thenselectthe baselineyouwanttouse. Thresholdvaluescalculatedfromthebaselineareappliedforallmetricscontained withinthebaseline.Ofcourse,youcaneditthethresholdvaluesforindividual metricsifneeded.

TuningandDiagnosticAdvisors AutomaticDatabaseDiagnosticMonitor:Aserverbasedexpertthatreviews databaseperformanceevery60minutes.ADDMsgoalistodetectpossiblesystem bottlenecksearlyandrecommendfixesbeforesystemperformancedegrades noticeably. SQLTuningAdvisor:ThisadvisoranalyzesanindividualSQLstatementandmakes recommendationsforimprovingitsperformance.Recommendationsmightinclude actionssuchasrewritingthestatement, statement changingtheinstanceconfiguration, configuration or addingindexes.TheSQLTuningAdvisorisnotinvokeddirectly.Insteaditiscalled fromwithinothertools,suchasTopSQLorTopSessions,tohelpoptimizehigh impactSQLstatements. SQLAccessAdvisor:ThisadvisoranalyzesallSQLstatementsissuedwithinagiven periodandsuggeststhecreationofadditionalindexesormaterializedviewsthat willimproveperformance. MemoryAdvisor:Thememoryadvisorisactuallyacollectionofseveraladvisory functionsthathelpdeterminethebestsettingsforthesharedpool,databasebuffer cache,andProgramGlobalArea.Inadditiontotheadvisoryfunctions,thispage providesacentralpointofcontrolforthelargepoolandtheJavapool.

TuningandDiagnosticAdvisors(continued) MeanTimeToRecover(MTTR)Advisor:TheMTTRadvisorassistsyouinsettingthe lengthoftimerequiredforthedatabasetorecoverafteraninstancecrash.MTTRand theuseofthisadvisorwillbecoveredmoreinlaterlessons. lessons SegmentAdvisor:Thisadvisorlooksfortablesandindexesthatareconsumingmore spacethantheyrequire.Theadvisorchecksforinefficientspaceconsumptionatthe tablespaceorschemalevelandproducesscriptstoreducespaceconsumptionwhere possible. UndoManagementAdvisor:TheUndoManagementAdvisorhelpsyoudeterminethe undotablespacesizethatisrequiredtosupportagivenretentionperiod.Undo managementand dthe h useof fthe h advisor d will llbe b covered dinalater l lesson. l

SQLTuningandAccessAdvisors ThegoalofSQLanalysisistohelpyouidentifyhighimpactSQLstatementsand makesuggestionsonhowtoimprovetheirperformance. SQLstatementperformancecanbeimprovedbyaddingorchangingindexing,by providingstagedaggregatedataasmaterializedviews,byrewritingtheSQLtobe moreefficient,andbycorrectingsetupflawssuchasimproperinitialization parameters. ManuallyanalyzingandtuningSQLstatementsisatimeconsumingprocessthat requiressubstantialexpertise.TheSQLtuningandaccesswizardshelpby: MakingiteasiertofindhighimpactSQLstatements RecognizingcommonerrorsinSQLstatementconstruction Recommendingplaceswhereindexesormaterializedviewscouldhelpand informingtheDBAofthecostofaddingthoseobjects

MemoryAdvisors SizingtheSGAtoosmallwillseverelydegradeperformance,butitisoftendifficult toknowhowmuchmemoryisenough.Conversely,mostexpertsagreethatthereis littlevalueinallocatingadditionalmemorytoanyoftheindividualSGAareasifthat memorydoesnothingtoimproveperformance.Infact,byconsumingvaluable memoryresourcesneedlessly,sizingtheSGAtoolargecandegradesystem performancejustasmuchassizingittoosmall. ThememoryadvisorsallowyoutoeasilyfindandsetyourSGAcomponentstothe mostefficientsizes.Eachoftheadvisorspresentstheadministratorwithagraph showingthebenefitofincreasedmemorycontrastedwiththeamountofmemory requiredtoachievethatbenefit.Theadministratorshouldtrytosizethedifferent cacheareassomewherenearthekneeofthecurve(thepointatwhich performancegainseitherleveloutorprovideminimalperformanceimprovement forthecostofthememoryallocation). RemembertobalancetheSGAandPGAneedswiththeoverallsystemmemory requirements.Itdoeslittlegoodtoincreasetheamountofmemoryallocatedtothe instanceifindoingsoyoudrivetheserverintoswapping(usingdisktosimulatereal memory).

SegmentAdvisor Whenrowsaredeletedfromatable,orwhendatawithinarowisupdatedtoa valuethatconsumeslessspacethantheoriginal,thespaceallocatedtothatrowis returnedtothetableforfutureuse. Overtimethisresultsintableswithmorespaceallocatedthanneeded.The segmentadvisorlooksfortablesorindexeswithexcessfreespace,andsuggests waystoreturnthatspacetotherestofthedatabase. Thesegmentadvisorcanberunusingexistingoptimizerstatistics(limitedmode)or canactuallyscanthetablesandindexes(comprehensivemode)tomakethebest recommendations.Theanalysisscopecanbenarrowedtoindividualtablesand indexes,orcancoveranentiretablespace. SegmentAdvisorrecommendationsusuallyrequirethattablepropertiesbe changedtoenablerowmovement.ThiscanbedonethroughEnterpriseManager byopeningtheAdministrationpropertiespage,clickingTables,andeditingthetable youwanttomodify.EnableRowMovementappearsontheOptionstaboftheEdit Tablepage.Alternatively,thefollowingSQLcommandcanbeused: SQL>ALTERTABLEowner.table_name ENABLEROW MOVEMENT;

AutomaticWorkloadRepository Bydefault,every30minutes,thedatabaseautomaticallycapturesstatistical informationfromtheSGA,andstoresitinsidetheAutomaticWorkloadRepository (AWR)intheformofsnapshots.Thesesnapshotsarestoredondiskandretained forsevendays(boththesnapshotintervalandretentionintervalscanbemodified bytheadministratorifdesired). TheAWRcontainshundredsoftables,allbelongingtotheSYSMAN schemaand storedintheSYSAUX tablespace. tablespace OracledoesnotsupportdirectSQLaccesstothe repository.Instead,useEnterpriseManagerorthe DBMS_WORKLOAD_REPOSITORY packagetoworkwiththeAWR.

ManagingtheAWR OpentheAdministrationpropertiespageandclicktheWorkloadRepositorylinkto accesstheAWRsettingspage. AWRsettingsincluderetentionperiod,collectioninterval,andcollectionlevel. Rememberthatdecreasinganyofthesesettingsimpactsthefunctionalityof componentsthatdependontheAWR,includingtheadvisors. Increasingthesettingscanprovideimprovedadvisorrecommendations,butdoes soatthecostofthespacerequiredtostorethesnapshotsandtheperformance expendedcollectingthesnapshotinformation. ConsidersettingcollectionleveltoALL whentuninganewapplication.TheALL settingcollectsSQLexecutionplansandtimingstatisticsthatenhancethe recommendationsoftheSQLadvisors.Whentuningiscomplete,thissettingshould bereturnedtotheTYPICAL setting.

AutomaticDatabaseDiagnosticMonitor(ADDM) Unliketheotheradvisors,theADDMrunsautomaticallyaftereachAWRsnapshot. Eachtimeasnapshotistaken,theADDMdoesananalysisoftheperiod correspondingtothelasttwosnapshots.ADDMproactivelymonitorstheinstance, anddetectsmostbottlenecksbeforetheybecomeasignificantproblem. Inmanycases,ADDMrecommendssolutionsfordetectedproblemsandeven quantifiesthebenefitsfortherecommendations. SomecommonproblemsdetectedbyADDMinclude: CPUbottlenecks PoorOracleNetconnectionmanagement Lockcontention(lockswillbediscussedinalaterlesson) I/Ocapacity UndersizingofOraclememorystructures HighloadSQLstatements HighPL/SQLandJavatime Highcheckpointloadandcause;forexample,smalllogfiles TheresultsofeachADDManalysisarestoredinsidetheAutomaticWorkload Repository,andarealsoaccessiblethroughtheEnterpriseManagerconsole.

ADDMFindings OntheADDMFindingspageyoucanseethedetailedfindingsforthelatestADDM run.DatabaseTimerepresentsthesumofthenonidletimespentbysessionsin thedatabasefortheanalysisperiod.Aspecificimpactpercentageisgivenforeach finding.Theimpactrepresentsthetimeconsumedbythecorrespondingissue comparedtothedatabasetimefortheanalysisperiod. Byclickingaparticularfinding,youaretakentotheADDMFindingDetailspage, whichcontainsmoreinformationaboutthefindingaswellasanyrecommendations theADDMmayhavegenerated.

ADDMRecommendations OntheADDMFindingDetailspage,youaregivensomerecommendationstosolve thecorrespondingissue.RecommendationsarecategorizedbySCHEMA,SQL Tuning,DBconfiguration,andmanyothers.TheBenefitcolumngivesyouthe maximumreductionindatabaseelapsetimeiftherecommendationis implemented.

Practice15:ProactiveMaintenance Background:Youwanttoproactivelymonitoryourdatabasesothatcommonproblems canbefixedbeforetheyaffectusers. Tasks: Configureyoursystemtoalertyouiftheapplicationtablespacefallsbelow25% freespace. Configureyoursystemtoalertyouiffreememoryintheshared,large,orjava poolsfallsbelow10%. UsetheSegmentAdvisortodetectandcorrectstorageproblems. EstablishabaselinemeasurementfortheWaitTime%metric. 1 Configure 1. C fi yoursystemtoalert l youifthe h USERS tablespace bl f falls ll below b l 25% freespace 2.Configureyoursystemtoalertyouwhensharedpool,largepool,orjavapool freememoryfallsbelow10%. 3.Usethesegmentadvisortodetectandcorrectstorageproblems 4.Monitorthewaittimepercentagetoestablishabaseline.

UndoData Oraclesavestheoldvalue(undodata)whenaprocesschangesdatainadatabase. Itstoresthedataasitexistedbeforebeingmodified.Capturingundodatapermits userstochangetheirminds(rollback).Undoalsosupportsreadconsistentand flashbackqueries. Readconsistentqueriesarequeries,startedbeforeadatachange,thatfinish sometimeafteradatachange.Oracleprovidesresultsconsistentwiththedataasof thetimeaquerystarted. started Forareadconsistentquerytosucceed, succeed theoriginal informationmuststillexistasundoinformation.Aslongastheundoinformationis retained,Oraclecanreconstructdatatosatisfyreadconsistentqueries. Flashbackqueriesarequeriesthatpurposefullyaskforapictureofthedataasit existedatsometimeinthepast.Aslongasundoinformationforthatpasttimestill exists,theflashbackqueriescancompletesuccessfully. Undodataisalsousedtorecoverfromfailedtransactions.Afailedtransaction occurswhenausersessionendsabnormally(possiblyduetonetworkerrorsora failureontheclientmachine)beforetheuserdecidestocommitorrollbackthe transaction.Failedtransactionsmayalsooccurwhentheinstancecrashes.Incase ofafailedtransaction,

UndoData(continued) thesafestbehaviorischoseandOraclereversesallchangesmadebyauser,restoring theoriginaldata. Undoinformationisretainedforalltransactionsatleastuntilthetransactionendsby: Userschangingtheirmind(rollsback) Usersendingatransaction(commits) Usersessionabnormallyterminating(rollsback) Usersessionnormallyterminatingwithanexit(commits) Undoinformationmayberetainedlongerdependingontheamountofdatabase activityandthedatabaseconfiguration.

TransactionsandUndoData Whenatransactionstarts,thattransactionisassignedtoanundosegment. Throughoutthelifeofthetransaction,anychangesmadeduringthetransactionwill copyoriginalvaluesforthechangeddatatotheundosegment.Youcantellwhich transactionsareassignedtowhichundosegmentsbycheckingthedynamic performanceviewv$transaction. Undosegmentsarespecializedsegmentsthatareautomaticallycreatedbythe instanceasneededtosupporttransactions transactions.Likeallsegments, segments undosegmentsare madeupofextentswhichinturnconsistofdatablocks.Undosegments automaticallygrowandshrinkasneeded,actingasacircularstoragebufferfortheir assignedtransactions. Transactionsfillextentsintheirundosegmentextentsuntilatransaction completes,orallspaceisconsumed.Ifanextentfillsupandmorespaceisneeded, thetransactionwillacquirethatspacefromthenextextentinthesegment.Once allextentshavebeenconsumed,thetransactionwilleitherwraparoundbackinto thefirstextent(overwritingundodatathatisnolongerneeded)orrequestthata newextentbeallocatedtotheundosegment(ifunabletowraparoundbecause theundoinformationinthefirstextentisstillrequired).

StoringUndoInformation Undosegmentscanexistonlyinaspecializedformoftablespacecalledanundo tablespace.Whereasadatabasemayhavemanyundotablespaces,eachinstance canopenonlyoneundotablespace. UndosegmentshaveasegmenttypeofTYPE 2 UNDOandarealwaysowned bySYS.Becausethesegmentsactasacircularbuffer,eachsegmentwillhavea minimumoftwoextents.Thedefaultmaximumnumberofextentsdependsonthe databaseblocksizebutisveryhigh(32,765 (32 765foran8Kblocksize). size) Undotablespacesarepermanent,locallymanagedtablespaceswithautomatic extentallocation.Theyaremanagedlikeanyothertablespacewiththeexceptionof recovery.Becauseundodataisrequiredtorecoverfromfailedtransactions(suchas mightoccurwhenaninstancecrashes),undotablespacescanberecoveredonly whiletheinstanceisintheMOUNT state.Recoveryconsiderationsforundo tablespaceswillbecoveredinalaterlesson.

MonitoringUndo Mostofthetimeundoismanagedautomaticallybytheinstancewithlittleneedfor DBAintervention.Afewthingsthatmayrequireadministratorinvolvementinclude: Insufficientspaceforundo UsersreceivingORA-01555 snapshot too old errormessages Undoinformationisalwaysretaineduntilatransactionends.Thatmeansthatif extremelylargeamountsofdataaredeletedorupdated(insertoperationsconsume verylittleundospacebecausetheoriginalimageofinserteddataisanullvalue) withoutperiodicallycommittingthechanges,theundotablespacemustbelarge enoughtocontaintheoriginaldata.Imagineacasewherea50GBtablehadall rowsdeletedwiththecommand: SQL>DELETEFROMreallybigtable; Theundotablespacewouldberequiredtomakeroomfor50GBoforiginal informationjustincasetheuserwhoissuedtheabovestatementchangedhisor hermindandwantedtorollbackthechange.Whentheundotablespacerunsout ofroomforundodata,usersreceiveanerrormessagesuchasthefollowing: ORA01650:unabletoextendrollbacksegment Note: Proactivemonitoring,discussedinanearlierlesson,detectsundotablespace spaceproblemsbeforetheyaffectusers.

MonitoringUndo(continued) Anotherpossibleproblemtheadministratormayencounterwithundoinformation occurswhenaqueryneedstoaccessundoinformationthathasalreadybeen overwritten Thismighthappeninalongrunningorflashbackquery. overwritten. query Whenaquery needsasnapshotofdataasofsometimeinthepast,andreconstructingthat snapshotrequiresundodatathatnolongerexists,thequeryreturnsthefollowing error: ORA01555:snapshottooold

AdministeringUndo OracleDatabase10g recommendstheuseofautomaticundomanagement, configuredbysettingtheUNDO_MANAGEMENT initializationparametertoAUTO. ManualundomanagementissupportedforbackwardscompatibilitywithOracle8i andearlierversions,butrequiresagreatdealmoreDBAinteraction. WithautomaticundomanagementtheDBAmanagesundoatthetablespacelevel, controllingwhichundotablespaceaninstanceuseswiththeUNDO_TABLESPACE initializationparameter. parameter Afterselectingtheundotablespacetheadministrator needonlyworryaboutprovidingsufficientspaceandconfiguringanundoretention interval. WithmanualmanagementtheDBAmustalsoconsider: Segmentsizingincludingmaximumextentsandextentsizing Identifyingandeliminatingblockingtransactions Creatingenoughrollbacksegments(inmanualmodeundosegmentsare knownasrollbacksegments)tohandletransactions Choosingatablespacetocontaintherollbacksegments(undotablespaces areonlyusedwithautomaticundomanagement)

ConfiguringUndoRetention UndoretentionisconfiguredwiththeUNDO_RETENTION initializationparameter. Thisparametersetstheageatwhichundoinformationexpiresandmaybe overwrittenasneeded. Automaticallymanagedundowillattempttoretainundoinformationuntilit expires,butifanactivetransactionneedsspaceintheundotablespace,committed (unexpired)informationwillbeoverwrittenregardlessoftheundoretention settingsratherthanallowatransactiontofail. fail Anundoretentionsettingof0turnsonautomaticundoretentiontuning.Inthis modetheinstanceretainsasmuchundoinformationasneededtosatisfythe longestrunningquery.Iftheundotablespaceistoosmalltosatisfytheundo retentionrequiredbythecurrentlongestrunningquery,automaticundoretention retainsasmuchundoaspossibleusingthecurrentavailablespace(without extendingtheundodatafiles)unlesstheamountofinformationretaineddrops below900seconds(15minutes).Automaticundoretentionkeepsatleast15 minutesofundoinformationifpossiblewithoutgivingaspaceerror.

ConfiguringUndoRetention(continued) Undoinformationisdividedintothreecategories: Uncommittedundoinformation:Supportsacurrentlyrunningtransactionandis requiredifauserwantstorollbackorifthetransactionfailed. failed Uncommitted undoinformationisneverbeoverwritten. Committedundoinformation:Nolongerneededtosupportarunning transaction,butstillneededtosatisfytheundoretentioninterval.Alsoknown asunexpiredundoinformation.Committedundoinformationisretainedwhen possiblewithoutcausinganactivetransactiontofailduetolackofspace. Expiredundoinformation:Nolongerneededtosupportarunningtransaction. Overwrittenwhen h spaceisrequired dby b anactivetransaction.

GuaranteeingUndoRetention Thedefaultundobehavioristooverwritecommittedtransactionsthathavenotyet expiredratherthanallowinganactivetransactiontofailduetolackofundospace. Thisbehaviorcanbechangedbyguaranteeingretention.Withguaranteed retention,undoretentionsettingsareenforcedeveniftheycausetransactionsto fail. RETENTION GUARANTEE isatablespaceattributeratherthananinitialization parameter ThisattributecanbechangedonlywithSQLcommandlinestatements. parameter. statements Thesyntaxtochangeanundotablespacetoguaranteeretentionisshowninthe slide.Toreturnaguaranteedundotablespacetoitsnormalsetting,usethe followingcommand: SQL>ALTERTABLESPACEundotbs1RETENTION NOGUARANTEE; Theretentionguaranteeappliesonlytoundotablespaces.Attemptstosetitona nonundotablespaceresultin: SQL>ALTERTABLESPACEexampleRETENTIONGUARANTEE; ERRORatline1: ORA30044:'Retention'canonlyspecifiedforundo tablespace

SizingtheUndoTablespace Undotablespacesshouldbesizedsothattheycancontaintheoriginalinformation foralltransactions.ClickingtheUndoManagementlinkonEnterpriseManagers Administrationpropertiespagerevealsanoverviewofsystemundoincluding currentsettings,undoconsumptionperminute,andthelengthofthelongest runningqueryobservedduringagiventimeperiod. Datafilesbelongingtoanundotablespacemaybecantoautomaticallyextend whentheyrunoutoffreespace. space Unlikeothertablespaces, tablespaces Oraclerecommendsthat datafilesassociatedwithundotablespacesnothaveautomaticextensionenabled. Whenfirstdeterminingundospacerequirements,youmaywanttoenable automaticextensionofthedatafiles,butafteryouhaveproperlysizedthe tablespaceyoushoulddisableit.Disablingautomaticextensioninanundo tablespacesdatafilespreventsasingleuserfrominadvertentlyconsuminglarge amountsofdiskspacebyneglectingtocommittransactions.

UsingtheUndoAdvisor TheUndoAdvisorisaccessedthroughtheUndoManagementpropertiespage.It providesanestimateoftheundotablespacesizerequiredtosatisfyagivenundo retention. EnterthedesiredretentionperiodandclicktheUpdateAnalysisandGraphbutton. Theanalysissectionoftheadvisordisplaysthetablespacesizerequiredtosupport theretentionperiod. Youcanalsoclickapointonthegraphtoseethetablespacesizerequiredto supporttheselectedperiod. Afteryouhaveselectedanundoretentionperiod,clickOKtoimplementthenew retentionperiod.

Practice16:ManagingUndo Background:Anewversionofyourapplicationincludesseveralreportsbasedonvery longrunningqueries.Configureyoursystemtosupportthesereports Tasks: Calculatetheamountofundospacerequiredtosupportareportthattakestwo daystorun. Resizetheundotablespacetosupporttheretentionperiodrequiredbythenew reports. 1.UsetheUndoAdvisortocalculatetheamountofundospacerequiredto supportareportthat h takes k twodays d torun.What h does d the h analysis l recommend d astheRequired Tablespace Size for New Undo Retention? ______________ 2. Resizetheundotablespacetosupporttheretentionperiod requiredbythenewreports(or1GB,whicheverissmaller).

Locks Beforethedatabaseallowsasessiontomodifydata,thesessionmustfirstlockthe databeingmodified.Alockgivesthesessionexclusivecontroloverthedatasothat noothertransactioncanmodifythelockeddatauntilthelockisreleased. Transactionscanlockindividualrowsofdata,multiplerows,orevenentiretables. OracleDatabase10g supportsbothmanualandautomaticlocking.Automatically acquiredlocksalwayschoosethelowestleveloflockingpossibletominimize potentialconflictswithothertransactions. transactions

LockingMechanism Thelockingmechanismisdesignedtoprovidethemaximumpossibledegreeof dataconcurrencywithinthedatabase.Transactionsthatmodifydataacquirerow levellocksratherthanpageortablelevellocks.Modificationstoobjects(suchas tablemoves)obtainobjectlevellocksratherthanwholedatabaseorschemalocks. Dataqueriesdonotrequirealock,andaquerysucceedsevenifsomeonehas lockedthedata(alwaysshowingtheoriginal,prelockvaluereconstructedfrom undoinformation). information) Whenmultipletransactionsneedtolockthesameresource,thefirsttransactionto requestthelockobtainsit.Othertransactionswaitenqueueuntilthefirst transactioncompletes.Thequeuemechanismisautomaticandrequiresno administratorinteraction. Alllocksarereleasedattheendofatransaction.Transactionsarecompletedwhen acommitorrollbackisissued.Inthecaseofafailedtransaction,thesame backgroundprocessthatautomaticallyrollsbackanychangesfromthefailed transactionreleasesalllocksheldbythetransaction.

DataConcurrency Thelockmechanismdefaultstoafinegrained,rowlevellockingmode.Different transactionscanbeupdatingdifferentrowswithinthesametablewithout interferingwithoneother. Whilethedefaultmodelistolockattherowlevel,OracleDatabase10g supports manuallockingathigherlevelsifneeded: SQL>LOCKTABLEhr.employeesINEXCLUSIVEMODE; Table(s)Locked. Locked Withtheabovestatement,anyothertransactionthattriestoupdatearowinthe lockedtablemustwaitenqueueuntilthetransactionthatissuedthelockrequest completes.EXCLUSIVE isthestrictestlockmode.Otherlockmodesare: ROW SHARE:Permitsconcurrentaccesstothelockedtable,butprohibits sessionsfromlockingtheentiretableforexclusiveaccess ROW EXCLUSIVE:ThesameasROW SHARE,butalsoprohibitslockingin SHARE mode.ROW EXCLUSIVE locksareautomaticallyobtainedwhen updating,inserting,ordeletingdata. SHARE:Permitsconcurrentqueriesbutprohibitsupdatestothelocked table.ASHARE lockisrequired(andautomaticallyrequested)tocreatean indexonatable.

DataConcurrency(continued) SHARE ROW EXCLUSIVE:Usedtoqueryawholetableandtoallowothersto queryrowsinthetable,butprohibitsothersfromlockingthetableinSHARE modeorupdatingrows EXCLUSIVE:Permitsqueriesonthelockedtablebutprohibitsanyother activityonit.Anexclusivelockisrequiredtodropatable. Likeanyrequestforalock,manuallockstatementswaitenqueueuntilallsessionsthat eitheralreadyhavelocks,orhavepreviouslyrequestedlocks,releasetheirlocks.The LOCK commandacceptsaspecialargumentthatcontrolsthewaitingbehavior, NOWAIT. NOWAIT returnscontroltoyouimmediatelyifthespecifiedtableisalreadylockedby anothersession. SQL>LOCKTABLEhr.employeesINSHAREMODENOWAIT; LOCKTABLEhr.employeesINSHAREMODENOWAIT * ERRORatline1: ORA00054:resourcebusyandacquirewithNOWAITspecified

DMLLocks EachDMLtransactionobtainstwolocks: Arowexclusivelockontheroworrowsbeingupdated.Therewillbeone rowexclusivelockregardlessofthenumberofrowschanged. Asharedtablelevellockonthetablebeingupdated.Thisistoprevent anothersessionfromlockingthewholetable(possiblytodroportruncate it)whilethechangeisbeingmade.

EnqueueMechanism Requestsforlocksareautomaticallyqueued.Assoonasthetransactionholdinga lockcompletes,thenextsessioninlinereceivesthelock. Theenqueuemechanismtrackstheorderinwhichlockswererequestedandthe requestedlockmode. Sessionsthatalreadyholdalockcanrequesttoconvert thatlockwithouthavingto gototheendofthequeue.Forexample,supposeasessionholdsasharedlockona table Thesessioncanrequesttoconvertthesharedlocktoanexclusivelock. table. lock As longasnooneelsealreadyhasanexclusiveorsharedlockonthetable,thesession holdingthesharedlockwillbegrantedanexclusivelockwithouthavingtowaitin thequeueagain.

LockConflicts Lockconflictsoccuroften,butareusuallyresolvedthroughtimeandtheenqueue mechanism.Incertainrarecasesalockconflictmayrequireadministrator intervention.Inthecaseabove,transaction2obtainsalockonasinglerowat 9:00:00andneglectstocommit,leavingthelockinplace.Transaction1attemptsto updatetheentiretable,requiringalockonallrows,at9:00:05.Transaction1is blockedbytransaction2untiltransaction2commitsat16:30:01. Theuserattemptingtoperformtransaction1wouldalmostcertainlycontactthe administratorforhelpinthiscase,andtheDBAwouldhavetodetectandresolve theconflict.

PossibleCausesofLockConflicts Themostcommoncauseoflockconflictisanuncommittedchange,buttherearea fewotherpossiblecauses: Longrunningtransactions.Manyapplicationsusebatchprocessingto performbulkupdates.Thesebatchjobsareusuallyscheduledfortimesof lowornouseractivity,butinsomecasesmaynothavefinishedormaytake toolongtorunduringthelowactivityperiod.Lockconflictsarecommon whentransactionandbatchprocessingarebeingperformedsimultaneously simultaneously. Unnecessarilyhighlockinglevels.Notalldatabasessupportrowlevel locking(Oracleaddedsupportforrowlevellocksin1988withrelease6). Somedatabasesstilllockatthepageortablelevel.Developerswriting applicationsintendedtorunonmanydifferentdatabasesoftenwritetheir applicationwithartificiallyhighlockinglevelssothattheOracledatabase behavessimilartotheselesscapabledatabases.DevelopersnewtoOracle alsosometimesunnecessarilycodeinhigherlockinglevelsthanrequiredby OracleDatabase10g.

DetectingLockConflicts UsetheBlockingSessionspageinEnterpriseManagertolocatelockconflicts. Conflictinglockrequestsareshowninhierarchicallayoutwiththesessionholding thelockatthetop,andsessionsenqueueforthelockshowinorderbelow. Foreachsessioninvolvedintheconflictyouaregiventheusername,sessionID,and thesecondsthesessionhasbeenwaiting.DrilldownintothesessionIDtosee actualSQLstatementsexecutedorbeingrequestedbythesession. ADDMwillalsoautomaticallydetectlockconflictsandcanadviseyouofinefficient lockingtrends.

ResolvingLockConflicts Toresolvealockconflict,thesessionholdingthelockmustreleaseit.Thebestway tohavethesessionreleasethelockistocontacttheuserandaskthatthe transactionbecompleted. Inanemergency,itispossiblefortheadministratortoterminatethesession holdingthelockbyclickingtheKillSessionbutton.Keepinmindthatwhena sessioniskilledallworkwithinthecurrenttransactionislost(rolledback).Users whosesessionarekilledmustloginagainandredoallworksincetheircommit commit. Userswhosesessionshavebeenkilledwillreceivethefollowingerrorthenexttime theytrytoissueanSQLstatement: ORA00028:yoursessionhasbeenkilled

Deadlocks Adeadlockisaspecialexampleofalockconflict.Deadlocksarisewhentwoor moresessionswaitfordatalockedbyeachother.Becauseeachiswaitingonthe other,neithercancompletetheirtransactiontoresolvetheconflict. TheOracleserverautomaticallydetectsandresolvesdeadlocksbyrollingbackthe statementthatdetectedthedeadlock. Intheexampleabove,transaction1mustresubmittheupdatefrom9:15,butthe updateissuedat9:00doesnotneedtoberesubmitted resubmitted.

Practice17:LocksintheOracleDatabase Background:TheHelpdeskjustreceivedacallfromSusanMavris,anHRrepresentative complainingthatthedatabaseisfrozen.Uponquestioningtheuser,youfindthatshe wastrying y gtoupdate p JohnChensp personnelrecordwithhisnewphone p number, ,but whensheenteredthenewdatahersessionfrozeandshecouldntdoanythingelse. Tasks: Detectwhichsessioniscausingthelockingconflict. Resolvetheconflictinfavorofthesessionthatcomplained. 1.SetupalockconflictbyrunningtheSQLscript $HOME/labs/lab17_01.sql.Donotworryifthesessionseemsto h hangthis thi i isth thecondition diti wearetrying t i t tocreate. t SQL>@$HOME/labs/lab17_01.sql 2.Detectwhichsessioniscausingthelockingconflict. 3.Resolvetheconflictinfavorofthesessionthatcomplained.

BackupandRecoveryIssues TheDBAsgoalistoensurethedatabaseisopenandavailablewhenusersneedit. Insupportofthatgoal,theDBA,usuallyworkingwiththesystemadministrator: Anticipatesandworksagainstcommoncausesoffailure Workstoincreasethemeantimebetweenfailure,ensuringhardwareisas reliableaspossible,thatcriticalcomponentsareprotectedbyredundancy, andthatoperatingsystemmaintenanceisperformedinatimelymanner. OracleprovidesadvancedconfigurationoptionstoincreaseMTBFincluding: RealApplicationClusters(discussedinanothercourse) Streams(discussedinanothercourse) Decreasesthemeantimetorecover,practicingrecoveryproceduresin advanceandconfiguringbackupssotheyarereadilyavailablewhenneeded Minimizesthelossofdata.DBAswhofollowacceptedbestpracticescan configuretheirdatabasessothatnocommittedtransactioniseverlost. Toolstoassistinguaranteeingthisinclude: Archivedredologs(discussedlaterinthislesson) StandbydatabasesandOracleDataGuard(discussedinanother course)

CategoriesofFailures Failurescanbedividedintoafewbroadcategories: Statementfailure:Asingledatabaseoperation(select,insert,update, delete)fails. Userprocessfailure:Asingledatabasesessionfails. Networkfailure:Connectivitytothedatabaseislost. Usererror:Ausersuccessfullycompletesanoperation,buttheoperation wasincorrect(droppingatable, table enteringincorrectdata) data). Instancefailure:Thedatabaseinstanceshutsdownunexpectedly. Mediafailure:Oneormoreofthedatabasefilesarelost(deleted,failed disk).

StatementFailures Whenasingledatabaseoperationfails,DBAinvolvementmaybeneededtocorrect errorswithuserprivilegesordatabasespaceallocation.

UserProcessFailure Userswhoareabnormallydisconnectedfromtheinstancemayhaveuncommitted workinprogressthatneedstobecleanedup.ThePMONbackgroundprocess periodicallypollsserverprocessestoensurethattheirsessionsarestillconnected. IfPMONfindsaserverprocesswhoseuserisnolongerconnected,PMONrecovers fromanyongoingtransactions,includingrollingbackuncommittedchangesand releasinganylocksheldbythefailedsession. DBAinterventionshouldnotberequiredtorecoverfromuserprocessfailurebut theadministratorshouldwatchfortrends.Oneortwousersdisconnecting abnormallyisnotacauseforconcern.Asmallpercentageofuserprocessfailuresis normal.Consistentandsystemicfailuresindicateotherproblems.Alarge percentageofabnormaldisconnectsmayindicateaneedforusertraining(teach themtologoutratherthanjustterminatingtheirprograms).Itmayalsobe indicativeofnetworkorapplicationproblems.

NetworkFailure Thebestsolutiontonetworkfailuresistoprovideredundantpathsfornetwork connections.Backuplisteners,networkconnection,andnetworkinterfacecards reducethechanceofnetworkfailuresaffectingsystemavailability.

UserErrors Usersmayinadvertentlydeleteormodifydata.Whenthathappens,theDBAmay needtoassisttheuserinrecoveringfromtheerror.Iftheuserhasnotyet committedorexitedtheirprogram,theycansimplyrollbacktheiroperation.Ifthe userhasalreadycommittedthechanges,flashbackqueriescanbeusedto determinewhatthepreviousvalueswere(andthenthedatacanbeupdatedto restoretheoriginalinformation.) SQL>SELECTsalaryFROMemployeesWHERE employee_id=100; SALARY 25 SQL>SELECTsalaryFROMemployees 2ASOFTIMESTAMP(SYSTIMESTAMPINTERVAL10minute) 3WHEREemployee_id=100; SALARY 24000 Incaseswhereflashbackqueriesarenotpossiblebecausetheundoretention periodhasbeenexceeded,theDBAmaystillbeabletorecovertheoriginal informationthroughtheuseofOracleLogMiner.

UserErrors(continued) OracleLogMinerallowsyoutoqueryyouronlineredologsandarchivedredologs throughanSQLinterface.Transactiondatamaypersistinonlineredologslongerthanit doesinundo undo,andifyouhaveconfiguredarchivingofredoinformationredopersists untilyoudeletethearchivedfiles. OracleLogMinerisdiscussedintheOracleDatabase10g:AdministrationWorkshopII courseandintheOracleDatabase:Utilities referencemanual. Userswhodroptablescanrecoverthosetablesfromtherecyclebinbyflashingthe tablebacktobeforethedrop. SQL>DROPTABLEhr.job_history; Table bl d dropped. d SQL>SELECTCOUNT(*)FROMhr.job_history; SELECTCOUNT(*)FROMhr.job_history * ERRORatline1: ORA00942:tableorviewdoesnotexist SQL>FLASHBACKTABLEhr.job_historyTOBEFOREDROP; Flashbackcomplete. SQL>SELECTCOUNT(*)FROMhr.job_history; COUNT(*) 10 Iftherecyclebinhasalreadybeenpurged,oriftheuserdroppedthetablewiththe PURGE option,thedroppedtablecanstill berecoveredbyusingpointintimerecovery (PITR)ifthedatabasehasbeenproperlyconfigured. PITRisdiscussedintheOracleDatabase10g:AdministrationWorkshopIIcourseandin theOracleDatabase:Backup pandRecovery yAdvancedUsersGuide.

InstanceFailure Instancefailureoccurswhenthedatabaseinstanceisshutdownbefore synchronizingalldatabasefiles.Aninstancefailurecanoccurduetohardwareor softwarefailure,orthroughtheuseoftheemergencyshutdowncommands SHUTDOWN ABORT andSTARTUP FORCE. Administratorinvolvementinrecoveringfrominstancefailureisusuallylimitedto restartingtheinstanceandworkingtopreventfutureoccurrences.

InstanceRecovery TheOracleDatabase10g automaticallyrecoversfrominstancefailure.AlltheDBA needstodoisstarttheinstancenormally.Theinstancewillmountthecontrolfiles andthenattempttoopenthedatafiles.Whenitdiscoversthedatafileshavenot beensynchronizedduringshutdown,theinstanceusesinformationcontainedinthe redologgroupstorollthedatafilesforwardtothetimeofshutdownandthen (becausetheundotablespacewasalsorolledforward)rollbackanyuncommitted transactions. transactions

PhasesofInstanceRecovery Inorderforaninstancetoopenadatafile,thesystemchangenumber(SCN) containedwithinthedatafilesheadermustmatchthecurrentSCNstoredinthe databasescontrolfiles. Ifthenumbersdonotmatch,theinstanceappliesredofromtheonlineredologs, sequentiallyredoingtransactionsuntilthedatafilesareuptodate.Afteralldata fileshavebeensynchronizedwiththecontrolfiles,thedatabaseisopenedand usersmaynowlogin. in Whenredowasapplied,all transactionswereappliedtobringthedatabaseupto thestateasofthetimeoffailure.Thisusuallyincludestransactionsthatwerein progressbuthadnotyetbeencommitted.Afterthedatabasehasbeenopened, thoseuncommittedtransactionsarerolledback.Attheendoftherollbackphaseof instancerecovery,thedatafileswillcontainonlycommitteddata.

TuningInstanceRecovery Transactioninformationisalwaysrecordedintheredologgroupsbeforethe instancereturnscommit complete foratransaction.Theinformationinthe redologgroupsguaranteesthatthetransactioncanberecoveredincaseofa failure.Thatsametransactioninformationalsoneedstobewrittentothedatafile. Thedatafilewriteusuallyhappenssometimeaftertheinformationisrecordedin theredologgroupsbecausethedatafilewriteprocessismuchslowerthanthe redowrites(randomwritesfordatafilesareslowerthanserialwritesforredolog files). Tokeeptrackofwhathasalreadybeenwrittentothedatafiles,thedatabaseuses checkpoints.Acheckpointguaranteesthatasofthetimethecheckpointoccurs,all datauptoacertainSCNisrecordedinthedatafile.Transactionsafterthe checkpointpositionmayormaynothaveyetbeenwrittentotheappropriatedata file.Inthegraphicabove,thestripedblockshavenotyetbeenwrittentodisk. Thetimerequiredforinstancerecoveryisthetimerequiredtobringthedatafiles fromtheirlastcheckpointtothelatestSCNrecordedinthecontrolfile.The administratorcontrolsthattimebysettingaMTTRtarget(inseconds)andthrough thesizeoftheredologgroups. Thedistancebetweenthecheckpointpositionandtheendoftheredologgroup canneverbemorethan90%ofthesmallestredologgroup.

MTTRAdvisor ClicktheMTTRAdvisorfromEnterpriseManagersAdvisorCenterforassistancein settingtheMTTRtarget.Theadvisorallowsyoutospecifyadesiredmeantimeto recoverandtranslatesthatintosettingsfortheFAST_START_MTTR_TARGET initializationparameter. Thedefaultsettingof0disablestheMTTRtarget,reducingthelikelihoodthatwrites totheloggroupswillwaitonwritestothedatafiles.Thisshouldbesettoavalue thatsupportstheservicelevelagreementforyoursystem. system SettingtheMTTRtargettoosmallmeansthatwritestotheloggroupswaitfor writestothedatafiles(impactingperformance).SettingtheMTTRtargettoolarge meansthattheinstancetakeslongertorecoverafteracrash.

MediaFailure Oracledefinesmediafailureasanyfailurewhichresultsinthelossorcorruptionof oneormoredatabasefiles(data,control,orredologfile). Recoveringfrommediafailurerequiresthatyourestoreandrecoverthemissing files.Toensureyourdatabasecanberecoveredfrommediafailure,followbest practicesasoutlinedinthenextfewpages.Recoveryfrommediafailurewillbe discussedinmoredetailinafuturelesson.

ConfiguringforRecoverability Toprovidethebestprotectionforyourdatayoushould: Scheduleregularbackups.Mostmediafailuresrequirethatyourestorethe lostordamagedfilefrombackup. Multiplexcontrolfiles.Allcontrolfilesassociatedwithadatabaseare identical.Recoveringfromthelossofsinglecontrolfileisnotdifficult. Recoveringfromthelossofall controlfilesismuchmorechallenging.Guard againstlosingallcontrolfilesbyhavingmultiplecopies(atleastthree). three) Multiplexredologgroups.Torecoverfrominstanceormediafailure,redo loginformationisusedtorolldatafilesforwardtothelastcommitted transaction.Ifyourredologgroupsrelyonasingleredologfile,thenthe lossofthatfilemeansdataislikelytobelost.Ensurethereareatleasttwo copiesofeachredologgroup. Retainarchivedcopiesofredologs.Ifafileislostandrestoredfrombackup, theinstancemustapplyredoinformationtobringthatfileuptothelatest SCNcontainedinthecontrolfile.Thedefaultsettingistooverwriteredo informationonceithasbeenwrittentothedatafiles.Yourdatabasecanbe configuredtoretainredoinformationinarchivedcopiesoftheredologs. ThisisknownasplacingthedatabaseinARCHIVELOG mode.

ControlFiles Thecontrolfileisasmallbinaryfilethatdescribesthestructureofthedatabase.It mustbeavailableforwritingbytheOracleserverwheneverthedatabaseis mountedoropen.Withoutthisfile,thedatabasecannotbemountedandrecovery orrecreationofthecontrolfilewillberequired.Yourdatabaseshouldhavea minimumoftwocontrolfiles(threeispreferred)ondifferentdiskstominimizethe impactofalossofonecontrolfile. IfyourdatabasewascreatedwiththeDBCA, DBCA youshouldalreadyhavethreecontrol files. Lossofasinglecontrolfilewillcausetheinstancetofailbecauseallcontrolfiles mustbeavailableatalltimes,butrecoveryisasimplematterofcopyingoneofthe othercontrolfiles.Lossofallcontrolfilesisslightlymoredifficulttorecoverfrom, butnotusuallycatastrophic.Recoveryfromlossofcontrolfileswillbediscussedin alaterlesson.

RedoLogFiles Redologgroupsaremadeuponeormoreredologfiles.Eachlogfilewithinagroup isaduplicateoftheothers.Oraclerecommendsthatredologgroupshaveatleast twofilespergroup,withthefilesdistributedonseparatedisks/controllerssothat nosingleequipmentfailurewilldestroyanentireloggroup. Lossofanentireloggroupisoneofthemostseriouspossiblemediafailures becauseitcanresultinlossofdata.Lossofasinglememberwithinamultiple memberloggroupistrivial, trivial andwillnotaffectdatabaseoperationotherthan causinganalerttobepublishedinthealertlog.Recoveryfromlossofasinglelog filewillbediscussedinalaterlesson.Recoveryfromlossofanentireloggroup requiresadvancedrecoverytechniquesandisdiscussedinOracleDatabase10g: WorkshopII. Rememberthatredologsheavilyinfluencedatabaseperformancebecausea commitcannotcompleteuntilthetransactioninformationhasbeenwrittentothe logs.Youshouldplaceyourredologfilesonyourfastestdisksservedbyyourfastest controllers.Ifpossible,donotplaceanyotherdatabasefilesonthesamedisksas yourredologfiles.Becauseonlyonegroupiswrittentoatagiventime,thereisno harminhavingmembersfromseveralgroupsonthesamedisk.

MultiplexingtheRedoLog Youcanmultiplexyourredologbyaddingamembertoanexistingloggroup.Performthe followingstepstoaddamembertoaredologgroup,thiscanbedonewhenthedatabase isopenwithnoimpactonuserperformance: 1. NavigatetotheRedoLogGroupspage. 2. SelectagroupandclicktheEditbutton,orclickthegroupnumber link.TheEditRedoLogGrouppageappears. 3. IntheRedoLogMemberssection,clickAdd.TheAddRedoLog Memberpageappears. 4 4. Enterthefilenameandthefiledirectory. directory ClickOK. OK Note: Itisrecommendedthatyoustoremembersonseparate drivestoprotectagainsttotallossoftheredologentriesintheeventofadisk failure. Repeatthesestepsforeveryexistinggroup. Whenyouaddtheredologmembertoagroup,thegroupsstatusismarkedINVALID. Thisistheexpectedstatebecauseamemberofthegrouphasnotyetbeenwrittento. Whenalogswitchoccursandtheinvalidgroupbecomesthecurrentgroup,thestatus changestoCURRENT.

ArchivedLogFiles Theinstancetreatstheonlineredologgroupsasacircularbufferinwhichtostore transactioninformation,fillingonegroupandthenmovingontothenext.Afterall groupshavebeenwrittento,theinstancebeginsoverwritinginformationinthefirst loggroup. Toconfigureyourdatabaseformaximumrecoverability,youshouldinstructthe databasetomakeacopyoftheonlineredologgroupbeforeallowingittobe overwritten Thesecopiesareknownasarchivedlogs overwritten. logs.Tofacilitatethecreationof archivelogsyoushould: 1.Specifyanamingconventionforyourarchivedlogs. 2.Specifyadestinationordestinationsforstoringyourarchivedlogs. 3.PlacethedatabaseinARCHIVELOG mode. Note: ThedestinationmustexistpriortoplacingthedatabaseinARCHIVELOG mode.Whenadirectoryisspecifiedasadestination,thereshouldbeatrailingslash attheendofthedirectoryname.

ArchivedLogFileNamingandDestinations ConfigurelogfilenamingandestinationsbyclickingConfigureRecoverySettings fromtheMaintenancepage. Eacharchivelogfilemusthaveauniquenametoavoidoverwritingolderlogfiles. Youspecifythenamingformatasshowabove.Tohelpcreateuniquefilenames, OracleDatabase10g allowsseveralwildcardcharactersinthenameformat: %s:Includesthelogsequencenumberaspartofthefilename %t:Includesthethreadnumberaspartofthefilename %r:ResetlogsID.Ensuresthatthearchivelogfilenameremainsuniqueeven aftercertainadvancedrecoverytechniquesthatresetlogsequencenumbers %d:IncludesthedatabaseIDaspartofthefilename Theformatmust include%s,%t,and%r.Theuseof%disoptionalbutitshouldbe includedifmultipledatabasessharethesamearchivelogdestination. Archivedlogfilescanbewrittentoasmanyastendifferentdestinations. Destinationsmaybelocal(adirectory)orremote(anOracleNetaliasforastandby database).Localdestinationsshouldendinaslash(/),orabackslash(\)ifusing Windows.

ArchiveLogFileNamingandDestinations (Continued) Thedefaultdestination(number10)sendsarchivedlogfilestoalocationdetermined bytheDB_RECOVERY_FILE_DEST initializationparameter. DB RECOVERY FILE DEST isalsoknownastheflashrecoveryarea.This DB_RECOVERY_FILE_DEST destinationisvisibleatthebottomoftheConfigureRecoverySettingspropertiespage astheFlashRecoveryAreaLocation.Ifyoudonotwantarchivessenttothislocation, simplydeleteUSE_DB_RECOVERY_FILE_DEST. InordertochangerecoverysettingsyoumustbeconnectedasSYSDBA orSYSOPER.

ARCHIVELOG Mode PlacingthedatabaseinARCHIVELOG modepreventsredologsfrombeing overwrittenuntiltheyhavebeenarchived,andisthelaststepinconfiguringthe databaseforarchivingredoinformation. TheSQLcommandtoplacethedatabaseinARCHIVELOG modeis: SQL>ALTERDATABASEARCHIVELOG; ThiscommandcanbeissuedonlywhilethedatabaseisintheMOUNT state,sothe instancemustberestartedtocompletethislaststep. step Youwillbeaskedfor operatingsystemanddatabasecredentialsduringtherestartofthedatabase.The databasecredentialsmust beforauserwithSYSDBA privileges. Aftertheinstanceisrestarted,thechangesyoumadetothearchiveprocesses,log format,andlogdestinationswilltakeeffect. WiththedatabaseinNOARCHIVELOG mode(thedefault),recoveryispossible onlyupuntilthetimeofthelastbackup.Alltransactionsmadeafterthatbackup arelost. InARCHIVELOG mode,recoveryispossibleupuntilthetimeofthelastcommit. MostproductiondatabasesareruninARCHIVELOG mode.

Practice18:BackupandRecoveryConcepts Background:Yourdatabaseisreadytomovefromtestanddevelopmentinto production.Configureyourdatabasetoreducethechancesoffailureordataloss. Tasks: Verifythatyouhavethreecontrolfilestoensuredualredundancy. Verifythatallredologgroupshavetwomemberstoensureredundancy. PlaceyourdatabaseinARCHIVELOG mode. Ensurethatredundantarchivelogfilesarecreated. 1.Verifythatyouhavethreecontrolfilestoensuredualredundancy. 2.Addadditionalmemberstoeachloggrouptoensureredundancy. 3 Place 3. Pl yourdatabase d b in i ARCHIVELOG mode. d Configure C fi redundant d d archive hi logdestinations,onetotheflashrecoveryarea,theotherto /u01/app/oracle/archive.

OracleDatabase10g:Administration WorkshopI19457

Terminology Awholedatabasebackupincludesalldatafilesandatleastonecontrolfile(remember thatallcontrolfileswithinadatabaseareidentical). Partialdatabasebackupsmayincludezeroormoretablespaces,zeroormoredatafiles, andmayormaynotincludeacontrolfile. Fullbackupsmakeacopyofeverydatablockwithinthefilesbeingbackedupthat containsdata. Incrementalbackupsmakeacopyofalldatablocksthathavechangedsincesome previousbackup.OracleDatabase10g supportstwolevelsofincrementalbackup(01).A level0orbaselinebackupisequivalenttoafullbackupandcontainsalldatablocks. blocks A level1incrementalbacksupalldatabaseblockschangedsincethelevel0backup.To restoreusingincrementalbackups,thebaselinebackupmustfirstberestored,andthen theincremental. Offlinebackups(alsoknownasconsistentbackups)aretakenwhilethedatabaseisnot open.Theyareconsistentbecauseatthetimeofthebackup,theSCNdatafileheaders matchestheSCNinthecontrolfiles. Onlinebackups(alsoknownashotorinconsistentbackups)aretakenwhilethedatabase isopen.Thebackupsareinconsistentbecausewiththedatabaseopenthereisno guaranteethatthedatafilesaresynchronizedwiththecontrolfiles.Inconsistentbackups requirerecoveryinordertobeused.

OracleDatabase10g:Administration WorkshopI19458

Terminology(continued) Imagecopiesareduplicatesofdataorarchivedlogfiles(similartosimplycopyingthefiles usingoperatingsystemcommands). Backupsetsarecopiesofoneormoredataorarchivedlogfiles.Withbackupsets,empty datablocksarenotstored,therebycausingbackupsetstouselessspaceondiskortape. Backupsetscanbecompressedtofurtherreducethespacerequirementsofthebackup. Imagecopiesmustbebackeduptodisk.Backupsetscanbesenttodiskordirectlyto tape. Theadvantageofcreatingabackupasanimagecopyisimprovedgranularityofthe restoreoperation operation.Withanimagecopyonlythefileorfilesneedtoberetrievedfrom tape.Withbackupsetstheentirebackupsetmustberetrievedfromtapebeforeyou extractthefileorfilesthatareneeded. Theadvantageofcreatingbackupsasbackupsetsisbetterspaceusage.Mostdatabases contain20%ormoreemptyblocks.Imagecopiesbackeverysingledatablockup,evenif thedatablockisempty.Backupsetssignificantlyreducethespacerequiredbythe backup.Inmostsystemstheadvantagesofbackupsetsoutweightheadvantagesof imagecopies. DatabasesinNOARCHIVELOG modemustperformoffline,full,wholedatabasebackups. DatabasesinARCHIVELOG modehaveaccesstothefullrangeofbackupoptions.

OracleDatabase10g:Administration WorkshopI19459

RecoveryManager(RMAN) RecoveryManageristhecomponentofOracleDatabase10g thatisusedtoperform backupandrecoveryoperations.RMANcantakeconsistentandinconsistentbackups, performincrementalorfullbackups,andbackupeitherthewholedatabaseoranportion ofit. RMANusesitsownpowerfuljobcontrolandscriptinglanguage,aswellasapublished APIthatinterfacesRMANwithmanypopularbackupsoftwaresolutions. RMANcanstorebackupsondiskforquickrecovery,orplacethemontapeforlongterm storage.InorderforRMANtostorebackupsontape,aninterfacetothetapedevice knownasamediamanagementlayer(MML)mustbeconfigured. configured EnterpriseManagersuppliesagraphicalinterfacetothemostcommonlyusedRMAN functionality.AdvancedbackupandrecoveryoperationsareaccessiblethroughRMANs commandlineclient.FormoreinformationonadvancedRMANcapabilities,refertothe OracleDatabase10g:AdministrationWorkshopII orOracleBackupandRecovery AdvancedUsersGuide.

OracleDatabase10g:Administration WorkshopI19460

ConfiguringBackupSettings NavigatetotheMaintenancepageandclickConfigureBackupSettings.Fromthis propertypageyoumanagethepersistentbackupsettingsthatwillbeusedforcreating backups.Thereareseparatesettingsfordiskandtape.Tapesettingsdependonthe mediamanagementlayercapabilities.Disksettingsinclude: Parallelism:Howmanyseparatestreamsofbackupinformationdoyouwantto create.Thebestsettingforparallelismdependsonyourhardware.AsingleCPU, singlediskcontroller,orsinglediskserverwouldnotbenefitfromconducting parallelbackups.Ashardwareresourcesincrease,theappropriatedegreeof parallelismalsoincreases. increases Diskbackuplocation:Whereshouldbackupsbestored?ThedefaultistheFlash RecoveryArea.Ifyouchangethis,clickTestDiskBackuptoverifythatRMANcan writetothenewlocation. Diskbackuptype:Selectimagecopy,backupset,orcompressedbackupset. ClicktheBackupSettabtosetthemaximumsizeofbackupsetfiles(backupsetscanbe dividedfurtherifneededforeasierarchiving). HostcredentialsarerequiredforEnterpriseManagertosaveanychangestothebackup settings.

OracleDatabase10g:Administration WorkshopI19461

ConfiguringBackupSettings(continued) ClickthePolicytabto: AutomaticallybackupthecontrolandSPFILEwitheachbackup.Youarealsogiven theopportunitytospecifyalocationforthesebackupsifyoudontwantthemto gototheflashrecoveryarea. Optimizebackupsbynotbackingupfilesthatexactlymatchafilealreadypartof theretainedbackups.Thissettingallowsyoutoskipreadonlyandofflinedata files. Enableblockchangetrackingandspecifyalocationforthetrackingfile.Ifyou intendtocreateincrementalbackupsthissettingcandecreasethetimerequired tochoosewhichblockstoincludeintheincrementalbackup. Excludetablespacefromawholedatabasebackup.Someadministratorschoose nottobackuptablespacescontainingdataorobjectsthatcaneasilyberecreated (suchasindexesordatathatisbatchloadedfrequently). Retentionpolicy:HowlongshouldRMANkeepyourbackups?Ifyouareusingthe flashrecoveryareatostorebackups,RMANautomaticallydeletesoldbackupsto makeroomfornewones(iftheretentionpolicyallowsit).Bydefaultonlythelast backupisretained.Theretentionpolicycanbespecifiedasanumberofbackups oranumberofdays.

OracleDatabase10g:Administration WorkshopI19462

SchedulingBackups:Strategy ClickScheduleBackupfromtheBackup/RecoverysectionoftheMaintenanceproperties page.SelecteithertheOraclesuggestedbackupstrategyoryourowncustomized strategy.TheOraclesuggestedbackupstrategymakesaonetimewholedatabase, baselineincrementallevel0,onlinebackup,andthenschedulesincrementallevel1 backupsforeachfollowingday. ByselectingCustomized,yougainaccesstoawiderrangeofconfigurationoptions.Select whichobjectsyouwanttobackupthewholedatabase(thedefault)orindividual tablespaces,datafiles,archivelogs,oranyOraclebackupscurrentlyresidingondisk(to movethemtotape) tape).

OracleDatabase10g:Administration WorkshopI19463

SchedulingBackups:Options Choosefullorincrementallevelbackups.Ifperformingafulldatabasebackup,youcan selectUseasthebaseofanincrementalbackupstrategytomakethefulldatabase backupanincrementallevel0.Ifusingimagecopies,selectingtheRefreshthelatest datafilecopyondisktothecurrenttimeusingtheincrementalbackupcheckbox updatestheexistingbackupratherthancreatinganewimagecopy. Selectonlineorofflinebackupmodes.RememberthatNOARCHIVELOG mode databasesmustperformofflinebackups. Youmayalsochoosetobackuparchivedlogfilesanddeletethemfromdiskoncethey aresuccessfullybackedup. up Clickthedeleteobsoletebackupstoremoveanybackupsthatfalloutsidetheretention policyyouconfiguredearlier.RMANwillautomaticallyremoveobsoletebackupsifyou arebackinguptotheflashrecoveryarea. Selectthemaximumnumberoffilesyouwanttoplaceineachbackupset.Limitingthe numberoffilespersetmayspeedtherestoreprocessbecausethesizeofthebackupset thatmustbereturnedfromtapewillbesmallerthanifasinglebackupsetcontainingall thedatafilesforthedatabasewerecreated.

OracleDatabase10g:Administration WorkshopI19464

SchedulingBackups:Settings FromtheSettingspageyoucanoverridemanyofthepersistentconfigurationsettingsyou createdearlier.

OracleDatabase10g:Administration WorkshopI19465

SchedulingBackups:Schedule Choosehowyouwantthebackuptobescheduledeitherasaonetimejoborasan automated,reoccurringprocess. Toconfigureadatabaseformaximumrecoverability,Oraclesuggestsregularlyscheduled backups.Automatingbackupscansimplifytheadministratorsworkload.

OracleDatabase10g:Administration WorkshopI19466

SchedulingBackups:Review RMANusesitsowncommandsyntaxandscriptinglanguage.TheEditRMANScriptbutton givesyoualookatthecommandsthebackupschedulerhasgeneratedbasedonyour inputs. FromthispageyoucancustomizetheRMANscriptsifneeded,orcopythemforrecording purposes.

OracleDatabase10g:Administration WorkshopI19467

BackupControlFiletoTrace ClickControlfilesintheStoragesectionoftheAdministrationpropertiespagetomanage yourdatabasescontrolfiles.Controlfileshaveanadditionalbackupoption;theymaybe backeduptotrace.AcontrolfiletracebackupcontainstheSQLstatementrequiredtore createthecontrolfilesintheeventthatallcontrolfilesarelost. Althoughitisveryunlikelythataproperlyconfigureddatabase,withmultiplecopiesof thecontrolfileplacedonseparatedisksandseparatecontrollers,wouldloseallcontrol filesatthesametime,itispossibleandthereforetheadministratorshouldbackthe controlfileuptotraceaftereachchangetothephysicalstructureofthedatabase(adding tablespacesordatafiles files,addingadditionalredologgroups). groups) TracecopiesofthecontrolfilecanbecreatedusingEnterpriseManager(asshowabove) byclickingControlfilesfromtheAdministrationpropertiespage,orwiththeSQL command: SQL>ALTERDATABASEBACKUPCONTROLFILETOTRACE; ThetracebackupiscreatedinthelocationspecifiedbytheUSER_DUMP_DEST initializationparameterwithafilenamesuchassid_ora_pid.trc.

OracleDatabase10g:Administration WorkshopI19468

BackupControlFiletoTrace(continued) Thetracefilecontainsinformationaboutarchivelogdestinationsfollowedbycommands thatcreatereplacementcontrolfilesandthenrecoverthedatabase:


CREATE CONTROLFILE REUSE DATABASE ORCL NORESETLOGS ARCHIVELOG MAXLOGFILES 16 MAXLOGMEMBERS 3 MAXDATAFILES 100 MAXINSTANCES 8 MAXLOGHISTORY 226 LOGFILE GROUP 1 '/oracle/oradata/orcl/redo01.log' SIZE 10M, GROUP 2 '/oracle/oradata/orcl/redo02.log' SIZE 10M, GROUP 3 '/oracle/oradata/orcl/redo03.log' SIZE 10M DATAFILE '/oracle/oradata/orcl/system01.dbf', '/oracle/oradata/orcl/undotbs01.dbf', '/oracle/oradata/orcl/sysaux01.dbf', '/oracle/oradata/orcl/users01.dbf', '/oracle/oradata/orcl/example01.dbf' CHARACTER SET WE8ISO8859P1; -- Commands to re-create incarnation table -- Below log names MUST be changed to existing filenames on -- disk. Any one log file from each branch can be used to -- re-create incarnation records. -- ALTER DATABASE REGISTER LOGFILE '/oracle/flash_recovery_area/ORCL/archivelog/2003_12_05/o1_mf_ / / / / i / / 1_1_%u_.arc'; -- ALTER DATABASE REGISTER LOGFILE '/oracle/flash_recovery_area/ORCL/archivelog/2003_12_05/o1_mf_ 1_1_%u_.arc'; -- Recovery is required if any of the datafiles are restored backups, -- or o if the last sh shutdown tdo n was as not no normal mal o or immediate immediate. RECOVER DATABASE -- All logs need archiving and a log switch is needed. ALTER SYSTEM ARCHIVE LOG ALL; -- Database can now be opened normally. ALTER DATABASE OPEN; -- Commands to add tempfiles to temporary tablespaces. information. -- Online tempfiles have complete space information -- Other tempfiles may require adjustment. ALTER TABLESPACE TEMP ADD TEMPFILE '/oracle/oradata/orcl/temp01.dbf' SIZE 20971520 REUSE AUTOEXTEND ON NEXT 655360 MAXSIZE 32767M;

OracleDatabase10g:Administration WorkshopI19469

ManageBackups ClickManageCurrentBackupsfromtheMaintenancepropertiespagetomanageyour existingbackups.Fromthispageyoucanseewhenabackupwascompleted,whereitwas created(diskortape),andifitisstillavailable. AtthetopoftheManageCurrentBackupspageyoucanseefourbuttonsthatallowyou toworkwithexistingbackups. CatalogAdditionalFiles:AlthoughRMAN(workingthroughEnterpriseManager)is therecommendedwaytocreatebackups,itispossibletocreateimagecopiesin otherways(forexample,byshuttingdownthedatabaseandcopyingthefiles). RMANandEnterpriseManagerwillnotknowaboutthosebackupsunlessyouadd themtothecatalog. CrosscheckAll:RMANcanautomaticallydeleteobsoletebackups,butyoucanalso deletethembyusingoperatingsystemcommands.Ifyoudeleteabackupoutside ofRMAN,thecatalogwillnotknowitismissinguntilyouperformacrosscheck betweenthecatalogandwhatisreallythere. DeleteAllObsolete:Deletesbackupsolderthantheretentionpolicy DeleteAllExpired:Deletesthecataloglistingforanybackupsthatwerenotfound whenthecrosscheckwasperformed

OracleDatabase10g:Administration WorkshopI19470

FlashRecoveryArea Theflashrecoveryareaisaspacesetasideondisktocontainarchivedlogs,backups,and flashbacklogs. Ifyouhaveconfiguredyourarchivedlogstobewrittentothislocation(withthe USE_DB_RECOVERY_AREA flaginoneofthelocations),itisimportanttomonitorthis spacetoensureitdoesntreachcapacity.Iftheinstanceisunabletocreateanarchived logduetolackofspace,itwillpauseuntiltheadministratorcorrectsthesituation. ClickingConfigureRecoverySettingsfromtheMaintenancepropertypagetakesyouto theFlashRecoveryAreasettings.Fromthispageyoucan: Specifythelocationoftheflashrecoveryarea Specifythesizeoftheflashrecoveryarea(Oraclesuggeststhisbeatleasttwice thesizeofthedatabasesoitcanholdabackupandseveralarchivedlogs) Verifyhowmuchoftheflashrecoveryareahasbeenconsumed Configureflashbackdatabase(flashbackdatabaseisdiscussedinOracleDatabase 10g:AdministrationWorkshopII andintheOracleDatabaseAdministration guide.

OracleDatabase10g:Administration WorkshopI19471

OracleDatabase10g:Administration WorkshopI19472

OracleDatabase10g:Administration WorkshopI19473

Practice19:DatabaseBackups Background:Yourdatabaseisreadytomovefromtestanddevelopmentintoproduction. Ensureyourdatabaseisconfiguredsothatrecoveryispossiblewithoutlossofdata. Tasks: Configureyourdatabaseforbackups. Backyourdatabaseupwhilethedatabaseisopenforuseractivity. Schedulenightlyincrementalbackupsforyourdatabase. 1. Configureyourdatabaseforbackups. SetParallelismto1. SetDiskBackupLocationto/u01/app/oracle/backup/. Note: The h directory d mustexistbefore b f abackup b k operationcanbe b performed. f d ChooseBackupSetasyourDiskBackupType. 2. Backupyourdatabasewhilethedatabaseisopenforuseractivity. 3. Schedulenightlyincrementalbackupsforyourdatabase. SettheJobNametoNightly_Backup andacceptthedefaultJobDescription Accepttodaysdateandusethedropdownlistsandoptionbuttonstoselect11:00PM fortheTime. SelectIntervalfromtheRepeatregion,andsettheFrequencyto1day. SelectIndefiniteintheRepeatUntilregion.

OracleDatabase10g:Administration WorkshopI19474

OracleDatabase10g:Administration WorkshopI20477

OpeningaDatabase Asadatabasemovesfromtheshutdownstagetobeingfullyopen,itperformsinternal consistencychecksateachstage. NOMOUNT:InorderforaninstancetoreachNOMOUNT (alsoknownasSTARTED) status,theinstancemustreadtheinitializationparameterfile.Nodatabasefiles arecheckedinreachingNOMOUNT. MOUNT:AstheinstancemovestoMOUNT status,itchecksthatallcontrolfiles listedintheinitializationparameterfilearepresentandsynchronized.Ifevenone controlfileismissingorcorrupt,theinstancewillreturnanerrortothe administratornotingthemissingcontrolfileandwillremainattheNOMOUNT state. OPEN:WhentheinstancemovesfromtheMOUNT totheOPEN stateit: Checksthatallredologgroupsknowntothecontrolfilehaveatleastone memberpresent.Anymissingmembersarenotedinthealertlog.

OracleDatabase10g:Administration WorkshopI20478

OpeningaDatabase(continued) Verifiesthatalldatafilesknowntothecontrolfilearepresentunlessthey havebeentakenoffline.Offlinefilesarenotcheckeduntilthe administratortriestobringthemonline. online Theadministratormaytakeadata fileofflineandopentheinstanceaslongasthedatafiledoesnotbelong totheSYSTEM orUNDO tablespaces.Ifanyfilesaremissinganerror notingthefirstmissingfileisreturnedtotheadministratorandthe instanceremainsattheMOUNT state.Whentheinstancefindsfilesthat aremissing,onlythefirstfilecausingaproblemappearsintheerror message.Tofindallfilesneedingrecovery,theadministratorcancheckthe v$recover_file dynamicperformanceviewtogetacompletelistof filesneedingattention: SQL>startup ORACLEinstancestarted. TotalSystemGlobalArea171966464bytes FixedSize775608bytes VariableSize145762888bytes DatabaseBuffers25165824bytes RedoBuffers262144bytes Databasemounted. ORA01157:cannotidentify/lockdatafile4 seeDBWRtracefile ORA01110:datafile4:'/oracle/oradata/orcl/users01.dbf' SQL>SELECTname,error 2FROMv$datafile 3JOINv$recover_file 4USING(file#); NAMEERROR /oracle/oradata/orcl/users01.dbfFILENOTFOUND /oracle/oradata/orcl/example01 dbfFILENOTFOUND /oracle/oradata/orcl/example01.dbf Verifiesthatalldatafilesthatarenotofflineorreadonlyaresynchronized withthecontrolfile.Ifnecessary,instancerecoveryisautomatically performed.Howeverifafileisoutofsynchronizationmorethancanbe recoveredusingtheonlineredologgroups,thentheadministratormust performmediarecovery.Ifanyfilesrequiremediarecovery,anerror messagenotingthefirstfilerequiringrecoveryisreturnedtothe administrator d i i and dthe h instance i remains i atthe h MOUNT state. ORA01113:file4needsmediarecovery ORA01110:datafile4:'/oracle/oradata/orcl/users01.dbf' Again,v$recover_file givesacompletelistoffilesneeding attention.Filesthatarepresentbutneedmediarecoverywillbelisted,but willnothaveanerrormessage.

OracleDatabase10g:Administration WorkshopI20479

ChangingInstanceStatus Whenstartingtheinstance,thedefaultstartmodeisOPEN.Youmaychoosetostartthe instanceinsomeothermode,orproblemswiththedatabasemayforceyoutostartin anothermode.TheAdvancedStartupOptionspropertiesscreenallowsyoutoselecta stateotherthanOPEN whenstartingtheinstanceandtoalterthestateiftheinstance hasalreadystartedinanothermode.YoumayalsouseSQLcommandstomodifyan instancesstatus: SQL>STARTUPNOMOUNT ORACLEinstancestarted. started TotalSystemGlobalArea188743680bytes FixedSize778036bytes VariableSize162537676bytes DatabaseBuffers25165824bytes RedoBuffers262144bytes SQL>ALTERDATABASEMOUNT Databasealtered. ALTERDATABASEOPEN OracleDatabase10g:AdministrationSQL> WorkshopI20480

KeepingaDatabaseOpen Afteraninstanceisopen,mediafailurecausinglossofacontrolfile,lossofamemberof aredologgroup,orlossofadatafilebelongingtotheSYSTEM orUNDO tablespaceswill causetheinstancetofail. Inmanycasesthefailedinstancewillnotcompletelyshutdown,butwillbeunableto continuetoperformwork.Recoveringfromthesetypesofmediafailuresmustbedone withthedatabasedown,sotheadministratorshouldusetheSHUTDOWN ABORT commandbeforebeginningrecoveryefforts. Lossofdatafilesbelongingtoothertablespacesdoesnotcauseinstancefailure,andthe databasecanberecoveredwhileopenwithworkcontinuinginothertablespaces. tablespaces

OracleDatabase10g:Administration WorkshopI20481

LossofaControlFile Recoveringfromlossofacontrolfile(aslongasatleastonecontrolfileremains)canbe accomplishedasfollows: 1. Iftheinstancedidnotalreadyfail,shutitdownusingSHUTDOWN ABORT. 2. Copyoneoftheremainingcontrolfilestothemissingfileslocation.Ifthemedia failurewasduetolossofadiskdriveorcontroller,copyoneoftheremainingcontrolfiles tosomeotherlocationandupdatetheinstancesparameterfiletopointtothenew location.Alternatively,youcandeletethereferencetothemissingcontrolfilefromthe initializationparameterfile.RememberthatOraclesuggestshavingatleast twocontrol filesatalltimes. times 3. Starttheinstance. RecoveringfromlossofallcontrolfilesiscoveredinOracleDatabase10g:Administration WorkshopII.

OracleDatabase10g:Administration WorkshopI20482

LossofaRedoLogFile Recoveringfromthelossofasingleloggroupmembershouldnotaffecttherunninginstance. 1. Determinethereisamissinglogfilebyexaminingthealertlog. 2 2. Restorethemissingfilebycopyingoneoftheremainingfilesfromthe samegroup. 3. Ifthemediafailurewasduetolossofadiskdriveorcontroller,rename themissingfile. 4. Ifthegrouphasalreadybeenarchived,orifyouareinnoarchivelog mode,youmaychoosetosolvetheproblembyclearingtheloggrouptorecreatethe missingfileorfiles.SelecttheappropriategroupandselecttheClearLogfile action.You canalsocleartheaffectedgroupmanuallywiththecommand: SQL>ALTERDATABASECLEARLOGFILEGROUP#; Note: DatabaseControlwillnotallowyoutoclearaloggroupthathasnotbeenarchived.Doing sobreaksthechainofredoinformation.Ifyoumustclearanunarchived loggroup,youshould immediately takeafullbackupofthewholedatabase.Failuretodosomayresultinalossofdata ifanotherfailureoccurs.Toclearanunarchived loggroupusethecommand: SQL>ALTERDATABASECLEARUNARCHIVEDLOGFILEGROUP#;

OracleDatabase10g:Administration WorkshopI20483

LossofaDataFileinNOARCHIVELOG Mode Thelossofany datafilefromadatabaseinNOARCHIVELOG moderequires completerestorationofthedatabaseincludingcontrolfilesandalldatafiles. WiththedatabaseinNOARCHIVELOG mode,recoveryispossibleonlyupuntilthe timeofthelastbackup,sousersmustreenterallchangesmadesincethatbackup. 1. Shutdowntheinstanceifitisnotalreadydown. 2. ClickPerformRecoveryfromtheMaintenanceproperties page. page 3. SelectWholeDatabaseasthetypeofrecovery.

OracleDatabase10g:Administration WorkshopI20484

LossofaNoncriticalDataFileinARCHIVELOG Mode WiththedatabaseinARCHIVELOG mode,thelossofanydatafilenotbelongingtothe SYSTEM orUNDO tablespacesonlyaffectsobjectsthatareinthemissingfile.Therestof thedatabaseremainsavailableforuserstocontinuework.Forthemissingdatafile, 1. ClickPerformRecoveryfromtheMaintenancepropertiespage. 2. SelectDatafilesastherecoverytypeandselectRestoreto currenttime. 3. Addalldatafilesneedingrecovery. 4. Determinewhetheryouwanttorestorethefilestothedefault locationor(ifmissingadiskorcontroller)toanewlocation. location 5. SubmittheRMANjobtorestoreandrecoverthemissingfiles.. BecausethedatabaseisinARCHIVELOG mode,recoveryupuntilthetimeofthelast commitispossibleandusersarenotrequiredtoreenteranydata.

OracleDatabase10g:Administration WorkshopI20485

LossofaSystemCriticalDataFile DatafilesbelongingtotheSYSTEM tablespaceorcontainingUNDO dataareconsidered systemcritical.Alossofoneofthesefilesrequiresthedatabasetoberestoredfromthe MOUNT state(unlikeotherdatafilesthatmayberestoredwiththedatabaseopen). 1. Iftheinstanceisnotalreadyshutdown,shutitdown. 2. Mountthedatabase. 3. ClickPerformRecoveryfromtheMaintenancepropertiespage. 4. SelectDatafilesastherecoverytypeandselectRestoreto currenttime. 5 5. Addalldatafilesneedingrecovery. recovery 6. Determinewhetheryouwanttorestorethefilestothedefault locationor(ifmissingadiskorcontroller)toanewlocation. 7. SubmittheRMANjobtorestoreandrecoverthemissingfiles. 8. Openthedatabase.Usersarenotrequiredtoreenterdatabecause therecoverywastothetimeofthelastcommit.

OracleDatabase10g:Administration WorkshopI20486

OracleDatabase10g:Administration WorkshopI20487

OracleDatabase10g:Administration WorkshopI20488

Practice20:DatabaseRecovery Background:ManyfailuresoftheOracledatabasecanbetracedtosomesortofmedia failuresuchasdiskorcontrollerfailure.Recoveryourdatabasefromavarietyof simulatedmediafailures failures. Tasks: Recoverfromlossofacontrolfile. Recoverfromlossofaredologmember. Recoverfromlossofanonsystemcriticaldatafile. Recoverfromlossofasystemcriticaldatafile. 1.Recoverfromlossofacontrolfile.. a) )A AsuserSYSTEM runthe h SQLscript i $HOME/labs/lab20_01_a.sql. SQL>@$HOME/labs/lab20_01_a.sql b)NowruntheSQLscript$HOME/labs/lab20_01_b.sql.This scriptdeletesoneofyourcontrolfiles. c)TheHelpdeskbeginsreceivingcallssayingthatthedatabaseappears tobedown.Troubleshootandrecoverasnecessary. y d)Whydidyouhavetousetwocommandstomovetheinstancestate fromNOMOUNT toOPEN? e)Whydidyouuseoperatingsystemcommandstorestorethecontrolfile insteadofusingOracleRecoveryManager? f)Whatisanotherwayyoucouldhavesolvedthisproblem? 2.Recoverfromlossofaredologmember. a)RuntheSQLscript$HOME/labs/lab20_02.sql $HOME/l b /l b20 02 l.Thisscript deletesoneofyourredologfiles. SQL>@$HOME/labs/lab20_02.sql b)DuringaroutinecheckofthealertlogforORA errors,younoticethe followingmessage: ORA00313:openfailedformembersofloggroup1ofthread1 g1thread1:'/oracle/oradata/orcl/redo01.log' g ORA00312:onlinelog ORA27037:unabletoobtainfilestatusLinuxError:2:Nosuchfile ordirectory c)Troubleshootandrecoverasnecessary. d)Whenclearingalogfile,whatdetermineswhetheracompletebackup isrequiredimmediatelyfollowingtheclearcommand? e)WhydoesntEnterpriseManagerproduceacriticalalertforamissing logfile? 3.Recoverfromlossofanonsystemorundodatafile. a)RuntheSQLscript$HOME/labs/lab20_03.sql.Thisscript deletesoneofyournonsystemorundodatafiles. SQL>@$HOME/labs/lab20_03.sql

OracleDatabase10g:Administration WorkshopI20489

Practice20:DatabaseRecovery(continued) b)TheHelpdeskhasreceivedacallfromausercomplainingthattheyare unabletoaccessthecountries tableintheHR applicationschema. Checkthetabletoseeifthereisaproblem. problem c)Troubleshootandrecoverasnecessary. 4.Recoverfromlossofasystem/undodatafile. a)Whyisrecoveryfromthelossofasystemdatafileoradatafile belongingtoanundotablespacedifferentfromrecoveringanonsystemor undodatafile? b)RuntheSQLscript$HOME/labs/lab20_04.sql.Thisscript deletesoneofyoursystemorundodatafiles. SQL>@$HOME/labs/lab20_04.sql c)TheHelpdeskbeginsreceivingcallssayingthatthedatabaseappears tobedown.Troubleshootandrecoverasnecessary.

OracleDatabase10g:Administration WorkshopI20490

Você também pode gostar