74916685 Oracle DBA Code Examples

download 74916685 Oracle DBA Code Examples

of 707

description

74916685 Oracle DBA Code Examples

Transcript of 74916685 Oracle DBA Code Examples

  • Page 1 Oracle DBA Code Examples

    Oracle DBA Code Examples

    Version Date: 30 July 2011

    Editor: Ahmed Baraka

  • Page 2 Oracle DBA Code Examples

    Document Purpose

    This document is edited to be a quick reference of code examples used to achieve specific Oracle DBA tasks. No explanation on any subject is presented.

    The document is simply oriented based on the required task, the code to perform the task and any precautions or warnings when using the code. Also, it will be specified if the code is version specific. The document mainly demonstrates using SQL and PL/SQL code to achieve any task. It does not concentrate on using OEM to perform a task. However, if there will be a significant advantage, there could be just some hints on using OEM for some tasks.

    Prerequisites

    The document assumes that the reader has already the knowledge of Oracle database administration.

    How to Use the Document

    1. Go to Contents section

    2. Search the required task

    3. Click on the required task link

    4. Read the warnings and/or usage guideline, if any.

    5. Make any modification in the code to match your case.

    Oracle Database Versions

    The code presented in the document is to operate on Oracle database versions 10g and 11g. It will be stated, if the code is version specific.

    Obtaining Latest Version of the Document

    Latest version can be obtained from my site or by emailing me at [email protected]

    Usage Terms

    Anyone is authorized to copy this document to any means of storage and present it in any format to any individual or organization for non-commercial purpose free.

    No individual or organization may use this document for commercial purpose without a written permission from the editor.

    This document is for informational purposes only, and may contain typographical errors and technical inaccuracies.

    There is no warranty of any type for the code or information presented in this document. The editor is not responsible for any loses or damage resulted from using the information or executing the code in this document.

    If any one wishes to correct a statement or a typing error or add a new piece of information, please send the request to [email protected]

  • Page 3 Oracle DBA Code Examples

    Document Parts

    Part 1 Oracle DBA Fundamentals _______________________ 36

    Part 2 Oracle Database Net Services ___________________ 238

    Part 3 Oracle Database Backup and Recovery ____________ 247

    Part 4 Oracle Database Security _______________________ 311

    Part 5 Oracle Database Performance Tuning _____________ 340

    Part 6 Oracle Automatic Storage Management (ASM) ______ 396

    Part 7 Oracle Real Application Cluster __________________ 410

    Part 8 Oracle RAC One Node __________________________ 529

    Part 9 Oracle Warehousing ___________________________ 551

    Part 10 Oracle Database Utilities _______________________ 556

    Part 11 Miscellaneous Oracle Database Topics _____________ 582

    Part 12 PL/SQL Samples ______________________________ 596

    Part 13 Appendixes__________________________________ 674

  • Page 4 Oracle DBA Code Examples

    Contents

    Part 1 Oracle DBA Fundamentals _______________________ 36

    DBA: Best Practices ____________________________________ 37DBA: Best Practice Guidelines for Standalone and RAC Databases____________37

    Oracle Database Installation Consideration __________________ 38Estimating Disk and Memoery Requirements ____________________________38Optimal Flexible Architecture_________________________________________38Oracle Products Installed with the 11.1 Release __________________________39

    Installing Oracle 10g R2 on Enterprise Linux 4 _______________ 40Installation Environment ____________________________________________40Required Software _________________________________________________40Used Hardware ___________________________________________________40Installation Plan___________________________________________________40

    1. Preinstallation tasks __________________________________________________ 402. Oracle Database 10g Software Installation_________________________________ 443. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software_____________ 444. Configure Listeners ___________________________________________________ 455. Create Database _____________________________________________________ 456. Postinstallation Tasks _________________________________________________ 45

    Installing Oracle 11g R2 on Enterprise Linux 5 _______________ 47Installation Environment ____________________________________________47Required Software _________________________________________________47Used Hardware ___________________________________________________47Installation Plan___________________________________________________47

    1. Preinstallation tasks __________________________________________________ 472. Oracle Database 11g Software Installation_________________________________ 533. Apply Patchset_______________________________________________________ 534. Configure Listeners ___________________________________________________ 535. Create Database _____________________________________________________ 536. Postinstallation Tasks _________________________________________________ 53

  • Page 5 Oracle DBA Code Examples

    Installing Oracle 11g R2 on Enterprise Linux 5.5 with ASM ______ 54Installation Environment ____________________________________________54Required Software _________________________________________________54Used Hardware ___________________________________________________54Installation Plan___________________________________________________54

    1. Preinstallation tasks __________________________________________________ 552. Oracle Grid Infrastructure installation_____________________________________ 603. Oracle Grid Infrastructure Patching_______________________________________ 614. Oracle Database 11g R2 Software Installation ______________________________ 615. Oracle Database 11g R2 Software Patching ________________________________ 626. Install EM Agent in cluster nodes (if required) ______________________________ 627. ASM Diskgroups Creation ______________________________________________ 628. Database Creation____________________________________________________ 629. Postinstallation tasks__________________________________________________ 6210. General Useful Postinstallation Tasks in Linux _____________________________ 62

    Managing Oracle Database Instance _______________________ 64Product Release Number ____________________________________________64

    Oracle Database Release Number Format____________________________________ 64Obtaining License Information________________________________________64Managing the Instance Architecture ___________________________________64

    Obtaining Information about the Instance Processes ___________________________ 64Obtaining Information about the SGA _______________________________________ 65Clearing the Buffer Cache ________________________________________________ 65

    Database Administration Authentication ________________________________65Using Operating System Authentication _____________________________________ 65Using Password File Authentication_________________________________________ 66Identifying Users SYSDBA or SYSOPER Users_________________________________ 66

    Data Dictionary and Dynamic Performance Views_________________________66Data Dictionary Creation _________________________________________________ 66

    Startup and Shutdown______________________________________________66Startup Levels _________________________________________________________ 66Shutdown Levels _______________________________________________________ 66Autostart of Database in Windows _________________________________________ 66Automatically Starting Databases in Unix ____________________________________ 66

  • Page 6 Oracle DBA Code Examples

    Quiescing a Database ______________________________________________71Suspending a Database _____________________________________________71Dropping a Database _______________________________________________71Initialization Files__________________________________________________71

    Managing Initialization Files ______________________________________________ 71Managing Parameters in SPFILE ___________________________________________ 72

    Alert and Trace Files _______________________________________________72Monitoring Alert and Trace Files ___________________________________________ 72

    Managing Oracle Database Physical Structure ________________ 74Managing Control Files______________________________________________74

    Obtaining Control File information__________________________________________ 74Creating Additional Copies, Renaming, and Relocating Control Files _______________ 74Creating New Control Files _______________________________________________ 74Backing Up Control Files _________________________________________________ 75Manage the Size of Control Files ___________________________________________ 75Multiplexing the Control File ______________________________________________ 76

    Maintaining Online Redo Log Files _____________________________________76Forcing Log Switches and Checkpoints ______________________________________ 76Adding Online Redo Log File Groups ________________________________________ 76Adding Online Redo Log File Members ______________________________________ 76Dropping Online Redo Log File Groups ______________________________________ 76Dropping Online Redo Log File Members_____________________________________ 76Relocating and Renaming Redo Log Members_________________________________ 76Verifying Blocks in Redo Log Files __________________________________________ 77Clearing a Redo Log File _________________________________________________ 77Viewing Redo Log Information_____________________________________________ 77

    Managing Archived Redo Logs ________________________________________77Obtaining Information about Archive Log ____________________________________ 77Changing the Database Archiving Mode _____________________________________ 78Specifying Archive Destinations and their Options _____________________________ 78Specifying the Minimum Number of Successful Destinations _____________________ 79Controlling Archiving to a Destination_______________________________________ 79Controlling Trace Output Generated by the Archivelog Process ___________________ 79

    Managing Tablespaces______________________________________________79Obtaining Tablespace Information__________________________________________ 79

  • Page 7 Oracle DBA Code Examples

    Creating a Locally Managed Tablespace _____________________________________ 83Specifying Segment Space Management_____________________________________ 83Adding Space to Tablespace ______________________________________________ 83Specifying Nonstandard Block Sizes for Tablespaces ___________________________ 83Using Bigfile Tablespace (BFT) ____________________________________________ 83Using Temporary Tablespace______________________________________________ 84Renaming a Tempfile____________________________________________________ 84Shrinking Temporary Tablespace __________________________________________ 84Using Default Temporary Tablespace _______________________________________ 85Using Temporary Tablespace Groups _______________________________________ 85Suppressing Redo Generation for a Tablespace _______________________________ 85Controlling Tablespaces Availability_________________________________________ 85Using Read-Only Tablespaces _____________________________________________ 85Renaming Tablespaces __________________________________________________ 85Default Permanent Tabelspace ____________________________________________ 85Dropping Tablespaces ___________________________________________________ 86Managing the SYSAUX Tablespace _________________________________________ 86Diagnosing and Repairing Locally Managed Tablespace Problems _________________ 86Verifying the Integrity of Segments Created in ASSM Tablespaces.________________ 86Checking Consistency of Segment Extent Map with Tablespace File Bitmaps_________ 87Verifying the Integrity of ASSM Tablespaces__________________________________ 88Marking the Segment Corrupt or Valid ______________________________________ 89Dropping a Corrupted Segment____________________________________________ 89Dumping a Segment Header and Bitmap Blocks_______________________________ 90Marking a DBA Range in Bitmap as Free or Used ______________________________ 90Rebuilding the Appropriate Bitmap _________________________________________ 91Rebuilding Quotas for Given Tablespace _____________________________________ 91Migrating from a Dictionary-Managed to a Locally Managed Tablespace ____________ 91Fixing the State of the Segments in A Tablespace _____________________________ 91Scenario 1: Fixing Bitmap When Allocated Blocks are Marked Free (No Overlap) _____ 91Scenario 2: Dropping a Corrupted Segment __________________________________ 92Scenario 3: Fixing Bitmap Where Overlap is Reported __________________________ 92Scenario 4: Correcting Media Corruption of Bitmap Blocks_______________________ 92Transporting Tablespaces Between Databases ________________________________ 92

    Managing Alert Thresholds __________________________________________94Getting the Current Threshold Setting ______________________________________ 94Setting Tablespace Alert Thresholds ________________________________________ 95Restoring a Tablespace to Database Default Thresholds_________________________ 96

  • Page 8 Oracle DBA Code Examples

    Modifying Database Default Thresholds _____________________________________ 97Viewing Alerts _________________________________________________________ 97

    Managing Datafiles and Tempfiles _____________________________________98Creating Datafiles ______________________________________________________ 98Enabling and Disabling Automatic Extension for a Datafile_______________________ 98Manually Resizing a Datafile ______________________________________________ 98Bringing Datafiles Online or Taking Offline in ARCHIVELOG Mode _________________ 98Taking Datafiles Offline in NOARCHIVELOG Mode______________________________ 98Renaming and Relocating Datafiles in a Single Tablespace_______________________ 99Dropping Datafiles______________________________________________________ 99Copying a File on a Local File System _______________________________________ 99Transferring a File to a Different Database __________________________________ 100Dumping a Data Block__________________________________________________ 100

    Managing Undo Tablespaces ________________________________________101Obtaining Information on Undo___________________________________________ 101Enabling Automatic Undo Management_____________________________________ 102Creating an Undo Tablespace ____________________________________________ 102Setting Startup Undo Tablespace _________________________________________ 102Tuning Undo Retention _________________________________________________ 102Using Undo Advisor ____________________________________________________ 103Setting the Undo Retention Period ________________________________________ 103Enabling Retention Guarantee____________________________________________ 103Dropping an Undo Tablespace____________________________________________ 103To Drop a Corrupt UNDO Tablespace ______________________________________ 104

    Using Oracle Managed Files (OMF) ___________________________________104

    Managing Schema Objects ______________________________ 106Chaching Small Tables in Memory____________________________________106Creating Virtual Columns___________________________________________106Creating Partitioned Tables _________________________________________106Partition Maintenance Operations ____________________________________111Setting Deferred Segment Creation___________________________________112Creating Multiple Tables and Views in a Single Operation__________________112Collecting Object Statistics _________________________________________113

    Collecting Index Statistics _______________________________________________ 113Collecting Table Statistics _______________________________________________ 113

  • Page 9 Oracle DBA Code Examples

    Collecting Schema Statistics _____________________________________________ 114Validating Tables, Indexes, Clusters, and Materialized Views _______________115Listing Chained and Migrated Rows of Tables and Clusters_________________115Truncating Tables or Clusters _______________________________________116Enabling and Disabling Triggers _____________________________________116Managing Integrity Constraints ______________________________________116

    Setting Constraint States and Deferability __________________________________ 116Modifying, Renaming, or Dropping Existing Integrity Constraints ________________ 117Reporting Constraint Exceptions __________________________________________ 117Obtaining Information on Constraints ______________________________________ 118

    Renaming Schema Objects _________________________________________118Managing Object Dependencies______________________________________118

    Manually Recompiling Views Procedures and Packages ________________________ 118Switching to a Different Schema _____________________________________118Using DBMS_METADATA to Display Information About Schema Objects ______118Specifying Storage Parameters at Object Creation _______________________118Managing Resumable Space Allocation ________________________________119

    Enabling Resumable Space Allocation ______________________________________ 119Detecting Suspended Statements _________________________________________ 119Obtaining Information about Suspended Statements __________________________ 121

    Reclaiming Wasted Space __________________________________________121Displaying Information About Space Usage for Schema Objects _________________ 121Segment Advisor ______________________________________________________ 124Shrinking Database Segments Online ______________________________________ 126Deallocating Unused Space ______________________________________________ 126

    Capacity Planning for Database Objects _______________________________127Estimating the Space Use of a Table_______________________________________ 127Obtaining Object Growth Trends __________________________________________ 128

    Using the SQL Access Advisor _______________________________________129Estimating the Space Use of a Table_______________________________________ 129

    Managing Tables______________________________________ 134Obtaining Information about Tables __________________________________134Creating Tables with some Options ___________________________________134

  • Page 10 Oracle DBA Code Examples

    DML Error Logging ________________________________________________135Enabling Direct-Path INSERT________________________________________135Automatically Collecting Statistics on Tables____________________________136Altering Tables___________________________________________________136Performing Online Redefinition with DBMS_REDEFINITION ________________137

    Redefining a Table _____________________________________________________ 137Redefining a Single Partition _____________________________________________ 139Migrating BasicFile LOBs to SecureFiles ____________________________________ 140

    Using Flashback Drop and Managing the Recycle Bin _____________________141Managing Index-Organized Tables ___________________________________141Managing External Tables __________________________________________142

    Managing Indexes ____________________________________ 145Using Indexes ___________________________________________________145Using Bitmap Join Indexes (BJI) _____________________________________146Partitioned Indexes _______________________________________________147

    Managing Materialized Views ____________________________ 148Obtaining Information about Materialized Views______________________________ 148Monitoring the Progress of a Materialized View Refresh ________________________ 148Materialized View Typical Refresh Errors____________________________________ 152Using Materialized Views ________________________________________________ 152Using Query Rewriting__________________________________________________ 155ReWrite Hints_________________________________________________________ 157Using EXPLAIN_MVIEW Procedure: Viewing Materialized View Capabilities _________ 157Using DBMS_ADVISOR.TUNE_MVIEW ______________________________________ 157Registering a User-defined Table as Materialized View _________________________ 158

    Managing Clusters and Hash Clusters______________________ 159

    Managing Views, Sequences, and Synonyms ________________ 161

    Managing Transactions_________________________________ 162Implementing Oracles Concurrency Control ____________________________162

    Oracle Isolaction Levels_________________________________________________ 162Oracle Lock Types _____________________________________________________ 162

  • Page 11 Oracle DBA Code Examples

    Identifying Blocking Sessions ____________________________________________ 163Using Autonomous Transaction ______________________________________163Managing Long Transactions with Workspace Manager____________________164

    Repairing Corrupted Data _______________________________ 172Options for Repairing Data Block Corruption____________________________172Detecting Corruptions Methods ______________________________________172Using dbv (DBVerify) Utility_________________________________________172Setting the Initialization Parameters for Detecting Corruption ______________172

    Verifying Block Integrity in Real Time: DB_BLOCK_CHECKING __________________ 172Verifying Block Integrity in Real Time: DB_BLOCK_CHECKSUM __________________ 173Detecting lost write: DB_LOST_WRITE_PROTECT_____________________________ 173Settubg the DB_ULTRA_SAFE Parameter (In Oracle 11g) ______________________ 173

    Using ANALYZE Command__________________________________________173Using EXP to Detect Corruption ______________________________________173Using DBMS_REPAIR ______________________________________________174

    DBMS_REPAIR Limitations and Restrictions _________________________________ 174Evaluate the Costs and Benefits of Using DBMS_REPAIR _______________________ 174Detect and Report Corruptions using DBMS_REPAIR __________________________ 175

    Managing Automated Database Maintenance Tasks___________ 177Predefined Automated Maintenance Tasks _____________________________177Predefined Maintenance Windows ____________________________________177Obtaining Information about Predefined Maintenance Tasks________________177Enabling and Disabling Maintenance Tasks _____________________________178Configuring Maintenance Windows ___________________________________178

    Managing Resources___________________________________ 180Obtaining Information on Database Resource Manager ___________________191Monitoring Oracle Database Resource Manager _________________________193

    Using Oracle Scheduler_________________________________ 195Using Jobs ______________________________________________________195Using Programs __________________________________________________202

  • Page 12 Oracle DBA Code Examples

    Using Schedules__________________________________________________203Using Job Classes ________________________________________________204Using Windows___________________________________________________205Using Window Groups _____________________________________________206Monitoring Job State with Email Notifications ___________________________207Using File Watchers _______________________________________________209Using Events Raised by the Scheduler_________________________________212Using Events Raised by an Application (Events-Based Jobs)________________214Using Chains ____________________________________________________217Allocating Resources Among Jobs ____________________________________221Administering Oracle Scheduler______________________________________221

    Configuring Oracle Scheduler ____________________________________________ 221Monitoring and Managing the Scheduler ____________________________________ 222Enabling, Using and Disabling Remote External Jobs __________________________ 223Import/Export and the Scheduler _________________________________________ 225Scheduler Privileges____________________________________________________ 225Scheduler Data Dictionary Views__________________________________________ 225Using the UTL_FILE Package _____________________________________________ 226

    Data Loading and Transforming Tools _____________________ 228

    Using Database Links __________________________________ 229

    Managing Diagnostic Data ______________________________ 230Setting the Automatic Diagnostic Repository Directory____________________230Using adrci Tool __________________________________________________230

    General usage of adrci__________________________________________________ 230Using adrci to Package Incidents__________________________________________ 231

    Managing Database Health Monitor___________________________________231Managing Data Recovery Advisor ____________________________________233Using SQL Test Case Builder ________________________________________233

    Patching Oracle Products _______________________________ 235Using Oracle Opatch ______________________________________________235

  • Page 13 Oracle DBA Code Examples

    Part 2 Oracle Database Net Services ___________________ 238

    Connectivity Naming Methods ___________________________ 239The Local Naming Method __________________________________________239The Easy Connect Naming Method ___________________________________239The External Naming Method________________________________________239The Directory Naming Method _______________________________________240Database Resident Connection Pooling (DRCP)__________________________240

    Oracle and Java Database Connectivity ____________________ 242Establishing Database Connectivity___________________________________242

    Miscellaneous Connectivity Options _______________________ 244Setting the Default Connect String ___________________________________244Installing the Instant Client _________________________________________244Setting Listener Options ___________________________________________244Setting Access Controls ____________________________________________244Changing Windows Hostname _______________________________________245

    Part 3 Oracle Database Backup and Recovery ____________ 247

    Backup Guidelines ____________________________________ 248Causes of Unplanned Down Time ____________________________________248Causes of Planned Down Time_______________________________________248Oracles Solution to Down Time______________________________________249Minimizing Unplanned Downtime Guidelines ____________________________249SLA Sample _____________________________________________________250Planning a Backup Strategy Guidelines ________________________________250

    Examples of Backup Schedules for a Database_______________ 251

    User-Managed Backups ________________________________ 252Obtaining Database File Information __________________________________252

    Making Whole Closed Database Backups ___________________________________ 252Making a Whole Open Backup ____________________________________________ 252

  • Page 14 Oracle DBA Code Examples

    Making Tablespace Backups _____________________________________________ 253Obtaining Backup Status Information _________________________________253Checking Datafiles Taken as Backup _________________________________253Handling Crash Before User-Manged Backup Ends _______________________253Backing up Control File ____________________________________________254Backing Up Initialization Files _______________________________________254

    User-Managed Complete Recovery ________________________ 255User-Managed Recovery in NOARCHIVELOG Mode _______________________255User-Managed Recovery in NOARCHIVELOG Mode Without Redo Log File _____255User-Managed Complete Recovery in ARCHIVELOG Mode _________________255Re-Creating Lost Datafiles Without Backup_____________________________256

    User-Managed Incomplete Recovery ______________________ 257Common Situations Requiring Incomplete Recovery______________________257User-Managed Incomplete Recovery Steps _____________________________257Recovering from Lost Control File by Re-Creating the Control File ___________257

    Flash Recovery Area ___________________________________ 261Obtaining Information on Flash Recovery Area __________________________261Configuring Flash Recovery Area_____________________________________261Backing Up the Flash Recovery Area __________________________________261Moving the Flash Recovery Area _____________________________________262

    Recovery Manager (RMAN)______________________________ 263Using A Media Management Layer (MML) with RMAN _____________________263Obtaining Information about and related to RMAN using Dictionary Views_____263Starting RMAN ___________________________________________________265Using rlwrap Utility with RMAN in Unix-Based Systems____________________266Configuring the RMAN Environment __________________________________266RMAN Channel Commands _________________________________________267Duration in days of RMAN information in Control File _____________________268Monitoring RMAN Jobs _____________________________________________268

  • Page 15 Oracle DBA Code Examples

    Using RMAN BACKUP Command _____________________________________268Backing Up Control File and SPFile ___________________________________269Backing Up Archived RedLogs _______________________________________269Backup in NOARCHIVELOG Mode_____________________________________270Encrypting RMAN Backups__________________________________________270Using Compression in RMAN Backups _________________________________270Using Multiplexed Backup Sets ______________________________________270Using Parallelization of Backup Sets __________________________________270Using Duplexed Backup Sets (Backupset Copies) ________________________271Making Image Copies______________________________________________271Validating Backup ________________________________________________272Incremental Backup_______________________________________________272Tags for Backups and Image Copies __________________________________272Creating Archival Backups __________________________________________272Monitoring RMAN Backups __________________________________________273RMAN Complete Recovery _______________________________________273

    Validating Backup Files _________________________________________________ 273Previewing Backup Files Required by a Restore ______________________________ 274Identifying Datafiles Requiring Recovery____________________________________ 274Performing Complete Recovery ___________________________________________ 274Restoring whole Database from RMAN Backups On a Different Node______________ 275Restoring whole Database from RMAN Backups from A 32 bit to 64 bit ____________ 278

    RMAN Incomplete Recovery_________________________________________278Simplified Recovery Through Resetlogs________________________________279Recovering from Lost Control File using RMAN __________________________279Block Media Recovery (BMR) ________________________________________280Trial Recovery ___________________________________________________280Handling Specific Errors During Recovery ______________________________280Configuring Instance Crash Recovery Time (MTTR) ______________________282Working with the Data Recovery Advisor in RMAN _______________________282RMAN Maintenance _______________________________________________282

    Cross Checking Backups and Copies _______________________________________ 282

  • Page 16 Oracle DBA Code Examples

    Deleting Backups and Copies ____________________________________________ 283Changing the Availability of RMAN Backups and Copies ________________________ 283Exempting a Backup or Copy from the Retention Policy ________________________ 283The CATALOG Command ________________________________________________ 284The CHANGE UNCATALOG Command ____________________________________ 284

    RMAN Catalog ___________________________________________________284Creating a Recovery Catalog _____________________________________________ 284RMAN Catalog Reporting ________________________________________________ 285Upgrading a Recovery Catalog ___________________________________________ 285Importing Recovery Catalogs ____________________________________________ 285Moving a Recovery Catalog ______________________________________________ 286Dropping a Recovery Catalog ____________________________________________ 286

    Virtual Private Catalogs ____________________________________________286Using RMAN Scripts _______________________________________________287

    Duplicating (Cloning) a Database_________________________ 289Database Duplication (Cloning) Methods_______________________________289Database Duplication Techniques ____________________________________289Database Duplication Prerequisites ___________________________________289Duplicating an Active Database using RMAN ____________________________289Duplicating a Database without Recovery Catalog or Target Connection ______291Manually Duplicating a Database_____________________________________293

    Using Oracle Flashback Technology _______________________ 297

    Flashback Options ____________________________________ 298

    Preparing Your Database for Flashback ____________________ 299

    Using Row Level Flashback Options _______________________ 300Flashback Query _________________________________________________300Flashback Versions Query __________________________________________300Flashback Transaction Query________________________________________301Flashback Transaction (Backout)_____________________________________301

    Using Table Level Flashback Options ______________________ 303

  • Page 17 Oracle DBA Code Examples

    Flashback Table __________________________________________________303Flashback Drop __________________________________________________303Flashback Data Archive ____________________________________________304

    Using Flashback Database ______________________________ 308When to use Flashback Database ____________________________________308Flashback Database Considerations___________________________________308Using Flashback Database __________________________________________308Restore Points ___________________________________________________309

    Part 4 Oracle Database Security _______________________ 311

    Oracle Database Security Management ____________________ 312

    Security Guidelines____________________________________ 313

    Managing Users ______________________________________ 315

    Database Authentication _______________________________ 317Managin Passwords _______________________________________________317External (OS) Authentication________________________________________317Proxy Authentication ______________________________________________318Logging In As a Different User_______________________________________318Killing User Sessions from OS _______________________________________318

    Controlling Database Access_____________________________ 320System and Object Privileges _______________________________________320Invoker Rights and Definer Rights____________________________________320Roles __________________________________________________________320Users, Roles, and Privileges Views____________________________________321Fine-Grained Data Access (Virtual Private Database VPD) _________________322

    Auditing Database ____________________________________ 325Standard Auditing ________________________________________________325Customizing Database Auditing with Triggers ___________________________326

  • Page 18 Oracle DBA Code Examples

    Auditing the Database Using System Trigger ___________________________328Using Fine Grained Auditing_________________________________________331

    Using Data Encryption _________________________________ 334Oracle Transparent Data Encryption (TDE) _____________________________334Tablespace Encryption_____________________________________________335

    Fine-Grained Access Control for UTL_* Packages ____________ 337Creating ACL ____________________________________________________337Access Control Lists Maintenance ____________________________________338Query Your Access Control List ______________________________________339

    Part 5 Oracle Database Performance Tuning _____________ 340

    Managing Performance Statistics _________________________ 341Managing OS Statistics ____________________________________________341Managing Database Statistics _______________________________________345

    System and Session Statistics____________________________________________ 345Time Model Statistics___________________________________________________ 346Wait Events __________________________________________________________ 347Active Session History (ASH)_____________________________________________ 349Segment Statistics_____________________________________________________ 351

    Handling Important Oracle Wait Events _______________________________351List of Idle Waits Events ___________________________________________353Using Performance Monitor Tool in Windows____________________________355Using OS Watcher for Windows ______________________________________355

    Optimizing Performance in Windows Server ________________ 357Optimizing Performance in Windows Server 2003________________________357

    Tuning the Database Instance ___________________________ 358Tuning the Shared Pool ____________________________________________358Tuning the Buffer Cache ___________________________________________359Tuning PGA _____________________________________________________361Dumping the PGA ________________________________________________361

  • Page 19 Oracle DBA Code Examples

    Using Server Result Cache__________________________________________362Obtaining Information about Object Locks _____________________________364Handling a Hanging Database _______________________________________365Accurately Measuring Process Size ___________________________________365

    Managing Automatic Workload Repository (AWR) ____________ 367

    Managing Automated Maintenance Tasks___________________ 369Using Automatic Database Diagnostic Monitor (ADDM)____________________369Using Automatic SQL Tuning Advisor _________________________________371

    Implementing Automatic Memory Management______________ 374

    Configuring DB_nK_CACHE_SIZE _________________________ 376

    Managing Optimizer Operations __________________________ 377Setting the Optimizer Mode_________________________________________377Defining Access Paths and Joins for the Query Optimizer __________________377Gathering Optimizer Statistics_______________________________________381

    Gathering Object Statistics ______________________________________________ 381Gathering System Statistics _____________________________________________ 382

    Changing Statistics Preferences______________________________________382Managing Pending and Published Statistics _____________________________383Managing Extended Statistics _______________________________________384

    MultiColumn Statistics __________________________________________________ 384Expression Statistics ___________________________________________________ 385

    A Simple Approach to Tuning SQL Statements _______________ 386

    Using Application Tracing Tools __________________________ 387Using the SQL Trace Facility and TKPROF ______________________________387Using the Event 10046 to Trace SQL Code _____________________________387Tracing End to End Application ______________________________________388Enabling and Disabling Statistic Gathering for End to End Tracing ___________389

  • Page 20 Oracle DBA Code Examples

    Writing Efficient SQL __________________________________ 391

    Improving SQL Processing Techniques_____________________ 394

    Using SQL Tuning Advisor_______________________________ 395

    Part 6 Oracle Automatic Storage Management (ASM) ______ 396

    Managing Oracle ASM __________________________________ 397Obtaining Information about ASM Instance_____________________________397Creating an ASM Instance __________________________________________397Managing Disk Groups and Disks in ASM_______________________________398

    Fundementals of Managing Disk Groups and Disks____________________________ 398Managing Disk Groups Attributes _________________________________________ 399

    Monitoring Long-Running Operations _________________________________401Migrating a Database to ASM________________________________________402Moving a Tablespace to ASM ________________________________________402Accessing an ASM instance from DB Console ___________________________403Managing ASM Files _______________________________________________404Using ASMCMD Utility _____________________________________________405Using SYSASM Privilege and OSASM Group_____________________________407Manually Upgrading Oracle AS from 10g to 11g _________________________408Verifying Manually ASM Device ______________________________________408

    Part 7 Oracle Real Application Cluster __________________ 410

    Oracle RAC Possible Installation Configurations _____________ 411

    Installing Oracle 10g R2 RAC on Enterprise Linux 4___________ 412Installation Environment ___________________________________________412Required Software ________________________________________________412Used Hardware __________________________________________________412Installation Plan__________________________________________________412

    1. Preinstallation tasks _________________________________________________ 4132. Oracle Clusterware installation _________________________________________ 420

  • Page 21 Oracle DBA Code Examples

    3. Oracle Database 10g Software Installation________________________________ 4244. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software____________ 4255. Install EM Agent in cluster nodes (if required) _____________________________ 4266. Configure Listeners __________________________________________________ 4267. Perform ASM installation ______________________________________________ 4278. Perform cluster database creation ______________________________________ 4279. Postinstallation tasks_________________________________________________ 42910. Useful Postinstallation Tasks __________________________________________ 430

    Installing Oracle 11g R2 RAC on Enterprise Linux 5___________ 431Main Changes in Oracle 11g Release 2 RAC ____________________________431Installation Environment ___________________________________________431Required Software ________________________________________________431Used Hardware __________________________________________________431Installation Plan__________________________________________________432

    1. Preinstallation tasks _________________________________________________ 4332. Oracle Grid Infrastructure installation____________________________________ 4403. Oracle Grid Infrastructure Patching______________________________________ 4424. Oracle Database 11g R2 Software Installation _____________________________ 4425. Oracle Database 11g R2 Software Patching _______________________________ 4436. Install EM Agent in cluster nodes (if required) _____________________________ 4437. ASM Diskgroups Creation _____________________________________________ 4438. RAC Database Creation _______________________________________________ 4449. Postinstallation tasks_________________________________________________ 44510. General Useful Postinstallation Tasks in Linux ____________________________ 446

    Installing Oracle 10g R2 RAC on Windows __________________ 447Installation Methods ______________________________________________447Installation Environment ___________________________________________447Required Software ________________________________________________447Used Virtual Hardware_____________________________________________447Installation Plan__________________________________________________448

    1. Preinstallation tasks _________________________________________________ 4482. Oracle Clusterware installation _________________________________________ 4503. Apply Patch Set 3 (10.2.0.4) on Clusterware software_______________________ 4524. Oracle ASM 10g Software Installation____________________________________ 453

  • Page 22 Oracle DBA Code Examples

    5. Apply Patchset 3 (10.2.0.4) on ASM Software _____________________________ 4546. Install EM Agent in cluster nodes (if required) _____________________________ 4547. Configure Listeners __________________________________________________ 4548. Create ASM Instance_________________________________________________ 4559. Install Oracle RAC Database Home Software ______________________________ 45610. Apply Patchset 3 (10.2.0.4) on Oracle RAC Software Home__________________ 45711. Perform cluster database creation _____________________________________ 45712. Useful Postinstallation Steps __________________________________________ 459

    Cleaning Up Clusterware Installation on Windows____________ 460

    Single Instance to RAC Conversion________________________ 462The Tools to Convert a Single Instance DB to RAC _______________________462Conversion Prerequisites for Oracle 10g R2 ____________________________462Using rconfig Utitlity ______________________________________________462Using DBCA _____________________________________________________463

    Administering RAC Database ____________________________ 465

    Administering Oracle Clusterware Components ______________ 466Managing Cluserware Daemons and Processes __________________________466

    Displaying Clusterware Processes _________________________________________ 466Starting, Stopping, Enabling and Disabling crs Stack __________________________ 466

    CSS Parameters__________________________________________________466Administering Voting Disks in RAC ___________________________________466

    Multiplexing Voting Disks________________________________________________ 466Dynamically Adding and Removing Voting Disks after Installing RAC _____________ 467Backing up Voting Disks ________________________________________________ 467Recovering Voting Disks ________________________________________________ 467

    Administering the Oracle Cluster Registry (OCR) ________________________467Replacing the OCR_____________________________________________________ 468Adding and Removing the OCR ___________________________________________ 468Repairing the OCR _____________________________________________________ 468Making Physical Backups of the OCR_______________________________________ 468Recovering the OCR using the Physical Backups______________________________ 469Making Logical Backups of the OCR (Exporting) ______________________________ 469Making Logical Backups of the OCR (Importing)______________________________ 469

  • Page 23 Oracle DBA Code Examples

    Diagnosing OCR Problems with the OCRDUMP and OCRCHECK Utilities____________ 470

    Administering Storage _________________________________ 471Datafile Access in Real Application Clusters _________________________________ 471Redo Log File Storage in Real Application Clusters ____________________________ 471Automatic Undo Management in Real Application Clusters ______________________ 471

    Administering ASM Instances with SRVCTL in RAC _______________________472

    Administering Cluster Databases _________________________ 473Displaying Current Instance in SQL*Plus Prompt ________________________473Starting and Stopping Instances and RAC Databases _____________________473

    Starting Up and Shutting Down with SQL*Plus_______________________________ 473Intermittent Windows Shutdown Issue in RAC Environments____________________ 473Starting Up and Shutting Down with SRVCTL ________________________________ 473

    Customizing How Oracle Clusterware Manages RAC Databases _____________474Switching Between the Database Automatic and Manual Policies ____________474Customizing Resource Parameters (like AUTO_START)____________________474Handling Initialization Parameter Files in RAC___________________________475

    Setting Server Parameter File Parameter Values for Real Application Clusters ______ 475Parameters Used in RAC Databases _______________________________________ 475Parameters that Must Have Identical Settings on All Instances __________________ 475Parameters That Must Have Unique Settings on All Instances ___________________ 476Parameters that Should Have Identical Settings on All Instances ________________ 476ASM Instance Initialization Parameters and RAC _____________________________ 476

    Dropping a RAC Database __________________________________________476

    Workload Management in RAC ___________________________ 477Types of Workload Distribution ______________________________________477Connection Load Balancing _________________________________________477

    Client-Side Load Balancing and Failover ____________________________________ 477Server-Side Load Balancing______________________________________________ 477

    Fast Application Notification (FAN) ___________________________________478Using Fast Application Notification Callouts_____________________________478Configuring the Server-Side ONS ____________________________________480Administering Load Balancing Advisory________________________________480

  • Page 24 Oracle DBA Code Examples

    Monitoring Load Balancing Advisory __________________________________481Transparent Application Failover (TAF) ________________________________482

    TAF Basic Configuration without FAN (From Client Side) _______________________ 482TAF Basic Configuration with FAN (Server-Side)______________________________ 482TAF Preconnect Configuration ____________________________________________ 482Verifying TAF Configuration______________________________________________ 483

    Enabling Distributed Transaction Processing for Services __________________483

    Administering Services_________________________________ 484Service Attributes ________________________________________________484Administering Services with DBCA____________________________________484Administering Services with PL/SQL __________________________________484Administering Services with SRVCTL __________________________________486Controlling the Preferred and Available Instances________________________486Using Services with Client Applications ________________________________487Services and the Scheduler _________________________________________487Measuring Performance by Service Using the AWR_______________________488Service Thresholds and Alerts _______________________________________490Service Performance Views _________________________________________491Restricted Session and Services _____________________________________491

    Configuring Recovery Manager and Archiving _______________ 492Backup Possible Distributions in RAC__________________________________492RMAN Restore Scenarios for Real Application Clusters ____________________492

    Cluster File System Restore Scheme_______________________________________ 492Non-Cluster File System Restore Scheme ___________________________________ 492

    RMAN and Oracle Net in Real Application Clusters _______________________492Connecting to Specific Node ________________________________________492Instance Recovery in Real Application Clusters__________________________493

    Single Node Failure in Real Application Clusters ______________________________ 493Multiple-Node Failures in Real Application Clusters____________________________ 493

    Configuring the RMAN Snapshot Control File Location ____________________493Configuring the RMAN Control File and SPFILE Autobackup Feature__________493

  • Page 25 Oracle DBA Code Examples

    Configuring Channels for RMAN in Real Application Clusters________________493Configuring Channels to use Automatic Workload Balancing ____________________ 493Configuring Channels to Use a Specific Instance _____________________________ 493

    Node Affinity Awareness of Fast Connections ___________________________494Archived Redo Log File Conventions in RAC ____________________________494Archive Redo Log Configuration Scenarios _____________________________494

    Automatic Storage Management and CFS Archiving Scheme ____________________ 494Non-Cluster File System Local Archiving Scheme _____________________________ 494

    Changing the Archiving Mode in Real Application Clusters _________________495Deleting Archived Redo Logs after a Successful Backup ___________________495Monitoring the Archiver Processes____________________________________495Log_Archive_Dest_1 Set To Default Even When DB_Recovery_File_Dest Is Set (Bug 6373164) __________________________________________________495Media Recovery in Real Application Clusters ____________________________497Parallel Recovery in Real Application Clusters ___________________________497Using a Flash Recovery Area in RAC __________________________________497

    Managing Backup and Recovery __________________________ 498

    Administrative Options_________________________________ 499Using Enterprise Manager Grid Control to Discover Nodes and Instances______499Additional Information About SQL*Plus in RAC __________________________499

    How SQL*Plus Commands Affect Instances _________________________________ 499Displaying Running Instances ____________________________________________ 499Displaying Connect Identifier_____________________________________________ 499

    Quiescing RAC Databases __________________________________________500Quiesced State and Cold Backups _________________________________________ 500

    Transparent Data Encryption and Wallets in RAC ________________________500Administering System and Network Interfaces with oifcfg _________________500

    Defining Network Interfaces with oifcfg ____________________________________ 500Syntax and Commands for the oifcfg Command-Line Tool ______________________ 500

    Changing Public or Interconnect IP Subnet Configuration__________________501Changing VIP Addresses ___________________________________________501

    Adding Nodes and Instances on UNIX-Based Systems_________ 503

  • Page 26 Oracle DBA Code Examples

    Adding Nodes to a RAC Environment__________________________________503Cloning Oracle Clusterware and RAC Software in Grid Environments _________503Quick-Start Node and Instance Addition Procedures______________________504

    Adding an Oracle Clusterware Home to a New Node __________________________ 504Adding an Oracle Home with RAC to a New Node_____________________________ 505

    Detailed Node and Instance Addition Procedure _________________________505Step 1: Connecting New Nodes to the Cluster___________________________505Step 2: Extending Clusterware and Oracle Software to New Nodes __________505Step 3: Preparing Storage on New Nodes ______________________________505Step 4: Adding Nodes at the Oracle RAC Database Layer__________________506Step 5: Adding Database Instances to New Nodes _______________________506

    Deleting Nodes and Instances on UNIX-Based Systems________ 507Option 1: Quick-Start Node and Instance Deletion Procedures______________507

    Deleting an Oracle Home with RAC from an Existing Node______________________ 507Deleting an Oracle Clusterware Home from an Existing Node ___________________ 508

    Option 2: Detailed Node and Instance Deletion Procedure _________________509Step 1: Deleting DB Instances from Real Application Clusters Databases _____509

    Using Enterprise Manager to Delete Database Instances from Existing Nodes_______ 509Using DBCA in Interactive Mode to Delete Database Instances from Existing Nodes__ 509Using DBCA in Silent Mode to Delete Instance from Existing Nodes_______________ 510

    Step 2: Deleting Nodes from Real Application Clusters Databases ___________510ASM Instance Clean-Up Procedures for Node Deletion ____________________511

    Adding and Deleting Nodes and Instances on Windows-Based Systems ____________________________________________ 512

    Cloning Oracle Clusterware and RAC Software in Grid Environments _________513Quick-Start Node and Database Instance Addition and Deletion Procedures ___513

    Adding an Oracle Clusterware Home to a New Node __________________________ 513Adding an Oracle Home with RAC to a New Node_____________________________ 513Deleting an Oracle Home with RAC from an Existing Node______________________ 513Deleting an Oracle Clusterware Home from an Existing Node ___________________ 513

    Detailed Node and Database Instance Addition and Deletion Procedures ______513Overview of Node Addition Procedures ________________________________513

  • Page 27 Oracle DBA Code Examples

    Step 1: Connecting New Nodes to the Cluster___________________________513Making Physical Connections_____________________________________________ 513Installing the Operating System __________________________________________ 513Verifying the Installation with the Cluster Verification Utility ____________________ 513Checking the Installation________________________________________________ 513

    Step 2: Extending Oracle Software to New Nodes at the Oracle Clusterware___513Step 3: Preparing Storage on New Nodes ______________________________513

    Raw Device Storage Preparation for New Nodes______________________________ 513Step 4: Adding Nodes at the Oracle RAC Database Layer__________________513Step 5: Adding Database Instances to New Nodes _______________________513

    Using Enterprise Manager to Add Database Instances to New Nodes______________ 513Using DBCA in Interactive Mode to Add Database Instances to New Nodes_________ 513Using DBCA in Silent Mode to Add Database Instances to New Nodes_____________ 513Connecting to iSQL*Plus after Adding a Node________________________________ 513

    Adding Nodes that Already Have Clusterware and Oracle Software to a Cluster 514Overview of Node Deletion Procedures ________________________________514Step 1: Deleting Instances from Real Application Clusters Databases ________514

    Using Enterprise Manager to Delete Database Instances from Existing Nodes_______ 514Using DBCA in Interactive Mode to Delete Database Instances from Existing Nodes__ 514Using DBCA in Silent Mode to Delete Instance from Existing Nodes_______________ 514

    Step 2: Deleting Nodes from Real Application Clusters Databases ___________514Step 3: ASM Instance Clean-Up Procedures for Node Deletion______________514

    Monitoring Performance ________________________________ 515RAC Common Tuning Tips __________________________________________515Instance Recovery and RAC_________________________________________515Global Cache Wait Events __________________________________________515Monitoring Performance in Enterprise Manager__________________________516

    Using the Cluster Database Performance Page _______________________________ 516Using the Cluster Database Instance Performance Page________________________ 516Using the Cluster Performance Page _______________________________________ 517Using the Cluster Interconnects Page ______________________________________ 517

    Making Applications Highly Available Using Oracle Clusterware _ 518Making an Application Highly Available Examples ________________________518

  • Page 28 Oracle DBA Code Examples

    Example1: Making an Application Highly Available ____________________________ 518Example2: Making an Application Highly Available ____________________________ 520Managing Automatic Oracle Clusterware Resource Operations for Action Scripts ____ 522Displaying Clusterware Application and Application Resource Status Information ____ 522Unregistering Applications and Application Resources _________________________ 523

    RAC Troubleshooting __________________________________ 524Diagnosing the Oracle Clusterware High Availability Components ___________524

    Debugging Recommnedation_____________________________________________ 524Clusterware Log Files and the Unified Log Directory Structure___________________ 524Dynamic Debugging____________________________________________________ 524Component Level Debugging_____________________________________________ 524Oracle Clusterware Shutdown and Startup __________________________________ 525Enabling and Disabling Oracle Clusterware Daemons __________________________ 525Diagnostics Collection Script _____________________________________________ 525The Oracle Clusterware Alerts ____________________________________________ 525Resource Debugging ___________________________________________________ 525Checking the Health of the Clusterware ____________________________________ 525Troubleshooting the Oracle Cluster Registry _________________________________ 525Troubleshooting Hostname Changes and CSS________________________________ 525Enabling Additional Tracing for Real Application Clusters High Availability__________ 526Diagnosing Oracle Real Application Clusters Components ______________________ 526Where to Find Files for Analyzing Errors ____________________________________ 526Using Instance-Specific Alert Files in Real Application Clusters __________________ 526Enabling Tracing for Java-Based Tools and Utilities in Real Application Clusters _____ 526Resolving Pending Shutdown Issues _______________________________________ 526

    Using the Cluster Verification Utility __________________________________526Cluster Verify Locations_________________________________________________ 526Cluster Verify Stages___________________________________________________ 526Cluster Verify Components ______________________________________________ 527CVU Component Verification Examples _____________________________________ 527Understanding CVU Commands, Help, Output, and Nodelist Shortcuts ____________ 528Performing Various CVU Tests____________________________________________ 528Known Issues for the Cluster Verification Utility ______________________________ 528

    Part 8 Oracle RAC One Node __________________________ 529

    Installing Oracle 11g R2 RAC One Node on Linux 5 ___________ 530

  • Page 29 Oracle DBA Code Examples

    Installation Environment ___________________________________________530Required Software ________________________________________________530Used Hardware __________________________________________________530Installation Plan__________________________________________________531

    1. Preinstallation tasks _________________________________________________ 5322. Oracle Grid Infrastructure installation____________________________________ 5393. Oracle Grid Infrastructure Patching______________________________________ 5424. Checking Oracle Grid Infrastructure Status _______________________________ 5425. Oracle Database 11g R2 Software Installation _____________________________ 5426. Oracle Database 11g R2 Software Patching _______________________________ 5437. Install EM Agent in cluster nodes (if required) _____________________________ 5448. ASM Diskgroups Creation _____________________________________________ 5449. RAC Database Creation _______________________________________________ 54510. Initialize the Database to RAC One Node (11.2.0.1 Only) ___________________ 54711. Postinstallation tasks________________________________________________ 54812. General Useful Postinstallation Tasks in Linux ____________________________ 548

    Instance Relocation using Omotion (11.2.0.1)_______________ 549

    Instance Relocation using Omotion (11.2.0.2)_______________ 550

    Part 9 Oracle Warehousing ___________________________ 551

    Oracle Warehouse Builder (OWB) ________________________ 552Oracle Warehouse Builder Architecture ________________________________552Starting and Stoping the Service_____________________________________552Configuring the Repository and Workspaces ____________________________552Steps of Using Warehouse Builder____________________________________553Mapping Operators _______________________________________________554

    Part 10 Oracle Database Utilities _______________________ 556

    Using SQL*Plus_______________________________________ 557Using SQL*Plus Command-Line Options _______________________________557Starting SQL*Plus Session__________________________________________557Controlling User Privileges in SQL*Plus ________________________________557

  • Page 30 Oracle DBA Code Examples

    Setting the SQL*Plus Environment with the SET Command ________________558Setting SQL*Plus Preferances _______________________________________558Logging SQL*Plus Errors ___________________________________________559Key SQL*Plus "Working" Commands__________________________________559Creating Command Files in SQL*Plus _________________________________559Copying Tables with the COPY Command ______________________________559Creating Web Pages Using SQL*Plus__________________________________560Using SQL to Generate SQL_________________________________________560Enabling AUTOTRACE for a User _____________________________________560Using rlwrap Utility with SQL*Plus in Unix-Based Systems _________________561Escaping Special Characters ________________________________________561

    Using SQL*Loader Utility _______________________________ 563Invoking SQL*Loader______________________________________________563Using SQL*Loader Control File ______________________________________563Loading Excel File into a Table using SQL*Loader________________________569Loading Large Fields into a Table ____________________________________569Using Direct Load Options __________________________________________570

    Data Pump Export and Import ___________________________ 571Data Pump Components ___________________________________________571Data Pump Export Interfaces________________________________________571Export Modes Parameters __________________________________________571Required Rrivileges _______________________________________________571Invoking Export Data Pump Examples_________________________________571Export Filtering Parameters _________________________________________572Export Remapping Parameters ______________________________________572Sampling Export Data _____________________________________________573Export Encryption Parameters _______________________________________573Export Estimating Parameters _______________________________________573Export Network Link Parameter______________________________________573Export PARALELL Parameter ________________________________________574

  • Page 31 Oracle DBA Code Examples

    Import Modes Parameters __________________________________________574File- and Directory-Related Parameters________________________________574Using TABLE_EXISTS_ACTION Parameter______________________________574Import Filtering Parameters_________________________________________574Import Remapping Parameters ______________________________________574Ignoring Nondeferred Constraints ____________________________________575Import Network Link Parameter _____________________________________575Import Flashback Parameters _______________________________________575Import PARALELL Parameter ________________________________________576Monitoring a Data Pump Jobs _______________________________________576

    LogMiner____________________________________________ 577Types of Supplemental Logging______________________________________577Levels of Supplemental Logging _____________________________________577Disabling Database-Level Supplemental Logging ________________________577LogMiner Dictionary Options ________________________________________578Redo Log File Options _____________________________________________578OPTIONS possible values in DBMS_LOGMNR.START_LOGMNR: _____________578Obtaining LogMiner Operational Information____________________________578Examples of Using LogMiner ________________________________________579

    Without Sepecifying the Redo Files ________________________________________ 579Wit Sepecifying the Redo Files ___________________________________________ 580

    Part 11 Miscellaneous Oracle Database Topics _____________ 582

    Managing Oracle Database Control________________________ 583Configuring and Using the Database Control____________________________583Implementing EM Database Control Auto Startup________________________583Dropping and Recreating the Management Repository ____________________584

    Installing Oracle 10g R5 (10.2) Enterprise Manager Grid Control for Linux x86 ___________________________________________ 585

    Installation Environment ___________________________________________585

  • Page 32 Oracle DBA Code Examples

    Required Software ________________________________________________585Used Hardware __________________________________________________585Installation Steps_________________________________________________585

    Remote Diagnostic Agent (RDA)__________________________ 593Using Remote Diagnostic Agent (RDA) ________________________________593

    Connect Oracle to SQL Server____________________________ 594Configuring and Using the Database Control____________________________594

    Part 12 PL/SQL Samples ______________________________ 596

    PL/SQL Basics _______________________________________ 597PL/SQL Data Types _______________________________________________597Controlling Compile-Time Displayed Warnings __________________________598Catching Returned Errors __________________________________________599Hiding Code _____________________________________________________599Controlling Program Flow___________________________________________599

    Using Cursors ________________________________________ 602

    Using Records________________________________________ 606

    Using Table Functions__________________________________ 608

    Using Collections _____________________________________ 610Using VARRAYS __________________________________________________610Using Nested Tables ______________________________________________613Using Associative Arrays ___________________________________________614Using Collection API_______________________________________________616

    Handling Errors_______________________________________ 621Predefined Exceptions _____________________________________________621Using User-Defined Exceptions ______________________________________621Using RAISE_APPLICATION_ERROR __________________________________622

  • Page 33 Oracle DBA Code Examples

    Autonomous Transactions ______________________________ 624

    Some Stored Subprobrams Concepts ______________________ 625Serially Reusable Packages _________________________________________625Stored Subprograms and Roles ______________________________________626Invokers vs. Definers Rights _______________________________________626Pinning an Programunit in the Shared Pool _____________________________627

    Using Triggers _______________________________________ 628Restrictions on Triggers_________________________________________________ 628

    Using DML Triggers _______________________________________________628Using Instead-of Triggers __________________________________________629Using System Triggers_____________________________________________630Handling Mutating Tables in Triggers _________________________________634Dropping and Disabling Triggers _____________________________________635

    Using Dynamic SQL____________________________________ 636Working with Native Dynamic SQL ___________________________________636Using DBMS_SQL_________________________________________________639

    Calling Java from PL/SQL _______________________________ 648

    Configuring Oracle Database to Use External Routines ________ 649

    Using Large Objects (LOBs) _____________________________ 652Creating LOB ____________________________________________________652Using SQL with Internal LOBs _______________________________________652Using LOBs in PL/SQL _____________________________________________653Performance Considerations ________________________________________662

    Using Returning Clause _________________________________________________ 662Using CONTEXT Index __________________________________________________ 663

    Migrating from LONGs to LOBs ______________________________________664

    PL/SQL Performance Tuning Tips_________________________ 665Use PL/SQL Profiler _______________________________________________665

  • Page 34 Oracle DBA Code Examples

    Use BULK COLLECT Clause _________________________________________666Set PLSQL_OPTIMIZE_LEVEL and Subprogram Inlining ___________________670Using Bind variables in Dynamic SQL _________________________________671Use NOCOPY Keyword _____________________________________________672Use Associative arrays_____________________________________________672Use Server Result Cache ___________________________________________672

    PL/SQL Miscellaneous Topics ____________________________ 673Accessing V$ Views from PL/SQL_____________________________________673

    Part 13 Appendixes__________________________________ 674

    Program Units and Scripts Used in the Document ____________ 675Return Parameter Value for Normal User ______________________________675Applying Random Load on Database Sample 1 __________________________676

    Setup _______________________________________________________________ 676Using the Load Generator Scripts _________________________________________ 682

    Applying Random Load on Database Sample 2 __________________________683Setup _______________________________________________________________ 683Using the Load Generator Scripts _________________________________________ 691

    SQL Usage Samples ___________________________________ 693Merge Command _________________________________________________693Multitable Inserts_________________________________________________693Parallel Insert ___________________________________________________694Deleting Duplicate Rows in a Table ___________________________________694Adding a Primary Key to a Table and then Filling it_______________________694

    More DBA Scripts _____________________________________ 696Compare Table Sizes in Two Databases _______________________________696

    Using Linux for Oracle _________________________________ 697Verifying the Kernel _______________________________________________697Checking for a Tainted Kernel _______________________________________697

  • Page 35 Oracle DBA Code Examples

    Supported Hardware ______________________________________________697Using Oracle Relink Utility __________________________________________697Certified and Supported File Systems _________________________________698Enterprise Linux Runlevels__________________________________________698Using /etc/oratab File and dbstart Utility_______________________________698Automating Jobs _________________________________________________699

    Using cron ___________________________________________________________ 699Using anacron ________________________________________________________ 700Using at command_____________________________________________________ 700Using batch command __________________________________________________ 701Task Scheduler _______________________________________________________ 701Configuring Linux Memory for Oracle ______________________________________ 701

    Using Linux Performance Monitoring Tools _____________________________701About Linux Tools _____________________________________________________ 702Using Linux Tools______________________________________________________ 702

    Checking Some General Guideline on Truning Oracle in Linux ______________703Troubleshooting Oracle Database in Linux _____________________________704

    Using OS Watcher (OSW) _______________________________________________ 704Using OS Watcher Graphs(OSWg)_________________________________________ 706Using the On-Board Monitor (LTOM) _______________________________________ 706Using strace__________________________________________________________ 707

  • Page 36 Oracle DBA Code Examples

    Part 1 Oracle DBA Fundamentals

  • Page 37 Oracle DBA Code Examples

    DBA: Best Practices

    DBA: Best Practice Guidelines for Standalone and RAC Databases

    Use SPFILE Use temporary tablespaces Register all instances with remote listeners Use Database Resource Manager Use resumable space allocation Use Automatic Segment Space Management Use locally managed tablespaces Use Automatic Undo Management Enable block checking Enable Flashback Database Enable ARCHIVELOG mode and use a flash recovery area Use auto-tune checkpointing Log checkpoints to the alert log Multiplex production and standby redo logs Set CONTROL_FILE_RECORD_KEEP_TIME long enough Create two or more control files

  • Page 38 Oracle DBA Code Examples

    Oracle Database Installation Consideration

    Estimating Disk and Memoery Requirements

    Make sure the storage vendor is listed in the Oracle Storage Compatibility Program (OSCP).

    Allocate swap space that is about two to three times your Oracle RAM allocation. On Estimating the RAM: o OS RAM: 20 percent of total RAM for MS-Windows, 10% of RAM for UNIX o Each Oracle connection consumes two megabytes of RAM + sort_area_size +

    hash_area_size o If dynamic memory sizing is not used:

    Shared_pool_size: If all the SQL statements that sent to ORACLE are using bind variable adequately, then 300M is enough in most cases

    Large_pool_size: For dedicated Oracle server: 20-30M Java_pool_size=10M Data buffer: All the rest RAM should be allocated to Data buffer.

    Optimal Flexible Architecture

    The OFA is a set of recommendations from Oracle Corporation aimed at simplifying management of complex software and databases often running under multiple versions of software.

    OFA Guidelines o Arrange at least four mount points that have names like /u01, /u02, /u03, and so

    on. o If the Oracle software owner is "oracle", make /u01/app/oracle your ORACLE_BASE

    # mkdir -p /u01/app/oracle # chown -R oracle:oinstall /u01/app/oracle # chmod -R 775 /u01/app/oracle

    o Make Oracle_HOME $ORACLE_BASE/product/version/{db|client|companion}_[n]. Examples: /u01/app/oracle/product/11.1.0/db_1 /u01/app/oracle/product/11.1.0/client_1 /u01/app/oracle/product/10.1.0.2.0/db_1

    o Install Flash Recovery Area in $ORACLE_BASE/flash_recovery_area in a mount point different from db files.

    o Administrative Files are to be created in ORACLE_BASE/admin/dbname o Store Oracle DB files in the mounted points.

    # mkdir /mount_point/oradata # chown oracle:oinstall /mount_point/oradata # chmod 775 /mount_point/oradata /u01/oradata/prod1/control01.ctl /u05/oradata/prod1/control02.ctl /u02/oradata/prod1/redo01.log /u04/oradata/prod1/redo02.log data file has this format: /u20/oradata/prod/system01.dbf

  • Page 39 Oracle DBA Code Examples

    Oracle Products Installed with the 11.1 Release

    The following products are installed by default with database server 11g: o Oracle Application Express o Oracle Warehouse Builder o Oracle Configuration Manager: Tool that collects and uploads configuration

    information to the Oracle configuration repository o Oracle SQL Developer o Oracle Database Vault: Tool that enables you to secure business data

  • Page 40 Oracle DBA Code Examples

    Installing Oracle 10g R2 on Enterprise Linux 4

    Installation Environment

    Emulation software: VMWare Server 2 on for Windows OS: Oracle Linux Enterprise 4.5 for x86: kernel 2.6.9

    Required Software

    Oracle Database 10g Release 2 for Linux x86 32-bit

    Used Hardware

    In the VMWare: create one virtual machine (oradb1) with the following specs: o 2 GB RAM o an ethernet card o one local hardisk with 20 GB

    Installation Plan

    1. Preinstallation tasks:

    o Hardware requirements o Software requirements o Environment configuration

    2. Oracle Database 10g Software Installation

    3. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software

    4. Configure Listeners

    5. Create Database

    6. Postinstallation tasks

    1. Preinstallation tasks

    Install Oracle Enterprise Linux in the first local hardisk. Install nothing in the remaining disks.

    Note: for a production system, consider becoming an Oracle Unbreakable Linux customer and register your server on the Unbreakable Linux Network.

    o Give the ethernet card IP 192.168.4.21 and the hostname oradb1.mydomain.com. Define a gateway. If it does not exist, make it same as the host IP address.

    o Insall the following packages: Desktop Environments

    o GNOME Desktop Environment

  • Page 41 Oracle DBA Code Examples

    Desktop o X Window System o Gnome

    Applications o Graphical Internet (optional)

    Servers o Do not select anything in this group.

    Development o Development Tools

    System o Administration Tools o System Tools

    Add the package 'sysstat' by clicking on the Details link and selecting "sysstat - The sar an iostat system monitoring commands." from the Optional Packages list.

    Miscellaneous o Do not select anything in this group.

    Complete the installation Install further packages: # to know distribution and version of Linux cat /etc/issue # to know kernel version (and its errata level) uname -r # from CD 3 rpm -Uvh libaio* rpm -Uvh openmotif21-2.1.30-11.RHEL4.6.i386.rpm rpm -Uvh openmotif-2.2.3-10.1.el4.i386.rpm # those packages downloaded from http://rpm.pbone.net rpm -e compat-libstdc++-296-2.96-132.7.2 rpm -Uvh compat-libstdc++-7.3-2.96.128.i386.rpm rpm -Uvh compat-libstdc++-devel-7.3-2.96.128.i386.rpm rpm -Uvh compat-gcc-7.3-2.96.128.i386.rpm rpm -Uvh compat-gcc-c++-7.3-2.96.128.i386.rpm # confirm the required packages are installed: rpm -qa|grep gcc- rpm -qa|grep glibc- rpm -qa|grep compat-db- rpm -qa|grep compat-gcc- rpm -qa|grep compat-gcc-c++- rpm -qa|grep compat-libstdc++- rpm -qa|grep compat-libstdc++-devel- rpm -qa|grep control-center-2.8.0 rpm -qa|grep openmotif21- rpm -qa|grep setarch- # SELINUX must be disabled

  • Page 42 Oracle DBA Code Examples

    cat /etc/selinux/config | grep SELINUX= vi /etc/selinux/config SELINUX=disabled shutdown -h now -r

    Check the hardware requirements # Hardware Requirements # At least 2 GB of physical memory grep MemTotal /proc/meminfo # swap space: twice the amount of physical memory grep SwapTotal /proc/meminfo # if you don't have enought swap, # you can add swap space by creating a temporary swap file. # let's say about 500MB: dd if=/dev/zero of=tempswap bs=1k count=500000 chmod 600 tempswap mke2fs tempswap mkswap tempswap swapon tempswap # 400 MB disk space in /tmp df -k /tmp # 4 GB of disk space for Oracle software df The size of the shared memory should be at least the greater of MEMORY_MAX_TARGET and MEMORY_TARGET for each Oracle instance on the computer. To determine the amount of shared memory available, enter the following command: df -h /dev/shm/ # to adjust the shared memory file system size: umount tmpfs mount -t tmpfs shmfs -o size=1200m /dev/shm

    Create the required network configuration: # Network names Resolution # configure /etc/hosts if no domain server is used cat /etc/hosts 127.0.0.1 localhost.localdomain oradb1.mydomain.com localhost oradb1

    Create and configure the required OS users and groups # inventory group groupadd -g 501 oinstall groupadd -g 502 dba # oracle software owner user /usr/sbin/useradd -u 200 -g oinstall -G dba oracle passwd oracle # make sure nobody user exists (if not there, create it useradd nobody) id nobody # The oracle User Environment # in /home/oracle/.bash_profile # export DISPLAY if required export ORACLE_BASE=/u01/app/oracle if [ $USER = "oracle" ]; then

  • Page 43 Oracle DBA Code Examples

    if [ $SHELL = "/bin/ksh" ]; then ulimit -p 16384 ulimit -n 65536 else ulimit -u 16384 -n 65536 fi umask 022 fi export EDITOR=vi export ORACLE_HOME=$ORACLE_BASE/product/10.2.0/db_1 export ORACLE_PATH=$ORACLE_BASE/common/oracle/sql:.:$ORACLE_HOME/rdbms/admin export ORACLE_SID=ora10g export NLS_LANG=AMERICAN_AMERICA.WE8ISO8859P1 export NLS_DATE_FORMAT="mm/dd/yyyy hh24:mi:ss" export PATH=.:${PATH}:$HOME/bin:$ORACLE_HOME/bin:$ORA_CRS_HOME/bin export PATH=${PATH}:/usr/bin:/bin:/usr/bin/X11:/usr/local/bin export PATH=${PATH}:$ORACLE_BASE/common/oracle/bin export ORACLE_TERM=xterm export TNS_ADMIN=$ORACLE_HOME/network/admin export ORA_NLS10=$ORACLE_HOME/nls/data export LD_LIBRARY_PATH=$ORACLE_HOME/lib export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:$ORACLE_HOME/oracm/lib export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}:/lib:/usr/lib:/usr/local/lib export CLASSPATH=$ORACLE_HOME/JRE export CLASSPATH=${CLASSPATH}:$ORACLE_HOME/jlib export CLASSPATH=${CLASSPATH}:$ORACLE_HOME/rdbms/jlib export CLASSPATH=${CLASSPATH}:$ORACLE_HOME/network/jlib export THREADS_FLAG=native export TEMP=/tmp export TMPDIR=/tmp # User Shell Limits # memlock is used to increase the per-process max locked memory vi /etc/security/limits.conf oracle soft nproc 2047 oracle hard nproc 16384 oracle soft nofile 1024 oracle hard nofile 65536 oracle soft memlock 3145728 oracle hard memlock 3145728

    Configure kernel parameters and shell limits Note: If you make a mistake with a parameter setting and your system does not start, then you must start Linux in the single-user runlevel (runlevel 1). At this runlevel, the /etc/sysctl.conf file is not run.

    # Configuring kernel parameters and shell limits # they can be tuned for a production db # Append the following to the /etc/sysctl.conf file as the root user: vi /etc/sysctl.conf kernel.sem = 250 32000 100 128 # maximum size may be given to SGA (max 4GB) # kernel.shmmax = 536870912 (512 M) # following is 1 GB kernel.shmmax =1073741824 net.ipv4.ip_local_port_range = 1024 65000 net.core.rmem_default = 4194304 net.core.rmem_max = 4194304

  • Page 44 Oracle DBA Code Examples

    net.core.wmem_default = 262144 net.core.wmem_max = 262144 # to take immediate effect /sbin/sysctl -p

    Configure hangcheck-timer kernel module: # check hangcheck-timer Module Configuration # with this module, if the kernel hangs, the machine will reboot # verify the module is loaded /sbin/lsmod | grep -i hang # if not loaded, load it vi /etc/modprobe.conf options hangcheck-timer hangcheck_tick=30 hangcheck_margin=180 # execute and add in the file vi /etc/rc.local /sbin/modprobe hangcheck-timer

    Create the required directories for the Oracle database software: # to know if there is an existing oracle inventory # from its output, ORACLE_BASE will be parent of oraInventory more /etc/oraInst.loc # to identify existing Oracle home directories more /etc/oratab # in the example above, /u01 should be owned by the root user # and writable by group oinstall cd / chown -R oracle:oinstall /u01 chmod -R 775 /u01/oracle mkdir -p /u01/app/oracle/product/10.2.0/db_1 mkdir /u01/stage chown -R oracle:oinstall /u01/app/oracle chmod -R 775 /u01/oracle chown oracle:oinstall /u01/stage

    As oracle, copy software installation into /u01/stage10g/db Disable screensavers on host & guest machines.

    o In Oracle Linux: Applications-> Preferences-> Screen Saver-> Mode: Disable Screen Saver

    o Do the same after logging off and logging on again as oracle user. Restart the machine.

    2. Oracle Database 10g Software Installation

    -- start OUI su - oracle cd /u01/stage10g/db ./runInstaller Follow the steps. Install database software only.

    3. Apply Patchset 3 (10.2.0.4) for Clusterware and Database Software

    # extract 10g Release 2 (10.2.0.4) Patch Set 3 for Linux x86 to

  • Page 45 Oracle DBA Code Examples

    /u01/stage10g/patch10.2.0.4/Disk1 mkdir /u01/stage10g/patch10.2.0.4 cd /u01/stage10g/patch10.2.0.4/Disk1 ./runInstaller Select path of ORACLE_HOME ->Next

    4. Configure Listeners

    cd /u01/app/oracle/product/10.2.0/db_1/bin ./netca & Add a new listener