Oracle9i Database Administrator`s Guide
Transcription
Oracle9i Database Administrator`s Guide
Oracle9i Database Administrator’s Guide Release 2 (9.2) March 2002 Part No. A96521-01 Oracle9i Database Administrator’s Guide, Release 2 (9.2) Part No. A96521-01 Copyright © 2001, 2002 Oracle Corporation. All rights reserved. Primary Author: Ruth Baylis Contributing Authors: Kathy Rich Graphic Designer: Valarie Moore Contributors: Lance Ashdown, Allen Brumm, Michele Cyran, Mary Ann Davidson, Harvey Eneman, Amit Ganesh, Carolyn Gray, Wei Huang, Robert Jenkins, Mark Kennedy, Sushil Kumar, Bill Lee, Yunrui Li, Diana Lorentz, Sujatha Muthulingam, Gary Ngai, Waleed Ojeil, Lois Price, Ananth Raghavan, Ann Rhee, Rajiv Sinha, Jags Srinivasan, Anh-Tuan Tran, Deborah Steiner, Janet Stern, Michael Stewart, Alex Tsukerman, Kothanda Umamageswaran, Steven Wertheimer, Daniel Wong The Programs (which include both the software and documentation) contain proprietary information of Oracle Corporation; they are provided under a license agreement containing restrictions on use and disclosure and are also protected by copyright, patent and other intellectual and industrial property laws. Reverse engineering, disassembly or decompilation of the Programs, except to the extent required to obtain interoperability with other independently created software or as specified by law, is prohibited. The information contained in this document is subject to change without notice. If you find any problems in the documentation, please report them to us in writing. Oracle Corporation does not warrant that this document is error-free. Except as may be expressly permitted in your license agreement for these Programs, no part of these Programs may be reproduced or transmitted in any form or by any means, electronic or mechanical, for any purpose, without the express written permission of Oracle Corporation. If the Programs are delivered to the U.S. Government or anyone licensing or using the programs on behalf of the U.S. Government, the following notice is applicable: Restricted Rights Notice Programs delivered subject to the DOD FAR Supplement are "commercial computer software" and use, duplication, and disclosure of the Programs, including documentation, shall be subject to the licensing restrictions set forth in the applicable Oracle license agreement. Otherwise, Programs delivered subject to the Federal Acquisition Regulations are "restricted computer software" and use, duplication, and disclosure of the Programs shall be subject to the restrictions in FAR 52.227-19, Commercial Computer Software - Restricted Rights (June, 1987). Oracle Corporation, 500 Oracle Parkway, Redwood City, CA 94065. The Programs are not intended for use in any nuclear, aviation, mass transit, medical, or other inherently dangerous applications. It shall be the licensee's responsibility to take all appropriate fail-safe, backup, redundancy, and other measures to ensure the safe use of such applications if the Programs are used for such purposes, and Oracle Corporation disclaims liability for any damages caused by such use of the Programs. Oracle is a registered trademark, and Oracle9i, Oracle8i, Oracle8, Oracle7, Oracle Names, Oracle Store, Oracle Transparent Gateway, PL/SQL, SQL*Net, and SQL*Plus are trademarks or registered trademarks of Oracle Corporation. Other names may be trademarks of their respective owners. Contents Send Us Your Comments ............................................................................................................... xxxi Preface...................................................................................................................................................... xxxiii What’s New in Oracle9i? ................................................................................................................. xlvii Part I 1 Basic Database Administration The Oracle Database Administrator Types of Oracle Users......................................................................................................................... Database Administrators............................................................................................................. Security Officers............................................................................................................................ Network Administrators ............................................................................................................. Application Developers ............................................................................................................... Application Administrators ........................................................................................................ Database Users.............................................................................................................................. Tasks of a Database Administrator ................................................................................................. Task 1: Evaluate the Database Server Hardware ..................................................................... Task 2: Install the Oracle Software............................................................................................. Task 3: Plan the Database ............................................................................................................ Task 4: Create and Open the Database...................................................................................... Task 5: Back Up the Database ..................................................................................................... Task 6: Enroll System Users ........................................................................................................ Task 7: Implement the Database Design ................................................................................... 1-2 1-2 1-3 1-3 1-3 1-4 1-4 1-4 1-5 1-5 1-5 1-6 1-7 1-7 1-7 iii Task 8: Back Up the Fully Functional Database ....................................................................... Task 9: Tune Database Performance .......................................................................................... Identifying Your Oracle Database Software Release................................................................... Release Number Format .............................................................................................................. Checking Your Current Release Number ............................................................................... Database Administrator Security and Privileges ....................................................................... The Database Administrator’s Operating System Account ................................................. Database Administrator Usernames ........................................................................................ Database Administrator Authentication ...................................................................................... Administrative Privileges.......................................................................................................... Selecting an Authentication Method ....................................................................................... Using Operating System (OS) Authentication ....................................................................... Using Password File Authentication ....................................................................................... Creating and Maintaining a Password File.................................................................................. Using ORAPWD ......................................................................................................................... Setting REMOTE_LOGIN_ PASSWORDFILE........................................................................ Adding Users to a Password File ............................................................................................. Maintaining a Password File..................................................................................................... Database Administrator Utilities................................................................................................... SQL*Loader ................................................................................................................................. Export and Import ...................................................................................................................... 2 Creating an Oracle Database Considerations Before Creating a Database .................................................................................. Planning for Database Creation.................................................................................................. Meeting Creation Prerequisites .................................................................................................. Deciding How to Create an Oracle Database ........................................................................... Using the Database Configuration Assistant................................................................................. Advantages of Using DBCA ....................................................................................................... Creating a Database Using DBCA.............................................................................................. Configuring Database Options ................................................................................................... Deleting a Database Using DBCA .............................................................................................. Managing DBCA Templates ....................................................................................................... Using DBCA Silent Mode .......................................................................................................... Manually Creating an Oracle Database........................................................................................ iv 1-7 1-8 1-8 1-8 1-10 1-10 1-10 1-11 1-13 1-13 1-15 1-17 1-18 1-20 1-20 1-22 1-23 1-24 1-26 1-26 1-26 2-2 2-2 2-4 2-4 2-5 2-6 2-7 2-9 2-9 2-9 2-13 2-14 Step 1: Decide on Your Instance Identifier (SID) ................................................................... Step 2: Establish the Database Administrator Authentication Method.............................. Step 3: Create the Initialization Parameter File ...................................................................... Step 4: Connect to the Instance ................................................................................................. Step 5: Start the Instance............................................................................................................ Step 6: Issue the CREATE DATABASE Statement ................................................................ Step 7: Create Additional Tablespaces .................................................................................... Step 8: Run Scripts to Build Data Dictionary Views.............................................................. Step 9: Run Scripts to Install Additional Options (Optional)............................................... Step 10: Create a Server Parameter File (Recommended) .................................................... Step 11: Back Up the Database.................................................................................................. Understanding the CREATE DATABASE Statement ................................................................ Protecting Your Database: Specifying Passwords for Users SYS and SYSTEM................ Clauses that Simplify Database Creation and Management................................................ Creating a Locally Managed SYSTEM Tablespace ................................................................ Specifying the Database Time Zone and Time Zone File ..................................................... Specifying FORCE LOGGING Mode ...................................................................................... Troubleshooting Database Creation ............................................................................................. Dropping a Database ....................................................................................................................... Considerations After Creating a Database .................................................................................. Some Security Considerations .................................................................................................. Installing Oracle’s Sample Schemas......................................................................................... Initialization Parameters and Database Creation....................................................................... Determining the Global Database Name ................................................................................ Specifying Control Files............................................................................................................. Specifying Database Block Sizes............................................................................................... Setting Initialization Parameters that Affect the Size of the SGA ...................................... Specifying the Maximum Number of Processes .................................................................... Specifying the Method of Undo Space Management............................................................ Setting License Parameters........................................................................................................ Managing Initialization Parameters Using a Server Parameter File ...................................... What is a Server Parameter File?.............................................................................................. Migrating to a Server Parameter File....................................................................................... Creating a Server Parameter File.............................................................................................. The SPFILE Initialization Parameter........................................................................................ 2-14 2-15 2-15 2-17 2-17 2-18 2-20 2-21 2-21 2-21 2-22 2-22 2-23 2-23 2-26 2-28 2-29 2-31 2-31 2-31 2-32 2-33 2-34 2-35 2-36 2-37 2-38 2-41 2-42 2-43 2-44 2-44 2-45 2-46 2-47 v Using ALTER SYSTEM to Change Initialization Parameter Values ................................... Exporting the Server Parameter File ........................................................................................ Backing Up the Server Parameter File ..................................................................................... Errors and Recovery for the Server Parameter File ............................................................... Viewing Parameter Settings ...................................................................................................... 3 Using Oracle-Managed Files What are Oracle-Managed Files? ..................................................................................................... Who Can Use Oracle-Managed Files? ....................................................................................... Benefits of Using Oracle-Managed Files ................................................................................... Oracle-Managed Files and Existing Functionality................................................................... Enabling the Creation and Use of Oracle-Managed Files........................................................... Setting the DB_CREATE_FILE_DEST Initialization Parameter............................................. Setting the DB_CREATE_ONLINE_LOG_DEST_n Initialization Parameter ...................... Creating Oracle-Managed Files........................................................................................................ How Oracle-Managed Files are Named .................................................................................... Creating Oracle-Managed Files at Database Creation ............................................................ Creating Datafiles for Tablespaces ........................................................................................... Creating Tempfiles for Temporary Tablespaces .................................................................... Creating Control Files ................................................................................................................ Creating Online Redo Log Files................................................................................................ Behavior of Oracle-Managed Files ................................................................................................ Dropping Datafiles and Tempfiles........................................................................................... Dropping Online Redo Log Files.............................................................................................. Renaming Files ............................................................................................................................ Managing Standby Databases................................................................................................... Scenarios for Using Oracle-Managed Files.................................................................................. Scenario 1: Create and Manage a Database with Multiplexed Online Redo Logs............ Scenario 2: Add Oracle-Managed Files to an Existing Database ......................................... 4 3-2 3-2 3-3 3-4 3-4 3-5 3-6 3-6 3-7 3-8 3-14 3-16 3-17 3-19 3-21 3-21 3-22 3-22 3-22 3-22 3-23 3-27 Starting Up and Shutting Down Starting Up a Database ...................................................................................................................... Options for Starting Up a Database ........................................................................................... Preparing to Start an Instance..................................................................................................... Using SQL*Plus to Start Up a Database .................................................................................... vi 2-47 2-49 2-50 2-50 2-51 4-2 4-2 4-3 4-3 Starting an Instance: Scenarios ................................................................................................... Altering Database Availability ........................................................................................................ Mounting a Database to an Instance.......................................................................................... Opening a Closed Database ...................................................................................................... Opening a Database in Read-Only Mode ............................................................................... Restricting Access to an Open Database ................................................................................. Shutting Down a Database ............................................................................................................. Shutting Down with the NORMAL Option ........................................................................... Shutting Down with the IMMEDIATE Option ...................................................................... Shutting Down with the TRANSACTIONAL Option .......................................................... Shutting Down with the ABORT Option ................................................................................ Quiescing a Database....................................................................................................................... Placing a Database into a Quiesced State................................................................................ Restoring the System to Normal Operation ........................................................................... Viewing the Quiesce State of an Instance ............................................................................... Suspending and Resuming a Database........................................................................................ Part II 5 4-5 4-9 4-9 4-10 4-10 4-11 4-11 4-12 4-12 4-13 4-13 4-14 4-15 4-16 4-16 4-17 Oracle Server Processes and Storage Structure Managing Oracle Processes Server Processes .................................................................................................................................. Dedicated Server Processes......................................................................................................... Shared Server Processes............................................................................................................... Configuring Oracle for the Shared Server ..................................................................................... Initialization Parameters for Shared Server.............................................................................. Setting the Initial Number of Dispatchers (DISPATCHERS)................................................. Setting the Initial Number of Shared Servers (SHARED_SERVERS) ................................... Modifying Dispatcher and Server Processes ............................................................................ Monitoring Shared Server ......................................................................................................... About Oracle Background Processes ............................................................................................ Monitoring the Processes of an Oracle Instance......................................................................... Process and Session Views ........................................................................................................ Monitoring Locks........................................................................................................................ Trace Files and the Alert File .................................................................................................... Managing Processes for Parallel Execution ................................................................................. 5-2 5-2 5-3 5-5 5-5 5-6 5-7 5-8 5-10 5-11 5-13 5-14 5-15 5-15 5-18 vii Managing the Parallel Execution Servers................................................................................ Altering Parallel Execution for a Session ................................................................................ Managing Processes for External Procedures.............................................................................. Terminating Sessions ....................................................................................................................... Identifying Which Session to Terminate ................................................................................. Terminating an Active Session ................................................................................................. Terminating an Inactive Session............................................................................................... 6 Managing Control Files What Is a Control File?....................................................................................................................... Guidelines for Control Files ............................................................................................................. Provide Filenames for the Control Files .................................................................................... Multiplex Control Files on Different Disks............................................................................... Place Control Files Appropriately.............................................................................................. Back Up Control Files................................................................................................................... Manage the Size of Control Files ................................................................................................ Creating Control Files ........................................................................................................................ Creating Initial Control Files....................................................................................................... Creating Additional Copies, Renaming, and Relocating Control Files ................................ Creating New Control Files......................................................................................................... Troubleshooting After Creating Control Files .............................................................................. Checking for Missing or Extra Files ........................................................................................... Handling Errors During CREATE CONTROLFILE .............................................................. Backing Up Control Files ................................................................................................................ Recovering a Control File Using a Current Copy ....................................................................... Recovering from Control File Corruption Using a Control File Copy ............................... Recovering from Permanent Media Failure Using a Control File Copy ............................ Dropping Control Files.................................................................................................................... Displaying Control File Information ............................................................................................ 7 6-2 6-2 6-2 6-3 6-3 6-3 6-4 6-4 6-4 6-5 6-5 6-9 6-9 6-10 6-10 6-10 6-10 6-11 6-11 6-12 Managing the Online Redo Log What Is the Online Redo Log?.......................................................................................................... Redo Threads................................................................................................................................. Online Redo Log Contents .......................................................................................................... How Oracle Writes to the Online Redo Log ............................................................................. viii 5-18 5-19 5-20 5-21 5-22 5-22 5-23 7-2 7-2 7-2 7-3 Planning the Online Redo Log......................................................................................................... Multiplexing Online Redo Log Files.......................................................................................... Placing Online Redo Log Members on Different Disks .......................................................... Setting the Size of Online Redo Log Members......................................................................... Choosing the Number of Online Redo Log Files................................................................... Controlling Archive Lag............................................................................................................ Creating Online Redo Log Groups and Members ..................................................................... Creating Online Redo Log Groups .......................................................................................... Creating Online Redo Log Members ....................................................................................... Relocating and Renaming Online Redo Log Members ............................................................ Dropping Online Redo Log Groups and Members ................................................................... Dropping Log Groups................................................................................................................ Dropping Online Redo Log Members ..................................................................................... Forcing Log Switches ....................................................................................................................... Verifying Blocks in Redo Log Files............................................................................................... Clearing an Online Redo Log File................................................................................................. Viewing Online Redo Log Information ....................................................................................... 8 7-5 7-5 7-9 7-9 7-10 7-10 7-12 7-13 7-13 7-14 7-16 7-16 7-17 7-18 7-18 7-19 7-20 Managing Archived Redo Logs What Is the Archived Redo Log? ..................................................................................................... Choosing Between NOARCHIVELOG and ARCHIVELOG Mode......................................... Running a Database in NOARCHIVELOG Mode................................................................... Running a Database in ARCHIVELOG Mode ......................................................................... Controlling Archiving........................................................................................................................ Setting the Initial Database Archiving Mode ........................................................................... Changing the Database Archiving Mode.................................................................................. Enabling Automatic Archiving................................................................................................... Disabling Automatic Archiving ................................................................................................. Performing Manual Archiving ................................................................................................... Specifying the Archive Destination................................................................................................ Specifying Archive Destinations .............................................................................................. Understanding Archive Destination Status............................................................................ Specifying the Mode of Log Transmission .................................................................................. Normal Transmission Mode ..................................................................................................... Standby Transmission Mode .................................................................................................... 8-2 8-2 8-2 8-3 8-4 8-5 8-5 8-6 8-8 8-9 8-9 8-10 8-12 8-14 8-14 8-14 ix Managing Archive Destination Failure ........................................................................................ Specifying the Minimum Number of Successful Destinations ............................................ Re-Archiving to a Failed Destination....................................................................................... Tuning Archive Performance by Specifying Multiple ARCn Processes................................ Controlling Trace Output Generated by the Archivelog Process ............................................ Viewing Information About the Archived Redo Log ................................................................ Dynamic Performance Views.................................................................................................... The ARCHIVE LOG LIST Command ...................................................................................... 9 Using LogMiner to Analyze Redo Logs Potential Uses for Data Stored in Redo Logs ................................................................................ Accessing Information Stored in Redo Logs ................................................................................. Redo Logs and Dictionary Files ....................................................................................................... Redo Logs....................................................................................................................................... Dictionary Options ....................................................................................................................... Tracking DDL Statements............................................................................................................ LogMiner Recommendations and Restrictions........................................................................... Recommendations ...................................................................................................................... Restrictions................................................................................................................................... Filtering Data That is Returned ..................................................................................................... Showing Only Committed Transactions ................................................................................. Skipping Redo Corruptions ...................................................................................................... Filtering Data By Time ............................................................................................................... Filtering Data By SCN ................................................................................................................ Accessing LogMiner Information.................................................................................................. Querying V$LOGMNR_CONTENTS .......................................................................................... Executing Reconstructed SQL Statements .............................................................................. Formatting of Returned Data .................................................................................................... Extracting Actual Data Values from Redo Logs .......................................................................... NULL Returns From the MINE_VALUE Function ............................................................... Usage Rules for the MINE_VALUE and COLUMN_PRESENT Functions ....................... Supplemental Logging..................................................................................................................... Database Supplemental Logging.............................................................................................. Table Supplemental Logging .................................................................................................... Steps in a Typical LogMiner Session ............................................................................................ x 8-16 8-16 8-18 8-19 8-21 8-23 8-23 8-24 9-2 9-3 9-4 9-4 9-5 9-9 9-10 9-10 9-11 9-12 9-12 9-14 9-14 9-15 9-15 9-16 9-17 9-17 9-18 9-18 9-19 9-19 9-20 9-22 9-23 Perform Initial Setup Activities ................................................................................................ Extract a Dictionary.................................................................................................................... Specify Redo Logs for Analysis ................................................................................................ Start a LogMiner Session ........................................................................................................... Query V$LOGMNR_CONTENTS ........................................................................................... End a LogMiner Session ............................................................................................................ Example Uses of LogMiner............................................................................................................. Example: Using LogMiner to Track Changes Made By a Specific User............................. Example: Using LogMiner to Calculate Table Access Statistics .......................................... 10 Managing Job Queues Enabling Processes Used for Executing Jobs............................................................................... Managing Job Queues ..................................................................................................................... The DBMS_JOB Package............................................................................................................ Submitting a Job to the Job Queue ........................................................................................... How Jobs Execute ....................................................................................................................... Removing a Job from the Job Queue ..................................................................................... Altering a Job............................................................................................................................. Broken Jobs ................................................................................................................................ Forcing a Job to Execute........................................................................................................... Terminating a Job ..................................................................................................................... Viewing Job Queue Information ................................................................................................. Displaying Information About a Job ..................................................................................... Displaying Information About Running Jobs ...................................................................... 11 9-24 9-24 9-24 9-26 9-28 9-28 9-28 9-28 9-30 10-2 10-3 10-3 10-4 10-9 10-10 10-11 10-12 10-14 10-14 10-15 10-15 10-15 Managing Tablespaces Guidelines for Managing Tablespaces ......................................................................................... Use Multiple Tablespaces.......................................................................................................... Specify Tablespace Default Storage Parameters .................................................................... Assign Tablespace Quotas to Users ......................................................................................... Creating Tablespaces........................................................................................................................ Locally Managed Tablespaces .................................................................................................. Dictionary-Managed Tablespaces .......................................................................................... Temporary Tablespaces ........................................................................................................... Coalescing Free Space in Dictionary-Managed Tablespaces ................................................. 11-2 11-2 11-3 11-3 11-3 11-5 11-10 11-12 11-16 xi How Oracle Coalesces Free Space.......................................................................................... Manually Coalescing Free Space ............................................................................................ Monitoring Free Space ............................................................................................................. Specifying Nonstandard Block Sizes for Tablespaces............................................................. Controlling the Writing of Redo Records .................................................................................. Altering Tablespace Availability ................................................................................................. Taking Tablespaces Offline ..................................................................................................... Bringing Tablespaces Online................................................................................................... Altering the Availability of Datafiles or Tempfiles.............................................................. Using Read-Only Tablespaces...................................................................................................... Making a Tablespace Read-Only............................................................................................ Making a Read-Only Tablespace Writable ........................................................................... Creating a Read-Only Tablespace on a WORM Device ...................................................... Delaying the Opening of Datafiles in Read Only Tablespaces .......................................... Dropping Tablespaces.................................................................................................................... Diagnosing and Repairing Locally Managed Tablespace Problems .................................... Scenario 1: Fixing Bitmap When Allocated Blocks are Marked Free (No Overlap) ....... Scenario 2: Dropping a Corrupted Segment......................................................................... Scenario 3: Fixing Bitmap Where Overlap is Reported....................................................... Scenario 4: Correcting Media Corruption of Bitmap Blocks .............................................. Scenario 5: Migrating from a Dictionary-Managed to a Locally Managed Tablespace . Migrating the SYSTEM Tablespace to a Locally Managed Tablespace................................ Transporting Tablespaces Between Databases.......................................................................... Introduction to Transportable Tablespaces .......................................................................... Limitations ................................................................................................................................. Compatibility Considerations for Transportable Tablespaces........................................... Transporting Tablespaces Between Databases: A Procedure ............................................ Object Behaviors ....................................................................................................................... Using Transportable Tablespaces........................................................................................... Viewing Tablespace Information................................................................................................. Listing Tablespaces and Default Storage Parameters: Example ........................................ Listing the Datafiles and Associated Tablespaces of a Database: Example ..................... Displaying Statistics for Free Space (Extents) of Each Tablespace: Example................... xii 11-16 11-17 11-18 11-19 11-20 11-21 11-21 11-23 11-23 11-24 11-25 11-27 11-27 11-28 11-29 11-30 11-32 11-32 11-32 11-33 11-33 11-34 11-34 11-35 11-36 11-36 11-37 11-43 11-46 11-50 11-51 11-51 11-51 12 Managing Datafiles Guidelines for Managing Datafiles............................................................................................... Determine the Number of Datafiles......................................................................................... Determine the Size of Datafiles ................................................................................................ Place Datafiles Appropriately................................................................................................... Store Datafiles Separate from Redo Log Files ........................................................................ Creating Datafiles and Adding Datafiles to a Tablespace......................................................... Changing a Datafile’s Size .............................................................................................................. Enabling and Disabling Automatic Extension for a Datafile ............................................... Manually Resizing a Datafile.................................................................................................... Altering Datafile Availability......................................................................................................... Bringing Datafiles Online or Taking Offline in ARCHIVELOG Mode .............................. Taking Datafiles Offline in NOARCHIVELOG Mode .......................................................... Altering the Availability of All Datafiles or Tempfiles in a Tablespace............................. Renaming and Relocating Datafiles............................................................................................ Renaming and Relocating Datafiles for a Single Tablespace ............................................. Renaming and Relocating Datafiles for Multiple Tablespaces .......................................... Dropping Datafiles ......................................................................................................................... Verifying Data Blocks in Datafiles .............................................................................................. Mapping Files to Physical Devices ............................................................................................. Overview of Oracle’s File Mapping Interface ...................................................................... How Oracle’s File Mapping Interface Works ....................................................................... Using Oracle’s File Mapping Interface .................................................................................. File Mapping Examples ........................................................................................................... Viewing Datafile Information ................................................................................................ 13 12-2 12-2 12-4 12-4 12-4 12-5 12-6 12-6 12-7 12-8 12-9 12-9 12-9 12-10 12-11 12-13 12-14 12-14 12-15 12-16 12-16 12-21 12-25 12-28 Managing Undo Space What is Undo? ................................................................................................................................... Specifying the Mode for Undo Space Management.................................................................. Starting an Instance in Automatic Undo Management Mode ............................................. Starting an Instance in Manual Undo Management Mode .................................................. Managing Undo Tablespaces.......................................................................................................... Creating an Undo Tablespace................................................................................................... Altering an Undo Tablespace ................................................................................................... Dropping an Undo Tablespace................................................................................................. 13-2 13-3 13-3 13-4 13-5 13-6 13-7 13-7 xiii Switching Undo Tablespaces .................................................................................................... 13-8 Establishing User Quotas for Undo Space .............................................................................. 13-9 Specifying the Retention Period for Undo Information........................................................ 13-9 Viewing Information About Undo Space.............................................................................. 13-11 Managing Rollback Segments...................................................................................................... 13-13 Guidelines for Managing Rollback Segments ...................................................................... 13-13 Creating Rollback Segments.................................................................................................... 13-19 Altering Rollback Segments .................................................................................................... 13-21 Explicitly Assigning a Transaction to a Rollback Segment ................................................ 13-24 Dropping Rollback Segments.................................................................................................. 13-25 Viewing Rollback Segment Information ............................................................................... 13-25 Part III 14 Schema Objects Managing Space for Schema Objects Managing Space in Data Blocks..................................................................................................... 14-2 Specifying the PCTFREE Parameter ........................................................................................ 14-2 Specifying the PCTUSED Parameter ....................................................................................... 14-5 Selecting Associated PCTUSED and PCTFREE Values ........................................................ 14-7 Specifying the Transaction Entry Parameters: INITRANS and MAXTRANS................... 14-8 Setting Storage Parameters ............................................................................................................. 14-8 Identifying the Storage Parameters.......................................................................................... 14-9 Setting Default Storage Parameters for Segments in a Tablespace ................................... 14-11 Setting Storage Parameters for Data Segments .................................................................... 14-11 Setting Storage Parameters for Index Segments................................................................... 14-12 Setting Storage Parameters for LOBs, Varrays, and Nested Tables .................................. 14-12 Changing Values for Storage Parameters ............................................................................. 14-13 Understanding Precedence in Storage Parameters.............................................................. 14-13 Example of How Storage Parameters Effect Space Allocation .......................................... 14-14 Managing Resumable Space Allocation..................................................................................... 14-14 Resumable Space Allocation Overview................................................................................. 14-15 Enabling and Disabling Resumable Space Allocation......................................................... 14-19 Detecting Suspended Statements ........................................................................................... 14-21 Resumable Space Allocation Example: Registering an AFTER SUSPEND Trigger........ 14-23 Deallocating Space.......................................................................................................................... 14-25 xiv Viewing the High Water Mark ............................................................................................... Issuing Space Deallocation Statements ................................................................................. Examples of Deallocating Space............................................................................................. Understanding Space Use of Datatypes ..................................................................................... 15 14-25 14-26 14-26 14-29 Managing Tables Guidelines for Managing Tables ................................................................................................... Design Tables Before Creating Them ...................................................................................... Specify How Data Block Space Is to Be Used......................................................................... Specify the Location of Each Table .......................................................................................... Consider Parallelizing Table Creation..................................................................................... Consider Using NOLOGGING When Creating Tables ........................................................ Estimate Table Size and Set Storage Parameters ................................................................... Plan for Large Tables ................................................................................................................. Table Restrictions........................................................................................................................ Creating Tables.................................................................................................................................. Creating a Table ......................................................................................................................... Creating a Temporary Table ..................................................................................................... Parallelizing Table Creation...................................................................................................... Automatically Collecting Statistics on Tables ........................................................................ Altering Tables ................................................................................................................................ Altering Physical Attributes of a Table ................................................................................. Moving a Table to a New Segment or Tablespace............................................................... Manually Allocating Storage for a Table .............................................................................. Modifying an Existing Column’s Definition ........................................................................ Adding Table Columns ........................................................................................................... Renaming Table Columns ....................................................................................................... Dropping Table Columns........................................................................................................ Redefining Tables Online ............................................................................................................. Features of Online Table Redefinition................................................................................... The DBMS_REDEFINITION Package ................................................................................... Steps for Online Redefinition of Tables................................................................................. Intermediate Synchronization ................................................................................................ Abort and Cleanup After Errors............................................................................................. Example of Online Table Redefinition .................................................................................. 15-2 15-2 15-2 15-3 15-4 15-4 15-4 15-5 15-6 15-6 15-7 15-8 15-8 15-9 15-10 15-11 15-12 15-12 15-13 15-13 15-14 15-14 15-16 15-16 15-17 15-17 15-19 15-20 15-20 xv Restrictions................................................................................................................................. Dropping Tables.............................................................................................................................. Managing Index-Organized Tables ............................................................................................. What are Index-Organized Tables.......................................................................................... Creating Index-Organized Tables .......................................................................................... Maintaining Index-Organized Tables.................................................................................... Analyzing Index-Organized Tables ....................................................................................... Using the ORDER BY Clause with Index-Organized Tables ............................................. Converting Index-Organized Tables to Regular Tables...................................................... Managing External Tables ............................................................................................................. Creating External Tables.......................................................................................................... Altering External Tables .......................................................................................................... Dropping External Tables........................................................................................................ System and Object Privileges for External Tables................................................................ Viewing Information About Tables ............................................................................................ 16 15-22 15-23 15-24 15-24 15-25 15-30 15-32 15-33 15-33 15-33 15-35 15-38 15-39 15-39 15-40 Managing Indexes Guidelines for Managing Indexes................................................................................................. 16-2 Create Indexes After Inserting Table Data.............................................................................. 16-3 Index the Correct Tables and Columns ................................................................................... 16-4 Order Index Columns for Performance................................................................................... 16-5 Limit the Number of Indexes for Each Table.......................................................................... 16-5 Drop Indexes That Are No Longer Required ........................................................................ 16-5 Specify Index Block Space Use.................................................................................................. 16-5 Estimate Index Size and Set Storage Parameters ................................................................... 16-6 Specify the Tablespace for Each Index..................................................................................... 16-6 Consider Parallelizing Index Creation .................................................................................... 16-7 Consider Creating Indexes with NOLOGGING .................................................................... 16-7 Consider Costs and Benefits of Coalescing or Rebuilding Indexes..................................... 16-8 Consider Cost Before Disabling or Dropping Constraints ................................................... 16-9 Creating Indexes................................................................................................................................ 16-9 Creating an Index Explicitly.................................................................................................... 16-10 Creating a Unique Index Explicitly........................................................................................ 16-11 Creating an Index Associated with a Constraint ................................................................. 16-11 Collecting Incidental Statistics when Creating an Index .................................................... 16-13 xvi Creating a Large Index ............................................................................................................ Creating an Index Online ........................................................................................................ Creating a Function-Based Index ........................................................................................... Creating a Key-Compressed Index ........................................................................................ Altering Indexes.............................................................................................................................. Altering Storage Characteristics of an Index ........................................................................ Rebuilding an Existing Index.................................................................................................. Monitoring Index Usage.......................................................................................................... Monitoring Space Use of Indexes................................................................................................ Dropping Indexes ........................................................................................................................... Viewing Index Information .......................................................................................................... 17 16-13 16-13 16-14 16-18 16-19 16-20 16-20 16-21 16-21 16-22 16-23 Managing Partitioned Tables and Indexes What Are Partitioned Tables and Indexes?.................................................................................. Partitioning Methods ....................................................................................................................... When to Use the Range Partitioning Method......................................................................... When to Use the Hash Partitioning Method .......................................................................... When to Use the List Partitioning Method ............................................................................. When to Use the Composite Range-Hash Partitioning Method.......................................... When to Use the Composite Range-List Partitioning Method ............................................ Creating Partitioned Tables .......................................................................................................... Creating Range-Partitioned Tables ........................................................................................ Creating Hash-Partitioned Tables.......................................................................................... Creating List-Partitioned Tables............................................................................................. Creating Composite Range-Hash Partitioned Tables ......................................................... Creating Composite Range-List Partitioned Tables ............................................................ Using Subpartition Templates to Describe Composite Partitioned Tables...................... Creating Partitioned Index-Organized Tables ..................................................................... Partitioning Restrictions for Multiple Block Sizes ............................................................... Maintaining Partitioned Tables ................................................................................................... Updating Global Indexes Automatically .............................................................................. Adding Partitions ..................................................................................................................... Coalescing Partitions................................................................................................................ Dropping Partitions.................................................................................................................. Exchanging Partitions .............................................................................................................. 17-2 17-3 17-4 17-5 17-5 17-7 17-8 17-10 17-11 17-12 17-13 17-14 17-15 17-17 17-19 17-22 17-22 17-26 17-27 17-31 17-32 17-35 xvii Merging Partitions .................................................................................................................... Modifying Default Attributes ................................................................................................. Modifying Real Attributes of Partitions ................................................................................ Modifying List Partitions: Adding Values ............................................................................ Modifying List Partitions: Dropping Values ........................................................................ Modifying a Subpartition Template....................................................................................... Moving Partitions ..................................................................................................................... Rebuilding Index Partitions .................................................................................................... Renaming Partitions ................................................................................................................. Splitting Partitions .................................................................................................................... Truncating Partitions................................................................................................................ Partitioned Tables and Indexes Examples.................................................................................. Moving the Time Window in a Historical Table.................................................................. Converting a Partition View into a Partitioned Table ......................................................... Viewing Information About Partitioned Tables and Indexes................................................ 18 17-38 17-43 17-44 17-45 17-46 17-48 17-48 17-50 17-51 17-52 17-59 17-61 17-61 17-62 17-64 Managing Clusters Guidelines for Managing Clusters ................................................................................................ 18-2 Choose Appropriate Tables for the Cluster ............................................................................ 18-4 Choose Appropriate Columns for the Cluster Key ............................................................... 18-4 Specify Data Block Space Use ................................................................................................... 18-5 Specify the Space Required by an Average Cluster Key and Its Associated Rows .......... 18-5 Specify the Location of Each Cluster and Cluster Index Rows............................................ 18-6 Estimate Cluster Size and Set Storage Parameters................................................................. 18-6 Creating Clusters............................................................................................................................... 18-6 Creating Clustered Tables ......................................................................................................... 18-7 Creating Cluster Indexes ........................................................................................................... 18-8 Altering Clusters ............................................................................................................................... 18-8 Altering Clustered Tables.......................................................................................................... 18-9 Altering Cluster Indexes.......................................................................................................... 18-10 Dropping Clusters .......................................................................................................................... 18-10 Dropping Clustered Tables ..................................................................................................... 18-11 Dropping Cluster Indexes ....................................................................................................... 18-11 Viewing Information About Clusters ......................................................................................... 18-11 xviii 19 Managing Hash Clusters When to Use Hash Clusters ............................................................................................................ Situations Where Hashing Is Useful ........................................................................................ Situations Where Hashing Is Not Advantageous .................................................................. Creating Hash Clusters.................................................................................................................... Creating Single-Table Hash Clusters....................................................................................... Controlling Space Use Within a Hash Cluster ....................................................................... Estimating Size Required by Hash Clusters ........................................................................... Altering Hash Clusters .................................................................................................................... Dropping Hash Clusters.................................................................................................................. Viewing Information About Hash Clusters ................................................................................ 20 Managing Views, Sequences, and Synonyms Managing Views ............................................................................................................................... Creating Views............................................................................................................................ Updating a Join View................................................................................................................. Altering Views .......................................................................................................................... Dropping Views........................................................................................................................ Replacing Views ....................................................................................................................... Managing Sequences ..................................................................................................................... Creating Sequences .................................................................................................................. Altering Sequences ................................................................................................................... Dropping Sequences ................................................................................................................ Managing Synonyms ..................................................................................................................... Creating Synonyms .................................................................................................................. Dropping Synonyms ................................................................................................................ Viewing Information About Views, Synonyms, and Sequences .......................................... 21 19-2 19-3 19-3 19-4 19-5 19-5 19-8 19-9 19-9 19-9 20-2 20-2 20-5 20-10 20-10 20-10 20-11 20-12 20-13 20-13 20-13 20-14 20-14 20-15 General Management of Schema Objects Creating Multiple Tables and Views in a Single Operation .................................................... Renaming Schema Objects ............................................................................................................. Analyzing Tables, Indexes, and Clusters ..................................................................................... Collecting Statistics for Tables, Indexes, and Clusters .......................................................... Validating Tables, Indexes, Clusters, and Materialized Views ........................................... 21-2 21-3 21-3 21-4 21-6 xix Listing Chained Rows of Tables and Clusters........................................................................ 21-7 Truncating Tables and Clusters ...................................................................................................... 21-9 Using DELETE .......................................................................................................................... 21-10 Using DROP and CREATE...................................................................................................... 21-10 Using TRUNCATE ................................................................................................................... 21-10 Enabling and Disabling Triggers................................................................................................. 21-11 Enabling Triggers...................................................................................................................... 21-13 Disabling Triggers .................................................................................................................... 21-13 Managing Integrity Constraints................................................................................................... 21-14 Integrity Constraint States....................................................................................................... 21-15 Setting Integrity Constraints Upon Definition ..................................................................... 21-17 Modifying, Renaming, or Dropping Existing Integrity Constraints ................................. 21-18 Deferring Constraint Checks................................................................................................... 21-20 Reporting Constraint Exceptions............................................................................................ 21-21 Viewing Constraint Information ............................................................................................ 21-23 Managing Object Dependencies.................................................................................................. 21-23 Manually Recompiling Views................................................................................................. 21-25 Manually Recompiling Procedures and Functions.............................................................. 21-25 Manually Recompiling Packages ........................................................................................... 21-25 Managing Object Name Resolution............................................................................................ 21-25 Changing Storage Parameters for the Data Dictionary ........................................................... 21-27 Structures in the Data Dictionary ........................................................................................... 21-28 Errors that Require Changing Data Dictionary Storage ..................................................... 21-30 Displaying Information About Schema Objects ...................................................................... 21-30 Using PL/SQL Packages to Display Information About Schema Objects ....................... 21-30 Using Views to Display Information About Schema Objects ............................................ 21-32 22 Detecting and Repairing Data Block Corruption Options for Repairing Data Block Corruption............................................................................ About the DBMS_REPAIR Package.............................................................................................. DBMS_REPAIR Procedures ...................................................................................................... Limitations and Restrictions ..................................................................................................... Using the DBMS_REPAIR Package .............................................................................................. Task 1: Detect and Report Corruptions ................................................................................... Task 2: Evaluate the Costs and Benefits of Using DBMS_REPAIR ..................................... xx 22-2 22-2 22-2 22-3 22-3 22-4 22-5 Task 3: Make Objects Usable..................................................................................................... Task 4: Repair Corruptions and Rebuild Lost Data............................................................... DBMS_REPAIR Examples .............................................................................................................. Using ADMIN_TABLES to Build a Repair Table or Orphan Key Table ............................ Using the CHECK_OBJECT Procedure to Detect Corruption ........................................... Fixing Corrupt Blocks with the FIX_CORRUPT_BLOCKS Procedure............................. Finding Index Entries Pointing into Corrupt Data Blocks: DUMP_ORPHAN_KEYS... Rebuilding Free Lists Using the REBUILD_FREELISTS Procedure ................................. Enabling or Disabling the Skipping of Corrupt Blocks: SKIP_CORRUPT_BLOCKS..... Part IV 23 Database Security Establishing Security Policies System Security Policy..................................................................................................................... Database User Management ..................................................................................................... User Authentication ................................................................................................................... Operating System Security........................................................................................................ Data Security Policy ......................................................................................................................... User Security Policy ......................................................................................................................... General User Security ................................................................................................................ End-User Security....................................................................................................................... Administrator Security .............................................................................................................. Application Developer Security ............................................................................................. Application Administrator Security ...................................................................................... Password Management Policy ..................................................................................................... Account Locking....................................................................................................................... Password Aging and Expiration ............................................................................................ Password History ..................................................................................................................... Password Complexity Verification ........................................................................................ Auditing Policy ............................................................................................................................... A Security Checklist....................................................................................................................... 24 22-7 22-7 22-8 22-9 22-10 22-12 22-13 22-13 22-14 23-2 23-2 23-2 23-3 23-3 23-4 23-4 23-6 23-8 23-10 23-12 23-12 23-13 23-14 23-15 23-16 23-20 23-20 Managing Users and Resources Managing Oracle Users ................................................................................................................... 24-2 xxi Creating Users ............................................................................................................................. 24-2 Altering Users.............................................................................................................................. 24-6 Dropping Users ........................................................................................................................... 24-7 User Authentication Methods ........................................................................................................ 24-8 Database Authentication ........................................................................................................... 24-9 External Authentication........................................................................................................... 24-11 Global Authentication and Authorization ............................................................................ 24-13 Proxy Authentication and Authorization ............................................................................. 24-16 Managing Resources with Profiles .............................................................................................. 24-18 Enabling and Disabling Resource Limits .............................................................................. 24-19 Creating Profiles ....................................................................................................................... 24-20 Assigning Profiles ..................................................................................................................... 24-20 Altering Profiles ........................................................................................................................ 24-21 Using Composite Limits .......................................................................................................... 24-21 Dropping Profiles ..................................................................................................................... 24-23 Viewing Information About Database Users and Profiles ..................................................... 24-23 Listing All Users and Associated Information ..................................................................... 24-25 Listing All Tablespace Quotas ................................................................................................ 24-25 Listing All Profiles and Assigned Limits .............................................................................. 24-25 Viewing Memory Use for Each User Session ....................................................................... 24-26 25 Managing User Privileges and Roles Understanding User Privileges and Roles ................................................................................... 25-2 System Privileges ........................................................................................................................ 25-2 Object Privileges.......................................................................................................................... 25-4 User Roles .................................................................................................................................... 25-5 Managing User Roles ....................................................................................................................... 25-6 Creating a Role ............................................................................................................................ 25-7 Specifying the Type of Role Authorization............................................................................. 25-8 Dropping Roles ......................................................................................................................... 25-10 Granting User Privileges and Roles ............................................................................................ 25-11 Granting System Privileges and Roles................................................................................... 25-11 Granting Object Privileges....................................................................................................... 25-12 Revoking User Privileges and Roles ........................................................................................... 25-16 Revoking System Privileges and Roles.................................................................................. 25-16 xxii Revoking Object Privileges ..................................................................................................... Cascading Effects of Revoking Privileges............................................................................. Granting to and Revoking from the User Group PUBLIC ..................................................... When Do Grants and Revokes Take Effect? .............................................................................. The SET ROLE Statement ........................................................................................................ Specifying Default Roles.......................................................................................................... Restricting the Number of Roles that a User Can Enable................................................... Granting Roles Using the Operating System or Network ..................................................... Using Operating System Role Identification ........................................................................ Using Operating System Role Management ........................................................................ Granting and Revoking Roles When OS_ROLES=TRUE ................................................... Enabling and Disabling Roles When OS_ROLES=TRUE ................................................... Using Network Connections with Operating System Role Management ....................... Viewing Privilege and Role Information................................................................................... Listing All System Privilege Grants....................................................................................... Listing All Role Grants ............................................................................................................ Listing Object Privileges Granted to a User.......................................................................... Listing the Current Privilege Domain of Your Session....................................................... Listing Roles of the Database.................................................................................................. Listing Information About the Privilege Domains of Roles............................................... 26 25-16 25-19 25-20 25-20 25-21 25-21 25-22 25-22 25-23 25-25 25-25 25-25 25-25 25-26 25-27 25-28 25-28 25-29 25-30 25-30 Auditing Database Use Guidelines for Auditing.................................................................................................................. Decide Whether to Use the Database or Operating System Audit Trail ............................ Keep Audited Information Manageable ................................................................................. Guidelines for Auditing Suspicious Database Activity ........................................................ Guidelines for Auditing Normal Database Activity ............................................................. What Information is Contained in the Audit Trail?................................................................... Information Stored in the Database Audit Trail .................................................................... Information Stored in an Operating System File ................................................................... Actions Audited by Default............................................................................................................ Auditing Administrative Users...................................................................................................... Managing the Audit Trail................................................................................................................ Enabling and Disabling Auditing ............................................................................................ Setting Auditing Options .......................................................................................................... 26-2 26-2 26-3 26-3 26-4 26-4 26-4 26-5 26-6 26-6 26-7 26-8 26-9 xxiii Auditing in a Multi-Tier Environment .................................................................................. Turning Off Audit Options ..................................................................................................... Controlling the Growth and Size of the Audit Trail............................................................ Protecting the Audit Trail........................................................................................................ Fine-Grained Auditing .................................................................................................................. Viewing Database Audit Trail Information............................................................................... Creating the Audit Trail Views............................................................................................... Deleting the Audit Trail Views............................................................................................... Using Audit Trail Views to Investigate Suspicious Activities ........................................... Part V 27 26-13 26-13 26-15 26-18 26-18 26-19 26-19 26-20 26-20 Database Resource Management Using the Database Resource Manager What Is the Database Resource Manager? ................................................................................... 27-2 What Problems Does the Database Resource Manager Address?....................................... 27-2 How Does the Database Resource Manager Address These Problems? ............................ 27-2 What are the Elements of the Database Resource Manager? ............................................... 27-3 Understanding Resource Plans................................................................................................. 27-4 Administering the Database Resource Manager ........................................................................ 27-8 Creating a Simple Resource Plan................................................................................................. 27-10 Creating Complex Resource Plans............................................................................................... 27-11 Using the Pending Area for Creating Plan Schemas ........................................................... 27-12 Creating Resource Plans .......................................................................................................... 27-14 Creating Resource Consumer Groups ................................................................................... 27-16 Specifying Resource Plan Directives...................................................................................... 27-17 Managing Resource Consumer Groups...................................................................................... 27-20 Assigning an Initial Resource Consumer Group ................................................................. 27-21 Changing Resource Consumer Groups ................................................................................. 27-21 Managing the Switch Privilege............................................................................................... 27-22 Enabling the Database Resource Manager ................................................................................ 27-24 Putting It All Together: Database Resource Manager Examples ........................................... 27-25 Multilevel Schema Example.................................................................................................... 27-25 Example of Using Several Resource Allocation Methods................................................... 27-27 An Oracle Supplied Plan ......................................................................................................... 27-28 Monitoring and Tuning the Database Resource Manager ...................................................... 27-29 xxiv Creating the Environment....................................................................................................... Why Is This Necessary to Produce Expected Results?........................................................ Monitoring Results ................................................................................................................... Viewing Database Resource Manager Information................................................................. Viewing Consumer Groups Granted to Users or Roles...................................................... Viewing Plan Schema Information ........................................................................................ Viewing Current Consumer Groups for Sessions ............................................................... Viewing the Currently Active Plans ...................................................................................... Part VI 28 27-29 27-30 27-31 27-31 27-32 27-33 27-33 27-34 Distributed Database Management Distributed Database Concepts Distributed Database Architecture ............................................................................................... Homogenous Distributed Database Systems ......................................................................... Heterogeneous Distributed Database Systems ...................................................................... Client/Server Database Architecture ...................................................................................... Database Links .................................................................................................................................. What Are Database Links? ........................................................................................................ What Are Shared Database Links?......................................................................................... Why Use Database Links? ....................................................................................................... Global Database Names in Database Links .......................................................................... Names for Database Links ...................................................................................................... Types of Database Links.......................................................................................................... Users of Database Links........................................................................................................... Creation of Database Links: Examples .................................................................................. Schema Objects and Database Links...................................................................................... Database Link Restrictions ...................................................................................................... Distributed Database Administration........................................................................................ Site Autonomy .......................................................................................................................... Distributed Database Security ................................................................................................ Auditing Database Links......................................................................................................... Administration Tools ............................................................................................................... Transaction Processing in a Distributed System ...................................................................... Remote SQL Statements .......................................................................................................... Distributed SQL Statements.................................................................................................... 28-2 28-2 28-5 28-6 28-8 28-8 28-10 28-11 28-12 28-14 28-15 28-16 28-19 28-20 28-22 28-23 28-24 28-24 28-31 28-31 28-33 28-33 28-34 xxv Shared SQL for Remote and Distributed Statements .......................................................... Remote Transactions ................................................................................................................ Distributed Transactions.......................................................................................................... Two-Phase Commit Mechanism............................................................................................. Database Link Name Resolution ............................................................................................ Schema Object Name Resolution............................................................................................ Global Name Resolution in Views, Synonyms, and Procedures ....................................... Distributed Database Application Development..................................................................... Transparency in a Distributed Database System ................................................................. Remote Procedure Calls (RPCs) ............................................................................................. Distributed Query Optimization ............................................................................................ Character Set Support for Distributed Environments............................................................. Client/Server Environment .................................................................................................... Homogeneous Distributed Environment.............................................................................. Heterogeneous Distributed Environment............................................................................. 29 28-34 28-35 28-35 28-35 28-36 28-38 28-42 28-44 28-44 28-46 28-47 28-47 28-48 28-48 28-49 Managing a Distributed Database Managing Global Names in a Distributed System .................................................................... 29-2 Understanding How Global Database Names Are Formed................................................. 29-2 Determining Whether Global Naming Is Enforced ............................................................... 29-3 Viewing a Global Database Name............................................................................................ 29-4 Changing the Domain in a Global Database Name............................................................... 29-4 Changing a Global Database Name: Scenario ........................................................................ 29-5 Creating Database Links ................................................................................................................. 29-8 Obtaining Privileges Necessary for Creating Database Links ............................................. 29-8 Specifying Link Types................................................................................................................ 29-9 Specifying Link Users............................................................................................................... 29-11 Using Connection Qualifiers to Specify Service Names Within Link Names ................. 29-13 Creating Shared Database Links.................................................................................................. 29-14 Determining Whether to Use Shared Database Links......................................................... 29-14 Creating Shared Database Links............................................................................................. 29-15 Configuring Shared Database Links ...................................................................................... 29-16 Managing Database Links............................................................................................................. 29-18 Closing Database Links............................................................................................................ 29-19 Dropping Database Links........................................................................................................ 29-19 xxvi Limiting the Number of Active Database Link Connections............................................. Viewing Information About Database Links............................................................................ Determining Which Links Are in the Database ................................................................... Determining Which Link Connections Are Open ............................................................... Creating Location Transparency .................................................................................................. Using Views to Create Location Transparency.................................................................... Using Synonyms to Create Location Transparency ............................................................ Using Procedures to Create Location Transparency ........................................................... Managing Statement Transparency............................................................................................. Managing a Distributed Database: Scenarios........................................................................... Creating a Public Fixed User Database Link ........................................................................ Creating a Public Fixed User Shared Database Link........................................................... Creating a Public Connected User Database Link............................................................... Creating a Public Connected User Shared Database Link.................................................. Creating a Public Current User Database Link .................................................................... 30 Developing Applications for a Distributed Database System Managing the Distribution of an Application’s Data................................................................ Controlling Connections Established by Database Links........................................................ Maintaining Referential Integrity in a Distributed System..................................................... Tuning Distributed Queries ........................................................................................................... Using Collocated Inline Views ................................................................................................. Using Cost-Based Optimization ............................................................................................... Using Hints.................................................................................................................................. Analyzing the Execution Plan................................................................................................... Handling Errors in Remote Procedures...................................................................................... 31 29-20 29-21 29-21 29-24 29-26 29-26 29-28 29-30 29-32 29-34 29-34 29-35 29-35 29-36 29-37 30-2 30-2 30-3 30-3 30-4 30-5 30-8 30-9 30-11 Distributed Transactions Concepts What Are Distributed Transactions?............................................................................................. Session Trees for Distributed Transactions ................................................................................. Clients........................................................................................................................................... Database Servers......................................................................................................................... Local Coordinators ..................................................................................................................... Global Coordinator..................................................................................................................... Commit Point Site....................................................................................................................... 31-2 31-4 31-5 31-5 31-6 31-6 31-6 xxvii Two-Phase Commit Mechanism ................................................................................................. Prepare Phase ............................................................................................................................ Commit Phase ........................................................................................................................... Forget Phase............................................................................................................................... In-Doubt Transactions.................................................................................................................... Automatic Resolution of In-Doubt Transactions ................................................................. Manual Resolution of In-Doubt Transactions ...................................................................... Relevance of System Change Numbers for In-Doubt Transactions .................................. Distributed Transaction Processing: Case Study ...................................................................... Stage 1: Client Application Issues DML Statements............................................................ Stage 2: Oracle Determines Commit Point Site .................................................................... Stage 3: Global Coordinator Sends Prepare Response ........................................................ Stage 4: Commit Point Site Commits ..................................................................................... Stage 5: Commit Point Site Informs Global Coordinator of Commit................................ Stage 6: Global and Local Coordinators Tell All Nodes to Commit ................................. Stage 7: Global Coordinator and Commit Point Site Complete the Commit................... 32 31-10 31-11 31-14 31-15 31-15 31-16 31-18 31-19 31-19 31-19 31-21 31-21 31-23 31-23 31-24 31-24 Managing Distributed Transactions Specifying the Commit Point Strength of a Node...................................................................... 32-2 Naming Transactions........................................................................................................................ 32-2 Viewing Information About Distributed Transactions ............................................................. 32-3 Determining the ID Number and Status of Prepared Transactions .................................... 32-3 Tracing the Session Tree of In-Doubt Transactions ............................................................... 32-5 Deciding How to Handle In-Doubt Transactions....................................................................... 32-7 Discovering Problems with a Two-Phase Commit................................................................ 32-8 Determining Whether to Perform a Manual Override.......................................................... 32-9 Analyzing the Transaction Data ............................................................................................... 32-9 Manually Overriding In-Doubt Transactions ........................................................................... 32-10 Manually Committing an In-Doubt Transaction ................................................................. 32-11 Manually Rolling Back an In-Doubt Transaction................................................................. 32-12 Purging Pending Rows from the Data Dictionary ................................................................... 32-13 Executing the PURGE_LOST_DB_ENTRY Procedure ........................................................ 32-13 Determining When to Use DBMS_TRANSACTION........................................................... 32-14 Manually Committing an In-Doubt Transaction: Example .................................................... 32-15 Step 1: Record User Feedback ................................................................................................. 32-16 xxviii Step 2: Query DBA_2PC_PENDING ..................................................................................... Step 3: Query DBA_2PC_NEIGHBORS on Local Node ..................................................... Step 4: Querying Data Dictionary Views on All Nodes...................................................... Step 5: Commit the In-Doubt Transaction ............................................................................ Step 6: Check for Mixed Outcome Using DBA_2PC_PENDING ...................................... Data Access Failures Due To Locks............................................................................................. Transaction Timeouts............................................................................................................... Locks from In-Doubt Transactions ........................................................................................ Simulating Distributed Transaction Failure.............................................................................. Managing Read Consistency ........................................................................................................ 32-16 32-18 32-19 32-22 32-22 32-23 32-23 32-24 32-24 32-25 Index xxix xxx Send Us Your Comments Oracle9i Database Administrator’s Guide, Release 2 (9.2) Part No. A96521-01 Oracle Corporation welcomes your comments and suggestions on the quality and usefulness of this document. Your input is an important part of the information used for revision. ■ ■ ■ ■ ■ Did you find any errors? Is the information clearly presented? Do you need more information? If so, where? Are the examples correct? Do you need more examples? What features did you like most? If you find any errors or have any other suggestions for improvement, please indicate the document title and part number, and the chapter, section, and page number (if available). You can send comments to us in the following ways: ■ ■ ■ Electronic mail: [email protected] FAX: (650) 506-7227 Attn: Server Technologies Documentation Manager Postal service: Oracle Corporation Server Technologies Documentation 500 Oracle Parkway, Mailstop 4op11 Redwood Shores, CA 94065 USA If you would like a reply, please give your name, address, telephone number, and (optionally) electronic mail address. If you have problems with the software, please contact your local Oracle Support Services. xxxi xxxii Preface This guide is for people who administer the operation of an Oracle database system. Referred to as database administrators (DBAs), they are responsible for creating Oracle databases, ensuring their smooth operation, and monitoring their use. This preface contains these topics: ■ Audience ■ Organization ■ Related Documentation ■ Conventions ■ Documentation Accessibility Note: The Oracle9i Database Administrator’s Guide contains information that describes the features and functionality of the Oracle9i [Standard Edition], Oracle9i Enterprise Edition, and Oracle9i Personal Edition products. These products have the same basic features. However, several advanced features are available only with the Oracle9i Enterprise Edition or Oracle9i Personal Edition, and some of these are optional. For example, to create partitioned tables and indexes, you must have the Oracle9i Enterprise Edition or Oracle9i Personal Edition. For information about the differences between the various editions of Oracle9i and the features and options that are available to you, please refer to Oracle9i Database New Features. xxxiii Audience Readers of this guide are assumed to be familiar with relational database concepts. They are also assumed to be familiar with the operating system environment under which they are running Oracle. Readers Interested in Installation and Upgrade Information Administrators frequently participate in installing the Oracle server software and upgrading existing Oracle databases to newer formats (for example, version 8 databases to Oracle9i format). This guide is not an installation or upgrade manual. If your primary interest is installation, see your operating system specific Oracle installation guide. If your primary interest is upgrading a database or application, see the Oracle9i Database Migration manual. Readers Interested in Application Design Information In addition to administrators, experienced users of Oracle and advanced database application designers might also find information in this guide useful. However, database application developers should also see the Oracle9i Application Developer’s Guide - Fundamentals and the documentation for the tool or language product they are using to develop Oracle database applications. Organization This document contains: Part I: Basic Database Administration Chapter 1, "The Oracle Database Administrator" This chapter serves as a general introduction to typical tasks performed by database administrators, such as installing software and planning a database. Chapter 2, "Creating an Oracle Database" This chapter discusses considerations for creating a database and takes you through the steps of creating one. Consult this chapter when in the database planning and creation stage. xxxiv Chapter 3, "Using Oracle-Managed Files" This chapter describes how you can direct the Oracle database server to create and manage your: ■ Datafiles ■ Tempfiles ■ Online redo log files ■ Control files Chapter 4, "Starting Up and Shutting Down" Consult this chapter when you wish to start up a database, alter its availability, or shut it down. Parameter files related to starting up and shutting down are also described here. Part II: Oracle Server Processes and Storage Structure Chapter 5, "Managing Oracle Processes" This chapter helps you to identify different Oracle processes, such as dedicated server processes and shared server processes. Consult this chapter when configuring, modifying, tracking and managing processes. Chapter 6, "Managing Control Files" This chapter describes all aspects of managing control files: naming, creating, troubleshooting, and dropping control files. Chapter 7, "Managing the Online Redo Log" This chapter describes all aspects of managing the online redo log: planning, creating, renaming, dropping, or clearing online redo log files. Chapter 8, "Managing Archived Redo Logs" Consult this chapter for information about archive modes and tuning archiving. Chapter 9, "Using LogMiner to Analyze Redo Logs" This chapter describes the use of LogMiner to analyze redo log files. xxxv Chapter 10, "Managing Job Queues" Consult this chapter before working with job queues. All aspects of submitting, removing, altering, and fixing job queues are described. Chapter 11, "Managing Tablespaces" This chapter provides guidelines to follow as you manage tablespaces, and describes how to create, manage, alter, drop and move data between tablespaces. Chapter 12, "Managing Datafiles" This chapter provides guidelines to follow as you manage datafiles, and describes how to create, change, alter, rename and view information about datafiles. Chapter 13, "Managing Undo Space" Consult this chapter to learn how to manage undo space, either by using an undo tablespace or rollback segments. Part III: Schema Objects Chapter 14, "Managing Space for Schema Objects" Consult this chapter for descriptions of common tasks, such as setting storage parameters, deallocating space and managing space. Chapter 15, "Managing Tables" Consult this chapter for general table management guidelines, as well as information about creating, altering, maintaining and dropping tables. Chapter 16, "Managing Indexes" Consult this chapter for general guidelines about indexes, including creating, altering, monitoring and dropping indexes. Chapter 17, "Managing Partitioned Tables and Indexes" Consult this chapter to learn about partitioned tables and indexes and how to create and manage them. Chapter 18, "Managing Clusters" Consult this chapter for general guidelines to follow when creating, altering, or dropping clusters. xxxvi Chapter 19, "Managing Hash Clusters" Consult this chapter for general guidelines to follow when creating, altering, or dropping hash clusters. Chapter 20, "Managing Views, Sequences, and Synonyms" This chapter describes all aspects of managing views, sequences and synonyms. Chapter 21, "General Management of Schema Objects" This chapter covers more varied aspects of schema management. The operations described in this chapter are not unique to any one type of schema objects. Consult this chapter for information about analyzing objects, truncation of tables and clusters, database triggers, integrity constraints, and object dependencies. Chapter 22, "Detecting and Repairing Data Block Corruption" This chapter describes methods for detecting and repairing data block corruption. Part IV: Database Security Chapter 23, "Establishing Security Policies" This chapter describes all aspects of database security, including system, data and user security policies, as well as specific tasks associated with password management. Chapter 24, "Managing Users and Resources" This chapter describes session and user licensing, user authentication, and provides specific examples of tasks associated with managing users and resources. Chapter 25, "Managing User Privileges and Roles" This chapter contains information about all aspects of managing user privileges and roles. Consult this chapter to find out how to grant and revoke privileges and roles. Chapter 26, "Auditing Database Use" This chapter describes how to create, manage and view audit information. xxxvii Part V: Database Resource Management Chapter 27, "Using the Database Resource Manager" This chapter describes how to use the Database Resource Manager to allocate resources. Part VI: Distributed Database Management Chapter 28, "Distributed Database Concepts" This chapter describes the basic concepts and terminology of Oracle’s distributed database architecture. Chapter 29, "Managing a Distributed Database" This chapter describes how to manage and maintain a distributed database system. Chapter 30, "Developing Applications for a Distributed Database System" This chapter describes considerations important when developing an application to run in a distributed database system. Chapter 31, "Distributed Transactions Concepts" This chapter describes what distributed transactions are and how Oracle maintains their integrity. Chapter 32, "Managing Distributed Transactions" This chapter describes how to manage and troubleshoot distributed transactions. Related Documentation For more information, see these Oracle resources: ■ Oracle9i Database Concepts Chapter 1 of Oracle9i Database Concepts contains an overview of the concepts and terminology related to Oracle and provides a foundation for the more detailed information in this guide. This chapter is a starting point to become familiar with the Oracle database server, and is recommended reading before starting Oracle9i Database Administrator’s Guide. The remainder of Oracle9i Database Concepts explains the Oracle architecture and features, and how they operate in more detail. xxxviii ■ Oracle9i Backup and Recovery Concepts This book introduces you to the concepts of backup and recovery. ■ Oracle9i User-Managed Backup and Recovery Guide This guide contains details of backup and recovery and enables you back up, copy, restore, and recover datafiles, control files, and archived redo logs. ■ Oracle9i Recovery Manager User’s Guide This guide contains information for using Recovery Manager (RMAN). RMAN is an Oracle tool that manages and automates backup and recovery operations. ■ Oracle9i Database Performance Planning This book exposes important considerations in setting up a database system and can help you understand tuning your database. It is mainly conceptual, defining terms, architecture, and design principles, and then outlines proactive and reactive tuning methods. ■ Oracle9i Database Performance Tuning Guide and Reference This book can be used as a reference guide for tuning your Oracle database system. ■ Oracle9i Application Developer’s Guide - Fundamentals Many of the tasks done by DBAs are shared by application developers. In some cases, descriptions of tasks seemed better located in an application level book, and in those cases, this fundamentals book is the primary reference. Many of the examples in this book use the sample schemas of the seed database, which is installed by default when you install Oracle. Refer to Oracle9i Sample Schemas for information on how these schemas were created and how you can use them yourself. In North America, printed documentation is available for sale in the Oracle Store at http://oraclestore.oracle.com/ Customers in Europe, the Middle East, and Africa (EMEA) can purchase documentation from http://www.oraclebookshop.com/ xxxix Other customers can contact their Oracle representative to purchase printed documentation. To download free release notes, installation documentation, white papers, or other collateral, please visit the Oracle Technology Network (OTN). You must register online before using OTN; registration is free and can be done at http://otn.oracle.com/admin/account/membership.html If you already have a username and password for OTN, then you can go directly to the documentation section of the OTN Web site at http://otn.oracle.com/docs/index.htm To access the database documentation search engine directly, please visit http://tahiti.oracle.com Conventions This section describes the conventions used in the text and code examples of this documentation set. It describes: ■ Conventions in Text ■ Conventions in Code Examples ■ Conventions for Windows Operating Systems Conventions in Text We use various conventions in text to help you more quickly identify special terms. The following table describes those conventions and provides examples of their use. Convention Meaning Bold Bold typeface indicates terms that are When you specify this clause, you create an defined in the text or terms that appear in index-organized table. a glossary, or both. Italics Italic typeface indicates book titles or emphasis. xl Example Oracle9i Database Concepts Ensure that the recovery catalog and target database do not reside on the same disk. Convention Meaning Example UPPERCASE monospace (fixed-width) font Uppercase monospace typeface indicates elements supplied by the system. Such elements include parameters, privileges, datatypes, RMAN keywords, SQL keywords, SQL*Plus or utility commands, packages and methods, as well as system-supplied column names, database objects and structures, usernames, and roles. You can specify this clause only for a NUMBER column. Lowercase monospace typeface indicates executables, filenames, directory names, and sample user-supplied elements. Such elements include computer and database names, net service names, and connect identifiers, as well as user-supplied database objects and structures, column names, packages and classes, usernames and roles, program units, and parameter values. Enter sqlplus to open SQL*Plus. lowercase monospace (fixed-width) font You can back up the database by using the BACKUP command. Query the TABLE_NAME column in the USER_ TABLES data dictionary view. Use the DBMS_STATS.GENERATE_STATS procedure. The password is specified in the orapwd file. Back up the datafiles and control files in the /disk1/oracle/dbs directory. The department_id, department_name, and location_id columns are in the hr.departments table. Set the QUERY_REWRITE_ENABLED initialization parameter to true. Note: Some programmatic elements use a mixture of UPPERCASE and lowercase. Connect as oe user. Enter these elements as shown. The JRepUtil class implements these methods. lowercase Lowercase italic monospace font italic represents placeholders or variables. monospace (fixed-width) font You can specify the parallel_clause. Run Uold_release.SQL where old_ release refers to the release you installed prior to upgrading. Conventions in Code Examples Code examples illustrate SQL, PL/SQL, SQL*Plus, or other command-line statements. They are displayed in a monospace (fixed-width) font and separated from normal text as shown in this example: SELECT username FROM dba_users WHERE username = ’MIGRATE’; The following table describes typographic conventions used in code examples and provides examples of their use. xli Convention Meaning Example [] Brackets enclose one or more optional items. Do not enter the brackets. DECIMAL (digits [ , precision ]) {} Braces enclose two or more items, one of {ENABLE | DISABLE} which is required. Do not enter the braces. | A vertical bar represents a choice of two {ENABLE | DISABLE} or more options within brackets or braces. [COMPRESS | NOCOMPRESS] Enter one of the options. Do not enter the vertical bar. ... Horizontal ellipsis points indicate either: ■ ■ That we have omitted parts of the code that are not directly related to the example CREATE TABLE ... AS subquery; That you can repeat a portion of the code SELECT col1, col2, ... , coln FROM employees; . . . Vertical ellipsis points indicate that we have omitted several lines of code not directly related to the example. Other notation You must enter symbols other than brackets, braces, vertical bars, and ellipsis points as shown. Italics UPPERCASE xlii SQL> SELECT NAME FROM V$DATAFILE; NAME -----------------------------------/fsl/dbs/tbs_01.dbf /fs1/dbs/tbs_02.dbf . . . /fsl/dbs/tbs_09.dbf 9 rows selected. acctbal NUMBER(11,2); acct CONSTANT NUMBER(4) := 3; Italicized text indicates placeholders or variables for which you must supply particular values. CONNECT SYSTEM/system_password Uppercase typeface indicates elements supplied by the system. We show these terms in uppercase in order to distinguish them from terms you define. Unless terms appear in brackets, enter them in the order and with the spelling shown. However, because these terms are not case sensitive, you can enter them in lowercase. SELECT last_name, employee_id FROM employees; DB_NAME = database_name SELECT * FROM USER_TABLES; DROP TABLE hr.employees; Convention Meaning Example lowercase Lowercase typeface indicates programmatic elements that you supply. For example, lowercase indicates names of tables, columns, or files. SELECT last_name, employee_id FROM employees; Note: Some programmatic elements use a mixture of UPPERCASE and lowercase. Enter these elements as shown. CREATE USER mjones IDENTIFIED BY ty3MU9; sqlplus hr/hr Conventions for Windows Operating Systems The following table describes conventions for Windows operating systems and provides examples of their use. Convention Meaning Example Choose Start > How to start a program. To start the Database Configuration Assistant, choose Start > Programs > Oracle - HOME_ NAME > Configuration and Migration Tools > Database Configuration Assistant. c:\winnt"\"system32 is the same as File and directory File and directory names are not case names sensitive. The following special characters C:\WINNT\SYSTEM32 are not allowed: left angle bracket (<), right angle bracket (>), colon (:), double quotation marks ("), slash (/), pipe (|), and dash (-). The special character backslash (\) is treated as an element separator, even when it appears in quotes. If the file name begins with \\, then Windows assumes it uses the Universal Naming Convention. C:\> Represents the Windows command prompt of the current hard disk drive. The escape character in a command prompt is the caret (^). Your prompt reflects the subdirectory in which you are working. Referred to as the command prompt in this manual. C:\oracle\oradata> xliii Convention Meaning Special characters The backslash (\) special character is sometimes required as an escape character for the double quotation mark (") special character at the Windows command prompt. Parentheses and the single quotation mark (’) do not require an escape character. Refer to your Windows operating system documentation for more information on escape and special characters. HOME_NAME xliv Example C:\>exp scott/tiger TABLES=emp QUERY=\"WHERE job=’SALESMAN’ and sal<1600\" C:\>imp SYSTEM/password FROMUSER=scott TABLES=(emp, dept) Represents the Oracle home name. The C:\> net start OracleHOME_ home name can be up to 16 alphanumeric NAMETNSListener characters. The only special character allowed in the home name is the underscore. Convention Meaning Example ORACLE_HOME and ORACLE_ BASE In releases prior to Oracle8i release 8.1.3, when you installed Oracle components, all subdirectories were located under a top level ORACLE_HOME directory that by default used one of the following names: Go to the ORACLE_BASE\ORACLE_ HOME\rdbms\admin directory. ■ C:\orant for Windows NT ■ C:\orawin98 for Windows 98 This release complies with Optimal Flexible Architecture (OFA) guidelines. All subdirectories are not under a top level ORACLE_HOME directory. There is a top level directory called ORACLE_BASE that by default is C:\oracle. If you install the latest Oracle release on a computer with no other Oracle software installed, then the default setting for the first Oracle home directory is C:\oracle\orann, where nn is the latest release number. The Oracle home directory is located directly under ORACLE_BASE. All directory path examples in this guide follow OFA conventions. Refer to Oracle9i Database Getting Started for Windows for additional information about OFA compliances and for information about installing Oracle products in non-OFA compliant directories. Documentation Accessibility Our goal is to make Oracle products, services, and supporting documentation accessible, with good usability, to the disabled community. To that end, our documentation includes features that make information available to users of assistive technology. This documentation is available in HTML format, and contains markup to facilitate access by the disabled community. Standards will continue to evolve over time, and Oracle Corporation is actively engaged with other market-leading technology vendors to address technical obstacles so that our documentation can be accessible to all of our customers. For additional information, visit the Oracle Accessibility Program Web site at xlv http://www.oracle.com/accessibility/ JAWS, a Windows screen reader, may not always correctly read the code examples in this document. The conventions for writing code require that closing braces should appear on an otherwise empty line; however, JAWS may not always read a line of text that consists solely of a bracket or brace. Accessibility of Code Examples in Documentation Accessibility of Links to External Web Sites in Documentation This documentation may contain links to Web sites of other companies or organizations that Oracle Corporation does not own or control. Oracle Corporation neither evaluates nor makes any representations regarding the accessibility of these Web sites. xlvi What’s New in Oracle9i? This section introduces new administrative features of Oracle9i Release 2 (9.2) that are discussed in this book and provides pointers to additional information. For a summary of all new features for Oracle9i, see Oracle9i Database New Features. The following section describes the new features discussed in the Oracle9i Database Administrator’s Guide. ■ Oracle9i Release 2 (9.2) New Features ■ Oracle9i Release 1 (9.0.1) New Features xlvii Oracle9i Release 2 (9.2) New Features Oracle9i, Release 2, further advances and refines the goals achieved by Oracle9i, Release 1. The following are summaries of the new features of Oracle9i, Release 2, that are discussed in this book. ■ Specifying Passwords for SYS and SYSTEM at Database Creation Oracle enables you to specify passwords for users SYS and SYSTEM using the following CREATE DATABASE clauses: – USER SYS IDENTIFIED BY password – USER SYSTEM IDENTIFIED BY password See Also: "Protecting Your Database: Specifying Passwords for Users SYS and SYSTEM" on page 2-23 ■ Specifying FORCE LOGGING Mode The FORCE LOGGING clause of the CREATE DATABASE, CREATE CONTROLFILE, and CREATE TABLESPACE statement enables you to force redo log records to be written even when NOLOGGING has been specified in a DDL statement. See Also: ■ ■ "Specifying FORCE LOGGING Mode" on page 2-29 ■ "The CREATE CONTROLFILE Statement" on page 6-6 ■ "Controlling the Writing of Redo Records" on page 11-20 Recovery Manager (RMAN) Backup of a Server Parameter File RMAN can now be used to create backups of a server parameter file. See Also: "Backing Up the Server Parameter File" on page 2-50 ■ New In LogMiner for Release 9.2 LogMiner release 9.2 has added support for several new features and changed some default behavior as follows: xlviii – LONG and LOB datatypes are supported for redo logs generated on a release 9.2 or later Oracle database. – Supplemental logging is turned off by default. This is a change from release 9.0.1, in which minimal supplemental logging was turned on by default. In release 9.2, the level of supplemental logging desired must be specified. – Different levels of supplemental logging are available: database supplemental logging and table supplemental logging. Within database supplemental logging, you have a choice of minimal or identification key logging. Within table supplemental logging, you have a choice of using conditional or unconditional log groups. See Also: Supplemental Logging on page 9-2 – Two new options have been added that affect the formatting of returned data. The DBMS_LOGMNR.NO_SQL_DELIMITER option suppresses the semi-colon at the end of SQL_REDO and SQL_UNDO statements. The DBMS_ LOGMNR.PRINT_PRETTY_SQL option formats the reconstructed SQL statements so that they are easier to read. See Also: Formatting of Returned Data on page 9-17 – A new option, DBMS_LOGMNR.CONTINUOUS_MINE, directs LogMiner to automatically add and mine redo log files that are archived after the LogMiner session has started. See Also: Continuous Mining on page 9-25 – Use of the DBMS_LOGMNR.NO_DICT_RESET_ONSELECT option is no longer necessary. When DDL tracking is enabled, LogMiner stores old metadata definitions so that a second select operation has all the needed metadata versions. – A new procedure, DBMS_LOGMNR_D.SET_TABLESPACE,recreates all LogMiner tables in a tablespace other than SYSTEM, which is the default. See Also: Oracle9i Supplied PL/SQL Packages and Types Reference ■ Creating a Locally Managed SYSTEM Tablespace You can now create a locally managed SYSTEM tablespace. This can be done at create database time by specifying the EXTENT MANAGEMENT LOCAL clause of xlix the CREATE DATABASE statement, or you can migrate your existing SYSTEM tablespace to locally managed by using the DBMS_SPACE_ ADMIN.TABLESPACE_MIGRATE_TO_LOCAL procedure. See Also: ■ ■ ■ "Creating a Locally Managed SYSTEM Tablespace" on page 2-26 "Migrating the SYSTEM Tablespace to a Locally Managed Tablespace" on page 11-34 Mapping Files to Physical Devices With the introduction of host based Logical Volume Managers (LVM), and sophisticated storage subsystems that provide RAID features, it is not easy to determine file to device mapping. Oracle has created new views and a new DBMS_STORAGE_MAP package to enable you to map files to physical devices. See Also: "Mapping Files to Physical Devices" on page 12-15 ■ Renaming Columns Existing table columns can now be renamed. See Also: "Renaming Table Columns" on page 15-14 ■ Renaming Constraints Existing constraints on tables can now be renamed. See Also: "Renaming Constraints" on page 21-19 ■ Specifying a Default List Partition You can now use the keyword DEFAULT as the value-list descriptor for a partition defined for a list-partitioned table. This partition is used for inserting rows into the list-partitioned table when the partition key column does not match any of the literal values specified in the value-list descriptor for the partition. See Also: "Creating List-Partitioned Tables" on page 17-13 l ■ Specifying Composite Range-List Partitioning This release introduces a new type of composite partitioning. You can now partition tables by the range-list method, where partitions are defined as range partitions and the subpartitions are defined as list partitions. See Also: "When to Use the Composite Range-List Partitioning Method" on page 17-8 ■ Optimizing SPLIT PARTITION and SPLIT SUBPARTITION Operations Under certain conditions, Oracle can perform a fast split operation that is more efficient than the normal split operation on a partition or subpartition. See Also: "Optimizing SPLIT PARTITION and SPLIT SUBPARTITION Operations" on page 17-58 ■ Auditing User SYS All operations done by user SYS (includes all AS SYSDBA and AS SYSOPER connections) can now be audited. See Also: "Auditing Administrative Users" on page 26-6 ■ Granting Object Privileges on Behalf of the Object Owner A new system privilege named GRANT ANY OBJECT PRIVILEGE allows you to grant object privileges as if you were the owner. It will appear (in views) as if the object owner granted the privilege, but audit records show the real person who granted the privilege. See Also: ■ ■ ■ "Granting Object Privileges on Behalf of the Object Owner" on page 25-14 "Revoking Object Privileges on Behalf of the Object Owner" on page 25-17 Removal of LOB Column Restriction You can now create LOB columns in tablespaces that specify automatic segment-space management. li ■ Elimination of Certain Distributed Database Initialization Parameters In earlier releases of Oracle, the DISTRIBUTED_TRANSACTIONS initialization parameter allowed you to specify a maximum number of distributed transactions in which a database can concurrently participate. This parameter has been eliminated and the number of concurrent distributed transactions is not limited. If specified, the DISTRIBUTED_TRANSACTIONS initialization parameter is ignored. Also in earlier releases of Oracle, the max number of branches for each distributed transaction was specified by the MAX_TRANSACTION_BRANCHES initialization parameter. This parameter was eliminated in Oracle8i, but the maximum number of branches of a distributed transaction is still limited to 32. If specified, the MAX_TRANSACTION_BRANCHES initialization parameter is ignored. Oracle9i Release 1 (9.0.1) New Features Oracle9i brings a major new release of the Oracle database server. It includes features to make the database more available. More online operations reduce the need for offline maintenance. Management of the database requires less effort. Oracle9i can automatically create and manage the underlying operating system files required by the database. There is a theme of self management. Performance is enhanced. The Database Resource Manager has new options that allow for more granular control of resources. The performance level required of a resource consumer group can be better sustained. Partitioning enhancements allow tables and indexes to be better partitioned for performance. Security enhancements are an important part of this release. Applications have available more and finer grained methods of implementing security and auditing. The following are summaries of the new features of Oracle9i that are discussed in this book. ■ Online redefinition of tables The new DBMS_REDEFINITION PL/SQL package provides a mechanism to redefine tables online. When a table is redefined online, it is accessible to DML during much of the redefinition process. This provides a significant increase in availability compared to traditional methods of redefining tables that require tables to be taken offline. See Also: "Redefining Tables Online" on page 15-16 lii ■ ONLINE option for ANALYZE VALIDATE STRUCTURE statement The ANALYZE statement can now perform validation while DML is ongoing within the object being analyzed. See Also: "Validating Tables, Indexes, Clusters, and Materialized Views" on page 21-6 ■ Controlling Archive Lag Oracle now provides a time-based means of switching the current online redo log group. In a primary/standby configuration, where all noncurrent logs of the primary site are archived and shipped to the standby database, this effectively limits the number of redo records, as measured in time, that will not be applied in the standby database. See Also: "Controlling Archive Lag" on page 7-10 ■ Suspending a database Oracle9i includes a database suspend/resume feature. The ALTER SYSTEM SUSPEND statement suspends a database by halting all input and output (I/O) to datafiles and control files. When the database is suspended all preexisting I/O operations are allowed to complete and any new database accesses are placed in a queued state. The ALTER SYSTEM RESUME statement resumes normal database operation. See Also: "Suspending and Resuming a Database" on page 4-17 ■ Quiescing a database Oracle9i allows you to place the database into a quiesced state, where only DBA transactions, queries, or PL/SQL statements are allowed. This quiesced state allows you to perform administrative actions that cannot safely be done otherwise. The ALTER SYSTEM QUIESCE RESTRICTED statement places a database into a quiesced state. See Also: "Quiescing a Database" on page 4-14 ■ Resumable Space Allocation Oracle provides a means for suspending, and later resuming, the execution of large database operations in the event of space allocation failures. This enables you to take corrective action, instead of the Oracle database server returning an liii error to the user. After the error condition is corrected, the suspended operation automatically resumes. See Also: "Managing Resumable Space Allocation" on page 14-14 ■ More archiving destinations The maximum number of destinations to which you can archive the online redo log, has been increased from 5 to 10. See Also: "Specifying the Archive Destination" on page 8-9 ■ Automatic segment- space management Locally managed tablespaces allow extents to be managed automatically by Oracle. Oracle9i allows free and used space within segments stored in locally managed tablespaces to also be managed automatically. Using the SEGMENT SPACE MANAGEMENT clause of CREATE TABLESPACE you specify AUTO or MANUAL to specify the type of segment space management Oracle will use. See Also: "Specifying Segment Space Management in Locally Managed Tablespaces" on page 11-8 ■ Update of global indexes when partition maintenance is performed By default, many table maintenance operations on partitioned tables invalidate (mark UNUSABLE) global indexes. You must then rebuild the entire global index or, if partitioned, all of its partitions. Oracle9i allows you to override this default behavior. When you specify the UPDATE GLOBAL INDEX clause in your ALTER TABLE statement for the maintenance operation, the global index is updated in conjunction with the base table operation. See Also: "Maintaining Partitioned Tables" on page 17-22 ■ Multiple block sizes Oracle now supports multiple block sizes. It has a standard block size, as set by the DB_BLOCK_SIZE initialization parameter, and additionally up to 4 nonstandard block sizes. Nonstandard block sizes are specified when creating tablespaces. The standard block size is used for the SYSTEM tablespace and most other tablespaces. Multiple block size support allows for the transporting of tablespaces with unlike block sizes between databases. liv See Also: "Specifying Database Block Sizes" on page 2-37 ■ Dynamic buffer cache The size of the buffer cache subcomponent of the System Global Area is now dynamic. The DB_BLOCK_BUFFERS initialization parameter has been replaced by a new dynamic parameter, DB_CACHE_SIZE, where the user specifies the size of the buffer subcache for the standard database block size. The buffer cache now consists of subcaches when multiple block sizes are specified for the database. Up to four DB_nK_CACHE_SIZE initialization parameters allow you to specify the sizes of buffer subcaches for the additional block sizes. See Also: "Setting Initialization Parameters that Affect the Size of the SGA" on page 2-38 ■ Dynamic SGA The initialization parameters affecting the size of SGA have been made dynamic. It is possible to alter the size of SGA dynamically through an ALTER SYSTEM SET statement. See Also: "Setting Initialization Parameters that Affect the Size of the SGA" on page 2-38 ■ Automatic undo management Historically, Oracle has used rollback segments to store undo. Undo is defined as information that can be used to roll back, or undo, changes to the database when necessary. Oracle now enables you to create an undo tablespace to store undo. Using an undo tablespace eliminates the complexities of managing rollback segment space, and enables you to exert control over how long undo is retained before being overwritten. See Also: Chapter 13, "Managing Undo Space" ■ Oracle managed files The Oracle managed files feature of Oracle9i eliminates the need for you to directly manage the files comprising an Oracle database. Through the DB_ CREATE_FILE_DEST and DB_CREATE_ONLINE_LOG_DEST_n initialization parameters, you specify the file system directory to be used for a particular type of file comprising a tablespace, online redo log file, or control file. Oracle then lv ensures that a unique file, an Oracle-managed file, is created and deleted when no longer needed. See Also: Chapter 3, "Using Oracle-Managed Files" ■ Automatic deletion of datafiles Oracle9i provides an option to automatically remove a tablespaces’s operating system files (datafiles) when the tablespace is dropped using the DROP TABLESPACE statement. A similar option for the ALTER DATABASE TEMPFILE statement, causes deletion the operating system files associated with a temporary file. See Also: ■ ■ ■ "Dropping Tablespaces" on page 11-29 "Altering a Locally Managed Temporary Tablespace" on page 11-14 Metadata API A new PL/SQL package, DBMS_METADATA.GET_DDL, allows you to obtain metadata (in the form of DDL used to create the object) about a schema object. See Also: "Using PL/SQL Packages to Display Information About Schema Objects" on page 21-30 ■ External tables Oracle9i allows you read-only access to data in external tables. External tables are defined as tables that do not reside in the database, and can be in any format for which an access driver is provided. The CREATE TABLE ... ORGANIZATION EXTERNAL statement specifies metadata describing the external table. Oracle currently provides the ORACLE_LOADER access driver which provides data mapping capabilities that are a subset of the SQL*Loader control file syntax. See Also: "Managing External Tables" on page 15-33 ■ Constraint enhancements Enhancements to the USING INDEX clause of CREATE TABLE or ALTER TABLE allow you to specify the creation or use of a specific index when a lvi unique or primary key constraint is created or enabled. Additionally, you can prevent the dropping of the index enforcing a unique or primary key constraint when the constraint is dropped or disabled. See Also: ■ ■ "Creating an Index Associated with a Constraint" on page 16-11 ■ "Managing Integrity Constraints" on page 21-14 Server parameter file Oracle has traditionally stored initialization parameters in a text initialization parameter file, often on a client machine. Starting with Oracle9i, you can elect to maintain initialization parameters in a server parameter file, which is a binary parameter file stored on the database server. Initialization parameters stored in a server parameter file are persistent, in that any changes made to the parameters while an instance is running persist across instance shutdown and startup. See Also: "Managing Initialization Parameters Using a Server Parameter File" on page 2-44 ■ Default temporary tablespace The new DEFAULT TEMPORARY TABLESPACE clause of the CREATE DATABASE statement allows you to create a default temporary tablespace at database creation time. This tablespace is used as the default temporary tablespace for users who are not otherwise assigned a temporary tablespace. See Also: "Creating a Default Temporary Tablespace" on page 2-24 ■ Setting the database time zone The CREATE DATABASE statement now has a SET TIME_ZONE clause that allows you to set the time zone of the database as a displacement from UTC (Coordinated Universal Time—formerly Greenwich Mean Time). Oracle normalizes all TIMESTAMP WITH LOCAL TIME ZONE data to the time zone of the database when the data is stored on disk. Additionally, a new session parameter TIME_ZONE has been added to the SET clause of ALTER SESSION. See Also: "Step 6: Issue the CREATE DATABASE Statement" on page 2-18 lvii ■ Transaction Naming Oracle now allows you to assign a name to a transaction. The transaction name is helpful in resolving in-doubt distributed transactions, and replaces a COMMIT COMMENT. See Also: "Naming Transactions" on page 32-2 ■ Database Configuration Assistant changes The Database Configuration Assistant has been redesigned. It now provides templates, which are saved definitions of databases, from which you can generate your database. Oracle provides templates, or you can create your own templates by modifying existing ones, defining new ones, or by capturing the definition of an existing database. When creating a database with the Database Configuration Assistant, you can either initially include, or later add as an option, Oracle’s new Sample Schemas. These schemas are the basis for many of the examples used in Oracle documentation. See Also: "Using the Database Configuration Assistant" on page 2-5 ■ Monitoring index usage A MONITORING USAGE clause has been added for the ALTER INDEX statement. It allows you to monitor an index to determine if it is actively being used. See Also: "Monitoring Index Usage" on page 16-21 ■ List partitioning Oracle introduces list partitioning, which enables you to specify a list of discrete values for the partitioning column in the description for each partition. The list partitioning method is specifically designed for modeling data distributions that follow discrete values. This cannot be easily done by range or hash partitioning. See Also: Chapter 17, "Managing Partitioned Tables and Indexes" lviii ■ Hash partitioning of index-organized tables In this release, support has been added for partitioning index-organized tables by the hash method. Previously, they could be partitioned, but only by the range method. See Also: "Creating Partitioned Index-Organized Tables" on page 17-19 ■ Dynamic job queue processes The job queue process creation has been made dynamic so that only the required number of processes are created to execute the jobs that are ready for execution. A job queue coordinator background process (CJQ) dynamically spawns Jnnn processes to execute jobs. See Also: "Enabling Processes Used for Executing Jobs" on page 10-2 ■ New in the Database Resource Manager for Oracle9i The following new functionality has been added to the Database Resource Manager: – Ability to create an active session pool. This pool consists of a specified maximum number of user sessions allowed to be concurrently active within a group of users. Additional sessions beyond the maximum are queued for execution, but you can specify a timeout period, after which queued jobs will abort. – Automatic switching of users from one group to another group based on administrator defined criteria. If a member of a particular group of users creates a session that executes for longer than a specified amount of time, that session can be automatically switched to another group of users with different resource requirements. – Ability to prevent the execution of operations that are estimated to run for a longer time than a predefined limit – Ability to create an undo pool. This pool consists of the amount of undo space that can be consumed in by a group of users. See Also: Chapter 27, "Using the Database Resource Manager" lix ■ Proxy authentication and authorization Oracle9i enables you to authorize a middle-tier server to act on behalf of a client. The GRANT CONNECT THROUGH clause of the ALTER USER statement specifies this functionality. You can also specify roles that the middle tier is permitted to activate when connecting as the client. See Also: "Proxy Authentication and Authorization" on page 24-16 ■ Application roles Oracle provides a mechanism by which roles granted to application users are enabled using a designated PL/SQL package. This feature introduces the IDENTIFIED USING package clause for the CREATE ROLE statement. See Also: "Role Authorization by an Application" on page 25-8 ■ Fine-grained auditing In Oracle’s traditional auditing methods, a fixed set of facts is recorded in the audit trail. Audit options can only be set to monitor access of objects or privileges. A new PL/SQL package, DBMS_FGA, allows applications to implement fine-grained auditing of data access based on content. See Also: "Fine-Grained Auditing" on page 26-18 ■ New in LogMiner for Release 9.0.1 LogMiner release 9.0.1 has added support for many new features. Some of the new features work with any redo log files from an Oracle 8.0 or later database. Other features only work with redo log files produced on Oracle9i or later. New Features for Redo Log Files Generated by Oracle9i or Later For any redo log files generated by Oracle9i or later, LogMiner now provides support for the following: lx – Index clusters – Chained and migrated rows – Direct path inserts (with ARCHIVELOG mode enabled) – Extracting the data dictionary into the redo log files. See Extracting a Dictionary to the Redo Logs on page 9-6. – Using the online catalog as the data dictionary. See "Using the Online Catalog" on page 9-8. – Tracking of all data definition language (DDL) operations, which enables you to monitor schema evolution. See "Tracking DDL Statements" on page 9-9. – Viewing user-executed DDL in the SQL_REDO column. Information regarding the original database user is also returned. – Generating SQL_REDO and SQL_UNDO with primary key information for updates. That is, updated rows are identified by primary keys and ROWIDs (provided supplemental logging is enabled), thereby making it easier to apply the statements to a different database. New Features for Redo Log Files Generated by Oracle Release 8.0 or Later For any redo log files generated by Oracle release 8.0 or later, LogMiner now provides support for the following: – Limiting V$LOGMNR_CONTENTS data to rows belonging to committed transactions only. This option enables you to filter out rolled back transactions and transactions that are in progress. See the information about options in "Start a LogMiner Session" on page 9-26. – Performing queries based on actual data values in the redo log files. See Extracting Actual Data Values from Redo Logs on page 9-18. See Also: Chapter 9, "Using LogMiner to Analyze Redo Logs" lxi lxii Part I Basic Database Administration Part I provides an overview of the responsibilities of a database administrator, and describes the creation of a database and how to start up and shut down an instance of the database. It contains the following chapters: ■ Chapter 1, "The Oracle Database Administrator" ■ Chapter 2, "Creating an Oracle Database" ■ Chapter 3, "Using Oracle-Managed Files" ■ Chapter 4, "Starting Up and Shutting Down" 1 The Oracle Database Administrator This chapter describes your responsibilities as a database administrator (DBA) who administers the Oracle database server. The following topics are discussed: ■ Types of Oracle Users ■ Tasks of a Database Administrator ■ Identifying Your Oracle Database Software Release ■ Database Administrator Security and Privileges ■ Database Administrator Authentication ■ Creating and Maintaining a Password File ■ Database Administrator Utilities The Oracle Database Administrator 1-1 Types of Oracle Users Types of Oracle Users The types of users and their roles and responsibilities at a site can vary. A small site can have one database administrator who administers the database for application developers and users. A very large site can find it necessary to divide the duties of a database administrator among several people, and among several areas of specialization. This section contains the following topics: ■ Database Administrators ■ Security Officers ■ Network Administrators ■ Application Developers ■ Application Administrators ■ Database Users Database Administrators Each database requires at least one database administrator (DBA) to administer it. Because an Oracle database system can be large and can have many users, often this is not a one person job. In such cases, there is a group of DBAs who share responsibility. A database administrator’s responsibilities can include the following tasks: ■ ■ ■ ■ ■ Installing and upgrading the Oracle server and application tools Allocating system storage and planning future storage requirements for the database system Creating primary database storage structures (tablespaces) after application developers have designed an application Creating primary objects (tables, views, indexes) once application developers have designed an application Modifying the database structure, as necessary, from information given by application developers ■ Enrolling users and maintaining system security ■ Ensuring compliance with your Oracle license agreement 1-2 Oracle9i Database Administrator’s Guide Types of Oracle Users ■ Controlling and monitoring user access to the database ■ Monitoring and optimizing the performance of the database ■ Planning for backup and recovery of database information ■ Maintaining archived data on tape ■ Backing up and restoring the database ■ Contacting Oracle Corporation for technical support Security Officers In some cases, a site assigns one or more security officers to a database. A security officer enrolls users, controls and monitors user access to the database, and maintains system security. As a DBA, you might not be responsible for these duties if your site has a separate security officer. Network Administrators Some sites have one or more network administrators. A network administrator can administer Oracle networking products, such as Oracle Net Services. See Also: Part VI, "Distributed Database Management" for information on network administration in a distributed environment Application Developers Application developers design and implement database applications. Their responsibilities include the following tasks: ■ Designing and developing the database application ■ Designing the database structure for an application ■ Estimating storage requirements for an application ■ Specifying modifications of the database structure for an application ■ Relaying the above information to a database administrator ■ Tuning the application during development ■ Establishing an application’s security measures during development The Oracle Database Administrator 1-3 Tasks of a Database Administrator Application developers can perform some of these tasks in collaboration with DBAs. Application Administrators An Oracle site can assign one or more application administrators to administrate a particular application. Each application can have its own administrator. Database Users Database users interact with the database through applications or utilities. A typical user’s responsibilities include the following tasks: ■ Entering, modifying, and deleting data, where permitted ■ Generating reports from the data Tasks of a Database Administrator The following tasks present a prioritized approach for designing, implementing, and maintaining an Oracle Database: Task 1: Evaluate the Database Server Hardware Task 2: Install the Oracle Software Task 3: Plan the Database Task 4: Create and Open the Database Task 5: Back Up the Database Task 6: Enroll System Users Task 7: Implement the Database Design Task 8: Back Up the Fully Functional Database Task 9: Tune Database Performance These tasks are discussed in succeeding sections. Note: If upgrading to a new release, back up your existing production database before installation. For information on preserving your existing production database, see Oracle9i Database Migration. 1-4 Oracle9i Database Administrator’s Guide Tasks of a Database Administrator Task 1: Evaluate the Database Server Hardware Evaluate how Oracle and its applications can best use the available computer resources. This evaluation should reveal the following information: ■ ■ ■ How many disk drives are available to Oracle and its databases How many, if any, dedicated tape drives are available to Oracle and its databases How much memory is available to the instances of Oracle you will run (see your system’s configuration documentation) Task 2: Install the Oracle Software As the database administrator, you install the Oracle database server software and any front-end tools and database applications that access the database. In some distributed processing installations, the database is controlled by a central computer (database server) and the database tools and applications are executed on remote computers (clients). In this case, you must also install the Oracle Net components necessary to connect the remote machines to the computer that executes Oracle. For more information on what software to install, see "Identifying Your Oracle Database Software Release" on page 1-8. See Also: For specific requirements and instructions for installation, refer to the following documentation: ■ ■ Your operating system specific Oracle documentation Your installation guides for your front-end tools and Oracle Net drivers. Task 3: Plan the Database As the database administrator, you must plan: ■ The logical storage structure of the database ■ The overall database design ■ A backup strategy for the database It is important to plan how the logical storage structure of the database will affect system performance and various database management operations. For example, before creating any tablespaces for your database, you should know how many datafiles will make up the tablespace, what type of information will be stored in The Oracle Database Administrator 1-5 Tasks of a Database Administrator each tablespace, and on which disk drives the datafiles will be physically stored. When planning the overall logical storage of the database structure, take into account the effects that this structure will have when the database is actually created and running. Such considerations include how the logical storage structure database will affect the following: ■ The performance of the computer executing Oracle ■ The performance of the database during data access operations ■ The efficiency of backup and recovery procedures for the database Plan the relational design of the database objects and the storage characteristics for each of these objects. By planning the relationship between each object and its physical storage before creating it, you can directly affect the performance of the database as a unit. Be sure to plan for the growth of the database. In distributed database environments, this planning stage is extremely important. The physical location of frequently accessed data dramatically affects application performance. During the planning stage, develop a backup strategy for the database. You can alter the logical storage structure or design of the database to improve backup efficiency. It is beyond the scope of this book to discuss relational and distributed database design. If you are not familiar with such design issues, refer to accepted industry-standard documentation. Part II, "Oracle Server Processes and Storage Structure" and Part III, "Schema Objects" provide specific information on creating logical storage structures, objects, and integrity constraints for your database. Task 4: Create and Open the Database When you complete the database design, you can create the database and open it for normal use. You can create a database at installation time, using the Database Configuration Assistant, or you can supply your own scripts for creating a database. Either way, refer to Chapter 2, "Creating an Oracle Database", for information on creating a database and Chapter 4, "Starting Up and Shutting Down" for guidance in starting up the database. 1-6 Oracle9i Database Administrator’s Guide Tasks of a Database Administrator Task 5: Back Up the Database After you create the database structure, carry out the backup strategy you planned for the database. Create any additional redo log files, take the first full database backup (online or offline), and schedule future database backups at regular intervals. See Also: For instructions on customizing your backup operations and performing recovery procedures see either of the following: ■ Oracle9i User-Managed Backup and Recovery Guide ■ Oracle9i Recovery Manager User’s Guide Task 6: Enroll System Users After you back up the database structure, you can enroll the users of the database in accordance with your Oracle license agreement, create appropriate roles for these users, and grant these roles. The following chapters will help you in this endeavor: ■ Chapter 23, "Establishing Security Policies" ■ Chapter 24, "Managing Users and Resources" ■ Chapter 25, "Managing User Privileges and Roles" Task 7: Implement the Database Design After you create and start the database, and enroll the system users, you can implement the planned logical structure database by creating all necessary tablespaces. When you complete this, you can create the objects for the database. Part II, "Oracle Server Processes and Storage Structure" and Part III, "Schema Objects" contain information which can help you create logical storage structures and objects for your database. Task 8: Back Up the Fully Functional Database Now that the database is fully implemented, again back up the database. In addition to regularly scheduled backups, you should always back up your database immediately after implementing changes to the database structure. The Oracle Database Administrator 1-7 Identifying Your Oracle Database Software Release Task 9: Tune Database Performance Optimizing the performance of the database is one of your ongoing responsibilities as a DBA. Additionally, Oracle provides a database resource management feature that enables you to control the allocation of resources to various user groups. The database resource manager is described in Chapter 27, "Using the Database Resource Manager". Oracle9i Database Performance Tuning Guide and Reference contains information about tuning your database and applications. See Also: Identifying Your Oracle Database Software Release Because the Oracle database server continues to evolve and can require maintenance, Oracle periodically produces new releases. Because only some users initially subscribe to a new release or require specific maintenance, multiple releases of the product can exist simultaneously. As many as five numbers may be required to fully identify a release. The significance of these numbers is discussed below. Release Number Format To understand the release level nomenclature used by Oracle, examine the following example of an Oracle database server labeled "Release 9.2.0.1.0." 1-8 Oracle9i Database Administrator’s Guide Identifying Your Oracle Database Software Release Figure 1–1 Example of an Oracle Release Number 9.2.0.1.0 Platform specific release number Major database release number Database maintenance release number Component specific release number Application server release number Note: Starting with release 9.2, maintenance releases of Oracle are denoted by a change to the second digit of a release number. In previous releases, the third digit indicated a particular maintenance release. Major Database Release Number This is the most general identifier. It represents a major new edition (or version) of the software that contains significant new functionality. Database Maintenance Release Number This digit represents a maintenance release level. Some new features may also be included. Application Server Release Number This digit reflects the release level of the Oracle9i Application Server (Oracle9iAS). Component Specific Release Number This digit identifies a release level specific to a component. Different components can have different numbers in this position depending upon, for example, component patch sets or interim releases. Platform Specific Release Number This digit identifies a platform specific release. Usually this is a patch set. Where different platforms require the equivalent patch set, this digit will be the same across the effected platforms. The Oracle Database Administrator 1-9 Database Administrator Security and Privileges Checking Your Current Release Number To identify the release of the Oracle database server that is currently installed and to see the release levels of other Oracle components you are using, query the data dictionary view PRODUCT_COMPONENT_VERSION. A sample query is shown below. Other product release levels may increment independently of the database server. COL PRODUCT FORMAT A35 COL VERSION FORMAT A15 COL STATUS FORMAT A15 SELECT * FROM PRODUCT_COMPONENT_VERSION; PRODUCT ----------------------------------NLSRTL Oracle9i Enterprise Edition PL/SQL TNS for Solaris: VERSION --------------9.2.0.1.0 9.2.0.1.0 9.2.0.1.0 9.2.0.1.0 STATUS --------------Production Production Production Production It’s important to convey to Oracle the information displayed by this query when you report problems with the software. Optionally, you can query the V$VERSION view to see component-level information. Database Administrator Security and Privileges To accomplish the administrative tasks of an Oracle DBA, you need extra privileges both within the database and possibly in the operating system of the server on which the database runs. Access to a database administrator’s account should be tightly controlled. This section contains the following topics: ■ The Database Administrator’s Operating System Account ■ Database Administrator Usernames The Database Administrator’s Operating System Account To perform many of the administrative duties for a database, you must be able to execute operating system commands. Depending on the operating system that executes Oracle, you might need an operating system account or ID to gain access to the operating system. If so, your operating system account might require more operating system privileges or access rights than many database users require (for 1-10 Oracle9i Database Administrator’s Guide Database Administrator Security and Privileges example, to perform Oracle software installation). Although you do not need the Oracle files to be stored in your account, you should have access to them. See Also: Your operating system specific Oracle documentation. The method of distinguishing a database administrator’s account is operating system specific. Database Administrator Usernames Two user accounts are automatically created with the database: ■ SYS (default password: CHANGE_ON_INSTALL) ■ SYSTEM (default password: MANAGER) Note: Oracle recommends that you specify passwords for SYS and SYSTEM at database creation time, rather that using these default passwords. This is explained in "Protecting Your Database: Specifying Passwords for Users SYS and SYSTEM" on page 2-23. If you use the default passwords, to prevent inappropriate access to the data dictionary tables or other tampering with the database, it is important that you change the passwords for the SYS and SYSTEM usernames immediately after creating an Oracle database. It is suggested that you create at least one additional administrator user, and grant that user the DBA role, to use when performing daily administrative tasks. It is recommended that you do not use SYS and SYSTEM for these purposes. The Oracle Database Administrator 1-11 Database Administrator Security and Privileges Note Regarding Security Enhancements: In this release of Oracle and in subsequent releases, several enhancements are being made to ensure the security of default database user accounts. ■ ■ During initial installation with the Database Configuration Assistant (DCBA), all default database user accounts except SYS, SYSTEM, SCOTT, DBSNMP, OUTLN, AURORA$JIS$UTILITY$, AURORA$ORB$UNAUTHENTICATED and OSE$HTTP$ADMIN are locked and expired. To activate a locked account, the DBA must manually unlock it and reassign it a new password. In addition, the DBCA prompts for passwords for users SYS and SYSTEM during initial installation of the database rather than assigning default passwords to them. A CREATE DATABASE statement issued manually also lets you supply passwords for these two users. SYS When any database is created, the user SYS is automatically created and granted the DBA role. All of the base tables and views for the database’s data dictionary are stored in the schema SYS. These base tables and views are critical for the operation of Oracle. To maintain the integrity of the data dictionary, tables in the SYS schema are manipulated only by Oracle. They should never be modified by any user or database administrator, and no one should create any tables in the schema of user SYS. (However, you can change the storage parameters of the data dictionary settings if necessary.) Ensure that most database users are never able to connect using the SYS account. SYSTEM When a database is created, the user SYSTEM is also automatically created and granted the DBA role. The SYSTEM username is used to create additional tables and views that display administrative information, and internal tables and views used by various Oracle 1-12 Oracle9i Database Administrator’s Guide Database Administrator Authentication options and tools. Never create in the SYSTEM schema tables of interest to individual users. The DBA Role A predefined role, named DBA, is automatically created with every Oracle database. This role contains most database system privileges. Therefore, it is very powerful and should be granted only to fully functional database administrators. Note: The DBA role does not include the SYSDBA or SYSOPER system privileges. These are special administrative privileges that allow an administrator to perform basic database administration tasks, such as creating the database and instance startup and shutdown. These system privileges are discussed in "Administrative Privileges" on page 1-13. Database Administrator Authentication As a DBA, you often perform special operations such as shutting down or starting up a database. Because only a DBA should perform these operations, the database administrator usernames require a secure authentication scheme. This section contains the following topics: ■ Administrative Privileges ■ Selecting an Authentication Method ■ Using Operating System (OS) Authentication ■ Using Password File Authentication Administrative Privileges Administrative privileges that are required for an administrator to perform basic database operations are granted through two special system privileges, SYSDBA and SYSOPER. You must have one of these privileges granted to you, depending upon the level of authorization you require. The Oracle Database Administrator 1-13 Database Administrator Authentication Note: The SYSDBA and SYSOPER system privileges allow access to a database instance even when the database is not open. Control of these privileges is totally outside of the database itself. While referred to as system privileges, SYSDBA and SYSOPER, can also be thought of as types of connections (for example, you specify: CONNECT AS SYSDBA) that enable you to perform certain database operations for which privileges cannot be granted in any other fashion. SYSDBA and SYSOPER The following are the operations that are authorized by the SYSDBA and SYSOPER system privileges: System Privilege Operations Authorized SYSDBA ■ ■ Perform STARTUP and SHUTDOWN operations ALTER DATABASE: open, mount, back up, or change character set ■ CREATE DATABASE ■ CREATE SPFILE ■ ARCHIVELOG and RECOVERY ■ Includes the RESTRICTED SESSION privilege Effectively, this system privilege allows a user to connect as user SYS. SYSOPER ■ Perform STARTUP and SHUTDOWN operations ■ CREATE SPFILE ■ ALTER DATABASE OPEN/MOUNT/BACKUP ■ ARCHIVELOG and RECOVERY ■ Includes the RESTRICTED SESSION privilege This privilege allows a user to perform basic operational tasks, but without the ability to look at user data. The manor in which you are authorized to use these privileges depends upon the method of authentication that you choose to use. 1-14 Oracle9i Database Administrator’s Guide Database Administrator Authentication When you connect with SYSDBA or SYSOPER privileges, you connect with a default schema, not with the schema that is generally associated with your username. For SYSDBA this schema is SYS; for SYSOPER the schema is PUBLIC. Connecting with Administrative Privileges: Example This example illustrates that a user is assigned another schema (SYS) when connecting with the SYSDBA system privilege. Assume that user scott has issued the following statements: CONNECT scott/password CREATE TABLE admin_test(name VARCHAR2(20)); Later, scott issues these statements: CONNECT scott/password AS SYSDBA SELECT * FROM admin_test; User scott now receives the following error: ORA-00942: table or view does not exist This is because scott now references the SYS schema by default. The table was created in the scott schema. See Also: ■ "Using Operating System (OS) Authentication" on page 1-17 ■ "Using Password File Authentication" on page 1-18 Selecting an Authentication Method The following methods are available for authenticating database administrators: ■ Operating system (OS) authentication ■ Password files Note: These methods replace the CONNECT INTERNAL syntax provided with earlier versions of Oracle. CONNECT INTERNAL is no longer allowed. The Oracle Database Administrator 1-15 Database Administrator Authentication Your choice will be influenced by whether you intend to administer your database locally on the same machine where the database resides, or whether you intend to administer many different databases from a single remote client. Figure 1–2 illustrates the choices you have for database administrator authentication schemes. Figure 1–2 Database Administrator Authentication Methods Remote Database Administration Do you have a secure connection? Local Database Administration Yes Do you want to use OS authentication? No Yes Use OS authentication No Use a password file If you are performing remote database administration, you should consult your Oracle Net documentation to determine if you are using a secure connection. Most popular connection protocols, such as TCP/IP and DECnet, are not secure. See Also: ■ Oracle9i Database Concepts for additional information about user authentication ■ "User Authentication" on page 23-2 ■ "User Authentication Methods" on page 24-8 ■ Oracle9i Net Services Administrator’s Guide Non-Secure Remote Connections To connect to Oracle as a privileged user over a non-secure connection, you must be authenticated by a password file. When using password file authentication, the 1-16 Oracle9i Database Administrator’s Guide Database Administrator Authentication database uses a password file to keep track of database usernames that have been granted the SYSDBA or SYSOPER system privilege. This form of authentication is discussed in "Using Password File Authentication" on page 1-18. Local Connections and Secure Remote Connections To connect to Oracle as a privileged user over a local connection or a secure remote connection, you have the following options: ■ ■ You can connect and be authenticated by a password file, provided the database has a password file and you have been granted the SYSDBA or SYSOPER system privilege. If the server is not using a password file, or if you have not been granted SYSDBA or SYSOPER privileges and are therefore not in the password file, you can use OS authentication. On most operating systems, OS authentication for database administrators involves placing the OS username of the database administrator in a special group, generically referred to as OSDBA. Using Operating System (OS) Authentication This section describes how to authenticate an administrator using the operating system. Preparing to Use OS Authentication To enable authentication of an administrative user using the operating system you must do the following: 1. Create an operating system account for the user. 2. Add the user to the OSDBA or OSOPER operating system defined groups. 3. Ensure that the initialization parameter, REMOTE_LOGIN_PASSWORDFILE, is set to NONE. This is the default value for this parameter. Connecting Using OS Authentication A user can be authenticated, enabled as an administrative user, and connected to a local database by typing one of the following SQL*Plus commands: CONNECT / AS SYSDBA CONNECT / AS SYSOPER The Oracle Database Administrator 1-17 Database Administrator Authentication For a remote database connection over a secure connection, the user must also specify the net service name of the remote database: CONNECT /@net_service_name AS SYSDBA CONNECT /@net_service_name AS SYSOPER SQL*Plus User’s Guide and Reference for syntax of the CONNECT command See Also: OSDBA and OSOPER Two special operating system groups control database administrator connections when using OS authentication. These groups are generically referred to as OSDBA and OSOPER. The groups are created and assigned specific names as part of the database installation process. The specific names vary depending upon your operating system and are listed in the following table: Operating System Group UNIX Windows OSDBA dba ORA_DBA OSOPER oper ORA_OPER The default names assumed by the Oracle Universal Installer can be overridden. How you create the OSDBA and OSOPER groups is operating system specific. The following describes how membership in the OSDBA or OSOPER group affects your connection to Oracle: ■ ■ ■ If you are a member of the OSDBA group, and specify AS SYSDBA when you connect to the database, you are granted the SYSDBA system privilege. If you are a member of the OSOPER group, and specify AS SYSOPER when you connect to the database, you are granted the SYSOPER system privilege. If you are not a member of the associated operating system group for SYSDBA or SYSOPER system privileges, the CONNECT command fails. See Also: Your operating system specific Oracle documentation for information about creating the OSDBA and OSOPER groups Using Password File Authentication This section describes how to authenticate an administrative user using password file authentication. 1-18 Oracle9i Database Administrator’s Guide Database Administrator Authentication Preparing to Use Password File Authentication To enable authentication of an administrative user using password file authentication you must do the following: 1. Create an operating system account for the user. 2. If not already created, Create the password file using the ORAPWD utility: ORAPWD FILE=filename PASSWORD=password ENTRIES=max_users 3. Set the REMOTE_LOGIN_PASSWORDFILE initialization parameter to EXCLUSIVE. 4. Connect to the database as user SYS (or as another user with the administrative privilege). 5. If the user does not already exist in the database, create the user. Grant the SYSDBA or SYSOPER system privilege to the user: GRANT SYSDBA to scott; This statement adds the user to the password file, thereby enabling connection AS SYSDBA. See Also: "Creating and Maintaining a Password File" on page 1-20 for instructions for creating and maintaining a password file Connecting Using Password File Authentication Administrative users can be connected and authenticated to a local or remote database by using the SQL*Plus CONNECT command. They must connect using their username and password and with the AS SYSDBA or AS SYSOPER clause. For example, user scott has been granted the SYSDBA privilege, so he can connect as follows: CONNECT scott/tiger AS SYSDBA However, since scott has not been granted the SYSOPER privilege, the following command will fail: CONNECT scott/tiger AS SYSOPER The Oracle Database Administrator 1-19 Creating and Maintaining a Password File Note: Operating system authentication takes precedence over password file authentication. Specifically, if you are a member of the OSDBA or OSOPER group for the operating system, and you connect as SYSDBA or SYSOPER, you will be connected with associated administrative privileges regardless of the username/password that you specify. If you are not in the OSDBA or OSOPER groups, and you are not in the password file, then the connection will fail. SQL*Plus User’s Guide and Reference for syntax of the CONNECT command See Also: Creating and Maintaining a Password File You can create a password file using the password file creation utility, ORAPWD. For some operating systems, you can create this file as part of your standard installation. This section contains the following topics: ■ Using ORAPWD ■ Setting REMOTE_LOGIN_ PASSWORDFILE ■ Adding Users to a Password File ■ Maintaining a Password File See Also: Your operating system specific Oracle documentation for information on using the installer utility to install the password file Using ORAPWD When you invoke the password file creation utility without supplying any parameters, you receive a message indicating the proper use of the command as shown in the following sample output: orapwd Usage: orapwd file=<fname> password=<password> entries=<users> where file - name of password file (mand), password - password for SYS (mand), 1-20 Oracle9i Database Administrator’s Guide Creating and Maintaining a Password File entries - maximum number of distinct DBAs and OPERs (opt), There are no spaces around the equal-to (=) character. The following command creates a password file named acct.pwd that allows up to 30 privileged users with different passwords. In this example, the file is initially created with the password secret for users connecting as SYS. ORAPWD FILE=acct.pwd PASSWORD=secret ENTRIES=30 Following are descriptions of the parameters in the ORAPWD utility. FILE This parameter sets the name of the password file being created. You must specify the full path name for the file. The contents of this file are encrypted, and the file cannot be read directly. This parameter is mandatory. The types of filenames allowed for the password file are operating system specific. Some operating systems require the password file to be a specific format and located in a specific directory. Other operating systems allow the use of environment variables to specify the name and location of the password file. See your operating system specific Oracle documentation for the names and locations allowed on your platform. If you are running multiple instances of Oracle using Oracle9i Real Application Clusters, the environment variable for each instance should point to the same password file. Caution: It is critically important to the security of your system that you protect your password file and the environment variables that identify the location of the password file. Any user with access to these could potentially compromise the security of the connection. PASSWORD This parameter sets the password for user SYS. If you issue the ALTER USER statement to change the password for SYS after connecting to the database, both the password stored in the data dictionary and the password stored in the password file are updated. This parameter is mandatory. ENTRIES This parameter specifies the number of entries that you require the password file to accept. This number corresponds to the number of distinct users allowed to connect The Oracle Database Administrator 1-21 Creating and Maintaining a Password File to the database as SYSDBA or SYSOPER. The actual number of allowable entries can be higher than the number of users because the ORAPWD utility continues to assign password entries until an operating system block is filled. For example, if your operating system block size is 512 bytes, it holds four password entries. The number of password entries allocated is always multiple of four. Entries can be reused as users are added to and removed from the password file. If you intend to specify REMOTE_LOGON_PASSWORDFILE=EXCLUSIVE, and to allow the granting of SYSDBA and SYSOPER privileges to users, this parameter is required. Caution: When you exceed the allocated number of password entries, you must create a new password file. To avoid this necessity, allocate a number of entries that is larger than you think you will ever need. Setting REMOTE_LOGIN_ PASSWORDFILE In addition to creating the password file, you must also set the initialization parameter REMOTE_LOGIN_PASSWORDFILE to the appropriate value. The values recognized are described as follows: 1-22 Value Description NONE Setting this parameter to NONE causes Oracle to behave as if the password file does not exist. That is, no privileged connections are allowed over non-secure connections. NONE is the default value for this parameter. EXCLUSIVE An EXCLUSIVE password file can be used with only one database. Only an EXCLUSIVE file can contain the names of users other than SYS. Using an EXCLUSIVE password file allows you to grant SYSDBA and SYSOPER system privileges to individual users and have them connect as themselves. SHARED A SHARED password file can be used by multiple databases. However, the only user recognized by a SHARED password file is SYS. You cannot add users to a SHARED password file. All users needing SYSDBA or SYSOPER system privileges must connect using the same name, SYS, and password. This option is useful if you have a single DBA administering multiple databases. Oracle9i Database Administrator’s Guide Creating and Maintaining a Password File Suggestion: To achieve the greatest level of security, you should set the REMOTE_LOGIN_PASSWORDFILE initialization parameter to EXCLUSIVE immediately after creating the password file. Adding Users to a Password File When you grant SYSDBA or SYSOPER privileges to a user, that user’s name and privilege information are added to the password file. If the server does not have an EXCLUSIVE password file (that is, if the initialization parameter REMOTE_LOGIN_ PASSWORDFILE is NONE or SHARED) you receive an error message if you attempt to grant these privileges. A user’s name remains in the password file only as long as that user has at least one of these two privileges. If you revoke both of these privileges, the user is removed from the password file. To Create a Password File and Add New Users to It 1. Follow the instructions for creating a password file as explained in "Using ORAPWD" on page 1-20. 2. Set the REMOTE_LOGIN_PASSWORDFILE initialization parameter to EXCLUSIVE. 3. Connect with SYSDBA privileges as shown in the following example: CONNECT SYS/password AS SYSDBA 4. Start up the instance and create the database if necessary, or mount and open an existing database. 5. Create users as necessary. Grant SYSDBA or SYSOPER privileges to yourself and other users as appropriate. See "Granting and Revoking SYSDBA and SYSOPER Privileges". Granting the SYSDBA or SYSOPER privilege to a user causes their username to be added to the password file. This enables the user to connect to the database as SYSDBA or SYSOPER by specifying username and password (instead of using SYS). The use of a password file does not prevent OS authenticated users from connecting if they meet the criteria for OS authentication. The Oracle Database Administrator 1-23 Creating and Maintaining a Password File Granting and Revoking SYSDBA and SYSOPER Privileges If your server is using an EXCLUSIVE password file, use the GRANT statement to grant the SYSDBA or SYSOPER system privilege to a user, as shown in the following example: GRANT SYSDBA TO scott; Use the REVOKE statement to revoke the SYSDBA or SYSOPER system privilege from a user, as shown in the following example: REVOKE SYSDBA FROM scott; Because SYSDBA and SYSOPER are the most powerful database privileges, the ADMIN OPTION is not used. Only a user currently connected as SYSDBA (or INTERNAL) can grant or revoke another user’s SYSDBA or SYSOPER system privileges. These privileges cannot be granted to roles, because roles are only available after database startup. Do not confuse the SYSDBA and SYSOPER database privileges with operating system roles, which are a completely independent feature. Chapter 25, "Managing User Privileges and Roles" for more information on system privileges See Also: Viewing Password File Members Use the V$PWFILE_USERS view to see the users who have been granted SYSDBA or SYSOPER system privileges for a database. The columns displayed by this view are as follows: Column Description USERNAME This column contains the name of the user that is recognized by the password file. SYSDBA If the value of this column is TRUE, then the user can log on with SYSDBA system privileges. SYSOPER If the value of this column is TRUE, then the user can log on with SYSOPER system privileges. Maintaining a Password File This section describes how to: 1-24 ■ Expand the number of password file users if the password file becomes full ■ Remove the password file Oracle9i Database Administrator’s Guide Creating and Maintaining a Password File ■ Avoid changing the state of the password file Expanding the Number of Password File Users If you receive the file full error (ORA-1996) when you try to grant SYSDBA or SYSOPER system privileges to a user, you must create a larger password file and re-grant the privileges to the users. To Replace a Password File 1. Note the users who have SYSDBA or SYSOPER privileges by querying the V$PWFILE_USERS view. 2. Shut down the database. 3. Delete the existing password file. 4. Follow the instructions for creating a new password file using the ORAPWD utility in "Using ORAPWD" on page 1-20. Ensure that the ENTRIES parameter is set to a number larger than you think you will ever need. 5. Follow the instructions in "Adding Users to a Password File" on page 1-23. Removing a Password File If you determine that you no longer require a password file to authenticate users, you can delete the password file and reset the REMOTE_LOGIN_PASSWORDFILE initialization parameter to NONE. After you remove this file, only those users who can be authenticated by the operating system can perform database administration operations. Caution: Do not remove or modify the password file if you have a database or instance mounted using REMOTE_LOGIN_ PASSWORDFILE=EXCLUSIVE (or SHARED). If you do, you will be unable to reconnect remotely using the password file. Even if you replace it, you cannot use the new password file, because the timestamps and checksums will be wrong. Changing the Password File State The password file state is stored in the password file. When you first create a password file, its default state is SHARED. You can change the state of the password file by setting the initialization parameter REMOTE_LOGIN_PASSWORDFILE. When you start up an instance, Oracle retrieves the value of this parameter from the The Oracle Database Administrator 1-25 Database Administrator Utilities parameter file stored on your client machine. When you mount the database, Oracle compares the value of this parameter to the value stored in the password file. If the values do not match, Oracle overwrites the value stored in the file. Caution: Use caution to ensure that an EXCLUSIVE password file is not accidentally changed to SHARED. If you plan to allow instance start up from multiple clients, each of those clients must have an initialization parameter file, and the value of the parameter REMOTE_LOGIN_PASSWORDFILE must be the same in each of these files. Otherwise, the state of the password file could change depending upon where the instance was started. Database Administrator Utilities Several utilities are available to help you maintain the data in your Oracle database. This section introduces two of these utilities: ■ SQL*Loader ■ Export and Import See Also: Oracle9i Database Utilities SQL*Loader SQL*Loader is used both by database administrators and by other users of Oracle. It loads data from standard operating system files (such as, files in text or C data format) into Oracle database tables. Export and Import The Export and Import utilities enable you to move existing data in Oracle format to and from Oracle databases. For example, export files can archive database data or move data among different Oracle databases that run on the same or different operating systems. 1-26 Oracle9i Database Administrator’s Guide 2 Creating an Oracle Database This chapter discusses the process of creating an Oracle database, and contains the following topics: ■ Considerations Before Creating a Database ■ Using the Database Configuration Assistant ■ Manually Creating an Oracle Database ■ Understanding the CREATE DATABASE Statement ■ Troubleshooting Database Creation ■ Dropping a Database ■ Considerations After Creating a Database ■ Initialization Parameters and Database Creation ■ Managing Initialization Parameters Using a Server Parameter File See Also: ■ ■ Chapter 3, "Using Oracle-Managed Files" for information about creating a database whose underlying operating system files are automatically created and managed by the Oracle database server Oracle9i Real Application Clusters Setup and Configuration for additional information specific to an Oracle Real Application Clusters environment Creating an Oracle Database 2-1 Considerations Before Creating a Database Considerations Before Creating a Database Database creation prepares several operating system files to work together as an Oracle database. You need only create a database once, regardless of how many datafiles it has or how many instances access it. Creating a database can also erase information in an existing database and create a new database with the same name and physical structure. The following topics can help prepare you for database creation. ■ Planning for Database Creation ■ Meeting Creation Prerequisites ■ Deciding How to Create an Oracle Database Planning for Database Creation Prepare to create the database by research and careful planning. The following are some recommended actions: Action ■ Plan the database tables and indexes and estimate the amount of space they will require. For more information... Part II, "Oracle Server Processes and Storage Structure" Part III, "Schema Objects" ■ ■ ■ Plan the layout of the underlying operating system files that are to comprise your database. Proper distribution of files can improve database performance dramatically by distributing the I/O for accessing the files. There are several ways to distribute I/O when you install Oracle and create your database. For example, placing redo log files on separate disks or striping; placing datafiles to reduce contention; and controlling density of data (number of rows to a data block). Oracle9i Database Performance Tuning Guide and Reference Consider using the Oracle Managed Files feature to create and manage the operating system files that comprise your database storage. This feature eases their administration. Chapter 3, "Using Oracle-Managed Files" Select the global database name, which is the name and location of the database within the network structure. Create the global database name by setting both the DB_ NAME and DB_DOMAIN initialization parameters. "Determining the Global Database Name" on page 2-35 2-2 Oracle9i Database Administrator’s Guide Your Oracle operating system specific documentation Considerations Before Creating a Database Action ■ For more information... Familiarize yourself with the initialization parameters that comprise the initialization parameter file. Become familiar with the concept and operation of a server parameter file. A server parameter file allows you to store and manage your initialization parameters persistently in a server-side disk file. "Initialization Parameters and Database Creation" on page 2-34 "What is a Server Parameter File?" on page 2-44 Oracle9i Database Reference ■ Select the database character set. All character data, including data in the data dictionary, is stored in the database character set. You must specify the database character set when you create the database. Oracle9i Database Globalization Support Guide If clients using different character sets will access the database, then choose a superset that includes all client character sets. Otherwise, character conversions may be necessary at the cost of increased overhead and potential data loss. You can also specify an alternate character set. ■ Consider what time zones your database must support. Oracle uses a time zone file, located in the Oracle home directory, as the source of valid time zones. If you determine that you need to use a time zone that is not in the default time zone file (timezone.dat), but that is present in the larger time zone file (timezlrg.dat), then you must set the ORA_TZFILE environment variable to point to the larger file. ■ Select the standard database block size. This is specified at database creation by the DB_BLOCK_SIZE initialization parameter and cannot be changed after the database is created. "Specifying the Database Time Zone File" on page 2-28 Oracle9i Database Globalization Support Guide "Specifying Database Block Sizes" on page 2-37 The SYSTEM tablespace and most other tablespaces use the standard block size. Additionally, you can specify up to four non-standard block sizes when creating tablespaces. ■ Use an undo tablespace to manage your undo records, rather than rollback segments. Chapter 13, "Managing Undo Space" Creating an Oracle Database 2-3 Considerations Before Creating a Database Action ■ Develop a backup and recovery strategy to protect the database from failure. It is important to protect the control file by multiplexing, to choose the appropriate backup mode, and to manage the online and archived redo logs. For more information... Chapter 7, "Managing the Online Redo Log" Chapter 8, "Managing Archived Redo Logs" Chapter 6, "Managing Control Files" Oracle9i Backup and Recovery Concepts ■ Familiarize yourself with the principles and options of starting up and shutting down an instance and mounting and opening a database. Chapter 4, "Starting Up and Shutting Down" Meeting Creation Prerequisites To create a new database, the following prerequisites must be met: ■ ■ ■ ■ The desired Oracle software is installed. This includes setting up various environment variables unique to your operating system and establishing the directory structure for software and database files. You have the operating system privileges associated with a fully operational database administrator. You must be specially authenticated by your operating system or through a password file, allowing you to start up and shut down an instance before the database is created or opened. This authentication is discussed in "Database Administrator Authentication" on page 1-13. There is sufficient memory available to start the Oracle instance. There is sufficient disk storage space for the planned database on the computer that executes Oracle. All of these are discussed in the Oracle installation guide specific to your operating system. Additionally, the Oracle Universal Installer will guide you through your installation and provide help in setting up environment variables, directory structure, and authorizations. Deciding How to Create an Oracle Database Creating a database includes the following operations: ■ Creating information structures, including the data dictionary, that Oracle requires to access and use the database 2-4 Oracle9i Database Administrator’s Guide Using the Database Configuration Assistant ■ Creating and initializing the control files and redo log files for the database ■ Creating new datafiles or erasing data that existed in previous datafiles You use the CREATE DATABASE statement to perform these operations, but other actions are necessary before you have an operational database. A few of these actions are creating users and temporary tablespaces, building views of the data dictionary tables, and installing Oracle built-in packages. This is why the database creation process involves executing prepared scripts. But, you do not necessarily have to prepare this script yourself. You have the following options for creating your new Oracle database: ■ Use the Database Configuration Assistant (DBCA). DBCA can be launched by the Oracle Universal Installer, depending upon the type of install that you select, and provides a graphical user interface (GUI) that guides you through the creation of a database. You can chose not to use DBCA, or you can launch it as a standalone tool at any time in the future to create a database. See "Using the Database Configuration Assistant" on page 2-5. ■ Create the database manually from a script. If you already have existing scripts for creating your database, you can still create your database manually. However, consider editing your existing script to take advantage of new Oracle features. Oracle provides a sample database creation script and a sample initialization parameter file with the database software files it distributes, both of which can be edited to suit your needs. See "Manually Creating an Oracle Database" on page 2-14. ■ Upgrade an existing database. If you are already using a previous release of Oracle, database creation is required only if you want an entirely new database. You can upgrade your existing Oracle database and use it with the new release of the Oracle software. Database upgrades are not discussed in this book. The Oracle9i Database Migration manual contains information about upgrading an existing Oracle database. Using the Database Configuration Assistant The Database Configuration Assistant (DBCA) an Oracle supplied tool that enables you to create an Oracle database, configure database options for an existing Oracle database, delete an Oracle database, or manage database templates. DBCA is launched automatically by the Oracle Universal Installer, but it can be invoked Creating an Oracle Database 2-5 Using the Database Configuration Assistant standalone from the Windows operating system start menu (under Configuration Assistants) or by entering the following on the UNIX command line: dbca DBCA can be run in three modes: Mode Description Interactive This is the default mode if you do not specify any parameters. This mode presents a wizard like GUI interface and provides complete DBCA functionality. Online help is provided. Progress Only This mode is typically used by other tools to create a database. For example, it is used by the Oracle Universal Installer, the Enterprise Manager Configuration Assistant, and the Oracle Internet Directory Configuration Assistant. In this mode, only a progress bar is displayed, and it is used when creating databases and templates. Silent This mode has only a command-line interface where parameters are specified. There is no other user interaction. Informational, error, and warning message are written to a log file. You specify the template of your choice, for customization or for the creation of a database. DBCA can be used to create single instance databases, or it can be used to create or add instances in an Oracle Real Application Clusters environment. This section primarily describes the use of DBCA in interactive mode. It contains the following topics: ■ Advantages of Using DBCA ■ Creating a Database Using DBCA ■ Configuring Database Options ■ Deleting a Database Using DBCA ■ Managing DBCA Templates ■ Using DBCA Silent Mode Advantages of Using DBCA These are a few of the advantages of using DBCA: 2-6 Oracle9i Database Administrator’s Guide Using the Database Configuration Assistant ■ ■ ■ You can use its wizards to guide you through a selection of options providing an easy means of creating and tailoring your database. It allows you to provide varying levels of detail. You can provide a minimum of input and allow Oracle to make decisions for you, eliminating the need to spend time deciding how best to set parameters or structure the database. Optionally, it allows you to be very specific about parameter settings and file allocations. It builds efficient and effective databases that take advantage of Oracle’s new features. It uses Optimal Flexible Architecture (OFA), whereby database files and administrative files, including initialization files, follow standard naming and placement practices. Creating a Database Using DBCA DBCA enables you to create a database from predefined templates provided by Oracle or from templates that you or others have created. A template is a description of a database. Templates are described in more detail in "Managing DBCA Templates" on page 2-9. Selecting the Template DBCA displays the templates that are available, which includes templates that Oracle ships with the DBCA product. These templates are described in "DBCA Templates Provided by Oracle" on page 2-11. If you or others have created templates, those will be displayed also. You select the appropriate template for the database that you want to create. Clicking the "Show Details..." button displays specific information about the database defined by a template. Including Datafiles When you select a template, you also specify whether the database definition is to include datafiles. This determines whether you use a seed template (includes datafiles), or a non-seed template (does not include datafiles), to create your database. Specifying Global Database Name and Database Features The next page that DBCA displays enables you provide a global database name and SID. Creating an Oracle Database 2-7 Using the Database Configuration Assistant Specifying Database Features The "Database Features" page is presented only when you select a non-seed template. It enables you to include optional database features. The following is a representative list of Oracle features that you can install in your database. Some of the listed options might already be included depending upon the database template that you selected. Those options that are already installed are noted as such (grayed out). ■ Oracle Spatial ■ Oracle Ultra Search ■ Oracle Label Security ■ Oracle Data Mining ■ Oracle OLAP Services ■ Sample Schemas You can also display a list of standard database features. These are features that Oracle recommends you always install, but you have the option of excluding them. These include: ■ Oracle JVM ■ Oracle Text ■ Oracle interMedia ■ XDB Protocol Specifying Mode, Initialization Parameters, and Datafiles The next pages enable you to further define your database. You specify mode (dedicated server of shared server), set initialization parameters, and specify datafile locations. Oracle can determine specific values for you based upon your description of the database you are trying to create. For example, Oracle can choose appropriate settings for SGA memory sizing parameters depending upon whether you select a typical or custom database. Completing Database Creation After you have completed the specification of the parameters that define your database you can: 2-8 Oracle9i Database Administrator’s Guide Using the Database Configuration Assistant ■ Create the database now ■ Save the description as a database template ■ Generate database creation scripts If you choose to generate scripts, you can use them to create the database later without using DBCA, or you can use them as a checklist Configuring Database Options When you elect to configure database options, you can add Oracle options that have not previously been configured for use with your database. This provides you the opportunity to add options and features that you did not include when you created the database. These options are discussed in "Specifying Database Features" on page 2-8. Deleting a Database Using DBCA DBCA enables you to delete a database. When you do so, you delete the database instance and its control file(s), redo log files, and datafiles. Any server parameter file (SPFILE) or initialization parameter file used by the database is also deleted. Managing DBCA Templates DBCA templates are XML files that contain information required to create a database. Templates are used in DBCA to create new databases and make clones of existing databases. The information in templates includes database options, initialization parameters, and storage attributes (for datafiles, tablespaces, control files and redo logs). Templates can be used just like scripts, and they can be used in silent mode. But they are more powerful than scripts, because you have the option of cloning a database. This saves time in database creation, because copying an already created seed database’s files to the correct locations takes less time than creating them as new. Templates are stored in the following directory: $ORACLE_HOME/assistants/dbca/templates Advantages of Using Templates The following are some of the advantages of using templates: Creating an Oracle Database 2-9 Using the Database Configuration Assistant ■ ■ ■ ■ They save you time. If you use a template you do not have to define the database. By creating a template containing your database settings, you can easily create a duplicate database without specifying parameters twice. They are easily edited. You can quickly change database options from the template settings. Templates are easy to share. They can be copied from one machine to another. Types of Templates There are two types of templates: ■ Seed templates ■ Non-seed templates The characteristics of each are shown in the following table: 2-10 Oracle9i Database Administrator’s Guide Using the Database Configuration Assistant Type File Extension Include Datafiles? Seed .dbc Yes Database Structure This type of template contains both the structure and the physical datafiles of an existing (seed) database. When you select a seed template, database creation is faster because the physical files and schema of the database have already been created. Your database starts as a copy of the seed database, rather than having to be built. You can change only the following: ■ Name of the database ■ Destination of the datafiles ■ Number control files ■ Number redo log groups ■ Initialization parameters Other changes can be made after database creation using custom scripts that can be invoked by DBCA, command line SQL statements, or the Oracle Enterprise Manager. The datafiles and redo logs for the seed database are stored in zipped format in another file with a .dfj extension. Usually the corresponding .dfj file of a .dbc file has the same file name, but this is not a requirement since the corresponding .dfj file’s location is stored in the .dbc file. Non-seed .dbt No This type of template is used to create a new database from scratch. It contains the characteristics of the database to be created. Seed templates are more flexible than their seed counterparts because all datafiles and redo logs are created to your specification (not copied), and names, sizes, and other attributes can be changed as required. DBCA Templates Provided by Oracle Oracle provides templates for the following environments: Creating an Oracle Database 2-11 Using the Database Configuration Assistant Environment Description of Environment DSS (Data Warehousing) Users perform numerous, complex queries that process large volumes of data. Response time, accuracy, and availability are key issues. These queries (typically read-only) range from a simple fetch of a few records to numerous complex queries that sort thousands of records from many different tables. OLTP (Online Transaction Processing) Many concurrent users performing numerous transactions requiring rapid access to data. Availability, speed, concurrence, and recoverability are key issues. Transactions consist of reading (SELECT statements), writing (INSERT and UPDATE statements), and deleting (DELETE statements) data in database tables. General Purpose This template creates a database designed for general purpose usage. It combines features of both the DSS and OLTP database templates. New Database This template allows you maximum flexibility in defining a database. Creating Templates Using DBCA The "Template Management" page provides you with three options that enable you to modify existing templates or to create your own custom templates. Your choices are: ■ From an existing template Using an existing template, you can create a new template based on the pre-defined template settings. You can add or change any template settings such as initialization parameters, storage parameters, or use custom scripts. ■ From an existing database (structure only) You can create a new template that contains structural information about an existing database, including database options, tablespaces, datafiles, and initialization parameters specified in the source database. User defined schema and their data will not be part of the created template. The source database can be either local or remote. ■ From an existing database (structure as well as data--a seed database) You can create a new template that has both the structural information and physical datafiles of an existing database. Databases created using such a 2-12 Oracle9i Database Administrator’s Guide Using the Database Configuration Assistant template are identical to the source database. User defined schema and their data will be part of the created template. The source database must be local. Oracle saves templates as XML files. While creating templates from existing databases, you can optionally choose to translate file paths into OFA (Optimal Flexible Architecture) or maintain existing file paths. OFA is recommended if the machine on which you plan to create the database using the template has a different directory structure. Non-OFA can be used if the target machine has a similar directory structure. Deleting DBCA Templates The "Template Management" page also allows you to delete existing templates. Using DBCA Silent Mode Silent mode does not have any user interface (other than what you initially input on the command line) or user interaction. It outputs all messages including information, errors, and warnings into a log file. From the command line enter the following command to see all of the DBCA options that are available when using silent mode: dbca -help The following sections contain examples that illustrate the use of silent mode. DBCA Silent Mode Example 1: Creating a Clone Database To create a clone database, enter the following on the command line: % dbca -silent -createDatabase -templateName Transaction_Processing.dbc -gdbname ora9i -sid ora9i -datafileJarLocation /private/oracle9i/ora9i/assistants/dbca/templates -datafileDestination /private/oracle9i/ora9i/oradata -responseFile NO_VALUE -characterset WE8ISO8859P1 DBCA Silent Mode Example 2: Creating a Seed Template To create a seed template, enter the following on the command line: % dbca -silent -createCloneTemplate -sourceDB ora9I -sysDBAUserName sys -sysDBAPassword change_on_install -templateName copy_of_ora9i.dbc -datafileJarLocation /private/oracle/ora9i/assistants/dbca/templates Creating an Oracle Database 2-13 Manually Creating an Oracle Database Manually Creating an Oracle Database This section presents the steps involved when you create a database manually. These steps should be followed in the order presented. You will previously have created your environment for creating your Oracle database, including most operating system dependent environmental variables, as part of the Oracle software installation process. Step 1: Decide on Your Instance Identifier (SID) Step 2: Establish the Database Administrator Authentication Method Step 3: Create the Initialization Parameter File Step 4: Connect to the Instance Step 5: Start the Instance. Step 6: Issue the CREATE DATABASE Statement Step 7: Create Additional Tablespaces Step 8: Run Scripts to Build Data Dictionary Views Step 9: Run Scripts to Install Additional Options (Optional) Step 10: Create a Server Parameter File (Recommended) Step 11: Back Up the Database. The examples shown in these steps are to create the database mynewdb. Note: At this point, you may not be familiar with all of the initialization parameters and database structures discussed in this section. These steps contain many cross references to other parts of this book to allow you to learn about and understand these parameters and structures. Step 1: Decide on Your Instance Identifier (SID) Decide on a unique Oracle system identifier (SID) for your instance and set the ORACLE_SID environment variable accordingly. This identifier is used to avoid confusion with other Oracle instances that you may create later and run concurrently on your system. The following example sets the SID for the instance and database we are about to create: 2-14 Oracle9i Database Administrator’s Guide Manually Creating an Oracle Database % setenv ORACLE_SID mynewdb The value of the DB_NAME initialization parameter should match the SID setting. Step 2: Establish the Database Administrator Authentication Method You must be authenticated and granted appropriate system privileges in order to create a database. You can use the password file or operating system authentication method. Database administrator authentication and authorization is discussed in the following sections of this book: ■ "Database Administrator Security and Privileges" on page 1-10 ■ "Database Administrator Authentication" on page 1-13 ■ "Creating and Maintaining a Password File" on page 1-20 Step 3: Create the Initialization Parameter File The instance (System Global Area and background processes) for any Oracle database is started using an initialization parameter file. One way of getting started on your initialization parameter file is to edit a copy of the sample initialization parameter file that Oracle provides on the distribution media, or the sample presented in this book. For ease of operation, store your initialization parameter file in Oracle’s default location, using the default name. That way, when you start your database, it is not necessary to specify the PFILE parameter because Oracle automatically looks in the default location for the initialization parameter file. Default parameter file locations are shown in the following table: Platform Default Name Default Location UNIX init$ORACLE_SID.ora $ORACLE_HOME/dbs For example, the initialization parameter file for the mynewdb database is named: For example, the initialization parameter file for the mynewdb database is stored in the following location: initmynewdb.ora /vobs/oracle/dbs/initmynewdb.ora init$ORACLE_SID.ora $ORACLE_HOME\database Windows The following is the initialization parameter file used to create the mynewdb database. Creating an Oracle Database 2-15 Manually Creating an Oracle Database Sample Initialization Parameter File # Cache and I/O DB_BLOCK_SIZE=4096 DB_CACHE_SIZE=20971520 # Cursors and Library Cache CURSOR_SHARING=SIMILAR OPEN_CURSORS=300 # Diagnostics and Statistics BACKGROUND_DUMP_DEST=/vobs/oracle/admin/mynewdb/bdump CORE_DUMP_DEST=/vobs/oracle/admin/mynewdb/cdump TIMED_STATISTICS=TRUE USER_DUMP_DEST=/vobs/oracle/admin/mynewdb/udump # Control File Configuration CONTROL_FILES=("/vobs/oracle/oradata/mynewdb/control01.ctl", "/vobs/oracle/oradata/mynewdb/control02.ctl", "/vobs/oracle/oradata/mynewdb/control03.ctl") # Archive LOG_ARCHIVE_DEST_1='LOCATION=/vobs/oracle/oradata/mynewdb/archive' LOG_ARCHIVE_FORMAT=%t_%s.dbf LOG_ARCHIVE_START=TRUE # Shared Server # Uncomment and use first DISPATCHES parameter below when your listener is # configured for SSL # (listener.ora and sqlnet.ora) # DISPATCHERS = "(PROTOCOL=TCPS)(SER=MODOSE)", # "(PROTOCOL=TCPS)(PRE=oracle.aurora.server.SGiopServer)" DISPATCHERS="(PROTOCOL=TCP)(SER=MODOSE)", "(PROTOCOL=TCP)(PRE=oracle.aurora.server.SGiopServer)", (PROTOCOL=TCP) # Miscellaneous COMPATIBLE=9.2.0 DB_NAME=mynewdb # Distributed, Replication and Snapshot DB_DOMAIN=us.oracle.com REMOTE_LOGIN_PASSWORDFILE=EXCLUSIVE # Network Registration INSTANCE_NAME=mynewdb 2-16 Oracle9i Database Administrator’s Guide Manually Creating an Oracle Database # Pools JAVA_POOL_SIZE=31457280 LARGE_POOL_SIZE=1048576 SHARED_POOL_SIZE=52428800 # Processes and Sessions PROCESSES=150 # Redo Log and Recovery FAST_START_MTTR_TARGET=300 # Resource Manager RESOURCE_MANAGER_PLAN=SYSTEM_PLAN # Sort, Hash Joins, Bitmap Indexes SORT_AREA_SIZE=524288 # Automatic Undo Management UNDO_MANAGEMENT=AUTO UNDO_TABLESPACE=undotbs See Also: ■ "Initialization Parameters and Database Creation" on page 2-34 for more information on some of these parameters and other initialization parameters that you decide to include Step 4: Connect to the Instance Start SQL*Plus and connect to your Oracle instance AS SYSDBA. $ SQLPLUS /nolog CONNECT SYS/password AS SYSDBA Step 5: Start the Instance. Start an instance without mounting a database. Typically, you do this only during database creation or while performing maintenance on the database. Use the STARTUP command with the NOMOUNT option. In this example, because the initialization parameter file is stored in the default location, you are not required to specify the PFILE clause: STARTUP NOMOUNT Creating an Oracle Database 2-17 Manually Creating an Oracle Database At this point, there is no database. Only the SGA is created and background processes are started in preparation for the creation of a new database. See Also: ■ ■ "Managing Initialization Parameters Using a Server Parameter File" on page 2-44 Chapter 4, "Starting Up and Shutting Down" to learn how to use the STARTUP command Step 6: Issue the CREATE DATABASE Statement To create the new database, use the CREATE DATABASE statement. The following statement creates database mynewdb: CREATE DATABASE mynewdb USER SYS IDENTIFIED BY pz6r58 USER SYSTEM IDENTIFIED BY y1tz5p LOGFILE GROUP 1 ('/vobs/oracle/oradata/mynewdb/redo01.log') SIZE 100M, GROUP 2 ('/vobs/oracle/oradata/mynewdb/redo02.log') SIZE 100M, GROUP 3 ('/vobs/oracle/oradata/mynewdb/redo03.log') SIZE 100M MAXLOGFILES 5 MAXLOGMEMBERS 5 MAXLOGHISTORY 1 MAXDATAFILES 100 MAXINSTANCES 1 CHARACTER SET US7ASCII NATIONAL CHARACTER SET AL16UTF16 DATAFILE '/vobs/oracle/oradata/mynewdb/system01.dbf' SIZE 325M REUSE EXTENT MANAGEMENT LOCAL DEFAULT TEMPORARY TABLESPACE tempts1 DATAFILE '/vobs/oracle/oradata/mynewdb/temp01.dbf' SIZE 20M REUSE UNDO TABLESPACE undotbs DATAFILE '/vobs/oracle/oradata/mynewdb/undotbs01.dbf' SIZE 200M REUSE AUTOEXTEND ON NEXT 5120K MAXSIZE UNLIMITED; A database is created with the following characteristics: ■ ■ 2-18 The database is named mynewdb. Its global database name is mynewdb.us.oracle.com. See "DB_NAME Initialization Parameter" and "DB_DOMAIN Initialization Parameter" on page 2-36. Three control files are created as specified by the CONTROL_FILES initialization parameter. See "Specifying Control Files" on page 2-36. Oracle9i Database Administrator’s Guide Manually Creating an Oracle Database ■ ■ ■ The password for user SYS is pz6r58 and the password for SYSTEM is y1tz5p. These two clauses that specify the passwords for SYS and SYSTEM are not mandatory in this release of Oracle9i. However, if you specify either clause, you must specify both clauses. For further information about the use of these clauses, see "Protecting Your Database: Specifying Passwords for Users SYS and SYSTEM" on page 2-23. The new database has three online redo log files as specified in the LOGFILE clause. MAXLOGFILES, MAXLOGMEMBERS, and MAXLOGHISTORY define limits for the redo log. See Chapter 7, "Managing the Online Redo Log". MAXDATAFILES specifies the maximum number of datafiles that can be open in the database. This number affects the initial sizing of the control file. Note: You can set several limits during database creation. Some of these limits are also subject to superseding limits of the operating system and can be affected by them. For example, if you set MAXDATAFILES, Oracle allocates enough space in the control file to store MAXDATAFILES filenames, even if the database has only one datafile initially. However, because the maximum control file size is limited and operating system dependent, you might not be able to set all CREATE DATABASE parameters at their theoretical maximums. For more information about setting limits during database creation, see the Oracle9i SQL Reference and your operating system specific Oracle documentation. ■ ■ ■ ■ ■ MAXINSTANCES specifies that only one instance can have this database mounted and open. The US7ASCII character set is used to store data in this database. The AL16UTF16 character set is specified as the NATIONAL CHARACRTER SET, used to store data in columns specifically defined as NCHAR, NCLOB, or NVARCHAR2. The SYSTEM tablespace, consisting of the operating system file /vobs/oracle/oradata/mynewdb/system01.dbf, is created as specified by the DATAFILE clause. If the file already exists, it is overwritten. The SYSTEM tablespace is a locally managed tablespace. See "Creating a Locally Managed SYSTEM Tablespace" on page 2-26. Creating an Oracle Database 2-19 Manually Creating an Oracle Database ■ ■ ■ The DEFAULT_TEMPORARY_TABLESPACE clause creates and names a default temporary tablespace for this database. See "Creating a Default Temporary Tablespace" on page 2-24. The UNDO_TABLESPACE clause creates and names an undo tablespace to be used to store undo records for this database if you have specified UNDO_ MANAGEMENT=AUTO in the initialization parameter file. See "Using Automatic Undo Management: Creating an Undo Tablespace" on page 2-24. Because the ARCHIVELOG clause is not specified in this CREATE DATABASE statement, redo log files will not initially be archived. This is customary during database creation and an ALTER DATABASE statement can be used later to switch to ARCHIVELOG mode. The initialization parameters in the initialization parameter file for mynewdb relating to archiving are LOG_ARCHIVE_DEST_1, LOG_ARCHIVE_FORMAT, and LOG_ARCHIVE_START. See Chapter 8, "Managing Archived Redo Logs". See Also: ■ ■ "Understanding the CREATE DATABASE Statement" on page 2-22 Oracle9i SQL Reference for more information about specifying the clauses and parameter values for the CREATE DATABASE statement Step 7: Create Additional Tablespaces To make the database functional, you need to create additional files and tablespaces for users. The following sample script creates some additional tablespaces: CONNECT SYS/password AS SYSDBA -- create a user tablespace to be assigned as the default tablespace for users CREATE TABLESPACE users LOGGING DATAFILE '/vobs/oracle/oradata/mynewdb/users01.dbf' SIZE 25M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL; -- create a tablespace for indexes, separate from user tablespace CREATE TABLESPACE indx LOGGING DATAFILE '/vobs/oracle/oradata/mynewdb/indx01.dbf' SIZE 25M REUSE AUTOEXTEND ON NEXT 1280K MAXSIZE UNLIMITED EXTENT MANAGEMENT LOCAL; EXIT 2-20 Oracle9i Database Administrator’s Guide Manually Creating an Oracle Database For information about creating tablespaces, see Chapter 11, "Managing Tablespaces". Step 8: Run Scripts to Build Data Dictionary Views Run the scripts necessary to build views, synonyms, and PL/SQL packages: CONNECT SYS/password AS SYSDBA @/vobs/oracle/rdbms/admin/catalog.sql @/vobs/oracle/rdbms/admin/catproc.sql EXIT The following table contains descriptions of the scripts: Script Description CATALOG.SQL Creates the views of the data dictionary tables, the dynamic performance views, and public synonyms for many of the views. Grants PUBLIC access to the synonyms. CATPROC.SQL Runs all scripts required for or used with PL/SQL. You may want to run other scripts. The scripts that you run are determined by the features and options you choose to use or install. Many of the scripts available to you are described in the Oracle9i Database Reference. See your Oracle installation guide for your operating system for the location of these scripts. Step 9: Run Scripts to Install Additional Options (Optional) If you plan to install other Oracle products to work with this database, see the installation instructions for those products. Some products require you to create additional data dictionary tables. Usually, command files are provided to create and load these tables into the database’s data dictionary. See your Oracle documentation for the specific products that you plan to install for installation and administration instructions. Step 10: Create a Server Parameter File (Recommended) Oracle recommends you create a server parameter file as a dynamic means of maintaining initialization parameters. The server parameter file is discussed in "Managing Initialization Parameters Using a Server Parameter File" on page 2-44. Creating an Oracle Database 2-21 Understanding the CREATE DATABASE Statement The following script creates a server parameter file from the text initialization parameter file and writes it to the default location. The instance is shut down, then restarted using the server parameter file (in the default location). CONNECT SYS/password AS SYSDBA -- create the server parameter file CREATE SPFILE='/vobs/oracle/dbs/spfilemynewdb.ora' FROM PFILE='/vobs/oracle/admin/mynewdb/scripts/init.ora'; SHUTDOWN -- this time you will start up using the server parameter file CONNECT SYS/password AS SYSDBA STARTUP EXIT Step 11: Back Up the Database. You should make a full backup of the database to ensure that you have a complete set of files from which to recover if a media failure occurs. For information on backing up a database, see Oracle9i Backup and Recovery Concepts. Understanding the CREATE DATABASE Statement When you execute a CREATE DATABASE statement, Oracle performs (at least) the following operations. The actual operations performed are in large part determined by the clauses that you specify in the CREATE DATABASE statement or initialization parameters that you have set. ■ Creates the datafiles for the database ■ Creates the control files for the database ■ Creates the redo log files for the database and establishes the ARCHIVELOG mode. ■ Creates the SYSTEM tablespace and the SYSTEM rollback segment ■ Creates the data dictionary ■ Sets the character set that stores data in the database ■ Sets the database time zone ■ Mounts and opens the database for use This section discusses several of the clauses of the CREATE DATABASE statement. It expands upon some of the clauses discussed in "Step 6: Issue the CREATE DATABASE Statement" on page 2-18 and introduces additional ones. 2-22 Oracle9i Database Administrator’s Guide Understanding the CREATE DATABASE Statement The following topics are contained in this section: ■ Protecting Your Database: Specifying Passwords for Users SYS and SYSTEM ■ Clauses that Simplify Database Creation and Management ■ Creating a Locally Managed SYSTEM Tablespace ■ Specifying the Database Time Zone and Time Zone File ■ Specifying FORCE LOGGING Mode Protecting Your Database: Specifying Passwords for Users SYS and SYSTEM The clauses of the CREATE DATABASE statement used for specifying the passwords for users SYS and SYSTEM are: ■ USER SYS IDENTIFIED BY password ■ USER SYSTEM IDENTIFIED BY password If not specified, these users are assigned the default passwords change_on_ install and manager, respectively. A record is written to the alert file indicating that the default passwords were used. To protect your database, you should change these passwords using the ALTER USER statement after database creation. While these clauses are optional in this Oracle release, Oracle strongly recommends that you specify them. The default passwords are commonly known, and if you neglect to change them later, you leave yourself vulnerable to attack by malicious users. See Also: "Some Security Considerations" on page 2-32 Clauses that Simplify Database Creation and Management In addition to using the Database Configuration Assistant for creating your database, Oracle9i offers you other options that can simplify the creation, operation, and management of your database. These options, and their associated CREATE DATABASE clauses, are discussed briefly in the following sections, and in more detail in later sections of this book: ■ Using Automatic Undo Management: Creating an Undo Tablespace ■ Creating a Default Temporary Tablespace ■ Using Oracle-Managed Files Creating an Oracle Database 2-23 Understanding the CREATE DATABASE Statement Using Automatic Undo Management: Creating an Undo Tablespace Oracle recommends that instead of using rollback segments in your database, you use an undo tablespace. This requires the use of a different set of initialization parameters, and optionally, the inclusion of the UNDO TABLESPACE clause in your CREATE DATABASE statement. You must include the following initialization parameter if you want to operate your database in automatic undo management mode: UNDO_MANAGEMENT=AUTO In this mode, rollback information, referred to as undo, is stored in an undo tablespace rather than rollback segments and is managed by Oracle. If you want to create and name a specific tablespace for the undo tablespace, you can include the UNDO TABLESPACE clause at database creation time. If you omit this clause, and automatic undo management is specified, Oracle creates a default undo tablespace named SYS_UNDOTBS. See Also: ■ ■ "Specifying the Method of Undo Space Management" on page 2-42 Chapter 13, "Managing Undo Space" for information about the creation and use of undo tablespaces Creating a Default Temporary Tablespace The DEFAULT TEMPORARY TABLESPACE clause of the CREATE DATABASE statement specifies that a temporary tablespace is to be created at database creation time. This tablespace is used as the default temporary tablespace for users who are not otherwise assigned a temporary tablespace. Users can be explicitly assigned a default temporary tablespace in the CREATE USER statement. But, if no temporary tablespace is specified, they default to using the SYSTEM tablespace. It is not good practice to store temporary data in the SYSTEM tablespace. To avoid this problem, and to avoid the need to assign every user a default temporary tablespace at CREATE USER time, you can use the DEFAULT TEMPORARY TABLESPACE clause of CREATE DATABASE. If you decide later to change the default temporary tablespace, or to create an initial one after database creation, you can do so. You do this by creating a new temporary tablespace (CREATE TEMPORARY TABLESPACE), then assign it as the temporary tablespace using the ALTER DATABASE DEFAULT TEMPORARY TABLESPACE 2-24 Oracle9i Database Administrator’s Guide Understanding the CREATE DATABASE Statement statement. Users will automatically be switched (or assigned) to the new temporary default tablespace. The following statement assigns a new default temporary tablespace: ALTER DATABASE DEFAULT TEMPORARY TABLESPACE tempts2; The new default temporary tablespace must be an existing temporary tablespace. When using a locally managed SYSTEM tablespace, the new default temporary tablespace must also be locally managed. You cannot drop a default temporary tablespace, but you can assign a new default temporary tablespace, then drop the former one. You are not allowed to change a default temporary tablespace to a permanent tablespace, nor can you take a default temporary tablespace offline. Users can obtain the name of the current default temporary tablespace using the DATABASE_PROPERTIES view. The PROPERTY_NAME column contains the value "DEFAULT_TEMP_TABLESPACE" and the PROPERTY_VALUE column contains the default temporary tablespace name. See Also: ■ ■ Oracle9i SQL Reference for the syntax of the DEFAULT TEMPORARY TABLESPACE clause of CREATE DATABASE and ALTER DATABASE "Temporary Tablespaces" on page 11-12 for information about creating and using temporary tablespaces Using Oracle-Managed Files You can minimize the number of clauses and parameters that you specify in your CREATE DATABASE statement by using the Oracle Managed Files feature. If you include the DB_CREATE_FILE_DEST or DB_CREATE_ONLINE_LOG_DEST_n initialization parameters in your initialization parameter file, you enable Oracle to create and manage the underlying operating system files of your database. Oracle will automatically create and manage the operating system files for the following database structures, dependent upon the initialization parameters you specify and how you specify clauses in your CREATE DATABASE statement: ■ Tablespaces ■ Temporary tablespaces ■ Control files Creating an Oracle Database 2-25 Understanding the CREATE DATABASE Statement ■ Online redo log files Briefly, this is how the Oracle Managed Files feature works, using the following CREATE DATABASE statement as an example: CREATE DATABASE rbdb1 USER SYS IDENTIFIED BY pz6r58 USER SYSTEM IDENTIFIED BY y1tz5p UNDO TABLESPACE undotbs DEFAULT TEMPORARY TABLESPACE tempts1; ■ ■ ■ ■ ■ ■ No DATAFILE clause is specified, therefore Oracle creates an Oracle-managed datafile for the SYSTEM tablespace. No LOGFILE clauses are included, therefore Oracle creates two online redo log file groups that are Oracle managed. No DATAFILE subclause is specified for the UNDO TABLESPACE clause, therefore Oracle creates an Oracle-managed datafile for the undo tablespace. No TEMPFILE subclause is specified for the DEFAULT TEMPORARY TABLESPACE clause, therefore Oracle creates an Oracle-managed tempfile. Additionally, if no CONTROL_FILES initialization parameter is specified in the initialization parameter file, Oracle creates an Oracle-managed control file. If using a server parameter file (see "Managing Initialization Parameters Using a Server Parameter File" on page 2-44) the initialization parameters are set accordingly and automatically. See Also: Chapter 3, "Using Oracle-Managed Files" for a complete description of the Oracle Managed Files feature and how to use it Creating a Locally Managed SYSTEM Tablespace When you specify the EXTENT MANAGEMENT LOCAL clause in the CREATE DATABASE statement, you cause Oracle to create a locally managed SYSTEM tablespace wherein Oracle determines extent sizes. The COMPATIBLE initialization parameter must be set to 9.2 or higher for this statement to be successful. If you do not specify the EXTENT MANAGEMENT LOCAL clause, the default is to create a dictionary-managed SYSTEM tablespace. Locally managed tablespaces provide better performance and greater ease of management over dictionary-managed tablespaces. A locally managed SYSTEM tablespace is created AUTOALLOCATE by default, meaning that it is system managed with extent sizes determined and controlled by Oracle. You may notice an increase 2-26 Oracle9i Database Administrator’s Guide Understanding the CREATE DATABASE Statement in the initial size of objects created in a locally managed SYSTEM tablespace because of the autoallocate policy. It is not possible to create a locally managed SYSTEM tablespace and specify UNIFORM extent size. When you create your database with a locally managed SYSTEM tablespace, ensure the following conditions are met: ■ ■ There must be a default temporary tablespace, and that tablespace cannot be the SYSTEM tablespace. You must not create rollback segments in dictionary-managed tablespaces. Attempting to create a rollback segment in a dictionary-managed tablespace will fail if the SYSTEM tablespace is locally managed. To meet the first condition, you can specify the DEFAULT TEMPORARY TABLESPACE clause in the CREATE DATABASE statement, or you cannot include the clause and allow Oracle to create the tablespace for you using a default name and in a default location. For fulfilling the second condition, Oracle recommends that instead of using rollback segments to manage the database’s undo records, that you use automatic undo management. You can include the UNDO TABLESPACE clause in the CREATE DATABASE statement to create a specific undo tablespace, or if you do not include the clause, Oracle creates a locally managed undo tablespace for you using the default name and in a default location. Note: When your SYSTEM tablespace is locally managed, there are restrictions on other tablespaces in the database. These restrictions are: ■ ■ ■ ■ You cannot create any dictionary-managed tablespaces in the database. You cannot migrate a locally managed tablespace to a dictionary-managed tablespace. You can transport dictionary-managed tablespaces into the database, but you are not allowed to alter them to read-write. Preexisting dictionary-managed tablespaces are allowed to remain in the database, but only in READ ONLY mode. They cannot be altered to READ WRITE. Creating an Oracle Database 2-27 Understanding the CREATE DATABASE Statement Oracle also allows you to migrate an existing dictionary-managed SYSTEM tablespace to a locally managed tablespace. using the DBMS_SPACE_ADMIN package. However, there is no procedure for backward migration. See Also: ■ ■ ■ Oracle9i SQL Reference for more specific information about the use of the DEFAULT TEMPORARY TABLESPACE and UNDO TABLESPACE clauses when EXTENT MANAGEMENT LOCAL is specified for the SYSTEM tablespace "Locally Managed Tablespaces" on page 11-5 "Migrating the SYSTEM Tablespace to a Locally Managed Tablespace" on page 11-34 Specifying the Database Time Zone and Time Zone File Oracle allows you to specify the database’s default time zone, and provides you with the option of choosing the size of the supporting time zone file. Specifying the Database Time Zone You set the database’s default time zone by specifying the SET TIME_ZONE clause of the CREATE DATABASE statement. If omitted, the default database time zone is the operating system time zone. The database time zone can be changed for a session with an ALTER SESSION statement. See Also: Oracle9i Database Globalization Support Guide for more information about setting the database time zone Specifying the Database Time Zone File Oracle9i enables you to specify the default time zone for your database using the SET TIME_ZONE clause of the CREATE DATABASE statement. This section provides information on the time zone files used to support this feature, specifically on Solaris platforms. Names of directories, filenames, and environment variables may differ for each platform but will probably be the same for all UNIX platforms. The time zone files contain the valid time zone names. The following information is included for each zone (note that abbreviations are only used in conjunction with the zone names): 2-28 ■ Offset from UTC ■ Transition times for daylight savings Oracle9i Database Administrator’s Guide Understanding the CREATE DATABASE Statement ■ Abbreviation for standard time ■ Abbreviation for daylight savings time There are 2 time zone files under the Oracle installation directory: ■ $ORACLE_HOME/oracore/zoneinfo/timezone.dat This is the default. It contains the most commonly used time zones and is smaller, thus enabling better database performance. ■ $ORACLE_HOME/oracore/zoneinfo/timezlrg.dat This file contains the larger set of defined time zones and should be used by users who require zones that are not defined in the default timezone.dat file. Note that this larger set of zone information may affect performance. To enable the use of the larger time zone datafile, do the following: 1. Shut down the database. 2. Set the environment variable ORA_TZFILE to the full path name of the location for the timezlrg.dat file. 3. Restart the database. Once the larger timezlrg.dat is used, it must continue to be used unless you are sure that none of the nondefault zones are used for data that is stored in the database. Also, all databases that share information must use the same time zone datafile. To view the time zone names, use the following query: SELECT * FROM V$TIMEZONE_NAMES; Specifying FORCE LOGGING Mode Through the use of the NOLOGGING clause allowed in some DDL statements (for example, CREATE TABLE), certain database operations will not generate redo records to the database redo log. Specifying NOLOGGING can speed up operations that can be easily recovered outside of the database recovery mechanisms, but it causes problems for media recovery and for a standby database. Oracle provides a means of forcing the writing of redo records for changes against the database, even where NOLOGGING has been specified in DDL statements. Oracle never generates redo records for temporary tablespaces and temporary segments, so forced logging has no affect for these. Creating an Oracle Database 2-29 Understanding the CREATE DATABASE Statement See Also: ■ ■ Oracle9i Database Concepts for additional information about NOLOGGING mode Oracle9i SQL Reference for information about operations that can be done in NOLOGGING mode Using the FORCE LOGGING Clause To put the database into FORCE LOGGING mode, use the FORCE LOGGING clause in the CREATE DATABASE statement. If you do not specify this clause, the database is not placed into FORCE LOGGING mode. Use the ALTER DATABASE statement to place the database into FORCE LOGGING mode after database creation. This statement can potentially wait a considerable time for completion because it waits for all unlogged direct writes to complete. You can cancel FORCE LOGGING mode using the following SQL statement: ALTER DATABASE NO FORCE LOGGING Independent of specifying FORCE LOGGING for the database, you can selectively specify FORCE LOGGING or NO FORCE LOGGING at the tablespace level. However, if FORCE LOGGING mode is in effect for the database, it takes precedence over the tablespace mode setting. If it is not in effect for the database, then the individual tablespace settings are enforced. Oracle recommends that either the entire database is placed into FORCE LOGGING mode, or individual tablespaces be placed into FORCE LOGGING mode, but not both. The FORCE LOGGING mode is a persistent attribute of the database. That is, if the database is shut down and restarted, it remains in the same logging mode state. However, if you re-create the control file, the database not restarted in the FORCE LOGGING mode unless you specify the FORCE LOGGING clause in the CREATE CONTROL FILE statement. See Also: "Controlling the Writing of Redo Records" on page 11-20 for information about using the FORCE LOGGING clause for tablespace creation. Performance Considerations of FORCE LOGGING Mode There is a performance degradation for FORCE LOGGING mode. If there is no standby database active, but the primary reason for specifying FORCE LOGGING is to ensure complete media recovery, then consider the following: 2-30 Oracle9i Database Administrator’s Guide Considerations After Creating a Database ■ How many media failures are likely to happen? ■ How serious is the damage if unlogged direct writes cannot be recovered? ■ Is the performance degradation caused by forced logging tolerable? If the database is running in NOARCHIVELOG mode, then generally there is no benefit to placing the database in FORCE LOGGING mode. This is because media recovery is not possible in this mode, thus there is performance degradation with little benefit. Troubleshooting Database Creation If for any reason database creation fails, shut down the instance and delete any files created by the CREATE DATABASE statement before you attempt to create it once again. After correcting the error that caused the failure of the database creation, try running the script again. Dropping a Database To drop a database, you must remove its datafiles, redo log files, and all other associated files (control files, initialization parameter files, archived log files). To view the names of the database’s datafiles, redo log files, and control files, query the data dictionary views V$DATAFILE, V$LOGFILE, and V$CONTROLFILE, respectively. If the database is in archive log mode, locate the archive log destinations by inspecting the initialization parameters LOG_ARCHIVE_DEST_n, or LOG_ ARCHIVE_DEST and LOG_ARCHIVE_DUPLEX_DEST. If you used the Database Configuration Assistant to create your database, you can use that tool to delete your database and clean up the files. See Also: Oracle9i Database Reference for more information about these views and initialization parameters Considerations After Creating a Database After you create a database, the instance is left running, and the database is open and available for normal database use. You may want to perform other actions, some of which are discussed in this section. Creating an Oracle Database 2-31 Considerations After Creating a Database Some Security Considerations A newly created database has least three users that are useful for administering your database: SYS, SYSTEM and OUTLN (owner of schema where stored outlines are stored). Caution: To prevent unauthorized access and protect the integrity of your database, the default passwords for SYS and SYSTEM should be changed immediately after the database is created. Depending on the features and options installed, other users can also be present. Some of these users are: ■ MDSYS (interMedia Spatial) ■ ORDSYS (interMedia Audio) ■ ORDPLUGINS (interMedia Audio) ■ CTXSYS (Oracle Text) ■ DBSNMP (Enterprise Manager Intelligent Agent) To change the password for user DBSNMP refer to Oracle Intelligent Agent User's Guide. Note Regarding Security Enhancements: In this release of Oracle and in subsequent releases, several enhancements are being made to ensure the security of default database user accounts. ■ ■ 2-32 During initial installation with the Database Configuration Assistant (DCBA), all default database user accounts except SYS, SYSTEM, SCOTT, DBSNMP, OUTLN, AURORA$JIS$UTILITY$, AURORA$ORB$UNAUTHENTICATED and OSE$HTTP$ADMIN are locked and expired. To activate a locked account, the DBA must manually unlock it and reassign it a new password. In addition, the DBCA prompts for passwords for users SYS and SYSTEM during initial installation of the database rather than assigning default passwords to them. A CREATE DATABASE statement issued manually also lets you supply passwords for these two users. Oracle9i Database Administrator’s Guide Considerations After Creating a Database See Also: ■ ■ ■ ■ "A Security Checklist" on page 23-20 for guidance on configuring your Oracle database in a secure manner "Database Administrator Usernames" on page 1-11 for more information about the users SYS and SYSTEM "Altering Users" on page 24-6 to learn how to add new users and change passwords Oracle9i SQL Reference for the syntax of the ALTER USER statement used for unlocking user accounts Installing Oracle’s Sample Schemas The Oracle database server distribution media can include various SQL files that let you experiment with the system, learn SQL, or create additional tables, views, or synonyms. Starting with Oracle9i, Oracle provides sample schemas that enable you to become familiar with Oracle functionality. Some Oracle documents and books use these sample schemas for presenting examples. There is an ongoing effort for most Oracle books to convert to the use of Sample Schemas based examples. The following table briefly describes the sample schemas: Schema Description Human Resources The Human Resources (HR) schema is a basic relational database schema. There are six tables in the HR schema: Employees, Departments, Locations, Countries, Jobs, and Job_ History. The Order Entry (OE) schema has links into HR schema Order Entry The Order Entry (OE) schema builds on the purely relational Human Relations (HR) schema with some object-relational and object-oriented features. The OE schema contains seven tables: Customers, Product_Descriptions, Product_Information, Order_ Items, Orders, Inventories, and Warehouses. The OE schema has links into the HR schema and PM schema. This schema also has synonyms defined on HR objects to make access transparent to users. Creating an Oracle Database 2-33 Initialization Parameters and Database Creation Schema Description Product Media Product Media (PM) schema includes two tables, online_media and print_media, one object type, adheader_typ, and one nested table, textdoc_typ. The PM schema includes interMedia and LOB column types. Note: To use Oracle Text you must create an Oracle Text index. Sales History The Sales History (SH) schema is an example of a relational star schema. It consists of one big range partitioned fact table sales and five dimension tables: times, promotions, channels, products and customers. The additional countries table linked to customers shows a simple snowflake. Queued Shipping The Queued Shipping (QS) schema is actually multiple schemas that contain message queues. Sample Schemas can be installed automatically for you by the Database Configuration Assistant or you can install it manually. The schemas and installation instructions are described in detail in Oracle9i Sample Schemas. Initialization Parameters and Database Creation Oracle has attempted to provide appropriate values in the starter initialization parameter file provided with your database software, or as created for you by the Database Configuration Assistant. You can edit these Oracle-supplied initialization parameters and add others, depending upon your configuration and options and how you plan to tune the database. For any relevant initialization parameters not specifically included in the initialization parameter file, Oracle supplies defaults. If you are creating an Oracle database for the first time, it is suggested that you minimize the number of parameter values that you alter. As you become more familiar with your database and environment, you can dynamically tune many initialization parameters using the ALTER SYSTEM statement. If you are using a traditional text initialization parameter file, your changes are only for the current instance. To make them permanent, you must update them manually in the initialization parameter file, otherwise they will be lost over the next shutdown and startup of the database. If you are using a server parameter file, initialization parameter file changes made by the ALTER SYSTEM statement can persist across shutdown and startup. This is discussed in "Managing Initialization Parameters Using a Server Parameter File" on page 2-44. 2-34 Oracle9i Database Administrator’s Guide Initialization Parameters and Database Creation This section introduced you to some of the initialization parameters you may choose to add or edit before you create your new database. The following topics are contained in this section: ■ Determining the Global Database Name ■ Specifying Control Files ■ Specifying Database Block Sizes ■ Setting Initialization Parameters that Affect the Size of the SGA ■ Specifying the Maximum Number of Processes ■ Specifying the Method of Undo Space Management ■ Setting License Parameters See Also: Oracle9i Database Reference for descriptions of all initialization parameters including their default settings Determining the Global Database Name A database’s global database name consists of the local database name that you assign and its location within a network structure. The DB_NAME initialization parameter determines the local name component of the database’s name, while the DB_DOMAIN parameter indicates the domain (logical location) within a network structure. The combination of the settings for these two parameters must form a database name that is unique within a network. For example, to create a database with a global database name of test.us.acme.com, edit the parameters of the new parameter file as follows: DB_NAME = test DB_DOMAIN = us.acme.com You can rename the GLOBAL_NAME of your database using the ALTER DATABASE RENAME GLOBAL_NAME statement. However, you must also shut down and restart the database after first changing the DB_NAME and DB_DOMAIN initialization parameters and re-creating the control file. See Also: Oracle9i Database Utilities for information about using the DBNEWID utility, which is another means of changing a database name Creating an Oracle Database 2-35 Initialization Parameters and Database Creation DB_NAME Initialization Parameter DB_NAME must be set to a text string of no more than eight characters. During database creation, the name provided for DB_NAME is recorded in the datafiles, redo log files, and control file of the database. If during database instance startup the value of the DB_NAME parameter (in the parameter file) and the database name in the control file are not the same, the database does not start. DB_DOMAIN Initialization Parameter DB_DOMAIN is a text string that specifies the network domain where the database is created. This is typically the name of the organization that owns the database. If the database you are about to create will ever be part of a distributed database system, pay special attention to this initialization parameter before database creation. See Also: Part VI, "Distributed Database Management" for more information about distributed databases Specifying Control Files Include the CONTROL_FILES initialization parameter in your new parameter file and set its value to a list of control filenames to use for the new database. When you execute the CREATE DATABASE statement, the control files listed in the CONTROL_ FILES parameter are created. If no filenames are listed for the CONTROL_FILES parameter, Oracle uses a default operating system dependent filename. If you want Oracle to create new operating system files when creating your database’s control files, the filenames listed in the CONTROL_FILES parameter must not match any filenames that currently exist on your system. If you want Oracle to reuse or overwrite existing files when creating your database’s control files, ensure that the filenames listed in the CONTROL_FILES parameter match the filenames that are to be reused. Caution: Use extreme caution when setting this option. If you inadvertently specify a file that you did not intend and execute the CREATE DATABASE statement, the previous contents of that file will be overwritten. Oracle Corporation strongly recommends you use at least two control files stored on separate physical disk drives for each database. See Also: Chapter 6, "Managing Control Files" 2-36 Oracle9i Database Administrator’s Guide Initialization Parameters and Database Creation Specifying Database Block Sizes The DB_BLOCK_SIZE initialization parameter specifies the standard block size for the database. This block size is used for the SYSTEM tablespace and by default in other tablespaces. Oracle can support up to four additional non-standard block sizes. DB_BLOCK_SIZE Initialization Parameter The most commonly used block size should be picked as the standard block size. In many cases, this is the only block size that you need to specify. Typically, DB_ BLOCK_SIZE is set to either 4K or 8K. If not specified, the default data block size is operating system specific, and is generally adequate. The block size cannot be changed after database creation, except by re-creating the database. If a database’s block size is different from the operating system block size, make the database block size a multiple of the operating system’s block size. For example, if your operating system’s block size is 2K (2048 bytes), the following setting for the DB_BLOCK_SIZE initialization parameter is valid: DB_BLOCK_SIZE=4096 You may want to specify a block size larger than your operating system block size. A larger data block size provides greater efficiency in disk and memory I/O (access and storage of data). Such cases include the following scenarios: ■ ■ Oracle is on a large computer system with a large amount of memory and fast disk drives. For example, databases controlled by mainframe computers with vast hardware resources typically use a data block size of 4K or greater. The operating system that runs Oracle uses a small operating system block size. For example, if the operating system block size is 1K and the default data block size matches this, Oracle may be performing an excessive amount of disk I/O during normal operation. For best performance in this case, a database block should consist of multiple operating system blocks. See Also: Your operating system specific Oracle documentation for details about the default block size. Non-Standard Block Sizes Tablespaces of non-standard block sizes can be created using the CREATE TABLESPACE statement and specifying the BLOCKSIZE clause. These non-standard block sizes can have any power-of-two value between 2K and 32K: specifically, 2K, Creating an Oracle Database 2-37 Initialization Parameters and Database Creation 4K, 8K, 16K or 32K. Platform-specific restrictions regarding the maximum block size apply, so some of these sizes may not be allowed on some platforms. To use non-standard block sizes, you must configure sub-caches within the buffer cache area of the SGA memory for all of the non-standard block sizes that you intend to use. The initialization parameters used for configuring these sub-caches are described in the next section, "Setting Initialization Parameters that Affect the Size of the SGA". The ability to specify multiple block sizes for your database is especially useful if you are transporting tablespaces between databases. You can, for example, transport a tablespace that uses a 4K block size from an OLTP environment to a datawarehouse environment that uses a standard block size of 8K. See Also: ■ "Creating Tablespaces" on page 11-3 ■ "Transporting Tablespaces Between Databases" on page 11-34 Setting Initialization Parameters that Affect the Size of the SGA The initialization parameters discussed in this section affect the amount of memory that is allocated to the System Global Area. Except for the SGA_MAX_SIZE initialization parameter, they are dynamic parameters which values can be changed by the ALTER SYSTEM statement. The size of the SGA is dynamic, and can grow or shrink by dynamically altering these parameters. 2-38 Oracle9i Database Administrator’s Guide Initialization Parameters and Database Creation Note: The memory for dynamic components in the SGA is allocated in the unit of granules. Granule size is determined by total SGA size. Generally speaking, on most platforms, if the total SGA size is equal to or less than 128 MB, then granule size is 4 MB. Otherwise, granule size is 16 MB. However, there may be some platform dependency. For example, on 32-bit Windows NT, the granule size is 8 MB for SGAs larger than 128 MB. Consult your operating system specific documentation for more details. You can query the V$SGA_DYNAMIC_COMPONENTS view to see the granule size that is being used by an instance. The same granule size is used for all dynamic components in the SGA. If you specify a size for a component that is not a multiple of granule size, Oracle will round the specified size up to the nearest multiple. For example, if the granule size is 4 MB and you specify DB_CACHE_SIZE as 10 MB, you will actually be allocated 12 MB. You can see a summary of information about the dynamic components of the SGA in the V$SGA_DYNAMIC_COMPONENTS view. Information about on-going SGA resize operations can be found in the V$SGA_CURRENT_RESIZE_OPS view, and information about the last 100 completed SGA resize operations can be found in the V$SGA_RESIZE_OPS view. To find the amount of SGA memory available for future dynamic SGA resize operations, query the V$SGA_DYNAMIC_FREE_MEMORY view. See Also: ■ ■ ■ Oracle9i Database Performance Tuning Guide and Reference for information about the monitoring and tuning of SGA components Oracle9i Database Reference for descriptions of the dynamic performance views used for monitoring the size of the SGA Oracle9i Database Concepts for a conceptual discussion of the SGA Creating an Oracle Database 2-39 Initialization Parameters and Database Creation Limiting the Size of the SGA The SGA_MAX_SIZE initialization parameter specifies the maximum size of the System Global Area for the lifetime of the instance. You can dynamically alter the initialization parameters affecting the size of the buffer caches, shared pool, and large pool, but only to the extent that the sum of these sizes and the sizes of the other components of the SGA (fixed SGA, variable SGA, and redo log buffers) does not exceed the value specified by SGA_MAX_SIZE. If you do not specify SGA_MAX_SIZE, then Oracle selects a default value that is the sum of all components specified or defaulted at initialization time. Setting the Buffer Cache Initialization Parameters The buffer cache initialization parameters determine the size of the buffer cache component of the SGA. You use them to specify the sizes of caches for the various block sizes used by the database. These initialization parameters are all dynamic. If you intend to use multiple block sizes in your database, you must have the DB_ CACHE_SIZE and at least one DB_nK_CACHE_SIZE parameter set. Oracle assigns an appropriate default value to the DB_CACHE_SIZE parameter, but the DB_nK_ CACHE_SIZE parameters default to 0, and no additional block size caches are configured. The size of a buffer cache affects performance. Larger cache sizes generally reduce the number of disk reads and writes. However, a large cache may take up too much memory and induce memory paging or swapping. DB_CACHE_SIZE Initialization Parameter The DB_CACHE_SIZE initialization parameter replaces the DB_BLOCK_BUFFERS initialization parameter that was used in previous releases. The DB_CACHE_SIZE parameter specifies the size of the cache of standard block size buffers, where the standard block size is specified by DB_ BLOCK_SIZE. For backward compatibility the DB_BLOCK_BUFFERS parameter will still work, but it remains a static parameter and cannot be combined with any of the dynamic sizing parameters. DB_nK_CACHE_SIZE Initialization Parameters The sizes and numbers of non-standard block size buffers are specified by the following initialization parameters: 2-40 ■ DB_2K_CACHE_SIZE ■ DB_4K_CACHE_SIZE ■ DB_8K_CACHE_SIZE Oracle9i Database Administrator’s Guide Initialization Parameters and Database Creation ■ DB_16K_CACHE_SIZE ■ DB_32K_CACHE_SIZE. Each parameter specifies the size of the buffer cache for the corresponding block size. For example: DB_BLOCK_SIZE=4096 DB_CACHE_SIZE=12M DB_2K_CACHE_SIZE=8M DB_8K_CACHE_SIZE=4M In the above example, the parameters specify that the standard block size of the database will be 4K. The size of the cache of standard block size buffers will be 12M. Additionally, 2K and 8K caches will be configured with sizes of 8M and 4M respectively. Note: These parameters cannot be used to size the cache for the standard block size. For example, if the value of DB_BLOCK_SIZE is 2K, it is illegal to set DB_2K_CACHE_SIZE. The size of the cache for the standard block size is always determined from the value of DB_CACHE_SIZE. Adjusting the Size of the Shared Pool The SHARED_POOL_SIZE initialization parameter is a dynamic parameter that allows you to specify or adjust the size of the shared pool component of the SGA. Oracle selects an appropriate default value. Adjusting the Size of the Large Pool The LARGE_POOL_SIZE initialization parameter is a dynamic parameter that allows you to specify or adjust the size of the large pool component of the SGA. Oracle selects an appropriate default value. Specifying the Maximum Number of Processes The PROCESSES initialization parameter determines the maximum number of operating system processes that can be connected to Oracle concurrently. The value of this parameter must be 6 or greater (5 for the background processes plus 1 for each user process). For example, if you plan to have 50 concurrent users, set this parameter to at least 55. Creating an Oracle Database 2-41 Initialization Parameters and Database Creation Specifying the Method of Undo Space Management Every Oracle database must have a method of maintaining information that is used to roll back, or undo, changes to the database. Such information consists of records of the actions of transactions, primarily before they are committed. Oracle refers to these records collectively as undo. Oracle allows you to store undo in an undo tablespace or in rollback segments. See Also: Chapter 13, "Managing Undo Space" UNDO_MANAGEMENT Initialization Parameter The UNDO_MANAGEMENT initialization parameter determines whether an instance will start up in automatic undo management mode, where undo is stored in an undo tablespace, or manual undo management mode, where undo is stored in rollback segments. A value of AUTO enables automatic undo management mode, MANUAL enables manual undo management mode. For backward compatibility, the default is MANUAL. UNDO_TABLESPACE Initialization Parameter When the instance starts up in automatic undo management mode, it selects the first available undo tablespace in the instance for storing undo. A default undo tablespace named SYS_UNDOTBS is automatically created when you execute a CREATE DATABASE statement and the UNDO_MANAGEMENT initialization parameter is set to AUTO. This is the undo tablespace that Oracle normally selects whenever you start up the database. Optionally, you can specify the UNDO_TABLESPACE initialization parameter. This causes the instance to use the undo tablespace specified by the parameter. The UNDO_TABLESPACE parameter can be used to assign a specific undo tablespace to an instance in an Oracle Real Application Clusters environment. If there is no undo tablespace available, the instance will start, but uses the SYSTEM rollback segment. This is not recommended in normal circumstances, and an alert message is written to the alert file to warn that the system is running without an undo tablespace. Oracle recommends using an undo tablespace rather than rollback segments. An undo tablespace is easier to administer and enables you to explicitly set an undo retention time. 2-42 Oracle9i Database Administrator’s Guide Initialization Parameters and Database Creation ROLLBACK_SEGMENTS Initialization Parameter The ROLLBACK_SEGMENTS parameter is a list of the non-system rollback segments an Oracle instance acquires at database startup if the database is to operate in manual undo management mode. List your rollback segments as the value of this parameter. If no rollback segments are specified, the system rollback segment is used. The ROLLBACK_SEGMENTS initialization parameter is supported for backward compatibility. Oracle recommends using an undo tablespace rather than rollback segments. Setting License Parameters Note: Oracle no longer offers licensing by the number of concurrent sessions. Therefore the LICENSE_MAX_SESSIONS and LICENSE_SESSIONS_WARNING initialization parameters have been deprecated and are no longer discussed in this book. If you use named user licensing, Oracle can help you enforce this form of licensing. You can set a limit on the number of users created in the database. Once this limit is reached, you cannot create more users. Note: This mechanism assumes that each person accessing the database has a unique user name and that no people share a user name. Therefore, so that named user licensing can help you ensure compliance with your Oracle license agreement, do not allow multiple users to log in using the same user name. To limit the number of users created in a database, set the LICENSE_MAX_USERS initialization parameter in the database’s initialization parameter file, as shown in the following example: LICENSE_MAX_USERS = 200 Creating an Oracle Database 2-43 Managing Initialization Parameters Using a Server Parameter File Managing Initialization Parameters Using a Server Parameter File Oracle has traditionally stored initialization parameters in a text initialization parameter file. Starting with Oracle9i, you can choose to maintain initialization parameters in a binary server parameter file. This section introduces the server parameter file, and explains how to manage initialization parameters using either method of storing the parameters. The following topics are contained in this section. ■ What is a Server Parameter File? ■ Migrating to a Server Parameter File ■ Creating a Server Parameter File ■ The SPFILE Initialization Parameter ■ Using ALTER SYSTEM to Change Initialization Parameter Values ■ Exporting the Server Parameter File ■ Backing Up the Server Parameter File ■ Errors and Recovery for the Server Parameter File ■ Viewing Parameter Settings What is a Server Parameter File? A server parameter file (SPFILE) can be thought of as a repository for initialization parameters that is maintained on the machine where the Oracle database server executes. It is, by design, a server-side initialization parameter file. Initialization parameters stored in a server parameter file are persistent, in that any changes made to the parameters while an instance is running can persist across instance shutdown and startup. This eliminates the need to manually update initialization parameters to make changes effected by ALTER SYSTEM statements persistent. It also provides a basis for self tuning by the Oracle database server. A server parameter file is initially built from a traditional text initialization parameter file using the CREATE SPFILE statement. It is a binary file that cannot be browsed or edited using a text editor. Oracle provides other interfaces for viewing and modifying parameter settings. 2-44 Oracle9i Database Administrator’s Guide Managing Initialization Parameters Using a Server Parameter File Caution: Although you can open the binary server parameter file with a text editor and view its text, do not manually edit it. Doing so will corrupt the file. You will not be able to start you instance, and if the instance is running, it could fail. At system startup, the default behavior of the STARTUP command is to read a server parameter file to obtain initialization parameter settings. The STARTUP command with no PFILE clause, reads the server parameter file from an operating system specific location. If you choose to use the traditional text initialization parameter file, you must specify the PFILE clause when issuing the STARTUP command. Explicit instructions for starting an instance using a server parameter file are contained in Starting Up a Database on page 4-2. Migrating to a Server Parameter File If you are currently using a traditional initialization parameter file, use the following steps to migrate to a server parameter file. 1. If the initialization parameter file is located on a client machine, transfer the file (for example, FTP) from the client machine to the server machine. Note: If you are using Oracle9i Real Application Clusters, you must combine all of your instance specific initialization parameter files into a single initialization parameter file. Instructions for doing this, and other actions unique to using a server parameter file for Oracle Real Application Cluster instances, are discussed in: ■ Oracle9i Real Application Clusters Setup and Configuration ■ Oracle9i Real Application Clusters Administration 2. Create a server parameter file using the CREATE SPFILE statement. This statement reads the initialization parameter file to create a server parameter file. The database does not have to be started to issue a CREATE SPFILE statement. 3. Start up the instance using the newly created server parameter file. Creating an Oracle Database 2-45 Managing Initialization Parameters Using a Server Parameter File Creating a Server Parameter File The server parameter file must initially be created from a traditional text initialization parameter file. It must be created prior to its use in the STARTUP command. The CREATE SPFILE statement is used to create a server parameter file. You must have the SYSDBA or the SYSOPER system privilege to execute this statement. The following example creates a server parameter file from initialization parameter file /u01/oracle/dbs/init.ora. In this example no SPFILE name is specified, so the file is created in a platform-specific default location and is named spfile$ORACLE_SID.ora. CREATE SPFILE FROM PFILE='/u01/oracle/dbs/init.ora'; Another example, below, illustrates creating a server parameter file and supplying a name. CREATE SPFILE='/u01/oracle/dbs/test_spfile.ora' FROM PFILE='/u01/oracle/dbs/test_init.ora'; The server parameter file is always created on the machine running the database server. If a server parameter file of the same name already exists on the server, it is overwritten with the new information. Oracle recommends that you allow the database server to default the name and location of the server parameter file. This will ease administration of your database. For example, the STARTUP command assumes this default location to read the parameter file. When the server parameter file is created from the initialization parameter file, comments specified on the same lines as a parameter setting in the initialization parameter file are maintained in the server parameter file. All other comments are ignored. The CREATE SPFILE statement can be executed before or after instance startup. However, if the instance has been started using a server parameter file, an error is raised if you attempt to re-create the same server parameter file that is currently being used by the instance. Note: When you use the Database Configuration Assistant to create a database, it can automatically create a server parameter file for you. 2-46 Oracle9i Database Administrator’s Guide Managing Initialization Parameters Using a Server Parameter File The SPFILE Initialization Parameter The SPFILE initialization parameter contains the name of the current server parameter file. When the default server parameter file is used by the server (that is, you issue a STARTUP command and do not specify a PFILE), the value of SPFILE is internally set by the server. The SQL*Plus command SHOW PARAMETERS SPFILE (or any other method of querying the value of a parameter) displays the name of the server parameter file that is currently in use. The SPFILE parameter can also be set in a traditional parameter file to indicate the server parameter file to use. You use the SPFILE parameter to specify a server parameter file located in a nondefault location. Do not use an IFILE initialization parameter within a traditional initialization parameter file to point to a server parameter file; instead, use the SPFILE parameter. See "Starting Up a Database" on page 4-2 for details about: ■ ■ Starting up a database that uses a server parameter file Using the SPFILE parameter to specify the name of a server parameter file to use at instance startup Using ALTER SYSTEM to Change Initialization Parameter Values The ALTER SYSTEM statement allows you to set, change, or delete (restore to default value) initialization parameter values. When the ALTER SYSTEM statement is used to alter a parameter setting in a traditional initialization parameter file, the change affects only the current instance, since there is no mechanism for automatically updating initialization parameters on disk. They must be manually updated in order to be passed to a future instance. Using a server parameter file overcomes this limitation. Setting or Changing Initialization Parameter Values Use the SET clause of the ALTER SYSTEM statement to set or change initialization parameter values. Additionally, the SCOPE clause specifies the scope of a change as described in the following table: Creating an Oracle Database 2-47 Managing Initialization Parameters Using a Server Parameter File SCOPE Clause Description SCOPE = SPFILE The change is applied in the server parameter file only. The effect is as follows: ■ ■ SCOPE = MEMORY For static parameters, the behavior is the same as for dynamic parameters. This is the only SCOPE specification allowed for static parameters. The change is applied in memory only. The effect is as follows: ■ ■ SCOPE = BOTH For dynamic parameters, the change is effective at the next startup and is persistent. For dynamic parameters, the effect is immediate, but it is not persistent because the server parameter file is not updated. For static parameters, this specification is not allowed. The change is applied in both the server parameter file and memory. The effect is as follows: ■ ■ For dynamic parameters, the effect is immediate and persistent. For static parameters, this specification is not allowed. It is an error to specify SCOPE=SPFILE or SCOPE=BOTH if the server is not using a server parameter file. The default is SCOPE=BOTH if a server parameter file was used to start up the instance, and MEMORY if a traditional initialization parameter file was used to start up the instance. For dynamic parameters, you can also specify the DEFERRED keyword. When specified, the change is effective only for future sessions. A COMMENT clause allows a comment string to be associated with the parameter update. When you specify SCOPE as SPFILE or BOTH, the comment is written to the server parameter file. The following statement changes the maximum number of job queue processes allowed for the instance. It also specifies a comment, and explicitly states that the change is to be made only in memory (that is, it is not persistent across instance shutdown and startup). ALTER SYSTEM SET JOB_QUEUE_PROCESSES=50 COMMENT='temporary change on Nov 29' SCOPE=MEMORY; 2-48 Oracle9i Database Administrator’s Guide Managing Initialization Parameters Using a Server Parameter File Another example illustrates setting a complex initialization parameter that takes a list of strings. Specifically, the parameter value being set is the LOG_ARCHIVE_ DEST_n initialization parameter. The case could be that either the parameter is being changed to a new value or a new archive destination is being added. ALTER SYSTEM SET LOG_ARCHIVE_DEST_4='LOCATION=/u02/oracle/rbdb1/',MANDATORY,'REOPEN=2' COMMENT='Add new destimation on Nov 29' SCOPE=SPFILE; Note that when a value consists of a list of strings, the syntax of the ALTER SYSTEM SET statement does not support editing each element of the list of values by the position or ordinal number. You must specify the complete list of values each time the parameter is updated, and the new list completely replaces the old list. Deleting Initialization Parameter Values For initialization parameters whose values are string values you can restore a parameter to its default value (effectively deleting it), by using the following syntax: ALTER SYSTEM SET parameter = ''; For numeric and boolean value parameters, you must specifically set the parameter back to its original default value. Exporting the Server Parameter File You can export a server parameter file to create a traditional text initialization parameter file. Reasons for doing this include: ■ ■ ■ Creating backups of the server parameter file For diagnostic purposes, listing all of the parameter values currently used by an instance. This is analogous to the SQL*Plus SHOW PARAMETERS command or selecting from the V$PARAMETER or V$PARAMETER2 views. Modifying of the server parameter file by first exporting it, editing the output file, and then re-creating it The exported file can also be used to start up an instance using the PFILE option. The CREATE PFILE statement is used to export a server parameter file. You must have the SYSDBA or the SYSOPER system privilege to execute this statement. The exported file is created on the database server machine. It contains any comments associated with the parameter in the same line as the parameter setting. Creating an Oracle Database 2-49 Managing Initialization Parameters Using a Server Parameter File The following example creates a text initialization parameter file from the server parameter file: CREATE PFILE FROM SPFILE; Because no names were specified for the files, a platform-specific name is used for the initialization parameter file, and it is created from the platform-specific default server parameter file. The following example creates a text initialization parameter file from a server parameter file where the names of the files are specified: CREATE PFILE='/u01/oracle/dbs/test_init.ora' FROM SPFILE='/u01/oracle/dbs/test_spfile.ora'; Backing Up the Server Parameter File You can create a backup of your server parameter file by exporting it, as described in "Exporting the Server Parameter File" on page 2-49. If the backup and recovery strategy for your database is implemented using Recovery Manager (RMAN), then you can use RMAN to create a backup. The server parameter file is backed up automatically by RMAN when you back up your database, but RMAN also allows you to specifically create a backup of the currently active server parameter file. See Also: Oracle9i Recovery Manager User’s Guide Errors and Recovery for the Server Parameter File If an error occurs while reading the server parameter file (during startup or an export operation), or while writing the server parameter file during its creation, the operation terminates with an error reported to the user. If an error occurs while reading or writing the server parameter file during a parameter update, the error is reported in the alert file and all subsequent parameter updates to the server parameter file are ignored. At this point, you have the following options: ■ ■ 2-50 Shut down the instance, recover the server parameter file, then restart the instance Continue to run without caring that subsequent parameter updates will not be persistent Oracle9i Database Administrator’s Guide Managing Initialization Parameters Using a Server Parameter File Viewing Parameter Settings You have several options for viewing parameter settings. Method Description SHOW PARAMETERS This SQL*Plus command displays the currently in use parameter values. CREATE PFILE This SQL statement creates a text initialization parameter file from the binary server parameter file. V$PARAMETER This view displays the currently in effect parameter values. V$PARAMETER2 This view displays the currently in effect parameter values. It is easier to distinguish list parameter values in this view because each list parameter value appears as a row. V$SPPARAMETER This view displays the current contents of the server parameter file. The view returns NULL values if a server parameter file is not being used by the instance. See Also: Oracle9i Database Reference for a complete description of views Creating an Oracle Database 2-51 Managing Initialization Parameters Using a Server Parameter File 2-52 Oracle9i Database Administrator’s Guide 3 Using Oracle-Managed Files This chapter discusses the use of the Oracle-managed files and contains the following topics: ■ What are Oracle-Managed Files? ■ Enabling the Creation and Use of Oracle-Managed Files ■ Creating Oracle-Managed Files ■ Behavior of Oracle-Managed Files ■ Scenarios for Using Oracle-Managed Files Using Oracle-Managed Files 3-1 What are Oracle-Managed Files? What are Oracle-Managed Files? Using Oracle-managed files simplifies the administration of an Oracle database. Oracle-managed files eliminate the need for you, the DBA, to directly manage the operating system files comprising an Oracle database. You specify operations in terms of database objects rather than filenames. Oracle internally uses standard file system interfaces to create and delete files as needed for the following database structures: ■ Tablespaces ■ Online redo log files ■ Control files Through initialization parameters, you specify the file system directory to be used for a particular type of file. Oracle then ensures that a unique file, an Oracle-managed file, is created and deleted when no longer needed. This feature does not affect the creation or naming of administrative files such as trace files, audit files, alert files, and core files. Who Can Use Oracle-Managed Files? Oracle-managed files are most useful for the following types of databases: ■ ■ Databases that are supported by the following: – A logical volume manager that supports striping/RAID and dynamically extensible logical volumes – A file system that provides large, extensible files Low end or test databases The Oracle Managed Files feature is not intended to ease administration of systems that use raw disks. This feature provides better integration with operating system functionality for disk space allocation. Since there is no operating system support for allocation of raw disks (it is done manually), this feature cannot help. On the other hand, because Oracle-managed files require that you use the operating system file system (unlike raw disks), you lose control over how files are laid out on the disks and thus, you lose some I/O tuning ability. What is a Logical Volume Manager? A logical volume manager (LVM) is a software package available with most operating systems. Sometimes it is called a logical disk manager (LDM). It allows 3-2 Oracle9i Database Administrator’s Guide What are Oracle-Managed Files? pieces of multiple physical disks to be combined into a single contiguous address space that appears as one disk to higher layers of software. An LVM can make the logical volume have better capacity, performance, reliability, and availability characteristics than any of the underlying physical disks. It uses techniques such as mirroring, striping, concatenation, and RAID 5 to implement these characteristics. Some LVMs allow the characteristics of a logical volume to be changed after it is created, even while it is in use. The volume may be resized or mirrored, or it may be relocated to different physical disks. What is a File System? A file system is a data structure built inside a contiguous disk address space. A file manager (FM) is a software package that manipulates file systems, but it is sometimes called the file system. All operating systems have file managers. The primary task of a file manager is to allocate and deallocate disk space into files within a file system. A file system allows the disk space to be allocated to a large number of files. Each file is made to appear as a contiguous address space to applications such as Oracle. The files may not actually be contiguous within the disk space of the file system. Files can be created, read, written, resized, and deleted. Each file has a name associated with it that is used to refer to the file. A file system is commonly built on top of a logical volume constructed by an LVM. Thus all the files in a particular file system have the same performance, reliability, and availability characteristics inherited from the underlying logical volume. A file system is a single pool of storage that is shared by all the files in the file system. If a file system is out of space, then none of the files in that file system can grow. Space available in one file system does not affect space in another file system. However some LVM/FM combinations allow space to be added or removed from a file system. An operating system can support multiple file systems. Multiple file systems are constructed to give different storage characteristics to different files as well as to divide the available disk space into pools that do not affect each other. Benefits of Using Oracle-Managed Files Consider the following benefits of using Oracle-managed files: ■ They make the administration of the database easier. Using Oracle-Managed Files 3-3 Enabling the Creation and Use of Oracle-Managed Files There is no need to invent filenames and define specific storage requirements. A consistent set of rules is used to name all relevant files. The file system defines the characteristics of the storage and the pool where it is allocated. ■ They reduce corruption caused by administrators specifying the wrong file. Each Oracle-managed file and filename is unique. Using the same file in two different databases is a common mistake that can cause very large down times and loss of committed transactions. Using two different names that refer to the same file is another mistake that causes major corruptions. ■ They reduce wasted disk space consumed by obsolete files. Oracle automatically removes old Oracle-managed files when they are no longer needed. Much disk space is wasted in large systems simply because no one is sure if a particular file is still required. This also simplifies the administrative task of removing files that are no longer required on disk and prevents the mistake of deleting the wrong file. ■ They simplify creation of test and development databases. You can minimize the time spent making decisions regarding file structure and naming, and you have fewer file management tasks. You can focus better on meeting the actual requirements of your test or development database. ■ Oracle-managed files make development of portable third-party tools easier. Oracle-managed files eliminate the need to put operating system specific file names in SQL scripts. Oracle-Managed Files and Existing Functionality Using Oracle-managed files does not eliminate any existing functionality. Existing databases are able to operate as they always have. New files can be created as managed files while old ones are administered in the old way. Thus, a database can have a mixture of Oracle-managed and unmanaged files. Enabling the Creation and Use of Oracle-Managed Files The following initialization parameters allow the database server to use the Oracle Managed Files feature: 3-4 Oracle9i Database Administrator’s Guide Enabling the Creation and Use of Oracle-Managed Files Parameter Description DB_CREATE_FILE_DEST Defines the location of the default file system directory where Oracle creates datafiles or tempfiles when no file specification is given in the creation operation. Also used as the default file system directory for online redo log and control files if DB_ CREATE_ONLINE_LOG_DEST_n is not specified. DB_CREATE_ONLINE_LOG_DEST_n Defines the location of the default file system directory for online redo log files and control file creation when no file specification is given in the creation operation. You can use this initialization parameter multiple times, where n specifies a multiplexed copy of the online redo log or control file. You can specify up to five multiplexed copies. The file system directory specified by either of these parameters must already exist: Oracle does not create it. The directory must also have permissions to allow Oracle to create the files in it. The default location is used whenever a location is not explicitly specified for the operation creating the file. Oracle creates the filename, and a file thus created is an Oracle-managed file. Both of these initialization parameters are dynamic, and can be set using the ALTER SYSTEM or ALTER SESSION statement. See Also: ■ ■ Oracle9i Database Reference for additional information about initialization parameters "How Oracle-Managed Files are Named" on page 3-7 Setting the DB_CREATE_FILE_DEST Initialization Parameter Include the DB_CREATE_FILE_DEST initialization parameter in your initialization parameter file to identify the default location for the database server to create: ■ Datafiles ■ Tempfiles ■ Online redo log files ■ Control files Using Oracle-Managed Files 3-5 Creating Oracle-Managed Files You specify the name of a file system directory that becomes the default location for the creation of the operating system files for these entities. The following example sets /u01/oradata/payroll as the default directory to use when creating Oracle-managed files: DB_CREATE_FILE_DEST = '/u01/oradata/payroll' Setting the DB_CREATE_ONLINE_LOG_DEST_n Initialization Parameter Include the DB_CREATE_ONLINE_LOG_DEST_n initialization parameter in your initialization parameter file to identify the default location for the database server to create: ■ Online redo log files ■ Control files You specify the name of a file system directory that becomes the default location for the creation of the operating system files for these entities. You can specify up to five multiplexed locations. For the creation of online redo log files and control files only, this parameter overrides any default location specified in the DB_CREATE_FILE_DEST initialization parameter. If you do not specify a DB_CREATE_FILE_DEST parameter, but you do specify this parameter, then only online redo log files and control files can be created as Oracle-managed files. It is recommended that you specify at least two parameters. For example: DB_CREATE_ONLINE_LOG_DEST_1 = '/u02/oradata/payroll' DB_CREATE_ONLINE_LOG_DEST_2 = '/u03/oradata/payroll' This allows multiplexing, which provides greater fault-tolerance for the online redo log and control file if one of the destinations fails. Creating Oracle-Managed Files If you have met any of the following conditions, then Oracle creates Oracle-managed files for you, as appropriate, when no file specification is given in the creation operation: ■ You have included either or both of the DB_CREATE_FILE_DEST and DB_ CREATE_ONLINE_LOG_DEST_n initialization parameters in your initialization parameter file. 3-6 Oracle9i Database Administrator’s Guide Creating Oracle-Managed Files ■ You have issued the ALTER SYSTEM or ALTER SESSION statement to dynamically set either or both the DB_CREATE_FILE_DEST and DB_CREATE_ ONLINE_LOG_DEST_n initialization parameters. If a statement that creates an Oracle-managed file finds an error or does not complete due to some failure, then any Oracle-managed files created by the statement are automatically deleted as part of the recovery of the error or failure. However, because of the large number of potential errors that can occur with file systems and storage subsystems, there can be situations where you must manually remove the files using operating system commands. When an Oracle-managed file is created, its filename is written to the alert file. This information can be used to find the file if it is necessary to manually remove the file. The following topics are discussed in this section: ■ How Oracle-Managed Files are Named ■ Creating Oracle-Managed Files at Database Creation ■ Creating Datafiles for Tablespaces ■ Creating Tempfiles for Temporary Tablespaces ■ Creating Control Files ■ Creating Online Redo Log Files See Also: Oracle9i SQL Reference How Oracle-Managed Files are Named The filenames of Oracle-managed files comply with the Oracle Flexible Architecture (OFA) standard for file naming. The assigned names are intended to meet the following requirements: ■ Database files are easily distinguishable from all other files. ■ Control files, online redo log files, and datafiles are identifiable as such. ■ The association of datafile to tablespace is clearly indicated. No two Oracle-managed files are given the same name. The name that is used for creation of an Oracle-managed file is constructed from three sources. ■ The default file system directory location ■ A port-specific file name template that is chosen based on the type of file Using Oracle-Managed Files 3-7 Creating Oracle-Managed Files ■ A unique string created by the Oracle database server or the operating system. This ensures that file creation does not damage an existing file and that the file cannot be mistaken for some other file. As a specific example, filenames for Oracle-managed files have the following format on Solaris: File Type Format Example Datafile o1_mf_%t_%u_.dbf /u01/oradata/payroll/o1_mf_tbs1_2ixfh90q_.dbf Tempfile o1_mf_%t_%u_.tmp /u01/oradata/payroll/o1_mf_temp1_6dygh80r_.tmp Redo log file o1_mf_%g_%u_.log /u01/oradata/payroll/o1_mf_1_wo94n2xi_.log Control file o1_mf_%u_.ctl /u01/oradata/payroll/o1_mf_cmr7t30p_.ctl where: ■ %t is the tablespace name. At most, eight characters of the tablespace name are used. If eight characters causes the name to be too long, then the tablespace name is truncated. Placing the tablespace name before the uniqueness string means that all the datafiles for a tablespace appear next to each other in an alphabetic file listing. ■ %u is an eight character string that guarantees uniqueness ■ %g is the online redo log file group number On other platforms the names are similar, subject to the constraints of the platform’s naming rules. Caution: Do not rename an Oracle-managed file. Oracle identifies an Oracle-managed file based on its name. If you rename the file, Oracle is no longer able to recognize it as an Oracle-managed file and will not manage the file accordingly. Creating Oracle-Managed Files at Database Creation The behavior of the CREATE DATABASE statement for creating database structures when using Oracle-managed files is discussed in this section. Specifying Control Files at Database Creation At database creation, the control file is created in the files specified by the CONTROL_FILES initialization parameter. If the CONTROL_FILES parameter is not 3-8 Oracle9i Database Administrator’s Guide Creating Oracle-Managed Files set and at least one of the initialization parameters required for the creation of Oracle-managed files is set, then an Oracle-managed control file is created in the default control file destinations. In order of precedence, the default destination is defined as follows: ■ ■ If DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, then an Oracle-managed control file copy is created in each directory specified. The file in the first directory is the primary control file. If the DB_CREATE_FILE_DEST initialization parameter is specified, and no DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, then an Oracle-managed control file is created in the directory specified. If the CONTROL_FILES parameter is not set and none of the above initialization parameters are set, then Oracle’s default behavior is operating system dependent. At least one copy of a control file is created in an operating system dependent default location. Any copies of control files created in this fashion are not Oracle-managed files, and you must add a CONTROL_FILES initialization parameter to any initialization parameter file. If Oracle creates an Oracle-managed control file, and if there is a server parameter file, then Oracle creates a CONTROL_FILES initialization parameter entry in the server parameter file. If there is no server parameter file, then you must manually include a CONTROL_FILES initialization parameter entry in the text initialization parameter file. See Also: Chapter 6, "Managing Control Files" Specifying Online Redo Log Files at Database Creation The LOGFILE clause is not required in the CREATE DATABASE statement, and omitting it provides a simple means of creating Oracle-managed online redo log files. If the LOGFILE clause is omitted, then online redo log files are created in the default online redo log file destinations. In order of precedence, the default destination is defined as follows: ■ ■ If DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, then Oracle creates two online redo files in each directory specified. More specifically, Oracle creates two online redo groups with corresponding members in each directory specified. These online redo log files are Oracle-managed files. If the DB_CREATE_FILE_DEST initialization parameter is specified, but no DB_CREATE_ONLINE_LOG_DEST_n parameters are specified, then two online redo log files (two groups with one member each) are created in the directory specified. These online redo log files are Oracle-managed files. Using Oracle-Managed Files 3-9 Creating Oracle-Managed Files ■ If the LOGFILE clause is omitted and neither of the above initialization parameters are specified, then two online redo log files are created in operating system dependent default locations. Any online redo log files created in this fashion are not Oracle-managed files. The default size of an Oracle-managed online redo log file is 100 (MB). Optionally, you can create Oracle-managed online redo log files, and override default attributes, by including the LOGFILE clause but omitting a filename. Online redo log files are created as above, except for the following: If no filename is provided in the LOGFILE clause of CREATE DATABASE, and none of the initialization parameters required for creating Oracle-managed files are provided, then the CREATE DATABASE statement fails. See Also: Chapter 7, "Managing the Online Redo Log" Specifying the SYSTEM Tablespace Datafile at Database Creation The DATAFILE clause is not required in the CREATE DATABASE statement, and omitting it provides a simple means of creating an Oracle-managed datafile for the SYSTEM tablespace. If the DATAFILE clause is omitted, then one of the following actions occurs: ■ ■ If DB_CREATE_FILE_DEST is set, then an Oracle-managed datafile for the SYSTEM tablespace is created in the DB_CREATE_FILE_DEST directory. If DB_CREATE_FILE_DEST is not set, then Oracle creates one SYSTEM tablespace datafile whose name and size are operating system dependent. Any SYSTEM tablespace datafile created in this manner is not an Oracle-managed file. The default size for an Oracle-managed datafile is 100 MB and the file is autoextensible with an unlimited maximum size. Optionally, you can create an Oracle-managed datafile for the SYSTEM tablespace and override default attributes. This is done by including the DATAFILE clause, omitting a filename, but specifying overriding attributes. When a filename is not supplied and the DB_CREATE_FILE_DEST parameter is set, an Oracle-managed datafile for the SYSTEM tablespace is created in the DB_CREATE_FILE_DEST directory with the specified attributes being overridden. However, if a filename is not supplied and the DB_CREATE_FILE_DEST parameter is not set, then the CREATE DATABASE statement fails. 3-10 Oracle9i Database Administrator’s Guide Creating Oracle-Managed Files When overriding the default attributes of an Oracle-managed file, if a SIZE value is specified but no AUTOEXTEND clause is specified, then the datafile is not autoextensible. Specifying the Undo Tablespace Datafile at Database Creation The DATAFILE subclause of the UNDO TABLESPACE clause is optional and a filename is not required in the file specification. If a filename is not supplied and the DB_CREATE_FILE_DEST parameter is set, then an Oracle-managed datafile is created in the DB_CREATE_FILE_DEST directory. If DB_CREATE_FILE_DEST is not set, then the statement fails with a syntax error. The UNDO TABLESPACE clause itself is optional in the CREATE DATABASE statement. If it is not supplied, and automatic undo management mode is enabled, then a default undo tablespace named SYS_UNDOTBS is created and a 10 MB datafile that is autoextensible is allocated as follows: ■ ■ If DB_CREATE_FILE_DEST is set, then an Oracle-managed datafile is created in the indicated directory. If DB_CREATE_FILE_DEST is not set, then the datafile location is operating system specific. See Also: Chapter 13, "Managing Undo Space" Specifying the Default Temporary Tablespace Tempfile at Database Creation The TEMPFILE subclause is optional for the DEFAULT TEMPORARY TABLESPACE clause and a filename is not required in the file specification. If a filename is not supplied and the DB_CREATE_FILE_DEST parameter set, then an Oracle-managed tempfile is created in the DB_CREATE_FILE_DEST directory. If DB_CREATE_FILE_ DEST is not set, then the CREATE DATABASE statement fails with a syntax error. The DEFAULT TEMPORARY TABLESPACE clause itself is optional. If it is not specified, then no default temporary tablespace is created. The default size for an Oracle-managed tempfile is 100 MB and the file is autoextensible with an unlimited maximum size. CREATE DATABASE Statement Using Oracle-Managed Files: Examples This section contains examples of the CREATE DATABASE statement when using the Oracle Managed Files feature. Using Oracle-Managed Files 3-11 Creating Oracle-Managed Files CREATE DATABASE: Example 1 This example creates a database with the following Oracle-managed files: ■ ■ ■ ■ A SYSTEM tablespace datafile in directory /u01/oradata/sample that is 100 MB and autoextensible up to an unlimited size Two online log groups with two members of 100 MB each, one each in /u02/oradata/sample and /u03/oradata/sample If automatic undo management mode is enabled, then an undo tablespace datafile in directory /u01/oradata/sample2 that is 10 MB and autoextensible up to an unlimited size. An undo tablespace named SYS_ UNDOTBS is created. If no CONTROL_FILES initialization parameter is specified, then two control files, one each in /u02/oradata/sample and /u03/oradata/sample. The control file in /u02/oradata/sample is the primary control file. The following parameter settings are included in the initialization parameter file: DB_CREATE_FILE_DEST = '/u01/oradata/sample' DB_CREATE_ONLINE_LOG_DEST_1 = '/u02/oradata/sample' DB_CREATE_ONLINE_LOG_DEST_2 = '/u03/oradata/sample' The following statement is issued at the SQL prompt: SQL> CREATE DATABASE sample; CREATE DATABASE: Example 2 This example creates a database with the following Oracle-managed files: ■ ■ ■ ■ A 100 MB SYSTEM tablespace datafile in directory /u01/oradata/sample2 that is autoextensible up to an unlimited size. Two online redo log files of 100 MB each in directory /u01/oradata/sample2. They are not multiplexed. An undo tablespace datafile in directory /u01/oradata/sample2 that is 10 MB and autoextensible up to an unlimited size. An undo tablespace named SYS_UNDOTBS is created. A control file in /u01/oradata/sample2 In this example, it is assumed that: ■ 3-12 No DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified in the initialization parameter file. Oracle9i Database Administrator’s Guide Creating Oracle-Managed Files ■ ■ No CONTROL_FILES initialization parameter was specified in the initialization parameter file. Automatic undo management mode is enabled. The following statements are issued at the SQL prompt: SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST = '/u01/oradata/sample2'; SQL> CREATE DATABASE sample2; This database configuration is not recommended for a production database. The example illustrates how a very low-end database or simple test database can easily be created. To better protect this database from failures, at least one more control file should be created and the online redo log should be multiplexed. CREATE DATABASE: Example 3 In this example, the file size for the Oracle-managed files for the default temporary tablespace and undo tablespace are specified. A database with the following Oracle-managed files is created: ■ ■ ■ ■ ■ A 400 MB SYSTEM tablespace datafile in directory /u01/oradata/sample3. Because SIZE is specified, the file in not autoextensible. Two online redo log groups with two members of 100 MB each, one each in directories /u02/oradata/sample3 and /u03/oradata/sample3 For the default temporary tablespace dflt_ts, a 10 MB tempfile in directory /u01/oradata/sample3. Because SIZE is specified, the file in not autoextensible. For the undo tablespace undo_ts, a 10 MB datafile in directory /u01/oradata/sample3. Because SIZE is specified, the file in not autoextensible. If no CONTROL_FILES initialization parameter was specified, then two control files, one each in directories /u02/oradata/sample3 and /u03/oradata/sample3. The control file in /u02/oradata/sample3 is the primary control file. The following parameter settings are included in the initialization parameter file: DB_CREATE_FILE_DEST = '/u01/oradata/sample3' DB_CREATE_ONLINE_LOG_DEST_1 = '/u02/oradata/sample3' DB_CREATE_ONLINE_LOG_DEST_2 = '/u03/oradata/sample3' The following statement is issued at the SQL prompt: Using Oracle-Managed Files 3-13 Creating Oracle-Managed Files SQL> CREATE DATABASE sample3 DATAFILE SIZE 400M 2> DEFAULT TEMPORARY TABLESPACE dflt_ts TEMPFILE SIZE 10M 3> UNDO TABLESPACE undo_ts DATAFILE SIZE 10M; Creating Datafiles for Tablespaces The following statements that can create datafiles are relevant to the discussion in this section: ■ CREATE TABLESPACE ■ CREATE UNDO TABLESPACE ■ ALTER TABLESPACE ... ADD DATAFILE When creating a tablespace, either a regular tablespace or an undo tablespace, the DATAFILE clause is optional. When you include the DATAFILE clause the filename is optional. If the DATAFILE clause or filename is not provided, then the following rules apply: ■ ■ If the DB_CREATE_FILE_DEST initialization parameter is specified, then an Oracle-managed datafile is created in the location specified by the parameter. If the DB_CREATE_FILE_DEST initialization parameter is not specified, then the statement creating the datafile fails. When you add a datafile to a tablespace with the ALTER TABLESPACE ... ADD DATAFILE statement the filename is optional. If the filename is not specified, then the same rules apply as discussed in the previous paragraph. By default, an Oracle-managed datafile for a regular tablespace is 100 MB and is autoextensible with an unlimited maximum size. However, if in your DATAFILE clause you override these defaults by specifying a SIZE value (and no AUTOEXTEND clause), then the datafile is not autoextensible. See Also: ■ ■ ■ "Specifying the SYSTEM Tablespace Datafile at Database Creation" on page 3-10 "Specifying the Undo Tablespace Datafile at Database Creation" on page 3-11 Chapter 11, "Managing Tablespaces" CREATE TABLESPACE: Examples The following are some examples of creating tablespaces with Oracle-managed files. 3-14 Oracle9i Database Administrator’s Guide Creating Oracle-Managed Files CREATE TABLESPACE: Example 1 The following example sets the default location for datafile creations to /u01/oradata/sample and then creates a tablespace tbs_1 with a datafile in that location. The datafile is 100 MB and is autoextensible with an unlimited maximum size. SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST = '/u01/oradata/sample'; SQL> CREATE TABLESPACE tbs_1; CREATE TABLESPACE: Example 2 This example creates a tablespace named tbs_2 with a datafile in the directory /u01/oradata/sample2. The datafile’s initial size is 400 MB and it is not autoextensible. The following parameter setting is included in the initialization parameter file: DB_CREATE_FILE_DEST = '/u01/oradata/sample2' The following statement is issued at the SQL prompt: SQL> CREATE TABLESPACE tbs_2 DATAFILE SIZE 400M AUTOEXTEND OFF; CREATE TABLESPACE: Example 3 This example creates a tablespace named tbs_3 with an autoextensible datafile in the directory /u01/oradata/sample3 with a maximum size of 800 MB and an initial size of 100 MB: The following parameter setting is included in the initialization parameter file: DB_CREATE_FILE_DEST = '/u01/oradata/sample3' The following statement is issued at the SQL prompt: SQL> CREATE TABLESPACE tbs_3 DATAFILE AUTOEXTEND ON MAXSIZE 800M; CREATE TABLESPACE: Example 4 The following example sets the default location for datafile creations to /u01/oradata/sample4 and then creates a tablespace named tbs_4 in that directory with two datafiles. Both datafiles have an initial size of 200 MB, and because a SIZE value is specified, they are not autoextensible SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST = '/u01/oradata/sample4'; SQL> CREATE TABLESPACE tbs_4 DATAFILE SIZE 200M, SIZE 200M; Using Oracle-Managed Files 3-15 Creating Oracle-Managed Files CREATE UNDO TABLESPACE: Example The following example creates an undo tablespace named undotbs_1 with a datafile in the directory /u01/oradata/sample. The datafile for the undo tablespace is 100 MB and is autoextensible with an unlimited maximum size. The following parameter setting is included in the initialization parameter file: DB_CREATE_FILE_DEST = '/u01/oradata/sample' The following statement is issued at the SQL prompt: SQL> CREATE UNDO TABLESPACE undotbs_1; ALTER TABLESPACE: Example This example adds an Oracle-managed autoextensible datafile to the tbs_1 tablespace. The datafile has an initial size of 100 MB and a maximum size of 800 MB. The following parameter setting is included in the initialization parameter file: DB_CREATE_FILE_DEST = '/u01/oradata/sample' The following statement is entered at the SQL prompt: SQL> ALTER TABLESPACE tbs_1 ADD DATAFILE AUTOEXTEND ON MAXSIZE 800M; Creating Tempfiles for Temporary Tablespaces The following statements that create tempfiles are relevant to the discussion in this section: ■ CREATE TEMPORARY TABLESPACE ■ ALTER TABLESPACE ... ADD TEMPFILE When creating a temporary tablespace the TEMPFILE clause is optional. If you include the TEMPFILE clause, then the filename is optional. If the TEMPFILE clause or filename is not provided, then the following rules apply: ■ ■ 3-16 If the DB_CREATE_FILE_DEST initialization parameter is specified, then an Oracle-managed tempfile is created in the location specified by the parameter. If the DB_CREATE_FILE_DEST initialization parameter is not specified, then the statement creating the tempfile fails. Oracle9i Database Administrator’s Guide Creating Oracle-Managed Files When you add a tempfile to a tablespace with the ALTER TABLESPACE ... ADD TEMPFILE statement the filename is optional. If the filename is not specified, then the same rules apply as discussed in the previous paragraph. When overriding the default attributes of an Oracle-managed file, if a SIZE value is specified but no AUTOEXTEND clause is specified, then the datafile is not autoextensible. See Also: "Specifying the Default Temporary Tablespace Tempfile at Database Creation" on page 3-11 CREATE TEMPORARY TABLESPACE: Example The following example sets the default location for datafile creations to /u01/oradata/sample and then creates a tablespace named temptbs_1 with a tempfile in that location. The tempfile is 100 MB and is autoextensible with an unlimited maximum size. SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST = '/u01/oradata/sample'; SQL> CREATE TEMPORARY TABLESPACE temptbs_1; ALTER TABLESPACE ... ADD TEMPFILE: Example The following example sets the default location for datafile creations to /u03/oradata/sample and then adds a tempfile in the default location to a tablespace named temptbs_1. The tempfile’s initial size is 100 MB. It is autoextensible with an unlimited maximum size. SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST = '/u03/oradata/sample'; SQL> ALTER TABLESPACE TBS_1 ADD TEMPFILE; Creating Control Files When you issue the CREATE CONTROLFILE statement, a control file is created (or reused, if REUSE is specified) in the files specified by the CONTROL_FILES initialization parameter. If the CONTROL_FILES parameter is not set, then the control file is created in the default control file destinations. In order of precedence, the default destination is defined as follows: ■ If DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, then an Oracle-managed control file copy is created in each directory specified. The file in the first directory is the primary control file. Using Oracle-Managed Files 3-17 Creating Oracle-Managed Files ■ ■ If the DB_CREATE_FILE_DEST initialization parameter is specified, and no DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, then an Oracle-managed control file is created in the directory specified. If neither DB_CREATE_ONLINE_LOG_DEST_n or DB_CREATE_ONLINE_LOG_ DEST_n initialization parameters are specified, then a control file is created in an operating system specific default location. This control file is not an Oracle-managed file. If Oracle creates an Oracle-managed control file, and there is a server parameter file, then Oracle creates a CONTROL_FILES initialization parameter for the server parameter file. If there is no server parameter file, then you must create a CONTROL_ FILES initialization parameter manually and include it in the initialization parameter file. If the datafiles in the database are Oracle-managed files, then the Oracle generated filenames for the files must be supplied in the DATAFILE clause of the statement. If the online redo log files are Oracle-managed files, then the NORESETLOGS or RESETLOGS keyword determines what can be supplied in the LOGFILE clause: ■ ■ If the NORESETLOGS keyword is used, then the Oracle generated filenames for the Oracle-managed online redo log files must be supplied in the LOGFILE clause. If the RESETLOGS keyword is used, then the online redo log file names can be supplied as with the CREATE DATABASE statement. See "Specifying Online Redo Log Files at Database Creation" on page 3-9. The sections that follow contain examples of using the CREATE CONTROLFILE statement with Oracle-managed files. See Also: "Specifying Control Files at Database Creation" on page 3-8 CREATE CONTROLFILE Using NORESETLOGS Keyword: Example The following CREATE CONTROLFILE statement is generated by an ALTER DATABASE BACKUP CONTROLFILE TO TRACE statement for a database with Oracle-managed datafiles and online redo log files: CREATE CONTROLFILE DATABASE sample LOGFILE GROUP 1 ('/u01/oradata/sample/ora_1_o220rtt9.log', '/u02/oradata/sample/ora_1_v2o0b2i3.log') SIZE 100M, GROUP 2 ('/u01/oradata/sample/ora_2_p22056iw.log', 3-18 Oracle9i Database Administrator’s Guide Creating Oracle-Managed Files '/u02/oradata/sample/ora_2_p02rcyg3.log') SIZE 100M NORESETLOGS DATAFILE '/u01/oradata/sample/ora_system_xu34ybm2.dbf' SIZE 100M MAXLOGFILES 5 MAXLOGHISTORY 100 MAXDATAFILES 10 MAXINSTANCES 2 ARCHIVELOG; CREATE CONTROLFILE Using RESETLOGS Keyword: Example The following is an example of a CREATE CONTROLFILE statement with the RESETLOGS option. Either DB_CREATE_ONLINE_LOG_DEST_n or DB_CREATE_ FILE_DEST must be set. CREATE CONTROLFILE DATABASE sample RESETLOGS DATAFILE '/u01/oradata/sample/ora_system_aawbmz51.dbf' SIZE 100M MAXLOGFILES 5 MAXLOGHISTORY 100 MAXDATAFILES 10 MAXINSTANCES 2 ARCHIVELOG; Later, you must issue the ALTER DATABASE OPEN RESETLOGS statement to re-create the online redo log files. This is discussed in "Using the ALTER DATABASE OPEN RESETLOGS Statement" on page 3-20. If the previous log files are Oracle-managed files, then they are not deleted. Creating Online Redo Log Files Online redo log files are created at database creation time. They can also be created when you issue either of the following statements: ■ ALTER DATABASE ADD LOGFILE ■ ALTER DATABASE OPEN RESETLOGS Using the ALTER DATABASE ADD LOGFILE Statement The ALTER DATABASE ADD LOGFILE statement allows you to later add a new group to your current online redo log. The filename in the ADD LOGFILE clause is optional if you are using Oracle-managed files. If a filename is not provided, then a Using Oracle-Managed Files 3-19 Creating Oracle-Managed Files redo log file is created in the default log file destination. In order of precedence, the default destination is defined as follows: ■ ■ If DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, then an Oracle-managed log file member is created in each directory specified in the parameters (up to MAXLOGMEMBERS for the database). If the DB_CREATE_FILE_DEST initialization parameter is specified and no DB_ CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, then an Oracle-managed log file member is created in the directory specified in the parameter. If a filename is not provided and you have not provided one of the initialization parameters required for creating Oracle-managed files, then the statement returns an error. The default size for an Oracle-managed log file is 100 MB. You continue to add and drop online redo log file members by specifying complete filenames. See Also: ■ ■ "Specifying Online Redo Log Files at Database Creation" on page 3-9 "Creating Control Files" on page 3-17 Adding New Online Redo Log Files: Example The following example creates a log file with a member in /u01/oradata/sample and another member in /u02/oradata/sample. The size of the log file is 100 MB. The following parameter settings are included in the initialization parameter file: DB_CREATE_ONLINE_LOG_DEST_1 = '/u01/oradata/sample' DB_CREATE_ONLINE_LOG_DEST_2 = '/u02/oradata/sample' The following statement is issued at the SQL prompt: SQL> ALTER DATABASE ADD LOGFILE; Using the ALTER DATABASE OPEN RESETLOGS Statement If you previously created a control file specifying RESETLOGS and either did not specify filenames or specified non-existent filenames, then Oracle creates online redo log files for you when you issue the ALTER DATABASE OPEN RESETLOGS 3-20 Oracle9i Database Administrator’s Guide Behavior of Oracle-Managed Files statement. The rules for determining the directories in which to store redo log files, when none are specified in the control file, are the same as those discussed in "Specifying Online Redo Log Files at Database Creation" on page 3-9. Behavior of Oracle-Managed Files The filenames of Oracle-managed files are accepted in SQL statements wherever a filename is used to identify an existing file. These filenames, like other filenames, are stored in the control file and, if using Recovery Manager (RMAN) for backup and recovery, in the RMAN catalog. They are visible in all of the usual fixed and dynamic performance views that are available for monitoring datafiles and tempfiles (for example, V$DATAFILE or DBA_DATA_FILES). The following are some examples of statements using Oracle generated filenames: SQL> ALTER DATABASE RENAME FILE 'ora_tbs01_ziw3bopb.dbf' TO 'tbs0101.dbf'; SQL> ALTER DATABASE DROP LOGFILE 'ora_1_wo94n2xi.log'; SQL> ALTER TABLE emp ALLOCATE EXTENT ( DATAFILE 'ora_tbs1_2ixfh90q.dbf' ); You can backup and restore Oracle-managed datafiles, tempfiles, and control files as you would corresponding non Oracle-managed files. Using Oracle generated filenames does not impact the use of logical backup files such as export files. This is particularly important for tablespace point-in-time recovery (TSPITR) and transportable tablespace export files. There are some cases where Oracle-managed files behave differently. These are discussed in the sections that follow. Dropping Datafiles and Tempfiles Unlike files that are not Oracle managed, when an Oracle-managed datafile or tempfile is dropped, the filename is removed from the control file and the file is automatically deleted from the file system. The statements that delete Oracle-managed files when they are dropped are: ■ DROP TABLESPACE ■ ALTER DATABASE TEMPFILE ... DROP Using Oracle-Managed Files 3-21 Scenarios for Using Oracle-Managed Files Dropping Online Redo Log Files When an Oracle-managed online redo log file is dropped its Oracle-managed files are deleted. You specify the group or members to be dropped. The following statements drop and delete online redo log files: ■ ALTER DATABASE DROP LOGFILE ■ ALTER DATABASE DROP LOGFILE MEMBER Renaming Files The following statements are used to rename files: ■ ALTER DATABASE RENAME FILE ■ ALTER TABLESPACE ... RENAME DATAFILE These statements do not actually rename the files on the operating system, but rather, the names in the control file are changed. If the old file is an Oracle-managed file and it exists, then it is deleted. You must specify each filename using the conventions for filenames on your operating system when you issue this statement. Managing Standby Databases The datafiles, control files, and online redo log files in a standby database can be Oracle managed. This is independent of whether Oracle-managed files are used on the primary database. When recovery of a standby database encounters redo for the creation of a datafile, if the datafile is an Oracle-managed file, then the recovery process creates an empty file in the local default file system location. This allows the redo for the new file to be applied immediately without any human intervention. When recovery of a standby database encounters redo for the deletion of a tablespace, it deletes any Oracle-managed datafiles in the local file system. Note that this is independent of the INCLUDING DATAFILES option issued at the primary database. Scenarios for Using Oracle-Managed Files This section further demonstrates the use of Oracle-managed files by presenting scenarios of their use. 3-22 Oracle9i Database Administrator’s Guide Scenarios for Using Oracle-Managed Files Scenario 1: Create and Manage a Database with Multiplexed Online Redo Logs In this scenario, a DBA creates a database where the datafiles and online redo log files are created in separate directories. The online redo log files and control files are multiplexed. The database uses an undo tablespace, and has a default temporary tablespace. The following are tasks involved with creating and maintaining this database. 1. Setting the initialization parameters The DBA includes three generic file creation defaults in the initialization parameter file before creating the database. Automatic undo management mode is also specified. DB_CREATE_FILE_DEST = '/u01/oradata/sample' DB_CREATE_ONLINE_LOG_DEST_1 = '/u02/oradata/sample' DB_CREATE_ONLINE_LOG_DEST_2 = '/u03/oradata/sample' UNDO_MANAGEMENT = AUTO The DB_CREATE_FILE_DEST parameter sets the default file system directory for the datafiles and tempfiles. The DB_CREATE_ONLINE_LOG_DEST_1 and DB_CREATE_ONLINE_LOG_ DEST_2 parameters set the default file system directories for online redo log file and control file creation. Each online redo log file and control file is multiplexed across the two directories. 2. Creating a database Once the initialization parameters are set, the database can be created by using this statement: SQL> CREATE DATABASE sample 2> DEFAULT TEMPORARY TABLESPACE dflt_tmp; Because a DATAFILE clause is not present and the DB_CREATE_FILE_DEST initialization parameter is set, the SYSTEM tablespace datafile is created in the default file system (/u01/oradata/sample in this scenario). The filename is uniquely generated by Oracle. The file is autoextensible with an initial size of 100 MB and an unlimited maximum size. The file is an Oracle-managed file. Because a LOGFILE clause is not present, two online redo log groups are created. Each log group has two members, with one member in the DB_ CREATE_ONLINE_LOG_DEST_1 location and the other member in the DB_ CREATE_ONLINE_LOG_DEST_2 location. The filenames are uniquely generated Using Oracle-Managed Files 3-23 Scenarios for Using Oracle-Managed Files by Oracle. The log files are created with a size of 100 MB. The log file members are Oracle-managed files. Similarly, because the CONTROL_FILES initialization parameter is not present, and two DB_CREATE_ONLINE_LOG_DEST_n initialization parameters are specified, two control files are created. The control file located in the DB_ CREATE_ONLINE_LOG_DEST_1 location is the primary control file; the control file located in the DB_CREATE_ONLINE_LOG_DEST_2 location is a multiplexed copy. The filenames are uniquely generated by Oracle. They are Oracle-managed files. Assuming there is a server parameter file, a CONTROL_ FILES initialization parameter is generated. Automatic undo management mode is specified, but because an undo tablespace is not specified and the DB_CREATE_FILE_DEST initialization parameter is set, a default undo tablespace named SYS_UNDOTBS is created in the directory specified by DB_CREATE_FILE_DEST. The datafile is a 10 MB datafile that is autoextensible. It is an Oracle-managed file. Lastly, a default temporary tablespace named dflt_tmp is specified. Because DB_CREATE_FILE_DEST is included in the parameter file, the tempfile for dflt_tmp is created in the directory specified by that parameter. The tempfile is 100 MB and is autoextensible with an unlimited maximum size. It is an Oracle-managed file. The resultant file tree, with generated filenames, is as follows: /u01 /oradata /sample /ora_system_cmr7t30p.dbf /ora_sys_undo_2ixfh90q.dbf /ora_dflt_tmp_157se6ff.tmp /u02 /oradata /sample /ora_1_0orrm31z.log /ora_2_2xyz16am.log /ora_cmr7t30p.ctl /u03 /oradata /sample /ora_1_ixfvm8w9.log /ora_2_q89tmp28.log /ora_x1sr8t36.ctl 3-24 Oracle9i Database Administrator’s Guide Scenarios for Using Oracle-Managed Files The internally generated filenames can be seen when selecting from the usual views. For example: SQL> SELECT NAME FROM V$DATAFILE; NAME ---------------------------------------------------/u01/oradata/sample/ora_system_cmr7t30p.dbf /u01/oradata/sample/ora_sys_undo_2ixfh90q.dbf 2 rows selected The name is also printed to the alert file when the file is created. 3. Managing control files The control file was created when generating the database, and a CONTROL_ FILES initialization parameter was added to the parameter file. If needed, then the DBA can re-create the control file or build a new one for the database using the CREATE CONTROLFILE statement. The correct Oracle-managed filenames must be used in the DATAFILE and LOGFILE clauses. The ALTER DATABASE BACKUP CONTROLFILE TO TRACE statement generates a script with the correct filenames. Alternatively, the filenames can be found by selecting from the V$DATAFILE, V$TEMPFILE, and V$LOGFILE views. The following example re-creates the control file for the sample database: SQL> CREATE CONTROLFILE REUSE 2> DATABASE sample 3> LOGFILE GROUP 1('/u02/oradata/sample/ora_1_0orrm31z.log', 4> '/u03/oradata/sample/ora_1_ixfvm8w9.log'), 5> GROUP 2('/u02/oradata/sample/ora_2_2xyz16am.log', 6> '/u03/oradata/sample/ora_2_q89tmp28.log') 7> NORESETLOGS 8> DATAFILE '/u01/oradata/sample/ora_system_cmr7t30p.dbf', 9> '/u01/oradata/sample/ora_sys_undo_2ixfh90q.dbf', 10> '/u01/oradata/sample/ora_dflt_tmp_157se6ff.tmp' 11> MAXLOGFILES 5 12> MAXLOGHISTORY 100 13> MAXDATAFILES 10 14> MAXINSTANCES 2 15> ARCHIVELOG; The control file created by this statement is located as specified by the CONTROL_FILES initialization parameter that was generated when the Using Oracle-Managed Files 3-25 Scenarios for Using Oracle-Managed Files database was created. The REUSE clause causes any existing files to be overwritten. 4. Managing the online redo log To create a new group of online redo log files, the DBA can use the ALTER DATABASE ADD LOGFILE statement. The following statement adds a log file with a member in the DB_CREATE_ONLINE_LOG_DEST_1 location and a member in the DB_CREATE_ONLINE_LOG_DEST_2 location. These files are Oracle-managed files. SQL> ALTER DATABASE ADD LOGFILE; Log file members continue to be added and dropped by specifying complete filenames. The GROUP clause can be used to drop a log file. In the following example the operating system file associated with each Oracle-managed log file member is automatically deleted. SQL> ALTER DATABASE DROP LOGFILE GROUP 3; 5. Managing tablespaces The default storage for all datafiles for future tablespace creations in the sample database is the location specified by the DB_CREATE_FILE_DEST initialization parameter (/u01/oradata/sample in this scenario). Any datafiles for which no filename is specified, are created in the file system specified by the initialization parameter DB_CREATE_FILE_DEST. For example: SQL> CREATE TABLESPACE tbs_1; The preceding statement creates a tablespace whose storage is in /u01/oradata/sample. A datafile is created with an initial size of 100 MB and it is autoextensible with an unlimited maximum size. The datafile is an Oracle-managed file. When the tablespace is dropped, the Oracle-managed files for the tablespace are automatically removed. The following statement drops the tablespace and all the Oracle-managed files used for its storage: SQL> DROP TABLESPACE tbs_1; Once the first datafile is full, Oracle does not automatically create a new datafile. More space can be added to the tablespace by adding another 3-26 Oracle9i Database Administrator’s Guide Scenarios for Using Oracle-Managed Files Oracle-managed datafile. The following statement adds another datafile in the location specified by DB_CREATE_FILE_DEST: SQL> ALTER TABLESPACE tbs_1 ADD DATAFILE; The default file system can be changed by changing the initialization parameter. This does not change any existing datafiles. It only affects future creations. This can be done dynamically using the following statement: SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST='/u04/oradata/sample'; 6. Archiving redo information Archiving of online redo log files is no different for Oracle-managed files, than it is for unmanaged files. A file system location for the archived log files can be specified using the LOG_ARCHIVE_DEST_n initialization parameters. The filenames are formed based on the LOG_ARCHIVE_FORMAT parameter or its default. The archived logs are not Oracle-managed files 7. Backup, restore, and recover Since an Oracle-managed file is compatible with standard operating system files, you can use operating system utilities to backup or restore Oracle-managed files. All existing methods for backing up, restoring, and recovering the database work for Oracle-managed files. Scenario 2: Add Oracle-Managed Files to an Existing Database Assume in this case that an existing database does not have any Oracle-managed files, but the DBA would like to create new tablespaces with Oracle-managed files and locate them in directory /u03/oradata/sample2. 1. Setting the initialization parameters To allow automatic datafile creation, set the DB_CREATE_FILE_DEST initialization parameter to the file system directory in which to create the datafiles. This can be done dynamically as follows: SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST = '/u03/oradata/sample2'; 2. Creating tablespaces Once DB_CREATE_FILE_DEST is set, the DATAFILE clause can be omitted from a CREATE TABLESPACE statement. The datafile is created in the location specified by DB_CREATE_FILE_DEST by default. For example: SQL> CREATE TABLESPACE tbs_2; Using Oracle-Managed Files 3-27 Scenarios for Using Oracle-Managed Files When the tbs_2 tablespace is dropped, its datafiles are automatically deleted. 3-28 Oracle9i Database Administrator’s Guide 4 Starting Up and Shutting Down This chapter describes the procedures for starting up and shutting down an Oracle database, and contains the following topics: ■ Starting Up a Database ■ Altering Database Availability ■ Shutting Down a Database ■ Quiescing a Database ■ Suspending and Resuming a Database See Also: For additional information specific to an Oracle Real Application Clusters environment: ■ Oracle9i Real Application Clusters Administration ■ Oracle9i Real Application Clusters Setup and Configuration Starting Up and Shutting Down 4-1 Starting Up a Database Starting Up a Database When you start up a database, you create an instance of that database, and you choose the state in which the database starts. Normally, you would start up an instance by mounting and opening the database, thus making it available for any valid user to connect to and perform typical data access operations. However, there are other options and these are also discussed in this section. This section contains the following topics relating to starting up an instance of a database: ■ Options for Starting Up a Database ■ Preparing to Start an Instance ■ Using SQL*Plus to Start Up a Database ■ Starting an Instance: Scenarios Options for Starting Up a Database There are options as to the method you use for starting up (and administering) an instance of your database. Using SQL*Plus To start up a database use SQL*Plus to connect to Oracle with administrator privileges and then issue the STARTUP command. While three methods are presented, using SQL*Plus is the only method that is within the scope of this book. Using Recovery Manager You can also use Recovery Manager (RMAN) to execute STARTUP (and SHUTDOWN) commands. You may prefer to do this if your are within the RMAN environment and do not want to invoke SQL*Plus. See Also: Oracle9i Recovery Manager User’s Guide Using Oracle Enterprise Manager You can choose to use the Oracle Enterprise Manager for administering your database, including starting it up and shutting it down. The Oracle Enterprise Manager is a separate Oracle product, that combines a graphical console, agents, common services, and tools to provide an integrated and comprehensive systems management platform for managing Oracle products. It enables you to perform the functions discussed in this book using a GUI interface, rather than command lines. 4-2 Oracle9i Database Administrator’s Guide Starting Up a Database See Also: ■ Oracle Enterprise Manager Concepts Guide ■ Oracle Enterprise Manager Administrator’s Guide Preparing to Start an Instance You must perform some preliminary steps before attempting to start an instance of your database using SQL*Plus. 1. Start SQL*Plus without connecting to the database: SQLPLUS /NOLOG 2. Connect to Oracle as SYSDBA: CONNECT username/password AS SYSDBA Now you are connected to Oracle and ready to start up an instance of your database. See Also: SQL*Plus User’s Guide and Reference for descriptions and syntax for the CONNECT, STARTUP, and SHUTDOWN commands. These commands are SQL*Plus commands. Using SQL*Plus to Start Up a Database You use the STARTUP command to start up a database instance. To start an instance, Oracle must read instance configuration parameters (the initialization parameters) from either a server parameter file or a traditional text initialization parameter file. When you issue the STARTUP command with no PFILE clause, Oracle reads the initialization parameters from a server parameter file (SPFILE) in a platform-specific default location. Note: For UNIX, the platform-specific default location (directory) for the server parameter file (or text initialization parameter file) is: $ORACLE_HOME/dbs For Windows NT and Windows 2000 the location is: $ORACLE_HOME\database Starting Up and Shutting Down 4-3 Starting Up a Database In the platform-specific default location, Oracle locates your initialization parameter file by examining filenames in the following order: 1. spfile$ORACLE_SID.ora 2. spfile.ora 3. init$ORACLE_SID.ora Note: The spfile.ora file is included in this search path because in a Real Application Clusters environment one server parameter file is used to store the initialization parameter settings for all instances. There is no instance specific location for storing a server parameter file. For more information about the server parameter file for a Real Application Clusters environment, see Oracle9i Real Application Clusters Administration. You can direct Oracle to read initialization parameters from a traditional text initialization parameter file, by using the PFILE clause of the STARTUP command. For example: STARTUP PFILE = /u01/oracle/dbs/init.ora Further, you can use this PFILE clause to start an instance with a nondefault server parameter file as follows: 1. Create a one line text initialization parameter file that contains only the SPFILE parameter. The value of the parameter is the nondefault server parameter file location. For example, create a text initialization parameter file /u01/oracle/dbs/spf_init.ora that contains only the following parameter: SPFILE = /u01/oracle/dbs/test_spfile.ora Note: You cannot use the IFILE initialization parameter within a text initialization parameter file to point to a server parameter file. In this context, you must use the SPFILE initialization parameter. 2. Start up the instance pointing to this initialization parameter file. 4-4 Oracle9i Database Administrator’s Guide Starting Up a Database STARTUP PFILE = /u01/oracle/dbs/spf_init.ora Since the server parameter file must reside on the machine running the database server, the above method also provides a means for a client machine to start a database that uses a server parameter file. It also eliminates the need for a client machine to maintain a client-side initialization parameter file. When the client machine reads the initialization parameter file containing the SPFILE parameter, it passes the value to the server where the specified server parameter file is read. You can start an instance in various modes: ■ ■ ■ Start the instance without mounting a database. This does not allow access to the database and usually would be done only for database creation or the re-creation of control files. Start the instance and mount the database, but leave it closed. This state allows for certain DBA activities, but does not allow general access to the database. Start the instance, and mount and open the database. This can be done in unrestricted mode, allowing access to all users, or in restricted mode, allowing access for database administrators only. Note: You cannot start a database instance if you are connected to the database through a shared server process. In addition, you can force the instance to start, or start the instance and have complete media recovery begin immediately. The STARTUP command options that you specify to achieve these states are illustrated in the following section. See Also: Chapter 2, "Creating an Oracle Database" for more information about initialization parameters, initialization parameter files, and server parameter files Starting an Instance: Scenarios The following scenarios describe and illustrate the various states in which you can start up an instance. Some restrictions apply when combining options of the STARTUP command. Starting Up and Shutting Down 4-5 Starting Up a Database Note: It is possible to encounter problems starting up an instance if control files, database files, or redo log files are not available. If one or more of the files specified by the CONTROL_FILES initialization parameter does not exist or cannot be opened when you attempt to mount a database, Oracle returns a warning message and does not mount the database. If one or more of the datafiles or redo log files is not available or cannot be opened when attempting to open a database, Oracle returns a warning message and does not open the database. See Also: SQL*Plus User’s Guide and Reference for information about the restrictions that apply when combining options of the STARTUP command Starting an Instance, and Mounting and Opening a Database Normal database operation means that an instance is started and the database is mounted and open. This mode allows any valid user to connect to the database and perform typical data access operations. Start an instance, read the initialization parameters from the default server parameter file location, and then mount and open the database by using the STARTUP command by itself (you can, of course, optionally specify a PFILE or SPFILE clause): STARTUP Starting an Instance Without Mounting a Database You can start an instance without mounting a database. Typically, you do so only during database creation. Use the STARTUP command with the NOMOUNT option: STARTUP NOMOUNT Starting an Instance and Mounting a Database You can start an instance and mount a database without opening it, allowing you to perform specific maintenance operations. For example, the database must be mounted but not open during the following tasks: 4-6 Oracle9i Database Administrator’s Guide Starting Up a Database Task For more information... Renaming datafiles Chapter 12, "Managing Datafiles" Adding, dropping, or renaming redo log files Chapter 7, "Managing the Online Redo Log" Enabling and disabling redo log archiving options Chapter 8, "Managing Archived Redo Logs" Performing full database recovery Oracle9i User-Managed Backup and Recovery Guide Oracle9i Recovery Manager User’s Guide Start an instance and mount the database, but leave it closed by using the STARTUP command with the MOUNT option: STARTUP MOUNT Restricting Access to a Database at Startup You can start an instance and mount and open a database in restricted mode so that the database is available only to administrative personnel (not general database users). Use this mode of database startup when you need to accomplish one of the following tasks: ■ Perform an export or import of database data ■ Perform a data load (with SQL*Loader) ■ Temporarily prevent typical users from using data ■ During certain migration and upgrade operations Typically, all users with the CREATE SESSION system privilege can connect to an open database. Opening a database in restricted mode allows database access only to users with both the CREATE SESSION and RESTRICTED SESSION system privilege. Only database administrators should have the RESTRICTED SESSION system privilege. Start an instance (and, optionally, mount and open the database) in restricted mode by using the STARTUP command with the RESTRICT option: STARTUP RESTRICT Later, use the ALTER SYSTEM statement to disable the RESTRICTED SESSION feature: Starting Up and Shutting Down 4-7 Starting Up a Database ALTER SYSTEM DISABLE RESTRICTED SESSION; If you open the database in nonrestricted mode and later find you need to restrict access, you can use the ALTER SYSTEM statement to do so, as described in "Restricting Access to an Open Database" on page 4-11. See Also: Oracle9i SQL Reference for more information on the ALTER SYSTEM statement Forcing an Instance to Start In unusual circumstances, you might experience problems when attempting to start a database instance. You should not force a database to start unless you are faced with the following: ■ ■ You cannot shut down the current instance with the SHUTDOWN NORMAL, SHUTDOWN IMMEDIATE, or SHUTDOWN TRANSACTIONAL commands. You experience problems when starting an instance. If one of these situations arises, you can usually solve the problem by starting a new instance (and optionally mounting and opening the database) using the STARTUP command with the FORCE option: STARTUP FORCE If an instance is running, STARTUP FORCE shuts it down with mode ABORT before restarting it. See Also: "Shutting Down with the ABORT Option" on page 4-13 to understand the side effects of aborting the current instance Starting an Instance, Mounting a Database, and Starting Complete Media Recovery If you know that media recovery is required, you can start an instance, mount a database to the instance, and have the recovery process automatically start by using the STARTUP command with the RECOVER option: STARTUP OPEN RECOVER If you attempt to perform recovery when no recovery is required, Oracle issues an error message. 4-8 Oracle9i Database Administrator’s Guide Altering Database Availability Automatic Database Startup at Operating System Start Many sites use procedures to enable automatic startup of one or more Oracle instances and databases immediately following a system start. The procedures for performing this task are specific to each operating system. For information about automatic startup, see your operating system specific Oracle documentation. Starting Remote Instances If your local Oracle server is part of a distributed database, you might want to start a remote instance and database. Procedures for starting and stopping remote instances vary widely depending on communication protocol and operating system. Altering Database Availability You can alter the availability of a database. You may want to do this in order to restrict access for maintenance reasons or to make the database read only. The following sections explain how to alter a database’s availability: ■ Mounting a Database to an Instance ■ Opening a Closed Database ■ Opening a Database in Read-Only Mode ■ Restricting Access to an Open Database Mounting a Database to an Instance When you need to perform specific administrative operations, the database must be started and mounted to an instance, but closed. You can achieve this scenario by starting the instance and mounting the database. To mount a database to a previously started, but not opened instance, use the SQL statement ALTER DATABASE with the MOUNT option as follows: ALTER DATABASE MOUNT See Also: "Starting an Instance and Mounting a Database" on page 4-6 for a list of operations that require the database to be mounted and closed (and procedures to start an instance and mount a database in one step) Starting Up and Shutting Down 4-9 Altering Database Availability Opening a Closed Database You can make a mounted but closed database available for general use by opening the database. To open a mounted database, use the ALTER DATABASE statement with the OPEN option: ALTER DATABASE OPEN After executing this statement, any valid Oracle user with the CREATE SESSION system privilege can connect to the database. Opening a Database in Read-Only Mode Opening a database in read-only mode enables you to query an open database while eliminating any potential for online data content changes. While opening a database in read-only mode guarantees that datafile and redo log files are not written to, it does not restrict database recovery or operations that change the state of the database without generating redo. For example, you can take datafiles offline or bring them online since these operations do not effect data content. If a query against a database in read-only mode uses temporary tablespace, for example to do disk sorts, then the issuer of the query must have a locally managed tablespace assigned as the default temporary tablespace. Otherwise, the query will fail. This is explained in "Creating a Locally Managed Temporary Tablespace" on page 11-13. Ideally, you open a database in read-only mode when you alternate a standby database between read-only and recovery mode. Be aware that these are mutually exclusive modes. The following statement opens a database in read-only mode: ALTER DATABASE OPEN READ ONLY; You can also open a database in read-write mode as follows: ALTER DATABASE OPEN READ WRITE; However, read-write is the default mode. Note: You cannot use the RESETLOGS clause with a READ ONLY clause. 4-10 Oracle9i Database Administrator’s Guide Shutting Down a Database See Also: Oracle9i SQL Reference for more information about the ALTER DATABASE statement Restricting Access to an Open Database To place an instance in restricted mode, use the SQL statement ALTER SYSTEM with the ENABLE RESTRICTED SESSION clause. After placing an instance in restricted mode, you should consider killing all current user sessions before performing any administrative tasks. To lift an instance from restricted mode, use ALTER SYSTEM with the DISABLE RESTRICTED SESSION option. See Also: "Restricting Access to a Database at Startup" on page 4-7 to learn some reasons for placing an instance in restricted mode Shutting Down a Database To initiate database shutdown, use the SQL*Plus SHUTDOWN command. Control is not returned to the session that initiates a database shutdown until shutdown is complete. Users who attempt connections while a shutdown is in progress receive a message like the following: ORA-01090: shutdown in progress - connection is not permitted Note: You cannot shut down a database if you are connected to the database through a shared server process. To shut down a database and instance, you must first connect as SYSOPER or SYSDBA. There are several modes for shutting down a database. These are discussed in the following sections: ■ Shutting Down with the NORMAL Option ■ Shutting Down with the IMMEDIATE Option ■ Shutting Down with the TRANSACTIONAL Option ■ Shutting Down with the ABORT Option Starting Up and Shutting Down 4-11 Shutting Down a Database Shutting Down with the NORMAL Option To shut down a database in normal situations, use the SHUTDOWN command with the NORMAL option: SHUTDOWN NORMAL Normal database shutdown proceeds with the following conditions: ■ ■ No new connections are allowed after the statement is issued. Before the database is shut down, Oracle waits for all currently connected users to disconnect from the database. The next startup of the database will not require any instance recovery procedures. Shutting Down with the IMMEDIATE Option Use immediate database shutdown only in the following situations: ■ To initiate an automated and unattended backup ■ When a power shutdown is going to occur soon ■ When the database or one of its applications is functioning irregularly and you cannot contact users to ask them to log off or they are unable to log off To shut down a database immediately, use the SHUTDOWN command with the IMMEDIATE option: SHUTDOWN IMMEDIATE Immediate database shutdown proceeds with the following conditions: ■ ■ ■ No new connections are allowed, nor are new transactions allowed to be started, after the statement is issued. Any uncommitted transactions are rolled back. (If long uncommitted transactions exist, this method of shutdown might not complete quickly, despite its name.) Oracle does not wait for users currently connected to the database to disconnect. Oracle implicitly rolls back active transactions and disconnects all connected users. The next startup of the database will not require any instance recovery procedures. 4-12 Oracle9i Database Administrator’s Guide Shutting Down a Database Shutting Down with the TRANSACTIONAL Option When you want to perform a planned shutdown of an instance while allowing active transactions to complete first, use the SHUTDOWN command with the TRANSACTIONAL option: SHUTDOWN TRANSACTIONAL Transactional database shutdown proceeds with the following conditions: ■ ■ ■ No new connections are allowed, nor are new transactions allowed to be started, after the statement is issued. After all transactions have completed, any client still connected to the instance is disconnected. At this point, the instance shuts down just as it would when a SHUTDOWN IMMEDIATE statement is submitted. The next startup of the database will not require any instance recovery procedures. A transactional shutdown prevents clients from losing work, and at the same time, does not require all users to log off. Shutting Down with the ABORT Option You can shut down a database instantaneously by aborting the database’s instance. If possible, perform this type of shutdown only in the following situations: ■ ■ ■ The database or one of its applications is functioning irregularly and none of the other types of shutdown works. You need to shut down the database instantaneously (for example, if you know a power shutdown is going to occur in one minute). You experience problems when starting a database instance. When you must do a database shutdown by aborting transactions and user connections, issue the SHUTDOWN command with the ABORT option: SHUTDOWN ABORT An aborted database shutdown proceeds with the following conditions: ■ No new connections are allowed, nor are new transactions allowed to be started, after the statement is issued. Starting Up and Shutting Down 4-13 Quiescing a Database ■ ■ ■ Current client SQL statements being processed by Oracle are immediately terminated. Uncommitted transactions are not rolled back. Oracle does not wait for users currently connected to the database to disconnect. Oracle implicitly disconnects all connected users. The next startup of the database will require instance recovery procedures. Quiescing a Database There are times when there is a need to put a database into a state where only DBA transactions, queries, fetches, or PL/SQL statements are allowed. This is called a quiesced state, in the sense that there are no ongoing non-DBA transactions, queries, fetches, or PL/SQL statements in the system. This quiesced state allows you or other administrators to perform actions that cannot safely be done otherwise. These actions are categorized as follows: ■ ■ Actions that can fail if concurrent user transactions access the same object. For example, changing the schema of a database table or adding a column to an existing table where a no-wait lock is required. Actions whose undesirable intermediate effect can be seen by concurrent user transactions. For example, a multistep procedure for reorganizing a table where the table is first exported, then dropped, and finally imported. A concurrent user who attempted to access the table after it was dropped, but before import, would see disturbing results. Without the ability to quiesce the database, you would be required to shut down the database and reopen it in restricted mode. This is a serious restriction, especially for systems requiring 24 x 7 availability. Quiescing a database is much less of a restriction because it eliminates the disruption to users and downtime associated with shutting down and restarting the database. Note: For this release of Oracle9i, in the quiesce database context a DBA is defined as user SYS or SYSTEM. Other users, including those with the DBA role are not allowed to issue the ALTER SYSTEM QUIESCE DATABASE statement or proceed after the database is quiesced. 4-14 Oracle9i Database Administrator’s Guide Quiescing a Database Placing a Database into a Quiesced State To place a database into a quiesced state, issue the following statement: ALTER SYSTEM QUIESCE RESTRICTED; Any non-DBA active sessions will proceed until they become inactive. An active session is defined as a session that is currently inside of a transaction, a query, a fetch, or a PL/SQL statement; or a session that is currently holding any shared resources (for example, enqueues). No inactive sessions are allowed to become active. If a user, for example, issues a SQL query in an attempt to force an inactive session to become active, the query will appear to be hung. When the database is later unquiesced, the session is resumed, and the blocked action (for example, the previously mentioned SQL query) will be processed. Once all non-DBA sessions become inactive, the ALTER SYSTEM QUIESCE RESTRICTED statement finishes, and the database is considered as in a quiesced state. In an Oracle Real Application Clusters environment, this statement affects all instances, not just the one that issues the statement. Note: You must have the Database Resource Manager feature activated, and it must have been activated since instance startup (all instances in an Oracle Real Application Clusters environment) to successfully issue the ALTER SYSTEM QUIESCE RESTRICTED statement. It is through the facilities of the Database Resource Manager that non-DBA sessions are prevented from becoming active. Also, while this statement is in effect, any attempt to change the current resource plan will be queued until after the system is unquiesced. For information about the Database Resource Manager, see Chapter 27, "Using the Database Resource Manager". The ALTER SYSTEM QUIESCE RESTRICTED statement may wait a long time for active sessions to become inactive. If you interrupt the request, or if your session abnormally terminates for some reason before all active sessions are quiesced, Oracle will automatically undo any partial effects of the statement. If a query is carried out by successive multiple Oracle Call Interface (OCI) fetches, the ALTER SYSTEM QUIESCE RESTRICTED statement does not wait for all fetches to finish; it only waits for the current fetch to finish. Starting Up and Shutting Down 4-15 Quiescing a Database For both dedicated and shared server connections, all non-DBA logins after this statement is issued are queued by the Database Resource Manager, and are not allowed to proceed. To the user, it appears as if the login is hung. The login will resume when the database is unquiesced. The database remains in the quiesced state even if the session that issued the statement exits. A DBA must log in to the database to issue the statement that specifically unquiesces the database. While in the quiesced state, you cannot use file system copy to backup the database’s datafiles as cold backups, even if you do a checkpoint on every instance. The reason for this is that in the quiesced state the file headers of online datafiles continue to look like they are being accessed. They do not look the same as if a clean shutdown were done. Similarly, to perform a hot backup of the datafiles of any online tablespace while the database is in a quiesced state, you are still required to first place the tablespace into backup mode using the ALTER TABLESPACE... BEGIN BACKUP statement. Restoring the System to Normal Operation The following statement restores the database to normal operation: ALTER SYSTEM UNQUIESCE; All non-DBA activity is allowed to proceed. In an Oracle Real Application Clusters environment, this statement is not required to be issued from the same session, or even the same instance, as that which imposed the quiesce state. If the session issuing the ALTER SYSTEM UNQUIESCE statement should terminate abnormally, the Oracle database server ensures that the unquiesce operation finishes. Viewing the Quiesce State of an Instance The V$INSTANCE view can be queried to see the current state of an instance. It contains a column named ACTIVE_STATE, whose values are shown in the following table: 4-16 ACTIVE_STATE Description NORMAL Normal unquiesced state QUIESCING Being quiesced, but there are still active non-DBA sessions running QUIESCED Quiesced, no active non-DBA sessions are active or allowed Oracle9i Database Administrator’s Guide Suspending and Resuming a Database Suspending and Resuming a Database The ALTER SYSTEM SUSPEND statement suspends a database by halting all input and output (I/O) to datafiles (file header and file data) and control files, thus allowing a database to be backed up without I/O interference. When the database is suspended all preexisting I/O operations are allowed to complete and any new database accesses are placed in a queued state. The suspend command suspends the database, and is not specific to an instance. Therefore, in an Oracle Real Application Clusters environment, if the suspend command is entered on one system, then internal locking mechanisms will propagate the halt request across instances, thereby quiescing all active instances in a given cluster. However, do not start a new instance while you suspend another instance, since the new instance will not be suspended. Use the ALTER SYSTEM RESUME statement to resume normal database operations. You can specify the SUSPEND and RESUME from different instances. For example, if instances 1, 2, and 3 are running, and you issue an ALTER SYSTEM SUSPEND statement from instance 1, then you can issue a RESUME from instance 1, 2, or 3 with the same effect. The suspend/resume feature is useful in systems that allow you to mirror a disk or file and then split the mirror, providing an alternative backup and restore solution. If you use a system that is unable to split a mirrored disk from an existing database while writes are occurring, then you can use the suspend/resume feature to facilitate the split. The suspend/resume feature is not a suitable substitute for normal shutdown operations, however, since copies of a suspended database can contain uncommitted updates. Caution: Do not use the ALTER SYSTEM SUSPEND statement as a substitute for placing a tablespace in hot backup mode. Precede any database suspend operation by an ALTER TABLESPACE BEGIN BACKUP statement. The following statements illustrate ALTER SYSTEM SUSPEND/RESUME usage. The V$INSTANCE view is queried to confirm database status. SQL> ALTER SYSTEM SUSPEND; System altered SQL> SELECT DATABASE_STATUS FROM V$INSTANCE; DATABASE_STATUS Starting Up and Shutting Down 4-17 Suspending and Resuming a Database --------SUSPENDED SQL> ALTER SYSTEM RESUME; System altered SQL> SELECT DATABASE_STATUS FROM V$INSTANCE; DATABASE_STATUS --------ACTIVE Oracle9i User-Managed Backup and Recovery Guide for details about backing up a database using the database suspend/resume feature See Also: 4-18 Oracle9i Database Administrator’s Guide Part II Oracle Server Processes and Storage Structure Part II presents the Oracle database server processes and underlying database storage structures that support its operation. It contains the following chapters: ■ Chapter 5, "Managing Oracle Processes" ■ Chapter 6, "Managing Control Files" ■ Chapter 7, "Managing the Online Redo Log" ■ Chapter 8, "Managing Archived Redo Logs" ■ Chapter 9, "Using LogMiner to Analyze Redo Logs" ■ Chapter 10, "Managing Job Queues" ■ Chapter 11, "Managing Tablespaces" ■ Chapter 12, "Managing Datafiles" ■ Chapter 13, "Managing Undo Space" 5 Managing Oracle Processes This chapter describes how to manage the processes of an Oracle instance, and contains the following topics: ■ Server Processes ■ Configuring Oracle for the Shared Server ■ About Oracle Background Processes ■ Monitoring the Processes of an Oracle Instance ■ Managing Processes for Parallel Execution ■ Managing Processes for External Procedures ■ Terminating Sessions Managing Oracle Processes 5-1 Server Processes Server Processes Oracle creates server processes to handle the requests of user processes connected to an instance. A server process can be either a dedicated server process, where one server process services only one user process, or if your database server is configured for shared server, it can be a shared server process, where a server process can service multiple user processes. See Also: Oracle9i Database Concepts Dedicated Server Processes Figure 5–1, "Oracle Dedicated Server Processes" illustrates how dedicated server processes work. In this diagram two user processes are connected to Oracle through dedicated server processes. In general, it is better to be connected through a dispatcher and use a shared server process. This is illustrated in Figure 5–2, "Oracle Shared Server Processes". A shared server process can be more efficient because it keeps the number of processes required for the running instance low. In the following situations, however, users and administrators should explicitly connect to an instance using a dedicated server process: ■ ■ To submit a batch job (for example, when a job can allow little or no idle time for the server process) To use Recovery Manager to back up, restore, or recover a database To request a dedicated server connection when Oracle is configured for shared server, users must connect using a net service name that is configured to use a dedicated server. Specifically, the net service name value should include the SERVER=DEDICATED clause in the connect descriptor. See Also: Oracle9i Net Services Administrator’s Guide for more information about requesting a dedicated server connection 5-2 Oracle9i Database Administrator’s Guide Server Processes Figure 5–1 Oracle Dedicated Server Processes User Process User Process Application Code Application Code Client Workstation Database Server Dedicated Server Process Oracle Server Code Oracle Server Code Program Interface System Global Area Shared Server Processes Consider an order entry system with dedicated server processes. A customer places an order as a clerk enters the order into the database. For most of the transaction, the clerk is on the telephone talking to the customer and the server process dedicated to the clerk’s user process remains idle. The server process is not needed during most of the transaction, and the system is slower for other clerks entering orders because the idle server process is holding system resources. The shared server architecture eliminates the need for a dedicated server process for each connection (see Figure 5–2). Managing Oracle Processes 5-3 Server Processes Figure 5–2 Oracle Shared Server Processes User Process Code Code Code Application Code Code Code Code Code Code 7 Client Workstation Database Server 1 Dispatcher Processes 6 Oracle Oracle Oracle Oracle Server Code Server Code Server Code Server Code Shared server processes 3 4 2 System Global Area Request Queue 5 Response Queues In a shared server configuration, client user processes connect to a dispatcher. A dispatcher can support multiple client connections concurrently. Each client connection is bound to a virtual circuit. A virtual circuit is a piece of shared memory used by the dispatcher for client database connection requests and replies. The dispatcher places a virtual circuit on a common queue when a request arrives. 5-4 Oracle9i Database Administrator’s Guide Configuring Oracle for the Shared Server An idle shared server picks up the virtual circuit from the common queue, services the request, and relinquishes the virtual circuit before attempting to retrieve another virtual circuit from the common queue. This approach enables a small pool of server processes to serve a large number of clients. A significant advantage of shared server architecture over the dedicated server model is the reduction of system resources, enabling the support of an increased number of users. The shared server architecture requires Oracle Net Services. User processes targeting the shared server must connect through Oracle Net Services, even if they are on the same machine as the Oracle instance. There are several things that must be done to configure your system for shared server. These are discussed in the next section. See Also: Oracle9i Net Services Administrator’s Guide for more information about shared server, including additional features such as connection pooling Configuring Oracle for the Shared Server You activate shared server by setting database initialization parameters. Shared server requires that an Oracle Net Services listener process be active. This section discusses setting shared server initialization parameters and how to alter them. This section contains the following topics: ■ Initialization Parameters for Shared Server ■ Setting the Initial Number of Dispatchers (DISPATCHERS) ■ Setting the Initial Number of Shared Servers (SHARED_SERVERS) ■ Modifying Dispatcher and Server Processes ■ Monitoring Shared Server Initialization Parameters for Shared Server The initialization parameters controlling shared server are: Parameter Description The following parameter is required by shared server: DISPATCHERS Configures dispatcher processes in the shared server architecture. Managing Oracle Processes 5-5 Configuring Oracle for the Shared Server Parameter Description The following parameters are optional (if not specified, Oracle selects defaults): MAX_DISPATCHERS Specifies the maximum number of dispatcher processes that can run simultaneously. SHARED_SERVERS Specifies the number of shared server processes created when an instance is started up. MAX_SHARED_SERVERS Specifies the maximum number of shared server processes that can run simultaneously. CIRCUITS Specifies the total number of virtual circuits that are available for inbound and outbound network sessions. SHARED_SERVER_SESSIONS Specifies the total number of shared server user sessions to allow. Setting this parameter enables you to reserve user sessions for dedicated servers. Other parameters affected by shared server that may require adjustment: LARGE_POOL_SIZE Specifies the size in bytes of the large pool allocation heap. Shared server may force the default value to be set too high, causing performance problems or problems starting the database. SESSIONS Specifies the maximum number of sessions that can be created in the system. May need to be adjusted for shared server. See Also: ■ Oracle9i Net Services Reference Guide ■ Oracle9i Database Reference Setting the Initial Number of Dispatchers (DISPATCHERS) The number of dispatcher processes started at instance startup is controlled by the DISPATCHERS initialization parameter. You can specify multiple DISPATCHERS parameters in the initialization file, but they must be adjacent to each other. Internally, Oracle will assign an INDEX value to each DISPATCHERS parameter, so that you can later specifically refer to that DISPATCHERS parameter in an ALTER SYSTEM statement. The appropriate number of dispatcher processes for each instance depends upon the performance you want from your database, the host operating system’s limit on the number of connections for each process (which is operating system dependent), 5-6 Oracle9i Database Administrator’s Guide Configuring Oracle for the Shared Server and the number of connections required for each network protocol. The instance must be able to provide as many connections as there are concurrent users on the database system. After instance startup, you can start more dispatcher processes if needed. This is discussed in "Adding and Removing Dispatcher Processes" on page 5-8. A ratio of 1 dispatcher for every 1000 connections works well for typical systems, but round up to the next integer. For example, if you anticipate 1500 connections at peak time, then you may want to configure 2 dispatchers. Being too aggressive in your estimates is not beneficial, because configuring too many dispatchers can degrade performance. Use this ratio as your guide, but tune according to your particular circumstances. The following are some examples of setting the DISPATCHERS initialization parameter. Example: Typical This is a typical example of setting the DISPATCHERS initialization parameter. DISPATCHERS="(PROTOCOL=TCP)" Example: Forcing the IP Address Used for Dispatchers To force the IP address used for the dispatchers, enter the following: DISPATCHERS="(ADDRESS=(PROTOCOL=TCP)\ (HOST=144.25.16.201))(DISPATCHERS=2)" This will start two dispatchers that will listen in on the IP address, which must be a valid IP address for the host that the instance is on. Example: Forcing the Port Used by Dispatchers To force the exact location of dispatchers, add the PORT as follows: DISPATCHERS="(ADDRESS=(PROTOCOL=TCP)(PORT=5000))" DISPATCHERS="(ADDRESS=(PROTOCOL=TCP)(PORT=5001))" Setting the Initial Number of Shared Servers (SHARED_SERVERS) The SHARED_SERVERS initialization parameter specifies the number of shared server processes that you want to create when an instance is started up. Oracle dynamically adjusts the number of shared server processes based on the length of the request queue. The number of shared server processes that can be created Managing Oracle Processes 5-7 Configuring Oracle for the Shared Server ranges between the values of the initialization parameters SHARED_SERVERS and MAX_SHARED_SERVERS. Typical systems seem to stabilize at a ratio of one shared server for every ten connections. For OLTP applications, the connections-to-servers ratio could be higher. This could happen when the rate of requests is low, or when the ratio of server usage to request is low. On the other hand, in applications where the rate of requests is high, or the server usage-to-request ratio is high, the connections-to-server ratio could be lower. Set MAX_SHARED_SERVERS to a reasonable value based on your application. Oracle provides good defaults for SHARED_SERVERS and MAX_SHARED_SERVERS for a typical configuration, but the optimal values for these settings can be different depending upon your application. Note: On Windows NT, take care when setting MAX_SHARED_ SERVERS to a high value because each server is a thread in a common process. MAX_SHARED_SERVERS is a static initialization parameter, so you cannot change it without shutting down your database. However, SHARED_SERVERS is a dynamic initialization parameter and can be changed using an ALTER SYSTEM statement. Modifying Dispatcher and Server Processes You can modify the settings for DISPATCHERS and SHARED_SERVERS dynamically when an instance is running. If you have the ALTER SYSTEM privilege, you can use the ALTER SYSTEM statement to make such changes. See Also: Oracle9i SQL Reference for information about the ALTER SYSTEM statement Adding and Removing Dispatcher Processes You can control the number of dispatcher processes in the instance. If monitoring the V$QUEUE, V$DISPATCHER and V$DISPATCHER_RATE views indicates that the load on the dispatcher processes is consistently high, starting additional dispatcher processes to route user requests may improve performance. In contrast, if the load on dispatchers is consistently low, reducing the number of dispatchers may improve performance. To change the number of dispatcher processes, use the SQL statement ALTER SYSTEM. You can start new dispatcher processes for an existing DISPATCHERS 5-8 Oracle9i Database Administrator’s Guide Configuring Oracle for the Shared Server value, or you can add new DISPATCHERS values. Dispatchers can be added up to the limit specified by MAX_DISPATCHERS. If you reduce the number of dispatchers for a particular shared server dispatcher value, the dispatchers are not immediately removed. Rather, as users disconnect, Oracle is eventually able to terminate dispatchers down to the limit you specify in DISPATCHERS. The following statement dynamically changes the number of dispatcher processes for the TCP/IP protocol to 5, and adds dispatcher processes for the TCP/IP with SSL (TCPS) protocol. There was no DISPATCHERS initialization parameter for the TCPS protocol (the only DISPATCHERS parameter was the one for the TCP protocol), so this statement effectively adds one. ALTER SYSTEM SET DISPATCHERS = '(PROTOCOL=TCP)(DISPATCHERS=5) (INDEX=0)', '(PROTOCOL=TCPS)(DISPATCHERS=2) (INDEX=1)'; If there are currently fewer than five dispatcher processes for TCP, Oracle creates new ones. If there are currently more than five, Oracle terminates some of them after the connected users disconnect. Note: The INDEX keyword can be used to identify which DISPATCHERS parameter to modify. The INDEX value can range from 0 to n, where n is one less than the defined number of DISPATCHERS parameters. If your ALTER SYSTEM statement specifies an INDEX value equal to n+1, where n is the current number of dispatchers, a new DISPATCHERS parameter is added. To identify the index number assigned to an DISPATCHERS parameter, query the CONF_INDX value in the V$DISPATCHER view. Shutting Down Specific Dispatcher Processes It is possible to shut down specific dispatcher processes. To identify the name of the specific dispatcher process to shut down, use the V$DISPATCHER dynamic performance view. SELECT NAME, NETWORK FROM V$DISPATCHER; NAME NETWORK ---- ------------------------------------------------------------------- Managing Oracle Processes 5-9 Configuring Oracle for the Shared Server D000 (ADDRESS=(PROTOCOL=tcp)(HOST=rbaylis-hpc.us.oracle.com)(PORT=3499)) D001 (ADDRESS=(PROTOCOL=tcp)(HOST=rbaylis-hpc.us.oracle.com)(PORT=3531)) D002 (ADDRESS=(PROTOCOL=tcp)(HOST=rbaylis-hpc.us.oracle.com)(PORT=3532)) Each dispatcher is uniquely identified by a name of the form Dnnn. To shut down dispatcher D002, issue the following statement: ALTER SYSTEM SHUTDOWN IMMEDIATE 'D002'; The IMMEDIATE keyword stops the dispatcher from accepting new connections and Oracle immediately terminates all existing connections through that dispatcher. After all sessions are cleaned up, the dispatcher process shuts down. If IMMEDIATE were not specified, the dispatcher would wait until all of its users disconnected and all of its connections terminated before shutting down. Changing the Minimum Number of Shared Server Processes After starting an instance, you can change the minimum number of shared server processes by using the SQL statement ALTER SYSTEM. Oracle will eventually terminate servers that are idle when there are more shared servers than the minimum limit you specify. If you set SHARED_SERVERS to 0, Oracle terminates all current servers when they become idle and does not start any new servers until you increase SHARED_ SERVERS. Thus, setting SHARED_SERVERS to 0 may be used to effectively disable shared server. The following statement dynamically sets the minimum number of shared server processes to two: ALTER SYSTEM SET SHARED_SERVERS = 2; Monitoring Shared Server The following are useful views for obtaining information about your shared server configuration and for monitoring performance. 5-10 View Description V$DISPATCHER Provides information on the dispatcher processes, including name, network address, status, various usage statistics, and index number. V$DISPATCHER_RATE Provides rate statistics for the dispatcher processes. Oracle9i Database Administrator’s Guide About Oracle Background Processes View Description V$QUEUE Contains information on the shared server message queues. V$SHARED_SERVER Contains information on the shared server processes. V$CIRCUIT Contains information about virtual circuits, which are user connections to the database through dispatchers and servers. V$SHARED_SERVER_MONITOR Contains information for tuning shared server. V$SGA Contains size information about various system global area (SGA) groups. May be useful when tuning shared server. V$SGASTAT Detailed statistical information about the SGA, useful for tuning. V$SHARED_POOL_RESERVED Lists statistics to help tune the reserved pool and space within the shared pool. See Also: ■ ■ Oracle9i Database Reference for a detailed description of these views Oracle9i Database Performance Tuning Guide and Reference for specific information about monitoring and tuning shared server About Oracle Background Processes To maximize performance and accommodate many users, a multiprocess Oracle system uses some additional processes called background processes. Background processes consolidate functions that would otherwise be handled by multiple Oracle programs running for each user process. Background processes asynchronously perform I/O and monitor other Oracle processes to provide increased parallelism for better performance and reliability. The following are some basic Oracle background processes, many of which are discussed in more detail elsewhere in this book. The use of additional Oracle database server features or options can cause more background processes to be present. For example, if you use Advanced Queuing, the queue monitor (QMNn) background process is present, or if you specified the FILE_MAPPING initialization parameter for mapping datafiles to physical devices on a storage subsystem, then the LMON process is present. Managing Oracle Processes 5-11 About Oracle Background Processes Process Name Description Database writer (DBWn) The database writer writes modified blocks from the database buffer cache to the datafiles. Oracle allows a maximum of 20 database writer processes (DBW0-DBW9 and DBWa-DBWj). The initialization parameter DB_WRITER_ PROCESSES specifies the number of DBWn processes. Oracle selects an appropriate default setting for this initialization parameter (or might adjust a user specified setting) based upon the number of CPUs and the number of processor groups. For more information about setting the DB_WRITER_PROCESSES initialization parameter, see the Oracle9i Database Performance Tuning Guide and Reference. Log writer (LGWR) The log writer process writes redo log entries to disk. Redo log entries are generated in the redo log buffer of the system global area (SGA), and LGWR writes the redo log entries sequentially into an online redo log file. If the database has a multiplexed redo log, LGWR writes the redo log entries to a group of online redo log files. See Chapter 7, "Managing the Online Redo Log" for information about the log writer process. Checkpoint (CKPT) At specific times, all modified database buffers in the system global area are written to the datafiles by DBWn. This event is called a checkpoint. The checkpoint process is responsible for signalling DBWn at checkpoints and updating all the datafiles and control files of the database to indicate the most recent checkpoint. System monitor (SMON) The system monitor performs crash recovery when a failed instance starts up again. In a cluster database (Oracle9i Real Application Clusters), the SMON process of one instance can perform instance recovery for other instances that have failed. SMON also cleans up temporary segments that are no longer in use and recovers dead transactions skipped during crash and instance recovery because of file-read or offline errors. These transactions are eventually recovered by SMON when the tablespace or file is brought back online. SMON also coalesces free extents within the database’s dictionary-managed tablespaces to make free space contiguous and easier to allocate (see "Coalescing Free Space in Dictionary-Managed Tablespaces" on page 11-16). Process monitor (PMON) The process monitor performs process recovery when a user process fails. PMON is responsible for cleaning up the cache and freeing resources that the process was using. PMON also checks on the dispatcher processes (see below) and server processes and restarts them if they have failed. Archiver (ARCn) One or more archiver processes copy the online redo log files to archival storage when they are full or a log switch occurs. Archiver processes are the subject of Chapter 8, "Managing Archived Redo Logs". 5-12 Oracle9i Database Administrator’s Guide Monitoring the Processes of an Oracle Instance Process Name Description Recoverer (RECO) The recoverer process is used to resolve distributed transactions that are pending due to a network or system failure in a distributed database. At timed intervals, the local RECO attempts to connect to remote databases and automatically complete the commit or rollback of the local portion of any pending distributed transactions. For information about this process and how to start it, see Chapter 32, "Managing Distributed Transactions". Dispatcher (Dnnn) Dispatchers are optional background processes, present only when the shared server configuration is used. Shared server was discussed previously in "Configuring Oracle for the Shared Server" on page 5-5. Global Cache Service (LMS) In an Oracle Real Application Clusters environment, this process manages resources and provides inter-instance resource control. See: Coordinator job queue process (CJQ0) ■ Oracle9i Real Application Clusters Concepts ■ Oracle9i Real Application Clusters Setup and Configuration. This is the coordinator of job queue processes for an instance. It monitors the JOB$ table (table of jobs in the job queue) and starts job queue processes (Jnnn) as needed to execute jobs The Jnnn processes execute job requests created by the DBMS_JOBS package. This is the subject of Chapter 10, "Managing Job Queues" Additionally, up to 1000 Jnnn processes can automatically refresh materialized views. They wake up periodically and refresh any materialized views that are scheduled to be refreshed. For information about creating and refreshing materialized views, see: ■ Oracle9i Replication ■ Oracle9i Replication Management API Reference. Yet another function of the Jnnn processes is to propagate queued messages to queues on other databases. See Oracle9i Application Developer’s Guide - Advanced Queuing for information on propagating queued messages. Unlike many Oracle background processes, if a job queue process or the coordinator (CJQ0) fails, it does not cause instance failure. See Also: Oracle9i Database Concepts for more information about Oracle’s background processes Monitoring the Processes of an Oracle Instance This section lists some of the data dictionary views that you can use to monitor an Oracle instance. These views are more general in their scope. There are other views, more specific to a process, that are discussed in the section of this book where the Managing Oracle Processes 5-13 Monitoring the Processes of an Oracle Instance process is described. Also presented are scripts and a view for monitoring the status of locks. See Also: ■ ■ Oracle9i Database Reference contains detailed descriptions of these views Oracle9i Database Performance Tuning Guide and Reference provides information for resolving performance problems and conflicts that may be revealed through the monitoring of these views Process and Session Views These views provide process and session specific information: 5-14 View Description V$PROCESS Contains information about the currently active processes V$SESSION Lists session information for each current session V$SESS_IO Contains I/O statistics for each user session V$SESSION_LONGOPS This view displays the status of various operations that run for longer than 6 seconds (in absolute time). These operations currently include many backup and recovery functions, statistics gathering, and query execution. More operations are added for every Oracle release. V$SESSION_WAIT Lists the resources or events for which active sessions are waiting V$SYSSTAT Contains session statistics V$RESOURCE_LIMIT Provides information about current and maximum global resource utilization for some system resources V$SQLAREA Contains statistics about shared SQL area and contains one row for each SQL string. Also provides statistics about SQL statements that are in memory, parsed, and ready for execution V$LATCH Contains statistics for non-parent latches and summary statistics for parent latches Oracle9i Database Administrator’s Guide Monitoring the Processes of an Oracle Instance Monitoring Locks The utllockt.sql script displays, in tree-structured fashion, the sessions in the system that are waiting for locks and the locks that they are waiting for. Using an ad hoc query tool, such as SQL*Plus, the script prints the sessions in the system that are waiting for locks and the corresponding blocking locks. The location of this script file is operating system dependent; see your operating system specific Oracle documentation. A second script, catblock.sql, creates the lock views that utllockt.sql needs, so you must run it before running utllockt.sql. The following view can be used for monitoring locks: View Description V$LOCK Lists the locks currently held by the Oracle server and outstanding requests for a lock or latch Trace Files and the Alert File Each server and background process can write to an associated trace file. When an internal error is detected by a process, it dumps information about the error to its trace file. Some of the information written to a trace file is intended for the database administrator, while other information is for Oracle Support Services. Trace file information is also used to tune applications and instances. The alert file, or alert log, is a special trace file. The alert file of a database is a chronological log of messages and errors, which includes the following: ■ ■ ■ ■ ■ All internal errors (ORA-600), block corruption errors (ORA-1578), and deadlock errors (ORA-60) that occur Administrative operations, such as CREATE, ALTER, and DROP statements and STARTUP, SHUTDOWN, and ARCHIVELOG statements Several messages and errors relating to the functions of shared server and dispatcher processes Errors occurring during the automatic refresh of a materialized view The values of all initialization parameters at the time the database and instance start Oracle uses the alert file to keep a log of these special operations as an alternative to displaying such information on an operator’s console (although many systems display information on the console). If an operation is successful, a "completed" message is written in the alert file, along with a timestamp. Managing Oracle Processes 5-15 Monitoring the Processes of an Oracle Instance Initialization parameters controlling the location and size of trace files are: ■ BACKGROUND_DUMP_DEST ■ USER_DUMP_DEST ■ MAX_DUMP_FILE_SIZE These parameters are discussed in the sections that follow. See Also: Oracle9i Database Reference for information about initialization parameters that control the writing to trace files Using the Trace Files You should periodically check the alert file and other trace files of an instance to see if the background processes have encountered errors. For example, when the Log Writer process (LGWR) cannot write to a member of a group, an error message indicating the nature of the problem is written to the LGWR trace file and the database’s alert file. If you see such error messages, a media or I/O problem has occurred, and should be corrected immediately. Oracle also writes values of initialization parameters to the alert file, in addition to other important statistics. For example, when you shut down an instance normally or immediately, Oracle writes the highest number of sessions concurrently connected to the instance, since the instance started, to the alert file. You can use this number to see if you need to upgrade your Oracle session license. Specifying the Location of Trace Files All trace files for background processes and the alert file are written to the destination directory specified by the initialization parameter BACKGROUND_DUMP_ DEST. All trace files for server processes are written to the destination directory specified by the initialization parameter USER_DUMP_DEST. The names of trace files are operating system specific, but each file usually includes the name of the process writing the file (such as LGWR and RECO). See Also: Your operating system specific Oracle documentation for information about the names of trace files Controlling the Size of Trace Files You can control the maximum size of all trace files (excluding the alert file) using the initialization parameter MAX_DUMP_FILE_SIZE. This limit is set as a number of operating system blocks. To control the size of an alert file, you must manually delete the file when you no longer need it; otherwise Oracle continues to append to 5-16 Oracle9i Database Administrator’s Guide Monitoring the Processes of an Oracle Instance the file. You can safely delete the alert file while the instance is running, although you might want to make an archived copy of it first. Controlling When Oracle Writes to Trace Files Background processes always write to a trace file when appropriate. In the case of the ARCn background process, it is possible, through an initialization parameter, to control the amount and type of trace information that is produced. This is described in "Controlling Trace Output Generated by the Archivelog Process" on page 8-21. Other background processes do not have this flexibility. Trace files are written on behalf of server processes whenever internal errors occur. Additionally, setting the initialization parameter SQL_TRACE = TRUE causes the SQL trace facility to generate performance statistics for the processing of all SQL statements for an instance and write them to the USER_DUMP_DEST directory. Optionally, trace files can be generated for server processes at user request. Regardless of the current value of the SQL_TRACE initialization parameter, each session can enable or disable trace logging on behalf of the associated server process by using the SQL statement ALTER SESSION SET SQL_TRACE. This example enables the SQL trace facility for a specific session: ALTER SESSION SET SQL_TRACE TRUE; Caution: Because the SQL trace facility for server processes can cause significant system overhead resulting in severe performance impact, enable this feature only when collecting statistics. For shared server, each session using a dispatcher is routed to a shared server process, and trace information is written to the server’s trace file only if the session has enabled tracing (or if an error is encountered). Therefore, to track tracing for a specific session that connects using a dispatcher, you might have to explore several shared server’s trace files. The DBMS_SESSION and DBMS_SYSTEM packages can also be used to control SQL tracing for a session. See Also: Oracle9i Database Performance Tuning Guide and Reference contains information about using the SQL trace facility and using TKPROF to interpret the generated trace files. Managing Oracle Processes 5-17 Managing Processes for Parallel Execution Managing Processes for Parallel Execution This section describes how to manage parallel processing of SQL statements. In this configuration Oracle can divide the work of processing an SQL statement among multiple parallel processes. The execution of many SQL statements can be parallelized. The degree of parallelism is the number of parallel execution servers that can be associated with a single operation. The degree of parallelism is determined by any of the following: ■ ■ A PARALLEL clause in a statement For objects referred to in a query, the PARALLEL clause that was used when the object was created or altered ■ A parallel hint inserted into the statement ■ A default determined by Oracle An example of using parallel execution is contained in "Parallelizing Table Creation" on page 15-8. The following topics are contained in this section: ■ Managing the Parallel Execution Servers ■ Altering Parallel Execution for a Session Note: The parallel execution feature described in this section is available with the Oracle9i Enterprise Edition and Oracle9i Personal Edition. See Also: ■ ■ Oracle9i Database Concepts and Oracle9i Data Warehousing Guide for additional information about parallel execution Oracle9i Database Performance Tuning Guide and Reference for information about using parallel hints Managing the Parallel Execution Servers With the parallel execution feature, a process known as the parallel execution coordinator dispatches the execution of a pool of parallel execution servers and coordinates the sending of results from all of these parallel execution servers back to the user. Parallel execution server processes remain associated with a statement 5-18 Oracle9i Database Administrator’s Guide Managing Processes for Parallel Execution throughout its execution phase. When the statement is completely processed, these processes become available to process other statements. Parallel execution can be tuned for you automatically by setting the initialization parameter PARALLEL_AUTOMATIC_TUNING = TRUE. With this setting, Oracle determines the default values for other initialization parameters that affect the performance of parallel execution. Altering Parallel Execution for a Session The ALTER SESSION statement can be used to control parallel execution for a session. Disabling Parallel Execution All subsequent DML (INSERT, UPDATE, DELETE), DDL (CREATE, ALTER), or query (SELECT) statements will not be parallelized after an ALTER SESSION DISABLE PARALLEL DML|DDL|QUERY statement is issued. They will be executed serially, regardless of any PARALLEL clause or parallel hints associated with the statement. The following statement disables parallel DDL: ALTER SESSION DISABLE PARALLEL DDL; Enabling Parallel Execution Where a PARALLEL clause or parallel hint is associated with a statement, those DML, DDL, or query statements will execute in parallel after an ALTER SESSION ENABLE PARALLEL DML|DDL|QUERY statement is issued. This is the default for DDL and query statements. A DML statement can be parallelized only if you specifically issue this statement. The following statement enables parallel processing of DML statements: ALTER SESSION ENABLE PARALLEL DML; Note: Parallel DML is available only if you have installed Oracle’s Partitioning Option. Forcing Parallel Execution You can force parallel execution of all subsequent DML, DDL, or query statements for which parallelization is possible with the ALTER SESSION FORCE PARALLEL DML|DDL|QUERY statement. Additionally you can force a specific degree of Managing Oracle Processes 5-19 Managing Processes for External Procedures parallelism to be in effect, overriding any PARALLEL clause associated with subsequent statements. If you do not specify a degree of parallelism in this statement, the default degree of parallelism is used. However, a degree of parallelism specified in a statement through a hint will override the degree being forced. The following statement forces parallel execution of subsequent statements and sets the overriding degree of parallelism to 5: ALTER SESSION FORCE PARALLEL DDL PARALLEL 5; To force the parallelization of DML, it must also be enabled as shown in "Enabling Parallel Execution". Managing Processes for External Procedures External procedures, are procedures that are called from another program, but are written in a different language. An example would be a PL/SQL program calling one or more C routines that are required to perform special-purpose processing. These callable routines are stored in a dynamic link library (DLL), or libunit in the case of a Java class method, and are registered with the base language. Oracle provides a special-purpose interface, the call specification (call spec), that enables users to call external procedures from other languages. Very briefly, to call an external procedure, the application must know the DLL or shared library in which the external procedure resides. It alerts a network listener process, which in turn starts an external procedure agent, which by default is named extproc. Using the network connection established by the listener, the application passes to the external procedure agent the name of the DLL, the name of the external procedure, and any parameters passed in by the application. Then, the external procedure agent loads the DLL and runs the external procedure and passes back to the application any values returned by the external procedure. The agent must reside on the same computer as the database server. To control access to DLLs, the database administrator grants execute privileges for the appropriate DLLs to application developers. The application developers write the external procedures and grant execute privilege on specific external procedures to other users. 5-20 Oracle9i Database Administrator’s Guide Terminating Sessions Note: The external library (DLL file) must be statically linked. In other words, it must not reference any external symbols from other external libraries (DLL files). These symbols are not resolved and can cause your external procedure to fail. The environment for calling external procedures, consisting of tnsnames.ora and listener.ora entries, is configured by default during the install of your database. You may need to perform additional network configuration steps for a higher level of security. These are documented in the Oracle9i Net Services Administrator’s Guide. See Also: Oracle9i Application Developer’s Guide - Fundamentals for information about external procedures Terminating Sessions In some situations, you might want to terminate current user sessions. For example, you might want to perform an administrative operation and need to terminate all non-administrative sessions. This section describes the various aspects of terminating sessions, and contains the following topics: ■ Identifying Which Session to Terminate ■ Terminating an Active Session ■ Terminating an Inactive Session When a session is terminated, the session’s transaction is rolled back and resources (such as locks and memory areas) held by the session are immediately released and available to other sessions. Terminate a current session using the SQL statement ALTER SYSTEM KILL SESSION. The following statement terminates the session whose system identifier is 7 and serial number is 15: ALTER SYSTEM KILL SESSION '7,15'; Managing Oracle Processes 5-21 Terminating Sessions Identifying Which Session to Terminate To identify which session to terminate, specify the session’s index number and serial number. To identify the system identifier (sid) and serial number of a session, query the V$SESSION dynamic performance view. The following query identifies all sessions for the user jward: SELECT SID, SERIAL#, STATUS FROM V$SESSION WHERE USERNAME = 'JWARD'; SID SERIAL# ----- --------7 15 12 63 STATUS -------ACTIVE INACTIVE A session is ACTIVE when it is making a SQL call to Oracle. A session is INACTIVE if it is not making a SQL call to Oracle. Oracle9i Database Reference for a description of the status values for a session See Also: Terminating an Active Session If a user session is processing a transaction (ACTIVE status) when it is terminated, the transaction is rolled back and the user immediately receives the following message: ORA-00028: your session has been killed If, after receiving the ORA-00028 message, a user submits additional statements before reconnecting to the database, Oracle returns the following message: ORA-01012: not logged on If an active session cannot be interrupted (it is performing network I/O or rolling back a transaction), the session cannot be terminated until the operation completes. In this case, the session holds all resources until it is terminated. Additionally, the session that issues the ALTER SYSTEM statement to terminate a session waits up to 60 seconds for the session to be terminated. If the operation that cannot be interrupted continues past one minute, the issuer of the ALTER SYSTEM statement receives a message indicating that the session has been "marked" to be terminated. A session marked to be terminated is indicated in V$SESSION with a status of KILLED and a server that is something other than PSEUDO. 5-22 Oracle9i Database Administrator’s Guide Terminating Sessions Terminating an Inactive Session If the session is not making a SQL call to Oracle (is INACTIVE) when it is terminated, the ORA-00028 message is not returned immediately. The message is not returned until the user subsequently attempts to use the terminated session. When an inactive session has been terminated, STATUS in the V$SESSION view is KILLED. The row for the terminated session is removed from V$SESSION after the user attempts to use the session again and receives the ORA-00028 message. In the following example, an inactive session is terminated. First, V$SESSION is queried to identify the SID and SERIAL# of the session, then the session is terminated. SELECT SID,SERIAL#,STATUS,SERVER FROM V$SESSION WHERE USERNAME = 'JWARD'; SID SERIAL# ----- -------7 15 12 63 2 rows selected. STATUS --------INACTIVE INACTIVE SERVER --------DEDICATED DEDICATED ALTER SYSTEM KILL SESSION '7,15'; Statement processed. SELECT SID, SERIAL#, STATUS, SERVER FROM V$SESSION WHERE USERNAME = 'JWARD'; SID SERIAL# ----- -------7 15 12 63 2 rows selected. STATUS --------KILLED INACTIVE SERVER --------PSEUDO DEDICATED Managing Oracle Processes 5-23 Terminating Sessions 5-24 Oracle9i Database Administrator’s Guide 6 Managing Control Files This chapter explains how to create and maintain the control files for your database and contains the following topics: ■ What Is a Control File? ■ Guidelines for Control Files ■ Creating Control Files ■ Troubleshooting After Creating Control Files ■ Backing Up Control Files ■ Recovering a Control File Using a Current Copy ■ Dropping Control Files ■ Displaying Control File Information See Also: Chapter 3, "Using Oracle-Managed Files" for information about creating control files that are both created and managed by the Oracle database server Managing Control Files 6-1 What Is a Control File? What Is a Control File? Every Oracle database has a control file. A control file is a small binary file that records the physical structure of the database and includes: ■ The database name ■ Names and locations of associated datafiles and online redo log files ■ The timestamp of the database creation ■ The current log sequence number ■ Checkpoint information The control file must be available for writing by the Oracle database server whenever the database is open. Without the control file, the database cannot be mounted and recovery is difficult. The control file of an Oracle database is created at the same time as the database. By default, at least one copy of the control file is created during database creation. On some operating systems the default is to create multiple copies. You should create two or more copies of the control file during database creation. You might also need to create control files later, if you lose control files or want to change particular settings in the control files. Guidelines for Control Files This section describes guidelines you can use to manage the control files for a database, and contains the following topics: ■ Provide Filenames for the Control Files ■ Multiplex Control Files on Different Disks ■ Place Control Files Appropriately ■ Back Up Control Files ■ Manage the Size of Control Files Provide Filenames for the Control Files You specify control file names using the CONTROL_FILES initialization parameter in the database’s initialization parameter file (see "Creating Initial Control Files" on page 6-4). The instance startup procedure recognizes and opens all the listed files. 6-2 Oracle9i Database Administrator’s Guide Guidelines for Control Files The instance writes to and maintains all listed control files during database operation. If you do not specify files for CONTROL_FILES before database creation, and you are not using the Oracle Managed Files feature, Oracle creates a control file and uses a default filename. The default name is operating system specific. Multiplex Control Files on Different Disks Every Oracle database should have at least two control files, each stored on a different disk. If a control file is damaged due to a disk failure, the associated instance must be shut down. Once the disk drive is repaired, the damaged control file can be restored using the intact copy of the control file from the other disk and the instance can be restarted. In this case, no media recovery is required. The following describes the behavior of multiplexed control files: ■ ■ ■ Oracle writes to all filenames listed for the initialization parameter CONTROL_ FILES in the database’s initialization parameter file. The first file listed in the CONTROL_FILES parameter is the only file read by the Oracle database server during database operation. If any of the control files become unavailable during database operation, the instance becomes inoperable and should be aborted. Note: Oracle strongly recommends that your database has a minimum of two control files and that they are located on separate disks. Place Control Files Appropriately As already suggested, each copy of a control file should be stored on a different disk drive. One practice is to store a control file copy on every disk drive that stores members of online redo log groups, if the online redo log is multiplexed. By storing control files in these locations, you minimize the risk that all control files and all groups of the online redo log will be lost in a single disk failure. Back Up Control Files It is very important that you back up your control files. This is true initially, and at any time after you change the physical structure of your database. Such structural changes include: Managing Control Files 6-3 Creating Control Files ■ ■ ■ Adding, dropping, or renaming datafiles Adding or dropping a tablespace, or altering the read-write state of the tablespace Adding or dropping redo log files or groups The methods for backing up control files are discussed in "Backing Up Control Files" on page 6-10. Manage the Size of Control Files The main determinants of a control file’s size are the values set for the MAXDATAFILES, MAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, and MAXINSTANCES parameters in the CREATE DATABASE statement that created the associated database. Increasing the values of these parameters increases the size of a control file of the associated database. See Also: ■ ■ Your operating system specific Oracle documentation contains more information about the maximum control file size. Oracle9i SQL Reference for a description of the CREATE DATABASE statement Creating Control Files This section describes ways to create control files, and contains the following topics: ■ Creating Initial Control Files ■ Creating Additional Copies, Renaming, and Relocating Control Files ■ Creating New Control Files Creating Initial Control Files The initial control files of an Oracle database are created when you issue the CREATE DATABASE statement. The names of the control files are specified by the CONTROL_FILES parameter in the initialization parameter file used during database creation. The filenames specified in CONTROL_FILES should be fully specified and are operating system specific. The following is an example of a CONTROL_FILES initialization parameter: CONTROL_FILES = (/u01/oracle/prod/control01.ctl, 6-4 Oracle9i Database Administrator’s Guide Creating Control Files /u02/oracle/prod/control02.ctl, /u03/oracle/prod/control03.ctl) If files with the specified names currently exist at the time of database creation, you must specify the CONTROLFILE REUSE clause in the CREATE DATABASE statement, or else an error occurs. Also, if the size of the old control file differs from the SIZE parameter of the new one, you cannot use the REUSE option. The size of the control file changes between some releases of Oracle, as well as when the number of files specified in the control file changes. Configuration parameters such as MAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, MAXDATAFILES, and MAXINSTANCES affect control file size. You can subsequently change the value of the CONTROL_FILES initialization parameter to add more control files or to change the names or locations of existing control files. See Also: Your operating system specific Oracle documentation contains more information about specifying control files. Creating Additional Copies, Renaming, and Relocating Control Files You can create an an additional control file copy by copying an existing control file to a new location and adding the file’s name to the list of control files. Similarly, you rename an existing control file by copying the file to its new name or location, and changing the file’s name in the control file list. In both cases, to guarantee that control files do not change during the procedure, shut down the instance before copying the control file. To Multiplex or Move Additional Copies of the Current Control Files 1. Shut down the database. 2. Copy an existing control file to a different location, using operating system commands. 3. Edit the CONTROL_FILES parameter in the database’s initialization parameter file to add the new control file’s name, or to change the existing control filename. 4. Restart the database. Creating New Control Files This section discusses when and how to create new control files. Managing Control Files 6-5 Creating Control Files When to Create New Control Files It is necessary for you to create new control files in the following situations: ■ ■ All control files for the database have been permanently damaged and you do not have a control file backup. You want to change one of the permanent database parameter settings originally specified in the CREATE DATABASE statement. These settings include the database’s name and the following parameters: MAXLOGFILES, MAXLOGMEMBERS, MAXLOGHISTORY, MAXDATAFILES, and MAXINSTANCES. For example, you would change a database’s name if it conflicted with another database’s name in a distributed environment. Or, as another example, you can change the value of MAXLOGFILES if the original setting is too low. The CREATE CONTROLFILE Statement You can create a new control file for a database using the CREATE CONTROLFILE statement. The following statement creates a new control file for the prod database (formerly a database that used a different database name): CREATE CONTROLFILE SET DATABASE prod LOGFILE GROUP 1 ('/u01/oracle/prod/redo01_01.log', '/u01/oracle/prod/redo01_02.log'), GROUP 2 ('/u01/oracle/prod/redo02_01.log', '/u01/oracle/prod/redo02_02.log'), GROUP 3 ('/u01/oracle/prod/redo03_01.log', '/u01/oracle/prod/redo03_02.log') NORESETLOGS DATAFILE '/u01/oracle/prod/system01.dbf' SIZE 3M, '/u01/oracle/prod/rbs01.dbs' SIZE 5M, '/u01/oracle/prod/users01.dbs' SIZE 5M, '/u01/oracle/prod/temp01.dbs' SIZE 5M MAXLOGFILES 50 MAXLOGMEMBERS 3 MAXLOGHISTORY 400 MAXDATAFILES 200 MAXINSTANCES 6 ARCHIVELOG; 6-6 Oracle9i Database Administrator’s Guide Creating Control Files Cautions: ■ ■ The CREATE CONTROLFILE statement can potentially damage specified datafiles and online redo log files. Omitting a filename can cause loss of the data in that file, or loss of access to the entire database. Employ caution when using this statement and be sure to follow the instructions in "Steps for Creating New Control Files". If the database had forced logging enabled before creating the new control file, and you want it to continue to be enabled, then you must specify the FORCE LOGGING clause in the CREATE CONTROLFILE statement. See "Specifying FORCE LOGGING Mode" on page 2-29. See Also: Oracle9i SQL Reference describes the complete syntax of the CREATE CONTROLFILE statement Steps for Creating New Control Files Complete the following steps to create a new control file. 1. Make a list of all datafiles and online redo log files of the database. If you follow recommendations for control file backups as discussed in "Backing Up Control Files" on page 6-10, you will already have a list of datafiles and online redo log files that reflect the current structure of the database. However, if you have no such list, executing the following statements will produce one. SELECT MEMBER FROM V$LOGFILE; SELECT NAME FROM V$DATAFILE; SELECT VALUE FROM V$PARAMETER WHERE NAME = 'CONTROL_FILES'; If you have no such lists and your control file has been damaged so that the database cannot be opened, try to locate all of the datafiles and online redo log files that constitute the database. Any files not specified in Step 5 are not recoverable once a new control file has been created. Moreover, if you omit any of the files that make up the SYSTEM tablespace, you might not be able to recover the database. 2. Shut down the database. If the database is open, shut down the database normally if possible. Use the IMMEDIATE or ABORT options only as a last resort. Managing Control Files 6-7 Creating Control Files 3. Back up all datafiles and online redo log files of the database. 4. Start up a new instance, but do not mount or open the database: STARTUP NOMOUNT 5. Create a new control file for the database using the CREATE CONTROLFILE statement. When creating a new control file, select the RESETLOGS option if you have lost any online redo log groups in addition to control files. In this case, you will need to recover from the loss of the redo logs (Step 8). You must also specify the RESETLOGS option if you have renamed the database. Otherwise, select the NORESETLOGS option. 6. Store a backup of the new control file on an offline storage device. See "Backing Up Control Files" on page 6-10 for instructions for creating a backup. 7. Edit the CONTROL_FILES initialization parameter for the database to indicate all of the control files now part of your database as created in Step 5 (not including the backup control file). If you are renaming the database, edit the DB_NAME parameter to specify the new name. 8. Recover the database if necessary. If you are not recovering the database, skip to Step 9. If you are creating the control file as part of recovery, recover the database. If the new control file was created using the NORESETLOGS option (Step 5), you can recover the database with complete, closed database recovery. If the new control file was created using the RESETLOGS option, you must specify USING BACKUP CONTROL FILE. If you have lost online or archived redo logs or datafiles, use the procedures for recovering those files. 9. Open the database using one of the following methods: ■ If you did not perform recovery, or you performed complete, closed database recovery in Step 8, open the database normally. ALTER DATABASE OPEN; ■ If you specified RESETLOGS when creating the control file, use the ALTER DATABASE statement, indicating RESETLOGS. ALTER DATABASE OPEN RESETLOGS; The database is now open and available for use. 6-8 Oracle9i Database Administrator’s Guide Troubleshooting After Creating Control Files See Also: Oracle9i User-Managed Backup and Recovery Guide contains additional information about: ■ Listing database files ■ Backing up all datafiles and online redo log files of the database ■ Recovering online or archived redo log files ■ Performing closed database recovery Troubleshooting After Creating Control Files After issuing the CREATE CONTROLFILE statement, you may encounter some common errors. This section describes the most common control file usage errors, and contains the following topics: ■ Checking for Missing or Extra Files ■ Handling Errors During CREATE CONTROLFILE Checking for Missing or Extra Files After creating a new control file and using it to open the database, check the alert file to see if Oracle has detected inconsistencies between the data dictionary and the control file, such as a datafile that the data dictionary includes but the control file does not list. If a datafile exists in the data dictionary but not in the new control file, Oracle creates a placeholder entry in the control file under the name MISSINGnnnn (where nnnn is the file number in decimal). MISSINGnnnn is flagged in the control file as being offline and requiring media recovery. The actual datafile corresponding to MISSINGnnnn can be made accessible by renaming MISSINGnnnn so that it points to the datafile only if the datafile was read-only or offline normal. If, on the other hand, MISSINGnnnn corresponds to a datafile that was not read-only or offline normal, then the rename operation cannot be used to make the datafile accessible, because the datafile requires media recovery that is precluded by the results of RESETLOGS. In this case, you must drop the tablespace containing the datafile. In contrast, if a datafile indicated in the control file is not present in the data dictionary, Oracle removes references to it from the new control file. In both cases, Oracle includes an explanatory message in the alert.log file to let you know what was found. Managing Control Files 6-9 Backing Up Control Files Handling Errors During CREATE CONTROLFILE If Oracle sends you an error (usually error ORA-01173, ORA-01176, ORA-01177, ORA-01215, or ORA-01216) when you attempt to mount and open the database after creating a new control file, the most likely cause is that you omitted a file from the CREATE CONTROLFILE statement or included one that should not have been listed. In this case, you should restore the files you backed up in Step 3 on page 6-8 and repeat the procedure from Step 4, using the correct filenames. Backing Up Control Files Use the ALTER DATABASE BACKUP CONTROLFILE statement to back up your control files. You have two options: 1. Back up the control file to a binary file (duplicate of existing control file) using the following statement: ALTER DATABASE BACKUP CONTROLFILE TO '/oracle/backup/control.bkp'; 2. Produce SQL statements that can later be used to re-create your control file: ALTER DATABASE BACKUP CONTROLFILE TO TRACE; This command writes a SQL script to the database’s trace file where it can be captured and edited to reproduce the control file. See Also: For more information on backing up your control files, depending upon your backup stratagy refer to one of the following books: ■ Oracle9i User-Managed Backup and Recovery Guide ■ Oracle9i Recovery Manager User’s Guide Recovering a Control File Using a Current Copy This section presents ways that you can recover your control file from a current backup or from a multiplexed copy. Recovering from Control File Corruption Using a Control File Copy This procedure assumes that one of the control files specified in the CONTROL_ FILES parameter is corrupted, the control file directory is still accessible, and you have a multiplexed copy of the control file. 6-10 Oracle9i Database Administrator’s Guide Dropping Control Files 1. With the instance shut down, use an operating system command to overwrite the bad control file with a good copy: % cp /u01/oracle/prod/control03.ctl /u01/oracle/prod/control02.ctl 2. Start SQL*Plus and open the database: SQL> STARTUP Recovering from Permanent Media Failure Using a Control File Copy This procedure assumes that one of the control files specified in the CONTROL_ FILES parameter is inaccessible due to a permanent media failure, and you have a multiplexed copy of the control file. 1. With the instance shut down, use an operating system command to copy the current copy of the control file to a new, accessible location: % cp /u01/oracle/prod/control01.ctl /u04/oracle/prod/control03.ctl 2. Edit the CONTROL_FILES parameter in the initialization parameter file to replace the bad location with the new location: CONTROL_FILES = (/u01/oracle/prod/control01.ctl, /u02/oracle/prod/control02.ctl, /u04/oracle/prod/control03.ctl) 3. Start SQL*Plus and open the database: SQL> STARTUP In any case where you have multiplexed control files, and you must get the database up in minimum time, you can do so by editing the CONTROL_FILES initialization parameter to remove the bad control file and restarting the database immediately. Then you can perform the reconstruction of the bad control file and at some later time shut down and restart the database after editing the CONTROL_ FILES initialization parameter to include the recovered control file. Dropping Control Files You can drop control files from the database. For example, you might want to do so if the location of a control file is no longer appropriate. Remember that the database must have at least two control files at all times. 1. Shut down the database. Managing Control Files 6-11 Displaying Control File Information 2. Edit the CONTROL_FILES parameter in the database’s initialization parameter file to delete the old control file’s name. 3. Restart the database. Note: This operation does not physically delete the unwanted control file from the disk. Use operating system commands to delete the unnecessary file after you have dropped the control file from the database. Displaying Control File Information The following views display information about control files: View Description V$DATABASE Displays database information from the control file V$CONTROLFILE Lists the names of control files V$CONTROLFILE_RECORD_SECTION Displays information about control file record sections V$PARAMETER Can be used to display the names of control files as specified in the CONTROL_FILES initialization parameter This example lists the names of the control files. SQL> SELECT NAME FROM V$CONTROLFILE; NAME ------------------------------------/u01/oracle/prod/control01.ctl /u02/oracle/prod/control02.ctl /u03/oracle/prod/control03.ctl 6-12 Oracle9i Database Administrator’s Guide 7 Managing the Online Redo Log This chapter explains how to manage the online redo log and contains the following topics: ■ What Is the Online Redo Log? ■ Planning the Online Redo Log ■ Creating Online Redo Log Groups and Members ■ Relocating and Renaming Online Redo Log Members ■ Dropping Online Redo Log Groups and Members ■ Forcing Log Switches ■ Verifying Blocks in Redo Log Files ■ Clearing an Online Redo Log File ■ Viewing Online Redo Log Information See Also: ■ ■ ■ Chapter 3, "Using Oracle-Managed Files" for information about creating online redo log files that are both created and managed by the Oracle database server Oracle9i Real Application Clusters Administration for more information about managing the online redo logs of instances when using Oracle Real Application Clusters Oracle9i Database Performance Tuning Guide and Reference to learn how checkpoints and the redo log impact instance recovery Managing the Online Redo Log 7-1 What Is the Online Redo Log? What Is the Online Redo Log? The most crucial structure for recovery operations is the online redo log, which consists of two or more preallocated files that store all changes made to the database as they occur. Every instance of an Oracle database has an associated online redo log to protect the database in case of an instance failure. Redo Threads Each database instance has its own online redo log groups. These online redo log groups, multiplexed or not, are called an instance’s thread of online redo. In typical configurations, only one database instance accesses an Oracle database, so only one thread is present. When running Oracle Real Application Clusters, however, two or more instances concurrently access a single database and each instance has its own thread. This chapter describes how to configure and manage the online redo log when the Oracle9i Real Application Clusters feature is not used. Hence, the thread number can be assumed to be 1 in all discussions and examples of statements. Online Redo Log Contents Online redo log files are filled with redo records. A redo record, also called a redo entry, is made up of a group of change vectors, each of which is a description of a change made to a single block in the database. For example, if you change a salary value in an employee table, you generate a redo record containing change vectors that describe changes to the data segment block for the table, the rollback segment data block, and the transaction table of the rollback segments. Redo entries record data that you can use to reconstruct all changes made to the database, including the rollback segments. Therefore, the online redo log also protects rollback data. When you recover the database using redo data, Oracle reads the change vectors in the redo records and applies the changes to the relevant blocks. Redo records are buffered in a circular fashion in the redo log buffer of the SGA (see "How Oracle Writes to the Online Redo Log") and are written to one of the online redo log files by the Oracle background process Log Writer (LGWR). Whenever a transaction is committed, LGWR writes the transaction’s redo records from the redo log buffer of the SGA to an online redo log file, and a system change number (SCN) is assigned to identify the redo records for each committed transaction. Only when all redo records associated with a given transaction are safely on disk in the online logs is the user process notified that the transaction has been committed. 7-2 Oracle9i Database Administrator’s Guide What Is the Online Redo Log? Redo records can also be written to an online redo log file before the corresponding transaction is committed. If the redo log buffer fills, or another transaction commits, LGWR flushes all of the redo log entries in the redo log buffer to an online redo log file, even though some redo records may not be committed. If necessary, Oracle can roll back these changes. How Oracle Writes to the Online Redo Log The online redo log of a database consists of two or more online redo log files. Oracle requires a minimum of two files to guarantee that one is always available for writing while the other is being archived (if in ARCHIVELOG mode). LGWR writes to online redo log files in a circular fashion. When the current online redo log file fills, LGWR begins writing to the next available online redo log file. When the last available online redo log file is filled, LGWR returns to the first online redo log file and writes to it, starting the cycle again. Figure 7–1 illustrates the circular writing of the online redo log file. The numbers next to each line indicate the sequence in which LGWR writes to each online redo log file. Filled online redo log files are available to LGWR for reuse depending on whether archiving is enabled. ■ ■ If archiving is disabled (NOARCHIVELOG mode), a filled online redo log file is available once the changes recorded in it have been written to the datafiles. If archiving is enabled (ARCHIVELOG mode), a filled online redo log file is available to LGWR once the changes recorded in it have been written to the datafiles and once the file has been archived. Managing the Online Redo Log 7-3 What Is the Online Redo Log? Figure 7–1 Circular Use of Online Redo Log Files by LGWR Online redo log file #1 1, 4, 7, ... Online redo log file #2 2, 5, 8, ... Online redo log file #3 3, 6, 9, ... LGWR Active (Current) and Inactive Online Redo Log Files At any given time, Oracle uses only one of the online redo log files to store redo records written from the redo log buffer. The online redo log file that LGWR is actively writing to is called the current online redo log file. Online redo log files that are required for instance recovery are called active online redo log files. Online redo log files that are not required for instance recovery are called inactive. If you have enabled archiving (ARCHIVELOG mode), Oracle cannot reuse or overwrite an active online log file until ARCn has archived its contents. If archiving is disabled (NOARCHIVELOG mode), when the last online redo log file fills writing continues by overwriting the first available active file. 7-4 Oracle9i Database Administrator’s Guide Planning the Online Redo Log Log Switches and Log Sequence Numbers A log switch is the point at which Oracle ends writing to one online redo log file and begins writing to another. Normally, a log switch occurs when the current online redo log file is completely filled and writing must continue to the next online redo log file. However, you can specify that a log switch occurs in a time-based manner, regardless of whether the current online redo log file is completely filled. You can also force log switches manually. Oracle assigns each online redo log file a new log sequence number every time that a log switch occurs and LGWR begins writing to it. If Oracle archives online redo log files, the archived log retains its log sequence number. The online redo log file that is cycled back for use is given the next available log sequence number. Each online or archived redo log file is uniquely identified by its log sequence number. During crash, instance, or media recovery, Oracle properly applies redo log files in ascending order by using the log sequence number of necessary archived and online redo log files. Planning the Online Redo Log This section describes guidelines you should consider when configuring a database instance’s online redo log, and contains the following topics: ■ Multiplexing Online Redo Log Files ■ Placing Online Redo Log Members on Different Disks ■ Setting the Size of Online Redo Log Members ■ Choosing the Number of Online Redo Log Files ■ Controlling Archive Lag Multiplexing Online Redo Log Files Oracle provides the capability to multiplex an instance’s online redo log files to safeguard against damage to its online redo log files. When multiplexing online redo log files, LGWR concurrently writes the same redo log information to multiple identical online redo log files, thereby eliminating a single point of redo log failure. Note: Oracle recommends that you multiplex your redo log files. The loss of the log file data can be catastrophic if recovery is required. Managing the Online Redo Log 7-5 Planning the Online Redo Log , , , Figure 7–2 Multiplexed Online Redo Log Files Disk A Disk B 1, 3, 5, ... A_LOG1 B_LOG1 Group 1 LGWR Group 2 A_LOG2 2, 4, 6, ... B_LOG2 Group 1 Group 2 The corresponding online redo log files are called groups. Each online redo log file in a group is called a member. In Figure 7–2, A_LOG1 and B_LOG1 are both members of Group 1, A_LOG2 and B_LOG2 are both members of Group 2, and so forth. Each member in a group must be exactly the same size. Notice that each member of a group is concurrently active, or, concurrently written to by LGWR, as indicated by the identical log sequence numbers assigned by LGWR. In Figure 7–2, first LGWR writes to A_LOG1 in conjunction with B_LOG1, then A_LOG2 in conjunction with B_LOG2, and so on. LGWR never writes concurrently to members of different groups (for example, to A_LOG1 and B_ LOG2). Responding to Online Redo Log Failure Whenever LGWR cannot write to a member of a group, Oracle marks that member as INVALID and writes an error message to the LGWR trace file and to the database’s alert file to indicate the problem with the inaccessible files. LGWR reacts differently when certain online redo log members are unavailable, depending on the reason for the unavailability. 7-6 Oracle9i Database Administrator’s Guide Planning the Online Redo Log If Then LGWR can successfully write to at least one member in a group Writing proceeds as normal. LGWR simply writes to the available members of a group and ignores the unavailable members. LGWR cannot access the next group at a log switch because the group needs to be archived Database operation temporarily halts until the group becomes available, or, until the group is archived. All members of the next group are inaccessible to LGWR at a log switch because of media failure Oracle returns an error and the database instance shuts down. In this case, you may need to perform media recovery on the database from the loss of an online redo log file. If the database checkpoint has moved beyond the lost redo log, media recovery is not necessary since Oracle has saved the data recorded in the redo log to the datafiles. Simply drop the inaccessible redo log group. If Oracle did not archive the bad log, use ALTER DATABASE CLEAR UNARCHIVED LOG to disable archiving before the log can be dropped. If all members of a group suddenly become inaccessible to LGWR while it is writing to them Oracle returns an error and the database instance immediately shuts down. In this case, you may need to perform media recovery. If the media containing the log is not actually lost—for example, if the drive for the log was inadvertently turned off—media recovery may not be needed. In this case, you only need to turn the drive back on and let Oracle perform instance recovery. Legal and Illegal Configurations To safeguard against a single point of online redo log failure, a multiplexed online redo log is ideally symmetrical: all groups of the online redo log have the same number of members. Nevertheless, Oracle does not require that a multiplexed online redo log be symmetrical. For example, one group can have only one member, while other groups have two members. This configuration protects against disk failures that temporarily affect some online redo log members but leave others intact. The only requirement for an instance’s online redo log is that it have at least two groups. Figure 7–3 shows legal and illegal multiplexed online redo log configurations. The second configuration is illegal because it has only one group. Managing the Online Redo Log 7-7 Planning the Online Redo Log , , , ,, , Figure 7–3 Legal and Illegal Multiplexed Online Redo Log Configuration LEGAL Disk A Group 1 Group 2 Group 3 ILLEGAL A_LOG1 A_LOG2 A_LOG3 Disk A Group 1 Group 2 Group 3 A_LOG1 Disk B B_LOG1 B_LOG2 B_LOG3 Disk B B_LOG1 Group 1 Group 2 Group 3 7-8 Oracle9i Database Administrator’s Guide Planning the Online Redo Log Placing Online Redo Log Members on Different Disks When setting up a multiplexed online redo log, place members of a group on different disks. If a single disk fails, then only one member of a group becomes unavailable to LGWR and other members remain accessible to LGWR, so the instance can continue to function. If you archive the redo log, spread online redo log members across disks to eliminate contention between the LGWR and ARCn background processes. For example, if you have two groups of duplexed online redo log members, place each member on a different disk and set your archiving destination to a fifth disk. Consequently, there is never contention between LGWR (writing to the members) and ARCn (reading the members). Datafiles and online redo log files should also be on different disks to reduce contention in writing data blocks and redo records. See Also: Oracle9i Backup and Recovery Concepts for more information about how the online redo log affects backup and recovery Setting the Size of Online Redo Log Members When setting the size of online redo log files, consider whether you will be archiving the redo log. Online redo log files should be sized so that a filled group can be archived to a single unit of offline storage media (such as a tape or disk), with the least amount of space on the medium left unused. For example, suppose only one filled online redo log group can fit on a tape and 49% of the tape’s storage capacity remains unused. In this case, it is better to decrease the size of the online redo log files slightly, so that two log groups could be archived for each tape. With multiplexed groups of online redo logs, all members of the same group must be the same size. Members of different groups can have different sizes. However, there is no advantage in varying file size between groups. If checkpoints are not set to occur between log switches, make all groups the same size to guarantee that checkpoints occur at regular intervals. See Also: Your operating system specific Oracle documentation. The default size of online redo log files is operating system dependent. Managing the Online Redo Log 7-9 Planning the Online Redo Log Choosing the Number of Online Redo Log Files The best way to determine the appropriate number of online redo log files for a database instance is to test different configurations. The optimum configuration has the fewest groups possible without hampering LGWR’s writing redo log information. In some cases, a database instance may require only two groups. In other situations, a database instance may require additional groups to guarantee that a recycled group is always available to LGWR. During testing, the easiest way to determine if the current online redo log configuration is satisfactory is to examine the contents of the LGWR trace file and the database’s alert log. If messages indicate that LGWR frequently has to wait for a group because a checkpoint has not completed or a group has not been archived, add groups. Consider the parameters that can limit the number of online redo log files before setting up or altering the configuration of an instance’s online redo log. The following parameters limit the number of online redo log files that you can add to a database: ■ ■ The MAXLOGFILES parameter used in the CREATE DATABASE statement determines the maximum number of groups of online redo log files for each database. Group values can range from 1 to MAXLOGFILES. The only way to override this upper limit is to re-create the database or its control file. Thus, it is important to consider this limit before creating a database. If MAXLOGFILES is not specified for the CREATE DATABASE statement, Oracle uses an operating system specific default value. The MAXLOGMEMBERS parameter used in the CREATE DATABASE statement determines the maximum number of members for each group. As with MAXLOGFILES, the only way to override this upper limit is to re-create the database or control file. Thus, it is important to consider this limit before creating a database. If no MAXLOGMEMBERS parameter is specified for the CREATE DATABASE statement, Oracle uses an operating system default value. See Also: Your operating system specific Oracle documentation for the default and legal values of the MAXLOGFILES and MAXLOGMEMBERS parameters Controlling Archive Lag You can force all enabled online redo log threads to switch their current logs in a time-based fashion. In a primary/standby configuration, changes are made available to the standby database by archiving and shipping logs of the primary site 7-10 Oracle9i Database Administrator’s Guide Planning the Online Redo Log to the standby database. The changes that are being applied by the standby database can lag the changes that are occurring on the primary database. This lag can happen because the standby database must wait for the changes in the primary database’s online redo log to be archived (into the archived redo log) and then shipped to it. To control or limit this lag, you set the ARCHIVE_LAG_TARGET initialization parameter. Setting this parameter allows you to limit, measured in time, how long the lag can become. Setting the ARCHIVE_LAG_TARGET Initialization Parameter When you set the ARCHIVE_LAG_TARGET initialization parameter, you cause Oracle to examine an instance’s current online redo log periodically. If the following conditions are met the instance will switch the log: ■ ■ The current log was created prior to n seconds ago, and the estimated archival time for the current log is m seconds (proportional to the number of redo blocks used in the current log), where n + m exceeds the value of the ARCHIVE_LAG_ TARGET initialization parameter. The current log contains redo records. In an Oracle Real Application Clusters environment, the instance also nudges other threads into switching and archiving logs if they are falling behind. This can be particularly useful when one instance in the cluster is more idle than the other instances (as when you are running a 2-node primary/secondary configuration of Oracle Real Application Clusters). Initialization parameter ARCHIVE_LAG_TARGET specifies the target of how many seconds of redo the standby could lose in the event of a primary shutdown or crash if the Data Guard environment is not configured in a no-data-loss mode. It also provides an upper limit of how long (in the number of seconds) the current log of the primary database can span. Because the estimated archival time is also considered, this is not the exact log switch time. The following initialization parameter setting sets the log switch interval to 30 minutes (a typical value). ARCHIVE_LAG_TARGET = 1800 A value of 0 disables this time-based log switching functionality. This is the default setting. You can set the ARCHIVE_LAG_TARGET initialization parameter even if there is no standby database. For example, the ARCHIVE_LAG_TARGET parameter can be set specifically to force logs to be switched and archived. Managing the Online Redo Log 7-11 Creating Online Redo Log Groups and Members ARCHIVE_LAG_TARGET is a dynamic parameter and can be set with the ALTER SYSTEM SET statement. Caution: The ARCHIVE_LAG_TARGET parameter must be set to the same value in all instances of an Oracle Real Application Clusters environment. Failing to do so results in unspecified behavior and is strongly discouraged. Factors Affecting the Setting of ARCHIVE_LAG_TARGET Consider the following factors when determining if you want to set the ARCHIVE_ LAG_TARGET parameter and in determining the value for this parameter. ■ Overhead of switching (as well as archiving) logs ■ How frequently normal log switches occur as a result of log full conditions ■ How much redo loss is tolerated in the standby database Setting ARCHIVE_LAG_TARGET may not be very useful if natural log switches already occur more frequently than the interval specified. However, in the case of irregularities of redo generation speed, the interval does provide an upper limit for the time range each current log covers. If the ARCHIVE_LAG_TARGET initialization parameter is set to a very low value, there can be a negative impact on performance. This can force frequent log switches. Set the parameter to a reasonable value so as not to degrade the performance of the primary database. Creating Online Redo Log Groups and Members Plan the online redo log of a database and create all required groups and members of online redo log files during database creation. However, there are situations where you might want to create additional groups or members. For example, adding groups to an online redo log can correct redo log group availability problems. To create new online redo log groups and members, you must have the ALTER DATABASE system privilege. A database can have up to MAXLOGFILES groups. See Also: Oracle9i SQL Reference for a complete description of the ALTER DATABASE statement 7-12 Oracle9i Database Administrator’s Guide Creating Online Redo Log Groups and Members Creating Online Redo Log Groups To create a new group of online redo log files, use the SQL statement ALTER DATABASE with the ADD LOGFILE clause. The following statement adds a new group of redo logs to the database: ALTER DATABASE ADD LOGFILE ('/oracle/dbs/log1c.rdo', '/oracle/dbs/log2c.rdo') SIZE 500K; Note: Use fully specify filenames of new log members to indicate where the operating system file should be created. Otherwise, the files will be created in either the default or current directory of the database server, depending upon your operating system. You can also specify the number that identifies the group using the GROUP option: ALTER DATABASE ADD LOGFILE GROUP 10 ('/oracle/dbs/log1c.rdo', '/oracle/dbs/log2c.rdo') SIZE 500K; Using group numbers can make administering redo log groups easier. However, the group number must be between 1 and MAXLOGFILES. Do not skip redo log file group numbers (that is, do not number your groups 10, 20, 30, and so on), or you will consume space in the control files of the database. Creating Online Redo Log Members In some cases, it might not be necessary to create a complete group of online redo log files. A group could already exist, but not be complete because one or more members of the group were dropped (for example, because of a disk failure). In this case, you can add new members to an existing group. To create new online redo log members for an existing group, use the SQL statement ALTER DATABASE with the ADD LOG MEMBER parameter. The following statement adds a new redo log member to redo log group number 2: ALTER DATABASE ADD LOGFILE MEMBER '/oracle/dbs/log2b.rdo' TO GROUP 2; Notice that filenames must be specified, but sizes need not be. The size of the new members is determined from the size of the existing members of the group. Managing the Online Redo Log 7-13 Relocating and Renaming Online Redo Log Members When using the ALTER DATABASE statement, you can alternatively identify the target group by specifying all of the other members of the group in the TO parameter, as shown in the following example: ALTER DATABASE ADD LOGFILE MEMBER '/oracle/dbs/log2c.rdo' TO ('/oracle/dbs/log2a.rdo', '/oracle/dbs/log2b.rdo'); Note: Fully specify the filenames of new log members to indicate where the operating system files should be created. Otherwise, the files will be created in either the default or current directory of the database server, depending upon your operating system. You may also note that the status of the new log member is shown as INVALID. This is normal and it will change to active (blank) when it is first used. Relocating and Renaming Online Redo Log Members You can use operating system commands to relocate online redo logs, then use the ALTER DATABASE statement to make their new names (locations) known to the database. This procedure is necessary, for example, if the disk currently used for some online redo log files is going to be removed, or if datafiles and a number of online redo log files are stored on the same disk and should be separated to reduce contention. To rename online redo log members, you must have the ALTER DATABASE system privilege. Additionally, you might also need operating system privileges to copy files to the desired location and privileges to open and back up the database. Before relocating your redo logs, or making any other structural changes to the database, completely back up the database in case you experience problems while performing the operation. As a precaution, after renaming or relocating a set of online redo log files, immediately back up the database’s control file. Use the following steps for relocating redo logs. The example used to illustrate these steps assumes: ■ ■ 7-14 The log files are located on two disks: diska and diskb. The online redo log is duplexed: one group consists of the members /diska/logs/log1a.rdo and /diskb/logs/log1b.rdo, and the second group consists of the members /diska/logs/log2a.rdo and /diskb/logs/log2b.rdo. Oracle9i Database Administrator’s Guide Relocating and Renaming Online Redo Log Members ■ The online redo log files located on diska must be relocated to diskc. The new filenames will reflect the new location: /diskc/logs/log1c.rdo and /diskc/logs/log2c.rdo. Steps for Renaming Online Redo Log Members 1. Shut down the database. SHUTDOWN 2. Copy the online redo log files to the new location. Operating system files, such as online redo log members, must be copied using the appropriate operating system commands. See your operating system specific documentation for more information about copying files. Note: You can execute an operating system command to copy a file (or perform other operating system commands) without exiting SQL*Plus by using the HOST command. Some operating systems allow you to use a character in place of the word HOST. For example, you can use ! in UNIX. The following example uses operating system commands (UNIX) to move the online redo log members to a new location: mv /diska/logs/log1a.rdo /diskc/logs/log1c.rdo mv /diska/logs/log2a.rdo /diskc/logs/log2c.rdo 3. Startup the database, mount, but do not open it. CONNECT / as SYSDBA STARTUP MOUNT 4. Rename the online redo log members. Use the ALTER DATABASE statement with the RENAME FILE clause to rename the database’s online redo log files. ALTER DATABASE RENAME FILE '/diska/logs/log1a.rdo', '/diska/logs/log2a.rdo' TO '/diskc/logs/log1c.rdo', '/diskc/logs/log2c.rdo'; 5. Open the database for normal operation. The online redo log alterations take effect when the database is opened. Managing the Online Redo Log 7-15 Dropping Online Redo Log Groups and Members ALTER DATABASE OPEN; Dropping Online Redo Log Groups and Members In some cases, you may want to drop an entire group of online redo log members. For example, you want to reduce the number of groups in an instance’s online redo log. In a different case, you may want to drop one or more specific online redo log members. For example, if a disk failure occurs, you may need to drop all the online redo log files on the failed disk so that Oracle does not try to write to the inaccessible files. In other situations, particular online redo log files become unnecessary. For example, a file might be stored in an inappropriate location. Dropping Log Groups To drop an online redo log group, you must have the ALTER DATABASE system privilege. Before dropping an online redo log group, consider the following restrictions and precautions: ■ ■ ■ An instance requires at least two groups of online redo log files, regardless of the number of members in the groups. (A group is one or more members.) You can drop an online redo log group only if it is inactive. If you need to drop the current group, first force a log switch to occur. Make sure an online redo log group is archived (if archiving is enabled) before dropping it. To see whether this has happened, use the V$LOG view. SELECT GROUP#, ARCHIVED, STATUS FROM V$LOG; GROUP# --------1 2 3 4 ARC --YES NO YES YES STATUS ---------------ACTIVE CURRENT INACTIVE INACTIVE Drop an online redo log group with the SQL statement ALTER DATABASE with the DROP LOGFILE clause. The following statement drops redo log group number 3: ALTER DATABASE DROP LOGFILE GROUP 3; When an online redo log group is dropped from the database, and you are not using the Oracle Managed Files feature, the operating system files are not deleted 7-16 Oracle9i Database Administrator’s Guide Dropping Online Redo Log Groups and Members from disk. Rather, the control files of the associated database are updated to drop the members of the group from the database structure. After dropping an online redo log group, make sure that the drop completed successfully, and then use the appropriate operating system command to delete the dropped online redo log files. When using Oracle-managed files, the cleanup of operating systems files is done automatically for you. Dropping Online Redo Log Members To drop an online redo log member, you must have the ALTER DATABASE system privilege. Consider the following restrictions and precautions before dropping individual online redo log members: ■ ■ ■ ■ It is permissible to drop online redo log files so that a multiplexed online redo log becomes temporarily asymmetric. For example, if you use duplexed groups of online redo log files, you can drop one member of one group, even though all other groups have two members each. However, you should rectify this situation immediately so that all groups have at least two members, and thereby eliminate the single point of failure possible for the online redo log. An instance always requires at least two valid groups of online redo log files, regardless of the number of members in the groups. (A group is one or more members.) If the member you want to drop is the last valid member of the group, you cannot drop the member until the other members become valid. To see a redo log file’s status, use the V$LOGFILE view. A redo log file becomes INVALID if Oracle cannot access it. It becomes STALE if Oracle suspects that it is not complete or correct. A stale log file becomes valid again the next time its group is made the active group. You can drop an online redo log member only if it is not part of an active or current group. If you want to drop a member of an active group, first force a log switch to occur. Make sure the group to which an online redo log member belongs is archived (if archiving is enabled) before dropping the member. To see whether this has happened, use the V$LOG view. To drop specific inactive online redo log members, use the ALTER DATABASE statement with the DROP LOGFILE MEMBER clause. The following statement drops the redo log /oracle/dbs/log3c.rdo: ALTER DATABASE DROP LOGFILE MEMBER '/oracle/dbs/log3c.rdo'; Managing the Online Redo Log 7-17 Forcing Log Switches When an online redo log member is dropped from the database, the operating system file is not deleted from disk. Rather, the control files of the associated database are updated to drop the member from the database structure. After dropping an online redo log file, make sure that the drop completed successfully, and then use the appropriate operating system command to delete the dropped online redo log file. To drop a member of an active group, you must first force a log switch. Forcing Log Switches A log switch occurs when LGWR stops writing to one online redo log group and starts writing to another. By default, a log switch occurs automatically when the current online redo log file group fills. You can force a log switch to make the currently active group inactive and available for online redo log maintenance operations. For example, you want to drop the currently active group, but are not able to do so until the group is inactive. You may also wish to force a log switch if the currently active group needs to be archived at a specific time before the members of the group are completely filled. This option is useful in configurations with large online redo log files that take a long time to fill. To force a log switch, you must have the ALTER SYSTEM privilege. Use the ALTER SYSTEM statement with the SWITCH LOGFILE clause. The following statement forces a log switch: ALTER SYSTEM SWITCH LOGFILE; Verifying Blocks in Redo Log Files You can configure Oracle to use checksums to verify blocks in the redo log files. If you set the initialization parameter DB_BLOCK_CHECKSUM to TRUE, block checking is enabled for all Oracle database blocks written to disk, including redo log blocks. The default value of DB_BLOCK_CHECKSUM is FALSE. If you enable block checking, Oracle computes a checksum for each redo log block written to the current log. Oracle writes the checksum in the header of the block. Oracle uses the checksum to detect corruption in a redo log block. Oracle tries to verify the redo log block when it writes the block to an archive log file and when the block is read from an archived log during recovery. 7-18 Oracle9i Database Administrator’s Guide Clearing an Online Redo Log File If Oracle detects a corruption in a redo log block while trying to archive it, the system attempts to read the block from another member in the group. If the block is corrupted in all members the redo log group, then archiving cannot proceed. Note: There is some overhead and decrease in database performance with DB_BLOCK_CHECKSUM enabled. Monitor your database performance to decide if the benefit of using data block checksums to detect corruption outweights the performance impact. See Also: Oracle9i Database Reference for a description of the DB_ BLOCK_CHECKSUM initialization parameter Clearing an Online Redo Log File An online redo log file might become corrupted while the database is open, and ultimately stop database activity because archiving cannot continue. In this situation the ALTER DATABASE CLEAR LOGFILE statement can be used reinitialize the file without shutting down the database. The following statement clears the log files in redo log group number 3: ALTER DATABASE CLEAR LOGFILE GROUP 3; This statement overcomes two situations where dropping redo logs is not possible: ■ If there are only two log groups ■ The corrupt redo log file belongs to the current group If the corrupt redo log file has not been archived, use the UNARCHIVED keyword in the statement. ALTER DATABASE CLEAR UNARCHIVED LOGFILE GROUP 3; This statement clears the corrupted redo logs and avoids archiving them. The cleared redo logs are available for use even though they were not archived. If you clear a log file that is needed for recovery of a backup, then you can no longer recover from that backup. Oracle writes a message in the alert log describing the backups from which you cannot recover. Managing the Online Redo Log 7-19 Viewing Online Redo Log Information Note: If you clear an unarchived redo log file, you should make another backup of the database. If you want to clear an unarchived redo log that is needed to bring an offline tablespace online, use the UNRECOVERABLE DATAFILE clause in the ALTER DATABASE CLEAR LOGFILE statement. If you clear a redo log needed to bring an offline tablespace online, you will not be able to bring the tablespace online again. You will have to drop the tablespace or perform an incomplete recovery. Note that tablespaces taken offline normal do not require recovery. Viewing Online Redo Log Information Use the following views to display online redo log information. View Description V$LOG Displays the redo log file information from the control file V$LOGFILE Identifies redo log groups and members and member status V$LOG_HISTORY Contains log history information The following query returns the control file information about the online redo log for a database. SELECT * FROM V$LOG; GROUP# THREAD# SEQ BYTES MEMBERS ARC STATUS FIRST_CHANGE# FIRST_TIM ------ ------- ----- ------- ------- --- --------- ------------- --------1 1 10605 1048576 1 YES ACTIVE 11515628 16-APR-00 2 1 10606 1048576 1 NO CURRENT 11517595 16-APR-00 3 1 10603 1048576 1 YES INACTIVE 11511666 16-APR-00 4 1 10604 1048576 1 YES INACTIVE 11513647 16-APR-00 To see the names of all of the member of a group, use a query similar to the following: SELECT * FROM V$LOGFILE; GROUP# STATUS MEMBER ------ ------- ---------------------------------- 7-20 Oracle9i Database Administrator’s Guide Viewing Online Redo Log Information 1 2 3 4 D:\ORANT\ORADATA\IDDB2\REDO04.LOG D:\ORANT\ORADATA\IDDB2\REDO03.LOG D:\ORANT\ORADATA\IDDB2\REDO02.LOG D:\ORANT\ORADATA\IDDB2\REDO01.LOG If STATUS is blank for a member, then the file is in use. See Also: Oracle9i Database Reference for detailed information about these views Managing the Online Redo Log 7-21 Viewing Online Redo Log Information 7-22 Oracle9i Database Administrator’s Guide 8 Managing Archived Redo Logs This chapter describes how to archive redo data. It contains the following topics: ■ What Is the Archived Redo Log? ■ Choosing Between NOARCHIVELOG and ARCHIVELOG Mode ■ Controlling Archiving ■ Specifying the Archive Destination ■ Specifying the Mode of Log Transmission ■ Managing Archive Destination Failure ■ Tuning Archive Performance by Specifying Multiple ARCn Processes ■ Controlling Trace Output Generated by the Archivelog Process ■ Viewing Information About the Archived Redo Log See Also: Oracle9i Real Application Clusters Administration for information specific to archiving in the Oracle Real Application Clusters environment Managing Archived Redo Logs 8-1 What Is the Archived Redo Log? What Is the Archived Redo Log? Oracle enables you to save filled groups of online redo log files to one or more offline destinations, known collectively as the archived redo log, or more simply archive log. The process of turning online redo log files into archived redo log files is called archiving. This process is only possible if the database is running in ARCHIVELOG mode. You can choose automatic or manual archiving. An archived redo log file is a copy of one of the identical filled members of an online redo log group. It includes the redo entries present in the identical member of a redo log group and also preserves the group’s unique log sequence number. For example, if you are multiplexing your online redo log, and if Group 1 contains member files a_log1 and b_log1, then the archiver process (ARCn) will archive one of these identical members. Should a_log1 become corrupted, then ARCn can still archive the identical b_log1. The archived redo log contains a copy of every group created since you enabled archiving. When running in ARCHIVELOG mode, the log writer process (LGWR) is not allowed to reuse and hence overwrite an online redo log group until it has been archived. The background process ARCn automates archiving operations when automatic archiving is enabled. Oracle starts multiple archiver processes as needed to ensure that the archiving of filled online redo logs does not fall behind. You can use archived redo logs to: ■ Recover a database ■ Update a standby database ■ Gain information about the history of a database using the LogMiner utility Choosing Between NOARCHIVELOG and ARCHIVELOG Mode This section describes the issues you must consider when choosing to run your database in NOARCHIVELOG or ARCHIVELOG mode, and contains these topics: ■ Running a Database in NOARCHIVELOG Mode ■ Running a Database in ARCHIVELOG Mode Running a Database in NOARCHIVELOG Mode When you run your database in NOARCHIVELOG mode, you disable the archiving of the online redo log. The database’s control file indicates that filled groups are not 8-2 Oracle9i Database Administrator’s Guide Choosing Between NOARCHIVELOG and ARCHIVELOG Mode required to be archived. Therefore, when a filled group becomes inactive after a log switch, the group is available for reuse by LGWR. The choice of whether to enable the archiving of filled groups of online redo log files depends on the availability and reliability requirements of the application running on the database. If you cannot afford to lose any data in your database in the event of a disk failure, use ARCHIVELOG mode. The archiving of filled online redo log files can require you to perform extra administrative operations. NOARCHIVELOG mode protects a database only from instance failure, but not from media failure. Only the most recent changes made to the database, which are stored in the groups of the online redo log, are available for instance recovery. In other words, if a media failure occurs while in NOARCHIVELOG mode, you can only restore (not recover) the database to the point of the most recent full database backup. You cannot recover subsequent transactions. Also, in NOARCHIVELOG mode you cannot perform online tablespace backups. Furthermore, you cannot use online tablespace backups previously taken while the database operated in ARCHIVELOG mode. You can only use whole database backups taken while the database is closed to restore a database operating in NOARCHIVELOG mode. Therefore, if you decide to operate a database in NOARCHIVELOG mode, take whole database backups at regular, frequent intervals. Running a Database in ARCHIVELOG Mode When you run a database in ARCHIVELOG mode, you specify the archiving of the online redo log. The database control file indicates that a group of filled online redo log files cannot be used by LGWR until the group is archived. A filled group is immediately available for archiving after a redo log switch occurs. The archiving of filled groups has these advantages: ■ ■ ■ A database backup, together with online and archived redo log files, guarantees that you can recover all committed transactions in the event of an operating system or disk failure. You can use a backup taken while the database is open and in normal system use if you keep an archived log. You can keep a standby database current with its original database by continually applying the original’s archived redo logs to the standby. Decide how you plan to archive filled groups of the online redo log. You can configure an instance to archive filled online redo log files automatically, or you can archive manually. For convenience and efficiency, automatic archiving is usually Managing Archived Redo Logs 8-3 Controlling Archiving best. Figure 8–1 illustrates how the archiver process (ARC0 in this illustration) writes filled online redo log files to the database’s archived redo log. If all databases in a distributed database operate in ARCHIVELOG mode, you can perform coordinated distributed database recovery. If any database in a distributed database uses NOARCHIVELOG mode, however, recovery of a global distributed database (to make all databases consistent) is limited by the last full backup of any database operating in NOARCHIVELOG mode. Figure 8–1 Online Redo Log File Use in ARCHIVELOG Mode 0001 0001 LGWR Log 0001 0001 0001 0002 0002 0001 0002 0002 0003 0003 ARC0 ARC0 ARC0 LGWR LGWR LGWR Log 0003 Log 0004 Log 0002 Archived Redo Log Files Online Redo Log Files TIME Controlling Archiving This section describes how to control the archiving mode of the database, and how to control the archiving process. The following topics are discussed: 8-4 Oracle9i Database Administrator’s Guide Controlling Archiving ■ Setting the Initial Database Archiving Mode ■ Changing the Database Archiving Mode ■ Enabling Automatic Archiving ■ Disabling Automatic Archiving ■ Performing Manual Archiving See Also: Your Oracle operating system specific documentation contains additional information on controlling archiving modes. Setting the Initial Database Archiving Mode You set a database’s initial archiving mode as part of database creation in the CREATE DATABASE statement. Usually, you can use the default of NOARCHIVELOG mode at database creation because there is no need to archive the redo information generated then. After creating the database, decide whether to change from the initial archiving mode. Note: If a database is automatically created during Oracle installation, the initial archiving mode of the database is operating system specific. Changing the Database Archiving Mode To switch a database’s archiving mode, use the ALTER DATABASE statement with the ARCHIVELOG or NOARCHIVELOG option. The following steps switch a database’s archiving mode from NOARCHIVELOG to ARCHIVELOG: 1. Shut down the database instance. SHUTDOWN An open database must first be closed and any associated instances shut down before you can switch the database’s archiving mode. You cannot disable archiving if any datafiles need media recovery. 2. Back up the database. Before making any major change to a database, always back up the database to protect against any problems. This will be your final backup of the database in NOARCHIVELOG mode and can be used if something goes wrong while Managing Archived Redo Logs 8-5 Controlling Archiving trying to change to ARCHIVELOG mode. See Oracle9i User-Managed Backup and Recovery Guide or Oracle9i Recovery Manager User’s Guide. 3. Edit the initialization parameter file to include initialization parameters specifying whether automatic archiving is enabled (see "Enabling Automatic Archiving" on page 8-6) and the destinations for the archive log files (see "Specifying Archive Destinations" on page 8-10). 4. Start a new instance and mount, but do not open, the database. STARTUP MOUNT To enable or disable archiving, the database must be mounted but not open. 5. Switch the database’s archiving mode. Then open the database for normal operations. ALTER DATABASE ARCHIVELOG; ALTER DATABASE OPEN; 6. Shut down the database. SHUTDOWN IMMEDIATE 7. Back up the database. Changing the database archiving mode updates the control file. After changing the database archiving mode, you must back up all of your database files and control file. Any previous backup is no longer usable because it was taken in NOARCHIVELOG mode. See Also: Oracle9i Real Application Clusters Administration for more information about switching the archiving mode when using Oracle9i Real Application Clusters Enabling Automatic Archiving You can enable automatic archiving of the online redo log. When automatic archiving is enabled, no action is required to copy a group after it fills: Oracle automatically archives it. However, even when automatic archiving is enabled, you can still perform manual archiving as described in "Performing Manual Archiving" on page 8-9. You can enable automatic archiving before or after instance startup. To enable automatic archiving after instance startup, you must be connected to Oracle with 8-6 Oracle9i Database Administrator’s Guide Controlling Archiving administrator privileges (AS SYSDBA), or have the ALTER SYSTEM system privilege. Ensure that an archived redo log destination and file name format have been specified before enabling automatic archiving. This is described in "Specifying Archive Destinations" on page 8-10. Caution: Oracle does not automatically archive log files unless the database is also in ARCHIVELOG mode. Enabling Automatic Archiving at Instance Startup To enable automatic archiving of filled groups each time an instance is started, include the initialization parameter LOG_ARCHIVE_START in the database’s initialization parameter file and set it to TRUE: LOG_ARCHIVE_START=TRUE The new value takes effect the next time you start the database. Enabling Automatic Archiving After Instance Startup To enable automatic archiving of filled online redo log groups without shutting down the current instance, use the ALTER SYSTEM statement specifying the ARCHIVE LOG START clause. For example: ALTER SYSTEM ARCHIVE LOG START; You can optionally include the archiving destination. Note: If an instance is shut down and restarted after automatic archiving is enabled using the ALTER SYSTEM statement, the instance is reinitialized using the settings of the initialization parameter file. Those settings may or may not enable automatic archiving. If your intent is to always archive redo log files automatically, then you should include LOG_ARCHIVE_START = TRUE in your initialization parameters. Controlling the Number of Archiver Processes Oracle starts additional archiver processes (ARCn) as needed to ensure that the automatic processing of filled redo log files does not fall behind. However, to avoid Managing Archived Redo Logs 8-7 Controlling Archiving any runtime overhead of invoking additional ARCn processes, you can specify the number of processes to be started at instance startup using the LOG_ARCHIVE_ MAX_PROCESSES initialization parameter. Up to 10 ARCn processes can be started. This parameter also limits the number of ARCn processes that can be started for the instance. No more than the specified number of processes can ever be started. The LOG_ARCHIVE_MAX_PROCESSES is dynamic, and can be changed using the ALTER SYSTEM statement. The following statement increases (or decreases) the number of ARCn processes currently running: ALTER SYSTEM SET LOG_ARCHIVE_MAX_PROCESSES=3; There is usually no need to change the LOG_ARCHIVE_MAX_PROCESSES initialization parameter from its default value of 2, because Oracle will adequately adjust ARCn processes according to system workload. Disabling Automatic Archiving You can disable automatic archiving of the online redo log groups at any time. After having disabled automatic archiving, you must manually archive groups of online redo log files in a timely fashion. If you run a database in ARCHIVELOG mode and disable automatic archiving, and if all groups of online redo log files are filled but not archived, then LGWR cannot reuse any inactive groups of online redo log groups. Therefore, database operation is temporarily suspended until you perform the necessary archiving. You can disable automatic archiving at or after instance startup. To disable automatic archiving after instance startup, you must be connected with administrator privileges or have the ALTER SYSTEM privilege. Disabling Automatic Archiving at Instance Startup To disable the automatic archiving of filled online redo log groups at database startup, set the LOG_ARCHIVE_START initialization parameter to FALSE: LOG_ARCHIVE_START=FALSE Disabling Automatic Archiving after Instance Startup To disable the automatic archiving of filled online redo log groups without shutting down the current instance, use the SQL statement ALTER SYSTEM with the ARCHIVE LOG STOP parameter. The following statement stops archiving: ALTER SYSTEM ARCHIVE LOG STOP; 8-8 Oracle9i Database Administrator’s Guide Specifying the Archive Destination If ARCn is archiving a redo log group when you attempt to disable automatic archiving, ARCn finishes archiving the current group, but does not begin archiving the next filled online redo log group. The instance does not have to be shut down to disable automatic archiving. If an instance is shut down and restarted after automatic archiving is disabled, however, the instance is reinitialized using the settings of the initialization parameter file, which may or may not enable automatic archiving. Performing Manual Archiving If you operate your database in ARCHIVELOG mode, but do not have automatic archiving enabled, then you must archive inactive groups of filled online redo log files or your database operation can be temporarily suspended. You can also use manual archiving, even when automatic archiving is enabled, for such action as rearchiving an inactive group of filled online redo log members to another location. In this case, however, it is possible that the instance can reuse the redo log group before you have finished manually archiving, and thereby overwrite the files. If this happens, Oracle will write an error message to the alert file. To archive a filled online redo log group manually, connect with administrator privileges. Use the ALTER SYSTEM statement with the ARCHIVE LOG clause to manually archive filled online redo log files. The following statement archives all unarchived log files: ALTER SYSTEM ARCHIVE LOG ALL; Specifying the Archive Destination When archiving redo logs, determine the destination to which you will archive and familiarize yourself with the various destination states. Develop a practice of using dynamic performance (V$) views, listed in "Viewing Information About the Archived Redo Log" on page 8-23, to access archive information. The following topics are contained in this section ■ Specifying Archive Destinations ■ Understanding Archive Destination Status Managing Archived Redo Logs 8-9 Specifying the Archive Destination Specifying Archive Destinations You must decide whether to make a single destination for the logs or multiplex them. When you multiplex them, you archive the logs to more than one location. You specify your choice by setting initialization parameters according to one of the following methods. Method Initialization Parameter Host Example 1 Local or remote LOG_ARCHIVE_DEST_1 = 'LOCATION=/disk1/arc' Local only LOG_ARCHIVE_DEST = '/disk1/arc' LOG_ARCHIVE_DEST_n where: LOG_ARCHIVE_DEST_2 = 'SERVICE=standby1' n is an integer from 1 to 10 2 LOG_ARCHIVE_DEST and LOG_ARCHIVE_DUPLEX_DEST LOG_ARCHIVE_DUPLEX_DEST = '/disk2/arc' See Also: ■ ■ Oracle9i Database Reference for additional information about the initialization parameters used to control the archiving of redo logs Oracle9i Data Guard Concepts and Administration for information about using the LOG_ARCHIVE_DEST_n initialization parameter for specifying a standby destination. There are additional keywords that can be specified with this initialization parameter and that are not discussed in this book. Method 1: Using the LOG_ARCHIVE_DEST_n Parameter The first method is to use the LOG_ARCHIVE_DEST_n parameter (where n is an integer from 1 to 10) to specify from one to ten different destinations for archival. Each numerically-suffixed parameter uniquely identifies an individual destination. You specify the location for LOG_ARCHIVE_DEST_n using these keywords: 8-10 Keyword Indicates Example LOCATION A local file system location. LOG_ARCHIVE_DEST_1 = 'LOCATION=/disk1/arc' SERVICE Remote archival through Oracle Net service name. LOG_ARCHIVE_DEST_2 = 'SERVICE=standby1' Oracle9i Database Administrator’s Guide Specifying the Archive Destination If you use the LOCATION keyword, specify a valid path name for your operating system. If you specify SERVICE, Oracle translates the net service name through the tnsnames.ora file to a connect descriptor. The descriptor contains the information necessary for connecting to the remote database. The service name must have an associated database SID, so that Oracle correctly updates the log history of the control file for the standby database. Perform the following steps to set the destination for archived redo logs using the LOG_ARCHIVE_DEST_n initialization parameter: 1. Use SQL*Plus to shut down the database. SHUTDOWN 2. Edit the LOG_ARCHIVE_DEST_n parameter to specify from one to ten archiving locations. The LOCATION keyword specifies an operating system specific path name. For example, enter: LOG_ARCHIVE_DEST_1 = 'LOCATION = /disk1/archive' LOG_ARCHIVE_DEST_2 = 'LOCATION = /disk2/archive' LOG_ARCHIVE_DEST_3 = 'LOCATION = /disk3/archive' If you are archiving to a standby database, use the SERVICE keyword to specify a valid net service name from the tnsnames.ora file. For example, enter: LOG_ARCHIVE_DEST_4 = 'SERVICE = standby1' 3. Edit the LOG_ARCHIVE_FORMAT initialization parameter, using %s to include the log sequence number as part of the file name and %t to include the thread number. Use capital letters (%S and %T) to pad the file name to the left with zeroes. For example, enter: LOG_ARCHIVE_FORMAT = arch%s.arc These settings will generate archived logs as follows for log sequence numbers 100, 101, and 102: /disk1/archive/arch100.arc, /disk1/archive/arch101.arc, /disk1/archive/arch102.arc /disk2/archive/arch100.arc, /disk2/archive/arch101.arc, /disk2/archive/arch102.arc /disk3/archive/arch100.arc, /disk3/archive/arch101.arc, /disk3/archive/arch102.arc Managing Archived Redo Logs 8-11 Specifying the Archive Destination Method 2: Using LOG_ARCHIVE_DEST and LOG_ARCHIVE_DUPLEX_DEST The second method, which allows you to specify a maximum of two locations, is to use the LOG_ARCHIVE_DEST parameter to specify a primary archive destination and the LOG_ARCHIVE_DUPLEX_DEST to specify an optional secondary archive destination. Whenever Oracle archives a redo log, it archives it to every destination specified by either set of parameters. Perform the following steps to use method 2: 1. Use SQL*Plus to shut down the database. SHUTDOWN 2. Specify destinations for the LOG_ARCHIVE_DEST and LOG_ARCHIVE_ DUPLEX_DEST parameter (you can also specify LOG_ARCHIVE_DUPLEX_DEST dynamically using the ALTER SYSTEM statement). For example, enter: LOG_ARCHIVE_DEST = '/disk1/archive' LOG_ARCHIVE_DUPLEX_DEST = '/disk2/archive' 3. Edit the LOG_ARCHIVE_FORMAT parameter, using %s to include the log sequence number as part of the file name and %t to include the thread number. Use capital letters (%S and %T) to pad the file name to the left with zeroes. For example, enter: LOG_ARCHIVE_FORMAT = arch_%t_%s.arc For example, the above settings generates archived logs as follows for log sequence numbers 100 and 101 in thread 1: /disk1/archive/arch_1_100.arc, /disk1/archive/arch_1_101.arc /disk2/archive/arch_1_100.arc, /disk2/archive/arch_1_101.arc See Also: The following books contain more information about archiving and standby databases: ■ Oracle9i User-Managed Backup and Recovery Guide ■ Oracle9i Recovery Manager User’s Guide ■ Oracle9i Data Guard Concepts and Administration. Understanding Archive Destination Status Each archive destination has the following variable characteristics that determine its status: 8-12 Oracle9i Database Administrator’s Guide Specifying the Archive Destination ■ ■ ■ Valid/Invalid—indicates whether the disk location or service name information is specified and valid Enabled/Disabled—indicates the availability state of the location and whether Oracle can use the destination Active/Inactive—indicates whether there was a problem accessing the destination Several combinations of these characteristics are possible. To obtain the current status and other information about each destination for an instance, query the V$ARCHIVE_DEST view. The characteristics determining a locations status that appear in the view are shown in Table 8–1. Note that for a destination to be used, its characteristics must be valid, enabled, and active. Table 8–1 Destination Status Characteristics STATUS Valid Enabled Active Meaning VALID True True True The user has properly initialized the destination, which is available for archiving. INACTIVE False n/a n/a The user has not provided or has deleted the destination information. ERROR True True False An error occurred creating or writing to the destination file; refer to error data. FULL True True False Destination is full (no disk space). DEFERRED True False True The user manually and temporarily disabled the destination. DISABLED True False False The user manually and temporarily disabled the destination following an error; refer to error data. BAD PARAM n/a n/a n/a A parameter error occurred; refer to error data. Usually this state is only seen when the LOG_ARCHIVE_ START initialization parameter is not set. Managing Archived Redo Logs 8-13 Specifying the Mode of Log Transmission The LOG_ARCHIVE_DEST_STATE_n (where n is an integer from 1 to 10) initialization parameter allows you to control the availability state of the specified destination (n). The destination state can have three values: ENABLE,DEFER, or ALTERNATE. The value ENABLE indicates that Oracle can use the destination, whereas DEFER indicates that the location is temporarily disabled. The third value, ALTERNATE, means that the destination is an alternate. It’s availability state is DEFER, unless there is a failure of its parent destination, in which case its state becomes ENABLE. Specifying the Mode of Log Transmission There are two modes of transmitting archived logs to their destination: normal archiving transmission and standby transmission mode. Normal transmission involves transmitting files to a local disk. Standby transmission involves transmitting files through a network to either a local or remote standby database. Normal Transmission Mode In normal transmission mode, the archiving destination is another disk drive of the database server. In this configuration archiving does not contend with other files required by the instance and can complete more quickly. Specify the destination with either the LOG_ARCHIVE_DEST_n or LOG_ARCHIVE_DEST parameters. Ideally, you should permanently move archived redo log files and corresponding database backups from the local disk to inexpensive offline storage media such as tape. Because a primary value of archived logs is database recovery, you want to ensure that these logs are safe should disaster strike your primary database. Standby Transmission Mode In standby transmission mode, the archiving destination is either a local or remote standby database. Caution: You can maintain a standby database on a local disk, but Oracle strongly encourages you to maximize disaster protection by maintaining your standby database at a remote site. If you are operating your standby database in managed recovery mode, you can keep your standby database in sync with your source database by automatically applying transmitted archive logs. 8-14 Oracle9i Database Administrator’s Guide Specifying the Mode of Log Transmission To transmit files successfully to a standby database, either ARCn or a server process must do the following: ■ ■ Recognize a remote location Transmit the archived logs in conjunction with a remote file server (RFS) process that resides on the remote server Each ARCn process has a corresponding RFS for each standby destination. For example, if three ARCn processes are archiving to two standby databases, then Oracle establishes six RFS connections. You can transmit archived logs through a network to a remote location by using Oracle Net. Indicate a remote archival by specifying a Oracle Net service name as an attribute of the destination. Oracle then translates the service name, through the tnsnames.ora file to a connect descriptor. The descriptor contains the information necessary for connecting to the remote database. The service name must have an associated database SID, so that Oracle correctly updates the log history of the control file for the standby database. The RFS process, which runs on the destination node, acts as a network server to the ARCn client. Essentially, ARCn pushes information to RFS, which transmits it to the standby database. The RFS process, which is required when archiving to a remote destination, is responsible for the following tasks: ■ ■ ■ ■ Consuming network I/O from the ARCn process Creating file names on the standby database by using the STANDBY_ARCHIVE_ DEST parameter Populating the log files at the remote site Updating the standby database’s control file (which Recovery Manager can then use for recovery) Archived redo logs are integral to maintaining a standby database, which is an exact replica of a database. You can operate your database in standby archiving mode, which automatically updates a standby database with archived redo logs from the original database. See Also: ■ ■ Oracle9i Data Guard Concepts and Administration Oracle9i Net Services Administrator’s Guide for informationn about connecting to a remote database using a service name Managing Archived Redo Logs 8-15 Managing Archive Destination Failure Managing Archive Destination Failure Sometimes archive destinations can fail, causing problems when you operate in automatic archiving mode. To minimize the problems associated with destination failure, Oracle provides you with options. Discussions of these options are contained in the following sections: ■ Specifying the Minimum Number of Successful Destinations ■ Re-Archiving to a Failed Destination Specifying the Minimum Number of Successful Destinations The optional initialization parameter LOG_ARCHIVE_MIN_SUCCEED_DEST=n (where n is an integer from 1 to 10, or 1 to 2 if you choose to use duplexing) determines the minimum number of destinations to which Oracle must successfully archive a redo log group before it can reuse online log files. The default value is 1. Specifying Mandatory and Optional Destinations Using the LOG_ARCHIVE_DEST_n parameter, you can specify whether a destination has the attributes OPTIONAL (default) or MANDATORY. The LOG_ ARCHIVE_MIN_SUCCEED_DEST=n parameter uses all MANDATORY destinations plus some number of OPTIONAL non-standby destinations to determine whether LGWR can overwrite the online log. When determining how to set your parameters, note the following: ■ ■ ■ ■ ■ 8-16 Not specifying MANDATORY for a destination is the same as specifying OPTIONAL. You must have at least one local destination, which you can declare OPTIONAL or MANDATORY. When using LOG_ARCHIVE_MIN_SUCCEED_DEST=n at least one local destination will operationally be treated as MANDATORY, since the minimum value for LOG_ARCHIVE_MIN_SUCCEED_DEST is 1. The failure of any MANDATORY destination, including a MANDATORY standby destination, makes the LOG_ARCHIVE_MIN_SUCCEED_DEST parameter irrelevant. The LOG_ARCHIVE_MIN_SUCCEED_DEST value cannot be greater than the number of destinations, nor greater than the number of MANDATORY destinations plus the number of OPTIONAL local destinations. Oracle9i Database Administrator’s Guide Managing Archive Destination Failure If you DEFER a MANDATORY destination, and Oracle overwrites the online log without transferring the archived log to the standby site, then you must transfer the log to the standby manually. ■ You can also establish which destinations are mandatory or optional by using the LOG_ARCHIVE_DEST and LOG_ARCHIVE_DUPLEX_DEST parameters. Note the following rules: Any destination declared by LOG_ARCHIVE_DEST is mandatory. ■ Any destination declared by LOG_ARCHIVE_DUPLEX_DEST is optional if LOG_ ARCHIVE_MIN_SUCCEED_DEST = 1 and mandatory if LOG_ARCHIVE_MIN_ SUCCEED_DEST = 2. ■ Sample Scenarios: Specifying the Number of Successful Destinations You can see the relationship between the LOG_ARCHIVE_DEST_n and LOG_ ARCHIVE_MIN_SUCCEED_DEST parameters most easily through sample scenarios. Scenario 1 In this scenario, you archive to three local destinations, each of which you declare as OPTIONAL. Table 8–2 illustrates the possible values for LOG_ARCHIVE_ MIN_SUCCEED_DEST=n in this case. Table 8–2 LOG_ARCHIVE_MIN_SECCEED_DEST Values for Scenario 1 Value Meaning 1 Oracle can reuse log files only if at least one of the OPTIONAL destinations succeeds. 2 Oracle can reuse log files only if at least two of the OPTIONAL destinations succeed. 3 Oracle can reuse log files only if all of the OPTIONAL destinations succeed. 4 or greater ERROR: The value is greater than the number of destinations. This scenario shows that even though you do not explicitly set any of your destinations to MANDATORY using the LOG_ARCHIVE_DEST_n parameter, Oracle must successfully archive to one or more of these locations when LOG_ARCHIVE_ MIN_SUCCEED_DEST is set to 1, 2, or 3. Scenario 2 In this scenario, consider a case in which: ■ You specify two MANDATORY destinations. Managing Archived Redo Logs 8-17 Managing Archive Destination Failure ■ You specify two OPTIONAL destinations. ■ No destination is a standby database. Table 8–3 shows the possible values for LOG_ARCHIVE_MIN_SUCCEED_DEST=n. Table 8–3 LOG_ARCHIVE_MIN_SUCCEED_DEST Values for Scenario 2 Value Meaning 1 Oracle ignores the value and uses the number of MANDATORY destinations (in this example, 2). 2 Oracle can reuse log files even if no OPTIONAL destination succeeds. 3 Oracle can reuse logs only if at least one OPTIONAL destination succeeds. 4 Oracle can reuse logs only if both OPTIONAL destinations succeed. 5 or greater ERROR: The value is greater than the number of destinations. This case shows that Oracle must archive to the destinations you specify as MANDATORY, regardless of whether you set LOG_ARCHIVE_MIN_SUCCEED_DEST to archive to a smaller number of destinations. Re-Archiving to a Failed Destination Use the REOPEN attribute of the LOG_ARCHIVE_DEST_n parameter to specify whether and when ARCn attempts to rearchive to a failed destination following an error. REOPEN applies to all errors, not just OPEN errors. REOPEN=n sets the minimum number of seconds before ARCn should try to reopen a failed destination. The default value for n is 300 seconds. A value of 0 is the same as turning off the REOPEN option. In other words, ARCn will not attempt to archive after a failure. If you do not specify the REOPEN keyword, ARCn will never reopen a destination following an error. You cannot use REOPEN to specify a limit on the number of attempts to reconnect and transfer archived logs. The REOPEN attempt either succeeds or fails, in which case the REOPEN information is reset. If you specify REOPEN for an OPTIONAL destination, Oracle can overwrite online logs if there is an error. If you specify REOPEN for a MANDATORY destination, Oracle stalls the production database when it cannot successfully archive. In this situation, consider the following options: ■ 8-18 Archive manually to the failed destination. Oracle9i Database Administrator’s Guide Tuning Archive Performance by Specifying Multiple ARCn Processes ■ ■ Change the destination by deferring the destination, specifying the destination as optional, or changing the service. Drop the destination. When using the REOPEN keyword, note the following: ■ ■ ■ ARCn reopens a destination only when starting an archive operation from the beginning of the log file, never during a current operation. ARCn always retries the log copy from the beginning. If a REOPEN time was specified or defaulted, ARCn checks to see whether the time of the recorded error plus the REOPEN interval is less than the current time. If it is, ARCn retries the log copy. The REOPEN clause successfully affects the ACTIVE=TRUE destination state. The VALID and ENABLED states are not changed. Tuning Archive Performance by Specifying Multiple ARCn Processes For most databases, ARCn has no effect on overall system performance. On some large database sites, however, archiving can have an impact on system performance. On one hand, if ARCn works very quickly, overall system performance can be reduced while ARCn runs, since CPU cycles are being consumed in archiving. On the other hand, if ARCn runs extremely slowly, it has little detrimental effect on system performance, but it takes longer to archive redo log files, and can create a bottleneck if all redo log groups are unavailable because they are waiting to be archived. You can specify up to ten ARCn processes for each database instance. Enable the multiple processing feature at startup or at runtime by setting the initialization parameter LOG_ARCHIVE_MAX_PROCESSES=n (where n is any integer from 1 to 10). By default, the parameter is set to 2. Because LGWR automatically increases the number of ARCn processes should the current number be insufficient to handle the current workload, the parameter is intended to allow you to specify the initial number of ARCn processes or to increase or decrease the current number. Assuming the initial number of ARCn processes was set to 4, the following statement will decrease the number of processes to 2. ALTER SYSTEM SET LOG_ARCHIVE_MAX_PROCESSES=2; When decreasing the number of ARCn processes, it is not determinate exactly which process will be stopped. Also, you are not allowed to alter the value of the parameter to 0, so at least one ARCn process is always active. Query the Managing Archived Redo Logs 8-19 Tuning Archive Performance by Specifying Multiple ARCn Processes V$ARCHIVE_PROCESSES view to see information about the state of each archive process. Processes that have stopped show as being in the IDLE state. Creating multiple processes is especially useful when you: ■ Use more than two online redo logs ■ Archive to more than one destination Multiple ARCn processing prevents the bottleneck that occurs when LGWR switches through the multiple online redo logs faster than a single ARCn process can write inactive logs to multiple destinations. Each ARCn process works on only one inactive log at a time, but must archive to each specified destination. For example, if you maintain five online redo log files, then you may decide to start the instance using three ARCn processes. As LGWR actively writes to one of the log files, the ARCn processes can simultaneously archive up to three of the inactive log files to various destinations. As Figure 8–2 illustrates, each instance of ARCn assumes responsibility for a single log file and archives it to all of the defined destinations. 8-20 Oracle9i Database Administrator’s Guide Controlling Trace Output Generated by the Archivelog Process Figure 8–2 Using Multiple ARCn Processes LGWR LOG1 (inactive) LOG2 (inactive) LOG3 (inactive) LOG4 (inactive) ARC0 ARC1 ARC2 Destination 1 LOG5 (active) Destination 2 Oracle9i Database Performance Tuning Guide and Reference for more information about tuning the archiving process See Also: Controlling Trace Output Generated by the Archivelog Process As discussed in "Trace Files and the Alert File" on page 5-15, background processes always write to a trace file when appropriate. In the case of the archivelog process, it is possible to control the output that is generated. The LOG_ARCHIVE_TRACE initialization parameter can be set to specify a trace level. The following values can be specified: Managing Archived Redo Logs 8-21 Controlling Trace Output Generated by the Archivelog Process Trace Level Meaning 0 Disable archivelog tracing - default setting. 1 Track archival of redo log file. 2 Track archival status for each archivelog destination. 4 Track archival operational phase. 8 Track archivelog destination activity. 16 Track detailed archivelog destination activity. 32 Track archivelog destination parameter modifications. 64 Track ARCn process state activity 128 Track FAL (fetch archived log) server releated activities 256 Supported in a future release 512 Tracks asynchronous LGWR activity 1024 RFS physical client tracking 2048 ARCn/RFS heartbeat tracking You can combine tracing levels by specifying a value equal to the sum of the individual levels that you would like to trace. For example, setting LOG_ARCHIVE_ TRACE=12, will generate trace level 8 and 4 output. You can set different values for the primary and any standby database. The default value for the LOG_ARCHIVE_TRACE parameter is 0, and at this level, error conditions still generate the appropriate alert and trace entries. You can change the value of this parameter dynamically using the ALTER SYSTEM statement. For example: ALTER SYSTEM SET LOG_ARCHIVE_TRACE=12; Changes initiated in this manner will take effect at the start of the next archiving operation. See Also: Oracle9i Data Guard Concepts and Administration for information about using this parameter with a standby database 8-22 Oracle9i Database Administrator’s Guide Viewing Information About the Archived Redo Log Viewing Information About the Archived Redo Log You can display information about the archived redo logs using the following: ■ Dynamic Performance Views ■ The ARCHIVE LOG LIST Command Dynamic Performance Views There are several dynamic performance views that contain useful information about archived redo logs. Dynamic Performance View Description V$DATABASE Identifies whether the database is in ARCHIVELOG or NOARCHIVELOG mode. V$ARCHIVED_LOG Displays historical archived log information from the control file. If you use a recovery catalog, the RC_ARCHIVED_LOG view contains similar information. V$ARCHIVE_DEST Describes the current instance, all archive destinations, and the current value, mode, and status of these destinations. V$ARCHIVE_PROCESSES Displays information about the state of the various archive processes for an instance. V$BACKUP_REDOLOG Contains information about any backups of archived logs. If you use a recovery catalog, the RC_BACKUP_REDOLOG contains similar information. V$LOG Displays all online redo log groups for the database and indicates which need to be archived. V$LOG_HISTORY Contains log history information such as which logs have been archived and the SCN range for each archived log. For example, the following query displays which online redo log group requires archiving: SELECT GROUP#, ARCHIVED Managing Archived Redo Logs 8-23 Viewing Information About the Archived Redo Log FROM SYS.V$LOG; GROUP# -------1 2 ARC --YES NO To see the current archiving mode, query the V$DATABASE view: SELECT LOG_MODE FROM SYS.V$DATABASE; LOG_MODE -----------NOARCHIVELOG See Also: Oracle9i Database Reference for detailed descriptions of data dictionary views The ARCHIVE LOG LIST Command The SQL*Plus command ARCHIVE LOG LIST can be used to show archiving information for the connected instance. For example: SQL> ARCHIVE LOG LIST Database log mode Automatic archival Archive destination Oldest online log sequence Next log sequence to archive Current log sequence Archive Mode Enabled D:\ORANT\oradata\IDDB2\archive 11160 11163 11163 This display tells you all the necessary information regarding the archived redo log settings for the current instance: 8-24 ■ The database is currently operating in ARCHIVELOG mode. ■ Automatic archiving is enabled. ■ The archived redo log’s destination is D:\ORANT\oradata\IDDB2\archive. ■ The oldest filled online redo log group has a sequence number of 11160. ■ The next filled online redo log group to archive has a sequence number of 11163. ■ The current online redo log file has a sequence number of 11163. Oracle9i Database Administrator’s Guide Viewing Information About the Archived Redo Log SQL*Plus User’s Guide and Reference for more information on the ARCHIVE LOG LIST command See Also: Managing Archived Redo Logs 8-25 Viewing Information About the Archived Redo Log 8-26 Oracle9i Database Administrator’s Guide 9 Using LogMiner to Analyze Redo Logs The Oracle LogMiner utility enables you to query redo logs through a SQL interface. Redo logs contain information about the history of activity on a database. This chapter contains the following sections: ■ Potential Uses for Data Stored in Redo Logs ■ Accessing Information Stored in Redo Logs ■ Redo Logs and Dictionary Files ■ LogMiner Recommendations and Restrictions ■ Filtering Data That is Returned ■ Accessing LogMiner Information ■ Querying V$LOGMNR_CONTENTS ■ Extracting Actual Data Values from Redo Logs ■ Supplemental Logging ■ Steps in a Typical LogMiner Session ■ Example Uses of LogMiner This chapter describes LogMiner functionality as it is used from the command line. You also have the option of accessing LogMiner functionality through the Oracle LogMiner Viewer graphical user interface (GUI). The LogMiner Viewer is a part of Oracle Enterprise Manager. Using LogMiner to Analyze Redo Logs 9-1 Potential Uses for Data Stored in Redo Logs Potential Uses for Data Stored in Redo Logs All changes made to user data or to the data dictionary are recorded in the Oracle redo logs. Therefore, redo logs contain all the necessary information to perform recovery operations. Because redo log data is often kept in archived files, the data is already available. To ensure that redo logs contain useful information, you should enable at least minimal supplemental logging. See Also: Supplemental Logging on page 9-19 The following are some of the potential uses for data contained in redo logs: ■ Pinpointing when a logical corruption to a database, such as errors made at the application level, may have begun. An example of an error made at the application level could be if a user mistakenly updated a database to give all employees 100 percent salary increases rather than 10 percent increases. It is important to know exactly when corruption began so that you know when to initiate time-based or change-based recovery. This enables you to restore the database to the state it was in just before corruption. See Also: See Extracting Actual Data Values from Redo Logs on page 9-18 for details about how you can use LogMiner to accomplish this. ■ ■ ■ Detecting and whenever possible, correcting user error, which is a more likely scenario than logical corruption. User errors include deleting the wrong rows because of incorrect values in a WHERE clause, updating rows with incorrect values, dropping the wrong index, and so forth. Determining what actions you would have to take to perform fine-grained recovery at the transaction level. If you fully understand and take into account existing dependencies, it may be possible to perform a table-based undo operation to roll back a set of changes. Normally you would have to restore the table to its previous state, and then apply an archived redo log to roll it forward. Performance tuning and capacity planning through trend analysis. You can determine which tables get the most updates and inserts. That information provides a historical perspective on disk access statistics, which can be used for tuning purposes. 9-2 Oracle9i Database Administrator’s Guide Accessing Information Stored in Redo Logs ■ Performing post-auditing. The redo logs contain all the information necessary to track any DML and DDL statements executed on the database, the order in which they were executed, and who executed them. Accessing Information Stored in Redo Logs Oracle Corporation provides SQL access to the redo logs through LogMiner, which is part of the Oracle database server. LogMiner presents the information in the redo logs through the V$LOGMNR_CONTENTS fixed view. This view contains historical information about changes made to the database including, but not limited to, the following: ■ The type of change made to the database (INSERT, UPDATE, DELETE, or DDL). ■ The SCN at which a change was made (SCN column). ■ The SCN at which a change was committed (COMMIT_SCN column). ■ ■ ■ ■ ■ The transaction to which a change belongs (XIDUSN, XIDSLT, and XIDSQN columns). The table and schema name of the modified object (SEG_NAME and SEG_OWNER columns). The name of the user who issued the DDL or DML statement to make the change (USERNAME column). Reconstructed SQL statements showing SQL that is equivalent (but not necessarily identical) to the SQL used to generate the redo records (SQL_REDO column). If a password is part of the statement in a SQL_REDO column, the password is encrypted. Reconstructed SQL statements showing the SQL statements needed to undo the change (SQL_UNDO column). SQL_UNDO columns that correspond to DDL statements are always NULL. Similarly, the SQL_UNDO column may be NULL for some datatypes and for rolled back operations. The redo logs contain internally generated numerical identifiers to identify tables and their associated columns. To reconstruct SQL statements, LogMiner needs to know how the internal identifiers map to user-defined names. This mapping information is stored in the data dictionary for the database. LogMiner provides a procedure (DBMS_LOGMNR_D.BUILD) that lets you extract the data dictionary. See Also: Oracle9i Supplied PL/SQL Packages and Types Reference for a complete description of the DBMS_LOGMNR_D.BUILD procedure Using LogMiner to Analyze Redo Logs 9-3 Redo Logs and Dictionary Files The following section describes redo logs and dictionary files in further detail. Redo Logs and Dictionary Files Before you begin using LogMiner, it is important to understand how LogMiner works with redo logs and dictionary files. This will help you to get accurate results and to plan the use of your system resources. The following concepts are discussed in this section: ■ Redo Logs ■ Dictionary Options ■ Tracking DDL Statements Redo Logs When you run LogMiner, you specify the names of redo logs that you want to analyze. LogMiner retrieves information from those redo logs and returns it through the V$LOGMNR_CONTENTS view. To ensure that the redo logs contain information of value to you, you must enable at least minimal supplemental logging. See Supplemental Logging on page 9-19. You can then use SQL to query the V$LOGMNR_CONTENTS view, as you would any other view. Each select operation that you perform against the V$LOGMNR_ CONTENTS view causes the redo logs to be read sequentially. Keep the following things in mind about redo logs: ■ ■ ■ ■ ■ The redo logs must be from a release 8.0 or later Oracle database. However, several of the LogMiner features introduced as of release 9.0.1 only work with redo logs produced on an Oracle9i or later database. See Restrictions on page 9-11. Support for LOB and LONG datatypes is available as of release 9.2, but only for redo logs generated on a release 9.2 Oracle database. The redo logs must use a database character set that is compatible with the character set of the database on which LogMiner is running. In general, the analysis of redo logs requires a dictionary that was generated from the same database that generated the redo logs. If you are using a dictionary that is in flat file format or that is stored in the redo logs, then the redo logs you want to analyze can be from either the database on which LogMiner is running or from other databases. 9-4 Oracle9i Database Administrator’s Guide Redo Logs and Dictionary Files ■ ■ ■ If you are using the online catalog as the LogMiner dictionary, you can only analyze redo logs from the database on which LogMiner is running. LogMiner must be running on the same hardware platform that generated the redo logs being analyzed. However, it does not have to be on the same system. It is important to specify the correct redo logs when running LogMiner. If you omit redo logs that contain some of the data you need, you will get inaccurate results when you query the V$LOGMNR_CONTENTS view. To determine which redo logs are being analyzed in the current LogMiner session you can look at the V$LOGMNR_LOGS view, which contains one row for each redo log. See Also: "Specify Redo Logs for Analysis" on page 9-24 Dictionary Options To fully translate the contents of redo logs, LogMiner requires access to a database dictionary. LogMiner uses the dictionary to translate internal object identifiers and datatypes to object names and external data formats. Without a dictionary, LogMiner returns internal object IDs and presents data as hex bytes. For example, instead of the SQL statement: INSERT INTO emp(name, salary) VALUES ('John Doe', 50000); LogMiner will display: insert into Object#2581(col#1, col#2) values (hextoraw('4a6f686e20446f65'), hextoraw('c306'));" A LogMiner dictionary file contains information that identifies the database it was created from and the time it was created. This information is used to validate the dictionary against the selected redo logs, automatically detecting any mismatch between LogMiner’s internal dictionary and the redo logs. The dictionary file must have the same database character set and be created from the same database as the redo logs being analyzed. However, once the dictionary is extracted, you can use it to mine the redo logs of that database in a separate database instance without being connected to the source database. Extracting a dictionary file also prevents problems that can occur when the current data dictionary contains only the newest table definitions. For instance, if a table Using LogMiner to Analyze Redo Logs 9-5 Redo Logs and Dictionary Files you are searching for was dropped sometime in the past, the current dictionary will not contain any references to it. LogMiner gives you three choices for your source dictionary: ■ Extracting the Dictionary to a Flat File ■ Extracting a Dictionary to the Redo Logs ■ Using the Online Catalog Extracting the Dictionary to a Flat File When the dictionary is in a flat file, fewer system resources are used than when it is contained in the redo logs. It is recommended that you regularly back up the dictionary extracts to ensure correct analysis of older redo logs. To extract database dictionary information to a flat file, use the DBMS_LOGMNR_ D.BUILD procedure with the STORE_IN_FLAT_FILE option. Be sure that no DDL operations occur while the dictionary is being built. The following steps describe how to extract a dictionary to a flat file (including extra steps you must take if you are using Oracle8). Steps 1 through 4 are preparation steps. You only need to do them once, and then you can extract a dictionary to a flat file as many times as you wish. 1. The DBMS_LOGMNR_D.BUILD procedure requires access to a directory where it can place the dictionary file. Because PL/SQL procedures do not normally access user directories, you must specify a directory for use by the DBMS_ LOGMNR_D.BUILD procedure or the procedure will fail. To specify a directory, set the initialization parameter, UTL_FILE_DIR, in the init.ora file. See Also: Oracle9i Database Reference for more information about the init.ora file For example, to set UTL_FILE_DIR to use /oracle/database as the directory where the dictionary file is placed, enter the following in the init.ora file: UTL_FILE_DIR = /oracle/database Remember that for the changes to the init.ora file to take effect, you must stop and restart the database. 2. For Oracle8 only. Otherwise, go to the next step: Use your operating system’s copy command to copy the dbmslmd.sql script, which is contained in the 9-6 Oracle9i Database Administrator’s Guide Redo Logs and Dictionary Files $ORACLE_HOME/rdbms/admin directory on the Oracle8i database, to the same directory in the Oracle8 database. For example, enter: % cp /8.1/oracle/rdbms/admin/dbmslmd.sql /8.0/oracle/rdbms/admin/dbmslmd.sql 3. If the database is closed, use SQL*Plus to mount and then open the database whose redo logs you want to analyze. For example, entering the STARTUP command mounts and opens the database: SQL> STARTUP 4. For Oracle8 only. Otherwise, go to the next step: Execute the copied dbmslmd.sql script on the 8.0 database to install the DBMS_LOGMNR_D package. For example, enter: @dbmslmd.sql You may need to enter the complete path to the script. 5. Execute the PL/SQL procedure DBMS_LOGMNR_D.BUILD. Specify a filename for the dictionary and a directory path name for the file. This procedure creates the dictionary files. For example, enter the following to create the file dictionary.ora in /oracle/database: SQL> EXECUTE DBMS_LOGMNR_D.BUILD(’dictionary.ora’, 2 ’/oracle/database/’, 3 OPTIONS => DBMS_LOGMNR_D.STORE_IN_FLAT_FILE); You could also specify a filename and location without specifying the STORE_ IN_FLAT_FILE option. The result would be the same. Extracting a Dictionary to the Redo Logs To extract a dictionary to the redo logs, the database must be open and in ARCHIVELOG mode and archiving must be enabled. While the dictionary is being extracted to the redo log stream, no DDL statements can be executed. Therefore, the dictionary snapshot extracted to the redo logs is guaranteed to be consistent, whereas the dictionary extracted to a flat file is not. To extract database dictionary information to the redo logs, use the DBMS_LOGMNR_ D.BUILD procedure with the STORE_IN_REDO_FILES option. Do not specify a filename or location. SQL> EXECUTE DBMS_LOGMNR_D.BUILD ( 2 OPTIONS=>DBMS_LOGMNR_D.STORE_IN_REDO_LOGS); Using LogMiner to Analyze Redo Logs 9-7 Redo Logs and Dictionary Files To ensure that the redo logs contain information of value to you, you must enable at least minimal supplemental logging. See Supplemental Logging on page 9-19. See Also: Oracle9i Recovery Manager User’s Guide for more information about ARCHIVELOG mode The process of extracting the dictionary to the redo logs does consume database resources, but if you limit the extraction to off-peak hours, this should not be a problem and it is faster than extracting to a flat file. Depending on the size of the dictionary, it may be contained in multiple redo logs. Provided the relevant redo logs have been archived, you can find out which redo logs contain the start and end of an extracted dictionary. To do so, query the V$ARCHIVED_LOG view, as follows: SQL> SELECT NAME FROM V$ARCHIVED_LOG WHERE DICTIONARY_BEGIN=’YES’; SQL> SELECT NAME FROM V$ARCHIVED_LOG WHERE DICTIONARY_END=’YES’; The names of the start and end redo logs, and possibly other logs in between them, are specified with the ADD_LOGFILE procedure when you are preparing to start a LogMiner session. It is recommended that you periodically back up the redo logs so that the information is saved and available at a later date. Ideally, this will not involve any extra steps because if your database is being properly managed, there should already be a process in place for backing up and restoring archived redo logs. Again, because of the time required, it is good practice to do this during off-peak hours. Using the Online Catalog To direct LogMiner to use the dictionary currently in use for the database, specify the online catalog as your dictionary source when you start LogMiner, as follows: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => 2 DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG); Using the online catalog means that you do not have to bother extracting a dictionary to a flat file or to the redo logs. In addition to using the online catalog to analyze online redo logs, you can use it to analyze archived redo logs provided you are on the same system that generated the archived redo logs. The online catalog contains the latest information about the database and may be the fastest way to start your analysis. Because DDL operations that change 9-8 Oracle9i Database Administrator’s Guide Redo Logs and Dictionary Files important tables are somewhat rare, the online catalog generally contains the information you need for your analysis. Remember, however, that the online catalog can only reconstruct SQL statements that are executed on the latest version of a table. As soon as the table is altered, the online catalog no longer reflects the previous version of the table. This means that LogMiner will not be able to reconstruct any SQL statements that were executed on the previous version of the table. Instead, LogMiner generates nonexecutable SQL in the SQL_REDO column (including hex-to-raw formatting of binary values) similar to the following example: insert into Object#2581(col#1, col#2) values (hextoraw('4a6f686e20446f65'), hextoraw('c306'));" The online catalog option requires that the database be open. The online catalog option is not valid with the DDL_DICT_TRACKING option. Tracking DDL Statements LogMiner automatically builds its own internal dictionary from the source dictionary that you specify when you start LogMiner (either a flat file dictionary, a dictionary in the redo logs, or an online catalog). If your source dictionary is a flat file dictionary or a dictionary in the redo logs, you can use the DDL_DICT_TRACKING option to direct LogMiner to track data definition language (DDL) statements. DDL tracking is disabled by default. To enable it, use the OPTIONS parameter to specify DDL_DICT_TRACKING when you start LogMiner. For example: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => 2 DBMS_LOGMNR.DDL_DICT_TRACKING); With this option set, LogMiner applies any DDL statements seen in the redo logs to its internal dictionary. For example, to see all the DDLs executed by user SYS, you could issue the following query: SQL> SELECT USERNAME, SQL_REDO 2 FROM V$LOGMNR_CONTENTS 3 WHERE USERNAME = ’SYS’ AND OEPRATION = ’DDL’; The information returned might be similar to the following, although the actual information and how it is displayed will be different on your screen. USERNAME SYS SQL_REDO ALTER TABLE SCOTT.ADDRESS ADD CODE NUMBER; Using LogMiner to Analyze Redo Logs 9-9 LogMiner Recommendations and Restrictions SYS CREATE USER KATHY IDENTIFIED BY VALUES ’E4C8B920449B4C32’ DEFAULT TABLESPACE TS1; Keep the following in mind when you use the DDL_DICT_TRACKING option: ■ ■ The DDL_DICT_TRACKING option is not valid with the DICT_FROM_ONLINE_ CATALOG option. The DDL_DICT_TRACKING option requires that the database be open. The ability to track DDL statements helps you monitor schema evolution because SQL statements used to change the logical structure of a table (because of DDL operations such as adding or dropping of columns) can be reconstructed. In addition, data manipulation language (DML) operations performed on new tables created after the dictionary was extracted can also be shown. Note: In general, it is a good idea to keep the DDL tracking feature enabled because if it is not enabled and a DDL event occurs, LogMiner returns some of the redo data as hex bytes. Also, a metadata version mismatch could occur. Because LogMiner automatically assigns versions to the database metadata, it will detect and notify you of any mismatch between its internal dictionary and the redo logs. Note: It is important to understand that the LogMiner internal dictionary is not the same as the LogMiner dictionary contained in a flat file or in redo logs. LogMiner does update its internal dictionary, but it does not update the dictionary that is contained in a flat file or in redo logs. LogMiner Recommendations and Restrictions When you are using LogMiner, keep the recommendations and restrictions described in the following sections in mind. Recommendations Oracle Corporation recommends that you take the following into consideration when you are using LogMiner: 9-10 Oracle9i Database Administrator’s Guide LogMiner Recommendations and Restrictions ■ All databases should employ an alternate tablespace for LogMiner tables. By default all LogMiner tables are created to use the SYSTEM tablespace. Use the DBMS_LOGMNR_D.SET_TABLESPACE routine to re-create all LogMiner tables in an alternate tablespace. For example, the following statement will re-create all LogMiner tables to use the logmnrts$ tablespace: SQL> EXECUTE DBMS_LOGMNR_D.SET_TABLESPACE(’logmnrts$’); See Also: Oracle9i Supplied PL/SQL Packages and Types Reference for a full description of the DBMS_LOGMNR_D.SET_TABLESPACE routine Restrictions The following restrictions apply when you are using LogMiner: ■ ■ The following are not supported: – Simple and nested abstract datatypes (ADTs) – Collections (nested tables and VARRAYs) – Object Refs – Index organized tables (IOTs) – CREATE TABLE AS SELECT of a table with a clustered key LogMiner runs only on databases of release 8.1 or higher, but you can use it to analyze redo logs from release 8.0 databases. However, the information that LogMiner is able to retrieve from a redo log depends on the version of the log, not the version of the database in use. For example, redo logs for Oracle9i can be augmented to capture additional information when supplemental logging is enabled. This allows LogMiner functionality to be used to its fullest advantage. Redo logs created with older releases of Oracle will not have that additional data and may therefore have limitations on the operations and datatypes supported by LogMiner. For example, the following features require that supplemental logging be turned on. (Note that in Oracle9i release 9.0.1, supplemental logging was always on (it was not available at all in releases prior to 9.0.1). But in release 9.2, you must specifically turn on supplemental logging; otherwise it will not be enabled.) – Support for index clusters, chained rows, and migrated rows (for chained rows, supplemental logging is required, regardless of the compatibility level to which the database is set). Using LogMiner to Analyze Redo Logs 9-11 Filtering Data That is Returned – Support for direct-path inserts (also requires that ARCHIVELOG mode be enabled). – Extracting the data dictionary into the redo logs. – DDL tracking. – Generating SQL_REDO and SQL_UNDO with primary key information for updates. – LONG and LOB datatypes are supported only if supplemental logging is enabled. See Also: Supplemental Logging on page 9-19 Filtering Data That is Returned LogMiner can potentially be dealing with large amounts of information. There are several methods you can use to limit the information that is returned to the V$LOGMNR_CONTENTS view, as well as the speed at which it is returned. These options are specified when you start LogMiner. ■ Showing Only Committed Transactions ■ Skipping Redo Corruptions ■ Filtering Data By Time ■ Filtering Data By SCN Showing Only Committed Transactions When you use the COMMITTED_DATA_ONLY option, only rows belonging to committed transactions are shown in the V$LOGMNR_CONTENTS view. This enables you to filter out rolled back transactions, transactions that are in progress, and internal operations. To enable this option, you specify it when you start LogMiner, as follows: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => 2 DBMS_LOGMNR.COMMITTED_DATA_ONLY); When you specify the COMMITTED_DATA_ONLY option, LogMiner groups together all DML operations that belong to the same transaction. Transactions are returned in the order in which they were committed. 9-12 Oracle9i Database Administrator’s Guide Filtering Data That is Returned If long-running transactions are present in the redo logs being analyzed, use of this option may cause an "Out of Memory" error. The default is for LogMiner to show rows corresponding to all transactions and to return them in the order in which they are encountered in the redo logs. For example, suppose you start LogMiner without specifying COMMITTED_DATA_ ONLY and you execute the following query: SQL> SELECT (XIDUSN || ’.’ || XIDSLT || ’.’ || XIDSQN) AS XID, 2 USERNAME AS USER, 3 SQL_REDO AS SQL_REDO 4 FROM V$LOGMNR_CONTENTS; The output would be as follows. Both committed and uncommitted transactions are returned and rows from different transactions are interwoven. XID 1.5.123 1.5.123 USER SCOTT SCOTT 1.6.124 1.6.124 KATHY KATHY 1.6.124 KATHY 1.5.123 SCOTT 1.6.124 1.7.234 1.5.123 1.7.234 KATHY GOUTAM SCOTT GOUTAM SQL_REDO SET TRANSACTION READ WRITE; INSERT INTO "SCOTT"."EMP"("EMPNO","ENAME") VALUES (8782, ’Frost’); SET TRANSACTION READ WRITE; INSERT INTO "SCOTT"."CUSTOMER"("ID","NAME","PHONE_DAY") VALUES (8839, ’Cummings’, ’415-321-1234’); INSERT INTO "SCOTT"."CUSTOMER"("ID","NAME","PHONE_DAY") VALUES (7934, ’Yeats’, ’033-334-1234’); INSERT INTO "SCOTT"."EMP" ("EMPNO","ENAME") VALUES (8566, ’Browning’); COMMIT; SET TRANSACTION READ WRITE; COMMIT; INSERT INTO "SCOTT"."CUSTOMER"("ID","NAME","PHONE_DAY") VALUES (8499, ’Emerson’, ’202-334-1234’); Now suppose you start LogMiner, but this time you specify the COMMITTED_ DATA_ONLY option. If you executed the previous query again, the output would look as follows: 1.6.124 1.6.124 KATHY KATHY 1.6.124 KATHY 1.6.124 1.5.123 1.5.123 KATHY SCOTT SCOTT SET TRANSACTION READ WRITE; INSERT INTO "SCOTT"."CUSTOMER"("ID","NAME","PHONE_DAY") VALUES (8839, ’Cummings’, ’415-321-1234’); INSERT INTO "SCOTT"."CUSTOMER"("ID","NAME","PHONE_DAY") VALUES (7934, ’Yeats’, ’033-334-1234’); COMMIT; SET TRANSACTION READ WRITE; INSERT INTO "SCOTT"."EMP" ("EMPNO","ENAME") Using LogMiner to Analyze Redo Logs 9-13 Filtering Data That is Returned 1.5.123 SCOTT 1.5.123 SCOTT VALUES (8566, ’Browning’); INSERT INTO "SCOTT"."EMP"("EMPNO","ENAME") VALUES (8782, ’Frost’); COMMIT; Because the commit for the 1.6.124 transaction happened before the commit for the 1.5.123 transaction, the entire 1.6.124 transaction is returned first. This is true even though the 1.5.123 transaction started before the 1.6.124 transaction. None of the 1.7.234 transaction is returned because a commit was never issued for it. Skipping Redo Corruptions When you use the SKIP_CORRUPTION option, any corruptions in the redo logs are skipped during select operations from the V$LOGMNR_CONTENTS view. Rows that are retrieved after the corruption are flagged with a "Log File Corruption Encountered" message. Additionally, for every corrupt redo record encountered, an informational row is returned that indicates how many blocks were skipped. The default is for the select operation to terminate at the first corruption it encounters in the redo log. To enable this option, you specify it when you start LogMiner, as follows: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => 2 DBMS_LOGMNR.SKIP_CORRUPTION); Filtering Data By Time To filter data by time, set the STARTTIME and ENDTIME parameters. The procedure expects date values. Use the TO_DATE function to specify date and time, as in this example: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR( 2 DICTFILENAME => '/oracle/dictionary.ora', 3 STARTTIME => TO_DATE('01-Jan-1998 08:30:00', 'DD-MON-YYYY HH:MI:SS'), 4 ENDTIME => TO_DATE('01-Jan-1998 08:45:00', 'DD-MON-YYYY HH:MI:SS')); If no STARTTIME or ENDTIME parameters are specified, the entire redo log is read from start to end, for each SELECT statement issued. The timestamps should not be used to infer ordering of redo records. You can infer the order of redo records by using the SCN. 9-14 Oracle9i Database Administrator’s Guide Accessing LogMiner Information Filtering Data By SCN To filter data by SCN (system change number), use the STARTSCN and ENDSCN parameters, as in this example: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR( 2 DICTFILENAME => '/oracle/dictionary.ora', 3 STARTSCN => 100, 4 ENDSCN => 150); The STARTSCN and ENDSCN parameters override the STARTTIME and ENDTIME parameters in situations where all are specified. If no STARTSCN or ENDSCN parameters are specified, the entire redo log is read from start to end, for each SELECT statement issued. Accessing LogMiner Information LogMiner information is contained in the following views. You can use SQL to query them as you would any other view. ■ V$LOGMNR_CONTENTS Shows changes made to user and table information. ■ V$LOGMNR_DICTIONARY Shows information about the LogMiner dictionary file, provided the dictionary was created using the STORE_IN_FLAT_FILE option. The information shown includes the database name and status information. ■ V$LOGMNR_LOGS Shows information about specified redo logs. There is one row for each redo log. ■ V$LOGMNR_PARAMETERS Shows information about optional LogMiner parameters, including starting and ending system change numbers (SCNs) and starting and ending times. See Also: Oracle9i Database Reference for detailed information about the contents of these views The rest of this section discusses the following topics with regard to accessing LogMiner information: Using LogMiner to Analyze Redo Logs 9-15 Querying V$LOGMNR_CONTENTS ■ Querying V$LOGMNR_CONTENTS ■ Extracting Actual Data Values from Redo Logs Querying V$LOGMNR_CONTENTS LogMiner output is contained in the V$LOGMNR_CONTENTS view. After LogMiner is started, you can issue SQL statements at the command line to query the data contained in V$LOGMNR_CONTENTS. When a SQL select operation is executed against the V$LOGMNR_CONTENTS view, the redo logs are read sequentially. Translated information from the redo logs is returned as rows in the V$LOGMNR_CONTENTS view. This continues until either the filter criteria specified at startup are met or the end of the redo log is reached. LogMiner returns all the rows in SCN order unless you have used the COMMITTED_ DATA_ONLY option to specify that only committed transactions should be retrieved. SCN order is the order normally applied in media recovery. For example, suppose you wanted to find out about any delete operations that a user named Ron had performed on the scott.orders table. You could issue a query similar to the following: SQL> SELECT OPERATION, SQL_REDO, SQL_UNDO 2 FROM V$LOGMNR_CONTENTS 3 WHERE SEG_OWNER = ’SCOTT’ AND SEG_NAME = ’ORDERS’ AND 4 OPERATION = ’DELETE’ AND USERNAME = ’RON’; The following output would be produced. The formatting may be different on your display than that shown here. OPERATION SQL_REDO DELETE delete from "SCOTT"."ORDERS" insert into "SCOTT"."ORDERS" where "ORDER_NO" = 2 and ("ORDER_NO", "QTY", "EXPR_SHIP") "QTY" = 3 and values(2,3,’Y’); "EXPR_SHIP" = ’Y’ and ROWID = ’AAABM8AABAAALm/AAA’ delete from "SCOTT"."ORDERS" insert into "SCOTT"."ORDERS" where "ORDER_NO" = 4 and ("ORDER_NO",’QTY","EXPR_SHIP") "QTY" = 7 and values(4,7,’Y’); "EXPR_SHIP" = ’Y’ and ROWID = ’AAABM8AABAAALm/AAC’; DELETE 9-16 Oracle9i Database Administrator’s Guide SQL_UNDO Querying V$LOGMNR_CONTENTS This output shows that user Ron deleted two rows from the scott.orders table. The reconstructed SQL statements are equivalent, but not necessarily identical, to the actual statement that Ron issued. The reason for this is that the original WHERE clause is not logged in the redo logs, so LogMiner can only show deleted (or updated or inserted) rows individually. Therefore, even though a single DELETE statement may have been responsible for the deletion of both rows, the output in V$LOGMNR_CONTENTS does not reflect that. Thus, the actual DELETE statement may have been DELETE FROM SCOTT.ORDERS WHERE EXPR_SHIP = ’Y’ or it might have been DELETE FROM SCOTT.ORDERS WHERE QTY < 8. Executing Reconstructed SQL Statements By default, SQL_REDO and SQL_UNDO statements are ended with a semicolon. Depending on how you plan to use the reconstructed statements, you may or may not want them to include the semicolon. To suppress the semicolon, specify the DBMS_LOGMNR.NO_SQL_DELIMITER option when you start LogMiner. Note that if the STATUS field of V$LOGMNR_CONTENTS contains dbms_ logmnr.invalid_sql, then the SQL cannot be executed. Formatting of Returned Data Sometimes a query can result in a large number of columns containing reconstructed SQL statements, which can be visually busy and hard to read. LogMiner provides the DBMS_LOGMNR.PRINT_PRETTY_SQL option to address this problem. The PRINT_PRETTY_SQL option formats the reconstructed SQL statements as follows, which makes them easier to read: insert into "SCOTT"."EMP" values "EMPNO": 5505, "ENAME": "Parker", "SAL": 9000 "DEPTNO": NULL; update "SCOTT"."EMP" set "EMPNO" = 5505 and "SAL" = 9000 where "EMPNO" = 5505 and "SAL" = 9000 and "ROWID" = AABBCEXFGHA; Using LogMiner to Analyze Redo Logs 9-17 Extracting Actual Data Values from Redo Logs SQL statements that are reconstructed when the PRINT_PRETTY_SQL option is enabled are not executable because they do not use standard SQL syntax. Extracting Actual Data Values from Redo Logs LogMiner lets you make queries based on actual data values. For instance, you could perform a query to show all updates to scott.emp that increased sal more than a certain amount. Data such as this can be used to analyze system behavior and to perform auditing tasks. LogMiner data extraction from redo logs is performed using two mine functions: DBMS_LOGMNR.MINE_VALUE and DBMS_LOGMNR.COLUMN_PRESENT. These functions are part of the DBMS_LOGMNR package. Support for these mine functions is provided by the REDO_VALUE and UNDO_VALUE columns in the V$LOGMNR_ CONTENTS view. The following is an example of how you could use the MINE_VALUE function to select all updates to scott.emp that increased the sal column to more than twice its original value: SQL> SELECT SQL_REDO FROM V$LOGMNR_CONTENTS 2 WHERE 3 SEG_NAME = ’emp’ AND 4 SEG_OWNER = ’SCOTT’ AND 5 OPERATION = ’UPDATE’ AND 6 DBMS_LOGMNR.MINE_VALUE(REDO_VALUE, ’SCOTT.EMP.SAL’) > 7 2*DBMS_LOGMNR.MINE_VALUE(UNDO_VALUE, ’SCOTT.EMP.SAL’); As shown in this example, the MINE_VALUE function takes two arguments. The first one specifies whether to mine the redo (REDO_VALUE) or undo (UNDO_VALUE) portion of the data. The second argument is a string that specifies the fully-qualified name of the column to be mined (in this case, SCOTT.EMP.SAL). The MINE_VALUE function always returns a string that can be converted back to the original datatype. NULL Returns From the MINE_VALUE Function If the MINE_VALUE function returns a NULL value, it can mean either: ■ The specified column is not present in the redo or undo portion of the data. ■ The specified column is present and has a null value. To distinguish between these two cases, use the DBMS_LOGMNR.COLUMN_PRESENT function which returns a 1 if the column is present in the redo or undo portion of the data. Otherwise, it returns a 0. For example, suppose you wanted to find out the 9-18 Oracle9i Database Administrator’s Guide Supplemental Logging increment by which the values in the sal column were modified and the corresponding transaction identifier. You could issue the following query: SQL> SELECT 2 (XIDUSN || ’.’ || XIDSLT || ’.’ || XIDSQN) AS XID, 3 (DBMS_LOGMNR.MINE_VALUE(REDO_VALUE, ’SCOTT.EMP.SAL’) 4 DBMS_LOGMNR.MINE_VALUE(UNDO_VALUE, ’SCOTT.EMP.SAL’)) AS INCR_SAL 5 FROM V$LOGMNR_CONTENTS 6 WHERE 7 DBMS_LOGMNR.COLUMN_PRESENT(REDO_VALUE, ’SCOTT.EMP.SAL’) = 1 AND 8 DBMS_LOGMNR.COLUMN_PRESENT(UNDO_VALUE, ’SCOTT.EMP.SAL’) = 1 AND 9 OPERATION = ’UPDATE’; Usage Rules for the MINE_VALUE and COLUMN_PRESENT Functions The following usage rules apply to the MINE_VALUE and COLUMN_PRESENT functions: ■ ■ ■ ■ They can only be used within a LogMiner session. They must be invoked in the context of a select operation from the V$LOGMNR_ CONTENTS view. They do not support LONG, LOB, ADT, or COLLECTION datatypes. When the column argument is of type DATE, the string that is returned is formatted in canonical form (DD-MON-YYYY HH24:MI:SS.SS) regardless of the date format of the current session. See Also: Oracle9i Supplied PL/SQL Packages and Types Reference for a description of the DBMS_LOGMNR package, which contains the MINE_VALUE and COLUMN_PRESENT functions Supplemental Logging Redo logs are generally used for instance recovery and media recovery. The data needed for such operations is automatically recorded in the redo logs. However, a redo-based application may require that additional information be logged in the redo logs. The following are examples of situations in which supplemental data may be needed: ■ An application that wanted to apply the reconstructed SQL statements to a different database would need to identify the update statement by its primary Using LogMiner to Analyze Redo Logs 9-19 Supplemental Logging key, not by its ROWID which is the usual method used by LogMiner. (Primary keys are not, by default, logged in the redo logs unless the key itself is changed by the update.) ■ To make tracking of row changes more efficient, an application may require that the before image of the whole row be logged, not just the modified columns. The default behavior of the Oracle database server is to not provide any supplemental logging at all, which means that certain features will not be supported (see Restrictions on page 9-11). If you want to make full use of LogMiner support, you must enable supplemental logging. The use of LogMiner with minimal supplemental logging enabled does not have any significant performance impact on the instance generating the redo logs. However, the use of LogMiner with database-wide supplemental logging enabled does impose significant overhead and effects performance. There are two types of supplemental logging: database supplemental logging and table supplemental logging. Each of these is described in the following sections. Database Supplemental Logging There are two types of database supplemental logging: minimal and identification key logging. Minimal supplemental logging logs the minimal amount of information needed for LogMiner to identify, group, and merge the REDO operations associated with DML changes. It ensures that LogMiner (and any products building on LogMiner technology) have sufficient information to support chained rows and various storage arrangements such as cluster tables. In most situations, you should at least enable minimal supplemental logging. To do so, execute the following statement: SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA Note: In LogMiner release 9.0.1, minimal supplemental logging was the default behavior. In release 9.2, the default is no supplemental logging. It must be specifically enabled. Identification key logging enables database-wide before-image logging of primary keys or unique indexes (in the absence of primary keys) for all updates. With this type of logging, an application can identify updated rows logically rather than resorting to ROWIDs. 9-20 Oracle9i Database Administrator’s Guide Supplemental Logging Identification key logging is necessary when supplemental log data will be the source of change in another database, such as a logical standby. To enable identification key logging, execute the following statement: SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA (PRIMARY KEY, UNIQUE INDEX) COLUMNS; This statement results in all primary key values, database-wide, being logged regardless of whether or not any of them are modified. If a table does not have a primary key, but has one or more non-null unique key constraints, one of the constraints is chosen arbitrarily for logging as a means of identifying the row getting updated. If the table has neither a primary key nor a unique index, then all columns except LONG and LOB are supplementally logged. Therefore, Oracle Corporation recommends that when you use supplemental logging, all or most tables be defined to have primary or unique keys. Note: Regardless of whether or not identification key logging is enabled, the SQL statements returned by LogMiner always contain the ROWID clause. You can filter out the ROWID clause by using the RTRIM function and appropriate arguments on the reconstructed SQL statement. To disable either minimal or identification key logging, execute the following statement. SQL> ALTER DATABASE DROP SUPPLEMENTAL LOG DATA; Usage Notes for Identification Key Logging Keep the following in mind when you use identification key logging: ■ ■ Identification key logging is not required for delete operations because DELETE statements contain all the column values required to identify a row. If the database is open when you enable identification key logging, all DML cursors in the cursor cache are invalidated. This can have a performance impact until the cache is repopulated. Using LogMiner to Analyze Redo Logs 9-21 Supplemental Logging Table Supplemental Logging Table supplemental logging uses log groups to log supplemental information. There are two types of log groups: ■ ■ Unconditional log groups - The before images of specified columns are logged any time the table is updated, regardless of whether the update affected any of the specified columns. This is sometimes referred to as an ALWAYS log group. Conditional log groups - The before images of all specified columns are logged only if at least one of the columns in the log group is updated. Unconditional Log Groups To enable supplemental logging that uses unconditional log groups, use the ALWAYS clause as shown in the following example: SQL> ALTER TABLE scott.emp 2 ADD SUPPLEMENTAL LOG GROUP emp_parttime (empno, ename, deptno) ALWAYS; This creates a log group named emp_parttime on scott.emp that consists of the columns empno, ename, and deptno. These columns will be logged every time an UPDATE statement is executed on scott.emp, regardless of whether or not the update affected them. If you wanted to have the entire row image logged any time an update was made, you could create a log group that contained all the columns in the table. Note: LOBs, LONGs, and ADTs cannot be part of a log group Conditional Log Groups To enable supplemental logging that uses conditional log groups, omit the ALWAYS clause from your ALTER TABLE statement, as shown in the following example: SQL> ALTER TABLE scott.emp 2 ADD SUPPLEMENTAL LOG GROUP emp_fulltime (empno, ename, deptno); This creates a log group named emp_fulltime on scott.emp. Just like the previous example, it consists of the columns empno, ename, and deptno. But because the ALWAYS clause was omitted, before images of the columns will be logged only if at least one of the columns is updated. Usage Notes for Log Groups Keep the following in mind when you use log groups: 9-22 Oracle9i Database Administrator’s Guide Steps in a Typical LogMiner Session ■ ■ ■ A column can belong to more than one log group. However, the before image of the columns gets logged only once. Redo logs do not contain any information about which log group a column is part of or whether a column’s before image is being logged because of log group logging or identification key logging. If you specify the same columns to be logged both conditionally and unconditionally, the columns are logged unconditionally. Steps in a Typical LogMiner Session This section describes the steps in a typical LogMiner session. Each step is described in its own subsection. 1. Perform Initial Setup Activities 2. Extract a Dictionary (unless you plan to use the online catalog) 3. Specify Redo Logs for Analysis 4. Start a LogMiner Session 5. Query V$LOGMNR_CONTENTS 6. End a LogMiner Session To run LogMiner, you use the DBMS_LOGMNR PL/SQL package. Additionally, you might also use the DBMS_LOGMNR_D package if you choose to extract a dictionary rather than use the online catalog. The DBMS_LOGMNR package contains the procedures used to initialize and run LogMiner, including interfaces to specify names of redo logs, filter criteria, and session characteristics. The DBMS_LOGMNR_D package queries the dictionary tables of the current database to create a LogMiner dictionary file. The LogMiner packages are owned by the SYS schema. Therefore, if you are not connected as user SYS, you must include SYS in your call. For example: EXECUTE SYS.DBMS_LOGMNR.END_LOGMNR See Also: ■ ■ Oracle9i Supplied PL/SQL Packages and Types Reference for details about syntax and parameters for these LogMiner packages Oracle9i Application Developer’s Guide - Fundamentals for information about executing PL/SQL procedures Using LogMiner to Analyze Redo Logs 9-23 Steps in a Typical LogMiner Session Perform Initial Setup Activities There are initial setup activities that you must perform before using LogMiner for the first time. You only need to perform these activities once, not every time you use LogMiner: ■ Enable the type of supplemental logging you want to use. At the very least, Oracle Corporation recommends that you enable minimal supplemental logging, as follows: SQL> ALTER DATABASE ADD SUPPLEMENTAL LOG DATA See Supplemental Logging on page 9-19 for more information. ■ Use the DBMS_LOGMNR_D.SET_TABLESPACE routine to re-create all LogMiner tables in an alternate tablespace. For example: SQL> EXECUTE DBMS_LOGMNR_D.SET_TABLESPACE(’logmnrts$’); See Recommendations on page 9-10 for more information. Extract a Dictionary To use LogMiner you must supply it with a dictionary by doing one of the following: ■ ■ ■ Extract database dictionary information to a flat file. See Extracting the Dictionary to a Flat File on page 9-6. Extract database dictionary information to the redo logs. See Extracting a Dictionary to the Redo Logs on page 9-7. Specify use of the online catalog by using the DICT_FROM_ONLINE_CATALOG option when you start LogMiner. See Using the Online Catalog on page 9-8. Specify Redo Logs for Analysis Before you can start LogMiner, you must specify the redo logs that you want to analyze. To do so, execute the DBMS_LOGMNR.ADD_LOGFILE procedure, as demonstrated in the following steps. You can add and remove redo logs in any order. 9-24 Oracle9i Database Administrator’s Guide Steps in a Typical LogMiner Session Note: If you will be mining in the same instance that is generating the redo logs, you only need to specify one archived redo log and the CONTINUOUS_MINE option when you start LogMiner. See Continuous Mining on page 9-25. 1. Use SQL*Plus to start an Oracle instance, with the database either mounted or unmounted. For example, enter: SQL> STARTUP 2. Create a list of redo logs. Specify the NEW option of the DBMS_LOGMNR.ADD_ LOGFILE procedure to signal that this is the beginning of a new list. For example, enter the following to specify /oracle/logs/log1.f: SQL> EXECUTE DBMS_LOGMNR.ADD_LOGFILE( 2 LOGFILENAME => '/oracle/logs/log1.f', 3 OPTIONS => DBMS_LOGMNR.NEW); 3. If desired, add more redo logs by specifying the ADDFILE option of the DBMS_ LOGMNR.ADD_LOGFILE procedure. For example, enter the following to add /oracle/logs/log2.f: SQL> EXECUTE DBMS_LOGMNR.ADD_LOGFILE( 2 LOGFILENAME => '/oracle/logs/log2.f', 3 OPTIONS => DBMS_LOGMNR.ADDFILE); The OPTIONS parameter is optional when you are adding additional redo logs. For example, you could simply enter the following: SQL> EXECUTE DBMS_LOGMNR.ADD_LOGFILE( 2 LOGFILENAME=>’/oracle/logs/log2.f’); 4. If desired, remove redo logs by specifying the REMOVEFILE option of the DBMS_LOGMNR.ADD_LOGFILE procedure. For example, enter the following to remove /oracle/logs/log2.f: SQL> EXECUTE DBMS_LOGMNR.ADD_LOGFILE( 2 LOGFILENAME => '/oracle/logs/log2.f', 3 OPTIONS => DBMS_LOGMNR.REMOVEFILE); Continuous Mining The continuous mining option is useful if you are mining in the same instance that is generating the redo logs. When you plan to use the continuous mining option, Using LogMiner to Analyze Redo Logs 9-25 Steps in a Typical LogMiner Session you only need to specify one archived redo log before starting LogMiner. Then, when you start LogMiner specify the DBMS_LOGMNR.CONTINUOUS_MINE option, which directs LogMiner to automatically add and mine subsequent archived redo logs and also the online catalog. Note: Continuous mining is not available in a Real Application Clusters environment. Start a LogMiner Session After you have created a dictionary file and specified which redo logs to analyze, you can start a LogMiner session. Take the following steps: 1. Execute the DBMS_LOGMNR.START_LOGMNR procedure to start LogMiner. It is recommended that you specify a dictionary option. If you do not, LogMiner cannot translate internal object identifiers and datatypes to object names and external data formats. Therefore, it would return internal object IDs and present data as hex bytes. Additionally, the MINE_VALUE and COLUMN_PRESENT functions cannot be used without a dictionary. If you are specifying the name of a flat file dictionary, you must supply a fully qualified filename for the dictionary file. For example, to start LogMiner using /oracle/database/dictionary.ora, issue the following command: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR( 2 DICTFILENAME =>'/oracle/database/dictionary.ora'); If you are not specifying a flat file dictionary name, then use the OPTIONS parameter to specify either the DICT_FROM_REDO_LOGS or DICT_FROM_ ONLINE_CATALOG option. If you specify DICT_FROM_REDO_LOGS, LogMiner expects to find a dictionary in the redo logs that you specified with the DBMS_LOGMNR.ADD_LOGFILE procedure. To determine which redo logs contain a dictionary, look at the V$ARCHIVED_LOG view. See Extracting a Dictionary to the Redo Logs on page 9-7 for an example. Note: If you add additional redo logs after your LogMiner session has been started, you must restart LogMiner. You can specify new startup parameters if desired. Otherwise, LogMiner uses the parameters you specified for the previous session. 9-26 Oracle9i Database Administrator’s Guide Steps in a Typical LogMiner Session For more information on using the online catalog, see Using the Online Catalog on page 9-8. 2. Optionally, you can filter your query by time or by SCN. See Filtering Data By Time on page 9-14 or Filtering Data By SCN on page 9-15. 3. You can also use the OPTIONS parameter to specify additional characteristics of your LogMiner session. For example, you might decide to use the online catalog as your dictionary and to have only committed transactions shown in the V$LOGMNR_CONTENTS view, as follows: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR(OPTIONS => 2 DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG + 3 DBMS_LOGMNR.COMMITTED_DATA_ONLY); The following list is a summary of LogMiner settings that you can specify with the OPTIONS parameter and where to find more information about them. ■ ■ ■ ■ ■ ■ ■ ■ ■ DBMS_LOGMNR.DICT_FROM_ONLINE_CATALOG — See Using the Online Catalog on page 9-8 DBMS_LOGMNR.DICT_FROM_REDO_LOGS — See step 1 in this list DBMS_LOGMNR.COMMITTED_DATA_ONLY — See Showing Only Committed Transactions on page 9-12 DBMS_LOGMNR.SKIP_CORRUPTION — See Skipping Redo Corruptions on page 9-14 DBMS_LOGMNR.DDL_DICT_TRACKING — See Tracking DDL Statements on page 9-9 DBMS_LOGMNR.NEW, DBMS_LOGMNR.ADDFILE, and DBMS_ LOGMNR.REMOVEFILE — See Specify Redo Logs for Analysis on page 9-24 DBMS_LOGMNR.NO_SQL_DELIMITER — See Formatting of Returned Data on page 9-17 DBMS_LOGMNR.PRINT_PRETTY_SQL — See Formatting of Returned Data on page 9-17 DBMS_LOGMNR.CONTINUOUS_MINE — See Continuous Mining on page 9-25 You can execute the DBMS_LOGMNR.START_LOGMNR procedure multiple times, specifying different options each time. This can be useful for example, if you did not get the desired results from a query of V$LOGMNR_CONTENTS, and Using LogMiner to Analyze Redo Logs 9-27 Example Uses of LogMiner want to restart LogMiner with different options. You do not need to re-add redo logs that were already added for a previous session. Query V$LOGMNR_CONTENTS At this point, LogMiner is started and you can perform queries against the V$LOGMNR_CONTENTS view. See Querying V$LOGMNR_CONTENTS on page 9-16 for examples of this. End a LogMiner Session To properly end a LogMiner session, use the DBMS_LOGMNR.END_LOGMNR procedure, as follows: SQL> EXECUTE DBMS_LOGMNR.END_LOGMNR; This procedure closes all the redo logs and allows all the database and system resources allocated by LogMiner to be released. If this procedure is not executed, LogMiner retains all its allocated resources until the end of the Oracle session in which it was invoked. It is particularly important to use this procedure to end LogMiner if either the DDL_DICT_TRACKING option or the DICT_FROM_REDO_LOGS option was used. Example Uses of LogMiner This section provides the following example uses of LogMiner. ■ Example: Using LogMiner to Track Changes Made By a Specific User ■ Example: Using LogMiner to Calculate Table Access Statistics Example: Using LogMiner to Track Changes Made By a Specific User This example shows how to see all changes made to the database in a specific time range by one of your users: joedevo.Connect to the database and then take the following steps: 9-28 ■ Step 1: Creating the Dictionary File ■ Step 2: Adding Redo Logs ■ Step 3: Starting LogMiner and Limiting the Search Range ■ Step 4: Querying V$LOGMNR_CONTENTS Oracle9i Database Administrator’s Guide Example Uses of LogMiner Step 1: Creating the Dictionary File To use LogMiner to analyze joedevo’s data, you must either create a dictionary file before joedevo makes any changes or specify use of the online catalog at LogMiner startup. See Extract a Dictionary on page 9-24 for examples of creating dictionaries. Step 2: Adding Redo Logs Assume that joedevo has made some changes to the database. You can now specify the names of the redo logs that you want to analyze, as follows: SQL> EXECUTE DBMS_LOGMNR.ADD_LOGFILE( 2 LOGFILENAME => 'log1orc1.ora', 3 OPTIONS => DBMS_LOGMNR.NEW); If desired, add additional redo logs, as follows: SQL> EXECUTE DBMS_LOGMNR.ADD_LOGFILE( 2 LOGFILENAME => 'log2orc1.ora', 3 OPTIONS => DBMS_LOGMNR.ADDFILE); Step 3: Starting LogMiner and Limiting the Search Range Start LogMiner and limit the search to the specified time range: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR( 2 DICTFILENAME => 'orcldict.ora', 3 STARTTIME => TO_DATE('01-Jan-1998 08:30:00', 'DD-MON-YYYY HH:MI:SS'), 4 ENDTIME => TO_DATE('01-Jan-1998 08:45:00', 'DD-MON-YYYY HH:MI:SS')); Step 4: Querying V$LOGMNR_CONTENTS At this point, the V$LOGMNR_CONTENTS view is available for queries. You decide to find all of the changes made by user joedevo to the salary table. Execute the following SELECT statement: SQL> SELECT SQL_REDO, SQL_UNDO FROM V$LOGMNR_CONTENTS 2 WHERE USERNAME = 'joedevo' AND SEG_NAME = 'salary'; For both the SQL_REDO and SQL_UNDO columns, two rows are returned (the format of the data display will be different on your screen). You discover that joedevo requested two operations: he deleted his old salary and then inserted a new, higher salary. You now have the data necessary to undo this operation. SQL_REDO -------delete * from SALARY where EMPNO = 12345 and ROWID = 'AAABOOAABAAEPCABA'; SQL_UNDO -------insert into SALARY(NAME, EMPNO, SAL) values ('JOEDEVO', 12345, 500) Using LogMiner to Analyze Redo Logs 9-29 Example Uses of LogMiner insert into SALARY(NAME, EMPNO, SAL) values('JOEDEVO',12345, 2500) delete * from SALARY where EMPNO = 12345 and ROWID = 'AAABOOAABAAEPCABA'; 2 rows selected Example: Using LogMiner to Calculate Table Access Statistics In this example, assume you manage a direct marketing database and want to determine how productive the customer contacts have been in generating revenue for a two week period in August. Assume that you have already created the dictionary and added the redo logs you want to search (as demonstrated in the previous example). Take the following steps: 1. Start LogMiner and specify a range of times: SQL> EXECUTE DBMS_LOGMNR.START_LOGMNR( 2 STARTTIME => TO_DATE('07-Aug-1998 08:30:00', 'DD-MON-YYYY HH:MI:SS'), 3 ENDTIME => TO_DATE('21-Aug-1998 08:45:00', 'DD-MON-YYYY HH:MI:SS'), 4 DICTFILENAME => '/usr/local/dict.ora'); 2. Query the V$LOGMNR_CONTENTS view to determine which tables were modified in the time range you specified, as shown in the following example. (This query filters out system tables that traditionally have a $ in their name.) SQL> SELECT SEG_OWNER, SEG_NAME, COUNT(*) AS Hits FROM 2 V$LOGMNR_CONTENTS WHERE SEG_NAME NOT LIKE '%$' GROUP BY 3 SEG_OWNER, SEG_NAME; 3. The following data is displayed. (The format of your display may be different.) SEG_OWNER --------CUST SCOTT SYS UNIV UNIV UNIV SEG_NAME -------ACCOUNT EMP DONOR DONOR EXECDONOR MEGADONOR Hits ---384 12 12 234 325 32 The values in the Hits column show the number of times that the named table had an insert, delete, or update operation performed on it during the two week period specified in the query. 9-30 Oracle9i Database Administrator’s Guide 10 Managing Job Queues This chapter describes how to use job queues to schedule the periodic execution of user jobs, and contains the following topics: ■ Enabling Processes Used for Executing Jobs ■ Managing Job Queues ■ Viewing Job Queue Information Managing Job Queues 10-1 Enabling Processes Used for Executing Jobs Enabling Processes Used for Executing Jobs You can schedule routines (jobs) to be run periodically using the job queue. To schedule a job you submit it to the job queue, using the Oracle supplied DBMS_JOB package, and specify the frequency at which the job is to be run. Additional functionality enables you to alter, disable, or delete a job that you previously submitted. Job queue (Jnnn) processes execute jobs in the job queue. For each instance, these job queue processes are dynamically spawned by a coordinator job queue (CJQ0) background process. The coordinator periodically selects jobs that are ready to run from the jobs shown in the DBA_JOBS view. It orders them by time, and then spawns Jnnn processes to run the selected jobs. Each Jnnn process executes one of the selected jobs. The JOB_QUEUE_PROCESSES initialization parameter controls whether a coordinator job queue process is started by an instance. If this parameter is set to 0, no coordinator job queue process is started at database startup, and consequently no job queue jobs are executed. The JOB_QUEUE_PROCESSES initialization parameter also specifies the maximum number of Jnnn processes that can concurrently run on an instance. The maximum number of processes that can be specified is 1000. The following initialization parameter setting causes the coordinator job queue process to start at database startup, and allows the spawning of a maximum of 60 concurrent Jnnn processes. JOB_QUEUE_PROCESSES = 60 In any given period that the coordinator job queue process scans the jobs shown in the DBA_JOBS view, it spawns at most only the number of Jnnn processes required to execute the jobs it has selected. While the above example allows for 60 concurrent Jnnn processes, if only 20 jobs are selected for execution, then the coordinator spawns, or reuses, only the number of Jnnn processes necessary to execute the 20 jobs (at least, 20). Any idle existing Jnnn processes are considered available for reuse. When a Jnnn process finishes execution of a job, it polls for another job to execute. If there are no jobs selected for execution, it enters an idle state, but wakes up periodically to poll again. If, after a predetermined number of tries, it still finds no jobs to execute, it terminates. The JOB_QUEUE_PROCESSES initialization parameter is dynamic and it can be modified by an ALTER SYSTEM statement. For example, the following statement sets the maximum number of concurrent Jnnn processes allowed to 20. 10-2 Oracle9i Database Administrator’s Guide Managing Job Queues ALTER SYSTEM SET JOB_QUEUE_PROCESSES = 20; If the new value is lower than the previous setting and less than the number of currently executing Jnnn processes, the excess processes are allowed to complete before they are terminated. Jnnn processes will not execute jobs if the instance is running in restricted mode. See also: "Restricting Access to an Open Database" on page 4-11 for information about enabling and disabling restricted mode Managing Job Queues This section describes the various aspects of managing job queues and contains the following topics: ■ The DBMS_JOB Package ■ Submitting a Job to the Job Queue ■ How Jobs Execute ■ Removing a Job from the Job Queue ■ Altering a Job ■ Broken Jobs ■ Forcing a Job to Execute ■ Terminating a Job The DBMS_JOB Package To schedule and manage jobs in the job queue, use the procedures in the DBMS_JOB package. There are no database privileges associated with using job queues. Any user who can execute the job queue procedures can use the job queue. The following are procedures of the DBMS_JOB package. They are described in this section as noted. Procedure Description SUBMIT Submits a job to the job queue. See "Submitting a Job to the Job Queue" on page 10-4. Managing Job Queues 10-3 Managing Job Queues Procedure Description REMOVE Removes a specified job from the job queue. See "Removing a Job from the Job Queue" on page 10-10. CHANGE Alters a specified job that has already been submitted to the job queue. You can alter the job description, the time at which the job will be run, or the interval between executions of the job. See "Altering a Job" on page 10-11. WHAT Alters the job description for a specified job. See "Altering a Job" on page 10-11. NEXT_DATE Alters the next execution time for a specified job. See "Altering a Job" on page 10-11. INTERVAL Alters the interval between executions for a specified job. See "Altering a Job" on page 10-11. BROKEN Sets or resets the job broken flag. If a job is marked as broken, Oracle does not attempt to execute it. See "Broken Jobs" on page 10-12. RUN Forces a specified job to run. See "Forcing a Job to Execute" on page 10-14. See Also: ■ Oracle9i Supplied PL/SQL Packages and Types Reference for syntax information for the DBMS_JOB package, and for information about other options available when using the DBMS_JOB package in an Oracle Real Application Clusters environment Submitting a Job to the Job Queue To submit a new job to the job queue, use the SUBMIT procedure in the DBMS_JOB package. You specify the following parameters with the SUBMIT procedure: 10-4 Parameter Description JOB An output parameter. This is the identifier assigned to the job you are creating. You must use this job number whenever you want to alter or remove the job. See "Job Number" on page 10-7. WHAT This is the PL/SQL code you want to have executed. See "Job Definition" on page 10-7. Oracle9i Database Administrator’s Guide Managing Job Queues Parameter Description NEXT_DATE This is the next date when the job will be run. The default value is SYSDATE. INTERVAL This is the date function that calculates the next time to execute the job. The default value is NULL. INTERVAL must evaluate to a future point in time or NULL. See "Job Execution Interval" on page 10-8. NO_PARSE This is a flag. If NO_PARSE is set to FALSE (the default), Oracle parses the procedure associated with the job. If NO_PARSE is set to TRUE, Oracle parses the procedure associated with the job the first time that the job is executed. If, for example, you want to submit a job before you have created the tables associated with the job, set NO_PARSE to TRUE. For example, consider the following statements that submit a new job to the job queue, then prints the job number. The job calls the procedure DBMS_ DDL.ANALYZE_OBJECT to generate statistics for the table hr.employees. The statistics are based on a sample of half the rows of the employees table. The job is run every 24 hours. VARIABLE jobno NUMBER BEGIN DBMS_JOB.SUBMIT(:jobno, 'DBMS_DDL.ANALYZE_OBJECT(''TABLE'', ''HR'', ''EMPLOYEES'', ''ESTIMATE'', NULL, 50);', SYSDATE, 'SYSDATE + 1'); COMMIT; END; / PRINT jobno JOBNO ---------14144 Note: For the submitted job to run, you must issue a COMMIT statement immediately after the DBMS_JOB.SUBMIT statement. Managing Job Queues 10-5 Managing Job Queues Job Environment When you submit a job to the job queue or alter a job’s definition, Oracle records the following environment characteristics: ■ The current user ■ The user submitting or altering a job ■ The current schema (may be different from current user or submitting user if ALTER SESSION SET CURRENT_SCHEMA statement has been issued) Oracle also records the following NLS parameters: ■ NLS_LANGUAGE ■ NLS_TERRITORY ■ NLS_CURRENCY ■ NLS_ISO_CURRENCY ■ NLS_NUMERIC_CHARACTERS ■ NLS_DATE_FORMAT ■ NLS_DATE_LANGUAGE ■ NLS_SORT Oracle restores all of these environment characteristics every time a job is executed. NLS_LANGUAGE and NLS_TERRITORY parameters determine the defaults for unspecified NLS parameters. You can change a job’s environment by using the DBMS_SQL package and the ALTER SESSION statement. See Also: ■ ■ Oracle9i Supplied PL/SQL Packages and Types Reference for more information about the DBMS_SQL package Oracle9i SQL Reference for information about use of the ALTER SESSION statement to alter a job’s environment Jobs and Import/Export Jobs can be exported and imported. Thus, if you define a job in one database, you can transfer it to another database. When exporting and importing jobs, the job’s number, environment, and definition remain unchanged. 10-6 Oracle9i Database Administrator’s Guide Managing Job Queues Note: If the job number of a job you want to import matches the number of a job already existing in the database, you will not be allowed to import that job. Submit the job as a new job in the database. Job Owner When you submit a job to the job queue, Oracle identifies you as the owner of the job. Only a job’s owner can alter the job, force the job to run, or remove the job from the queue. Job Number A queued job is identified by its job number. When you submit a job, its job number is automatically generated from the JOBSEQ sequence owned by user SYS. Once a job is assigned a job number, that number does not change. Even if the job is exported and imported, its job number remains the same. Job Definition The job definition is the PL/SQL code specified in the WHAT parameter of the SUBMIT procedure. Normally, the job definition is a single call to a procedure. The procedure call can have any number of parameters. Note: In the job definition, use two single quotation marks around strings. Always include a semicolon at the end of the job definition. The following are examples of valid job definitions: ■ 'myproc(''10-JAN-99'', next_date, broken);' ■ 'scott.emppackage.give_raise(''JFEE'', 3000.00);' ■ 'dbms_job.remove(job);' Managing Job Queues 10-7 Managing Job Queues Note: Running a job from a job is not supported. You will receive an error message if you attempt to do so. For example, the following statements produce the "ORA-32317 cannot run a job from another job" error message in the alert file: DECLARE jobno number; BEGIN DBMS_JOB.SUBMIT(jobno, 'DBMS_JOB.RUN(23587);'); DBMS_JOB.RUN(jobno); END; / Job Execution Interval If a job should be executed periodically at a set interval, use a date expression similar to 'SYSDATE + 7' in the INTERVAL parameter. Below are shown some common date expressions used for job execution intervals. Date Expression Evaluation 'SYSDATE + 7' Exactly seven days from the last execution 'SYSDATE + 1/48' Every half hour 'NEXT_DAY(TRUNC(SYSDATE), ''MONDAY'') + 15/24' Every Monday at 3PM 'NEXT_DAY(ADD_MONTHS(TRUNC(SYSDATE, ''Q''), 3), ''THURSDAY'')' First Thursday of each quarter Note: When specifying NEXT_DATE or INTERVAL, remember that date literals and strings must be enclosed in single quotation marks. Also, the value of INTERVAL must be enclosed in single quotation marks. The INTERVAL date function is evaluated immediately before a job is executed. When the job completes successfully, the date calculated from INTERVAL becomes the new NEXT_DATE. For example, if you set the execution interval to 'SYSDATE + 7' on Monday, but for some reason (such as a network failure) the job is not executed until Thursday, 'SYSDATE + 7' then executes every Thursday, not Monday. If the INTERVAL date function evaluates to NULL and the job completes successfully, the job is deleted from the queue. 10-8 Oracle9i Database Administrator’s Guide Managing Job Queues If you always want to automatically execute a job at a specific time, regardless of the last execution (for example, every Monday), the INTERVAL and NEXT_DATE parameters should specify a date expression similar to 'NEXT_ DAY(TRUNC(SYSDATE), ''MONDAY'')'. Database Links and Jobs If you submit a job that uses a database link, the link must include a username and password. Anonymous database links will not succeed. How Jobs Execute Jnnn processes execute jobs. To execute a job, the process creates a session to run the job. When a Jnnn process runs a job, the job is run in the same environment in which it was submitted and with the owner’s default privileges. The owner must be explicitly granted the necessary object privileges for all objects referenced within the job definition. When you force a job to run using the procedure DBMS_JOB.RUN, the job is run by your user process and with your default privileges only. Privileges granted to you through roles are unavailable. You must be explicitly granted the necessary object privileges for all objects referenced within the job definition. Job Queue Locks Oracle uses job queue locks to ensure that a job is executed in only one session at a time. When a job is being run, its session acquires a job queue (JQ) lock for that job. You can use the locking views in the data dictionary to examine information about locks currently held by sessions. The following query lists the session identifier, lock type, and lock identifiers for all sessions holding JQ locks: SELECT SID, TYPE, ID1, ID2 FROM V$LOCK WHERE TYPE = 'JQ'; SID TY ID1 ID2 --------- -- --------- --------12 JQ 0 14144 1 row selected. In the query above, the identifier for the session holding the lock is 12. The ID1 column is always 0 for JQ locks. The ID2 column is the job number of the job the Managing Job Queues 10-9 Managing Job Queues session is running. This view can be joined with the DBA_JOBS_RUNNING view to obtain more information about the job. See Also: ■ ■ ■ "Viewing Job Queue Information" on page 10-15 for more information about views Oracle9i Database Reference for more information about the V$LOCK view Oracle9i Database Concepts for more information about locking Job Execution Errors When a job fails, information about the failure is recorded in a trace file and the alert log. Oracle writes message number ORA-12012 and includes the job number of the failed job. The following can prevent the successful execution of queued jobs: ■ A network or instance failure ■ An exception when executing the job If a job returns an error while Oracle is attempting to execute it, Oracle tries to execute it again. The first attempt is made after one minute, the second attempt after two minutes, the third after four minutes, and so on, with the interval doubling between each attempt. If the job fails 16 times, Oracle automatically marks the job as broken and no longer tries to execute it. However, between attempts, you have the opportunity to correct the problem that is preventing the job from running. This will not disturb the retry cycle, and Oracle will eventually attempt to run the job again. Removing a Job from the Job Queue To remove a job from the job queue, use the REMOVE procedure in the DBMS_JOB package. The following statements remove job number 14144 from the job queue: BEGIN DBMS_JOB.REMOVE(14144); END; / 10-10 Oracle9i Database Administrator’s Guide Managing Job Queues Restrictions: ■ You can remove currently executing jobs from the job queue. However, the job will not be interrupted, and the current execution will be completed. ■ You can remove only jobs you own. If you try to remove a job that you do not own, you receive a message that states the job is not in the job queue. Altering a Job To alter a job that has been submitted to the job queue, use the procedures CHANGE, WHAT, NEXT_DATE, or INTERVAL in the DBMS_JOB package. Restriction: ■ You can alter only jobs that you own. If you try to alter a job that you do not own, you receive a message that states the job is not in the job queue. CHANGE You can alter any of the user-definable parameters associated with a job by calling the DBMS_JOB.CHANGE procedure. In this example, job number 14144 is altered to execute every three days: BEGIN DBMS_JOB.CHANGE(14144, NULL, NULL, 'SYSDATE + 3'); END; / If you specify NULL for WHAT, NEXT_DATE, or INTERVAL when you call the procedure DBMS_JOB.CHANGE, the current value remains unchanged. Note: When you change a job’s definition using the WHAT parameter in the procedure DBMS_JOB.CHANGE, Oracle records your current environment. This becomes the new environment for the job. WHAT You can alter the definition of a job by calling the DBMS_JOB.WHAT procedure. The following example changes the definition for job number 14144: BEGIN DBMS_JOB.WHAT(14144, Managing Job Queues 10-11 Managing Job Queues 'DBMS_DDL.ANALYZE_OBJECT(''TABLE'', ''HR'', ''DEPARTMENTS'', ''ESTIMATE'', NULL, 50);'); END; / Note: When you execute the procedure DBMS_JOB.WHAT, Oracle records your current environment. This becomes the new environment for the job. NEXT_DATE You can alter the next execution time for a job by calling the DBMS_JOB.NEXT_ DATE procedure, as shown in the following example: BEGIN DBMS_JOB.NEXT_DATE(14144, SYSDATE + 4); END; / INTERVAL The following example illustrates changing the execution interval for a job by calling the DBMS_JOB.INTERVAL procedure: BEGIN DBMS_JOB.INTERVAL(14144, 'NULL'); END; / In this case, the job will not run again after it successfully executes and it will be deleted from the job queue. Broken Jobs A job is labeled as either broken or not broken. Oracle does not attempt to run broken jobs. However, you can force a broken job to run by calling the procedure DBMS_JOB.RUN. How a Job Becomes Broken When you submit a job it is considered not broken. There are two ways a job can break: 10-12 Oracle9i Database Administrator’s Guide Managing Job Queues ■ Oracle has failed to successfully execute the job after 16 attempts. ■ You have marked the job as broken, using the procedure DBMS_JOB.BROKEN: BEGIN DBMS_JOB.BROKEN(14144, TRUE); END; / Once a job has been marked as broken, Oracle will not attempt to execute the job until you either mark the job as not broken, or force the job to be executed by calling the procedure DBMS_JOB.RUN. The following example marks job 14144 as not broken and sets its next execution date to the following Monday: BEGIN DBMS_JOB.BROKEN(14144, FALSE, NEXT_DAY(SYSDATE, 'MONDAY')); END; / Restriction: ■ You can mark as broken only jobs that you own. If you call DBMS_JOB.BROKEN for a job that you do not own, you receive a message stating that the job is not in the job queue. Running Broken Jobs If a problem has caused a job to fail 16 times, Oracle marks the job as broken. Once you have fixed this problem, you can run the job by either: ■ ■ Forcing the job to run by calling DBMS_JOB.RUN Marking the job as not broken by calling DBMS_JOB.BROKEN and waiting for Oracle to execute the job If you force the job to run by calling the procedure DBMS_JOB.RUN, Oracle runs the job immediately. If the job succeeds, then Oracle labels the job as not broken and resets its count of the number of failed executions for the job to zero. Once you reset a job’s broken flag (by calling either RUN or BROKEN), job execution resumes according to the scheduled execution intervals set for the job. Managing Job Queues 10-13 Managing Job Queues Forcing a Job to Execute There may be times when you would like to manually execute a job. For example, if you have fixed a broken job, you may want to test the job immediately by forcing it to execute. To force a job to execute immediately, use the procedure RUN in the DBMS_JOB package. When you run a job using DBMS_JOB.RUN, Oracle recomputes the next execution date. For example, if you create a job on a Monday with a NEXT_DATE value of SYSDATE and an INTERVAL value of 'SYSDATE + 7', the job is run every 7 days starting on Monday. However, if you execute RUN on Wednesday, the next execution date will be set to the next Wednesday. The following statement runs job 14144 in your session and recomputes the next execution date: BEGIN DBMS_JOB.RUN(14144); END; / Note: When you force a job to run, the job is executed in your current session. Running the job reinitializes your session’s packages. Restrictions: ■ You can only run jobs that you own. If you try to run a job that you do not own, you receive a message that states the job is not in the job queue. ■ The procedure RUN contains an implicit commit. Once you execute a job using RUN, you cannot roll back. Terminating a Job You can terminate a running job by marking the job as broken, identifying the session running the job, and disconnecting that session. You should mark the job as broken, so that Oracle does not attempt to run the job again. After you have identified the session running the job (using V$SESSION or V$LOCK, as shown earlier), you can disconnect the session using the SQL statement ALTER SYSTEM. For examples of viewing information about jobs and sessions, see the next section, "Viewing Job Queue Information". 10-14 Oracle9i Database Administrator’s Guide Viewing Job Queue Information See Also: ■ Oracle9i Database Reference for more information on V$SESSION ■ "Terminating Sessions" on page 10-2 Viewing Job Queue Information You can view information about jobs in the job queue using the data dictionary views listed below: View Description DBA_JOBS DBA view describes all the jobs in the database. ALL view describes all jobs that are accessible to the current user. USER view describes all jobs owned by the current user. ALL_JOBS USER_JOBS Lists all jobs in the database that are currently running. This view can be joined with V$LOCK to identify jobs that have locks. DBA_JOBS_RUNNING Displaying Information About a Job The following query creates a listing of the job number, next execution time, failure count, and broken status for each job you have submitted: SELECT JOB, NEXT_DATE, NEXT_SEC, FAILURES, BROKEN FROM DBA_JOBS; JOB NEXT_DATE ------- --------9125 01-JUN-01 14144 24-OCT-01 9127 01-JUN-01 3 rows selected. NEXT_SEC FAILURES B -------- -------- 00:00:00 4 N 16:35:35 0 N 00:00:00 16 Y Displaying Information About Running Jobs You can also display information about only the jobs currently running. The following query lists the session identifier, job number, user who submitted the job, and the start times for all currently running jobs: SELECT SID, r.JOB, LOG_USER, r.THIS_DATE, r.THIS_SEC FROM DBA_JOBS_RUNNING r, DBA_JOBS j WHERE r.JOB = j.JOB; Managing Job Queues 10-15 Viewing Job Queue Information SID JOB ----- ---------12 14144 25 8536 2 rows selected. LOG_USER ------------HR QS THIS_DATE --------24-OCT-94 24-OCT-94 THIS_SEC -------17:21:24 16:45:12 See Also: Oracle9i Database Reference for more information on data dictionary views 10-16 Oracle9i Database Administrator’s Guide 11 Managing Tablespaces This chapter describes the various aspects of tablespace management, and contains the following topics: ■ Guidelines for Managing Tablespaces ■ Creating Tablespaces ■ Coalescing Free Space in Dictionary-Managed Tablespaces ■ Specifying Nonstandard Block Sizes for Tablespaces ■ Controlling the Writing of Redo Records ■ Altering Tablespace Availability ■ Using Read-Only Tablespaces ■ Dropping Tablespaces ■ Diagnosing and Repairing Locally Managed Tablespace Problems ■ Migrating the SYSTEM Tablespace to a Locally Managed Tablespace ■ Transporting Tablespaces Between Databases ■ Viewing Tablespace Information See Also: Chapter 3, "Using Oracle-Managed Files" for information about creating datafiles and tempfiles that are both created and managed by the Oracle database server Managing Tablespaces 11-1 Guidelines for Managing Tablespaces Guidelines for Managing Tablespaces Before working with tablespaces of an Oracle database, familiarize yourself with the guidelines provided in the following sections: ■ Use Multiple Tablespaces ■ Specify Tablespace Default Storage Parameters ■ Assign Tablespace Quotas to Users See Also: Oracle9i Database Concepts for a complete discussion of database structure, space management, tablespaces, and datafiles Use Multiple Tablespaces Using multiple tablespaces allows you more flexibility in performing database operations. For example, when a database has multiple tablespaces, you can perform the following tasks: ■ ■ ■ ■ ■ ■ ■ Separate user data from data dictionary data to reduce contention among dictionary objects and schema objects for the same datafiles. Separate one application’s data from another’s to prevent multiple applications from being affected if a tablespace must to be taken offline. Store different tablespaces’ datafiles on separate disk drives to reduce I/O contention. Separate rollback segment data from user data, preventing a single disk failure from causing permanent loss of data. Take individual tablespaces offline while others remain online, providing better overall availability. Reserve a tablespace for a particular type of database use, such as high update activity, read-only activity, or temporary segment storage. This enables you to optimize usage of the tablespace. Back up individual tablespaces. Some operating systems set a limit on the number of files that can be simultaneously open. These limits can affect the number of tablespaces that can be simultaneously online. To avoid exceeding your operating system’s limit, plan your tablespaces efficiently. Create only enough tablespaces to fill your needs, and create these tablespaces with as few files as possible. If you need to increase the size of a 11-2 Oracle9i Database Administrator’s Guide Creating Tablespaces tablespace, add one or two large datafiles, or create datafiles with the autoextend option set on, rather than many small datafiles. Review your data in light of these factors and decide how many tablespaces you need for your database design. Specify Tablespace Default Storage Parameters When you create a new dictionary-managed tablespace, you can specify default storage parameters for objects that will be created in the tablespace. Storage parameters specified when an object is created override the default storage parameters of the tablespace containing the object. If you do not specify storage parameters when creating an object, the object’s segment automatically uses the default storage parameters for the tablespace. Set the default storage parameters for a tablespace to account for the size of a typical object that the tablespace will contain (you estimate this size). You can specify different storage parameters for an unusual or exceptional object when creating that object. You can also alter your default storage parameters at a later time. You cannot specify default storage parameters for tablespaces that are specifically created as locally managed. Note: If you do not specify the default storage parameters for a new dictionary-managed tablespace, Oracle chooses default storage parameters appropriate for your operating system. Assign Tablespace Quotas to Users Grant to users who will be creating tables, clusters, materialized views, indexes, and other objects the privilege to create the object and a quota (space allowance or limit) in the tablespace intended to hold the object’s segment. The security administrator is responsible for granting the required privileges to create objects to database users and for assigning tablespace quotas, as necessary, to database users. See Also: "Assigning Tablespace Quotas" on page 24-4 Creating Tablespaces Before you can create a tablespace you must create a database to contain it. The first tablespace in any database is always the SYSTEM tablespace, and the first datafiles Managing Tablespaces 11-3 Creating Tablespaces of any database are automatically allocated in the SYSTEM tablespace during database creation. The steps for creating tablespaces vary by operating system. In all cases, however, you should create through your operating system a directory structure in which your datafiles will be allocated. On most operating systems you indicate the size and fully specified filenames when creating a new tablespace or altering a tablespace by adding datafiles. In each situation Oracle automatically allocates and formats the datafiles as specified. To create a new tablespace, use the SQL statement CREATE TABLESPACE or CREATE TEMPORARY TABLESPACE. You must have the CREATE TABLESPACE system privilege to create a tablespace. Later, you can use the ALTER TABLESPACE or ALTER DATABASE statements to alter the tablespace. You must have the ALTER TABLESPACE or ALTER DATABASE system privilege, correspondingly. Prior to Oracle8i, all tablespaces were created as dictionary-managed. Dictionary-managed tablespaces rely on data dictionary tables to track space utilization. Beginning with Oracle8i, you were able to create locally managed tablespaces, which use bitmaps (instead of data dictionary tables) to track used and free space. These locally managed tablespaces provide better performance and greater ease of management. Note: Beginning in Oracle9i the default for non-SYSTEM permanent tablespaces is locally managed whenever both of the following criteria are met: ■ ■ The EXTENT MANAGEMENT clause is not specified The COMPATIBLE initialization parameter is set to 9.0.0 or higher You can also create a special type of tablespace called an undo tablespace. This tablespace is specifically designed to contain undo records. These are records generated by Oracle that are used to roll back, or undo, changes to the database for recovery, read consistency, or as requested by a ROLLBACK statement. Creating and managing undo tablespaces is the subject of Chapter 13, "Managing Undo Space". Permanent and temporary tablespaces are discussed in the following sections: 11-4 ■ Locally Managed Tablespaces ■ Dictionary-Managed Tablespaces Oracle9i Database Administrator’s Guide Creating Tablespaces ■ Temporary Tablespaces See Also: ■ ■ ■ Chapter 2, "Creating an Oracle Database" and your Oracle installation documentation for your operating system for information about tablespaces that are created at database creation Oracle9i SQL Reference for more information about the syntax and use of the CREATE TABLESPACE, CREATE TEMPORARY TABLESPACE, ALTER TABLESPACE, and ALTER DATABASE statements. "Specifying Database Block Sizes" on page 2-37 for information about initialization parameters necessary to create tablespaces with nonstandard block sizes Locally Managed Tablespaces Locally managed tablespaces track all extent information in the tablespace itself, using bitmaps, resulting in the following benefits: ■ ■ ■ ■ ■ Improved concurrency and speed of space operations, because space allocations and deallocations predominantly modify locally managed resources (bitmaps stored in header files) rather than requiring centrally managed resources such as enqueues Improved performance, because recursive operations that are sometimes required during dictionary-managed space allocation are eliminated Readable standby databases are allowed, because locally managed temporary tablespaces (used, for example, for sorts) are locally managed and thus do not generate any undo or redo. Simplified space allocation—when the AUTOALLOCATE clause is specified, appropriate extent size is automatically selected Reduced user reliance on the data dictionary because necessary information is stored in file headers and bitmap blocks All tablespaces, including the SYSTEM tablespace, can be locally managed. Additionally, the DBMS_SPACE_ADMIN package provides maintenance procedures for locally managed tablespaces. Managing Tablespaces 11-5 Creating Tablespaces See Also: ■ ■ "Creating a Locally Managed SYSTEM Tablespace" on page 2-26 "Diagnosing and Repairing Locally Managed Tablespace Problems" on page 11-30 Creating a Locally Managed Tablespace To create a locally managed tablespace, specify LOCAL in the EXTENT MANAGEMENT clause of the CREATE TABLESPACE statement. You then have two options. You can have Oracle manage extents for you automatically with the AUTOALLOCATE option (the default), or you can specify that the tablespace is managed with uniform extents of a specific size (UNIFORM SIZE). If the tablespace is expected to contain objects of varying sizes requiring different extent sizes and having many extents, then AUTOALLOCATE is the best choice. If it is not important to you to have a lot of control over space allocation and deallocation, AUTOALLOCATE presents a simplified way for you to manage a tablespace. Some space may be wasted but the benefit of having Oracle manage your space most likely outweighs this drawback. On the other hand, if you want exact control over unused space, and you can predict exactly the space to be allocated for an object or objects and the number and size of extents, then UNIFORM is a good choice. This ensures that you will never have an unusable amount of space in your tablespace. 11-6 Oracle9i Database Administrator’s Guide Creating Tablespaces Note: When you do not explicitly specify the type of extent management, and the default is to create a locally managed tablespace, Oracle determines extent management as described below. If your CREATE TABLESPACE statement does not include a DEFAULT storage clause, then Oracle creates a locally managed autoallocated tablespace. If your CREATE TABLESPACE statement does include a DEFAULT storage clause, then Oracle considers the following: ■ ■ If you specified the MINIMUM EXTENT clause, Oracle evaluates whether the values of MINIMUM EXTENT, INITIAL, and NEXT are equal and the value of PCTINCREASE is 0. If so, Oracle creates a locally managed uniform tablespace with extent size = INITIAL. If the MINIMUM EXTENT, INITIAL, and NEXT parameters are not equal, or if PCTINCREASE is not 0, Oracle ignores any extent storage parameters you may specify and creates a locally managed, autoallocated tablespace. If you did not specify MINIMUM EXTENT clause, Oracle evaluates only whether the storage values of INITIAL and NEXT are equal and PCTINCREASE is 0. If so, the tablespace is locally managed and uniform. Otherwise, the tablespace is locally managed and autoallocated. The following statement creates a locally managed tablespace named lmtbsb and specifies AUTOALLOCATE: CREATE TABLESPACE lmtbsb DATAFILE '/u02/oracle/data/lmtbsb01.dbf' SIZE 50M EXTENT MANAGEMENT LOCAL AUTOALLOCATE; AUTOALLOCATE causes the tablespace to be system managed with the smallest extent size being 64K. There is an increase in initial space allocated for objects in autoallocated tablespaces. This is because the objects have a minimum size of two blocks in dictionary-managed tablespaces, whereas in autoallocated locally managed tablespaces, the minimum object size is 64K. Alternatively, this tablespace could be created specifying the UNIFORM clause. If UNIFORM SIZE is specified, then the tablespace is managed with uniform size extents of the specified SIZE. The default SIZE is 1M. Managing Tablespaces 11-7 Creating Tablespaces In the following example, a 128K extent size is specified. Each 128K extent (which, if the tablespace block size is 2K, is equivalent to 64 Oracle blocks) is represented by a bit in the extent bitmap for this file. CREATE TABLESPACE lmtbsb DATAFILE '/u02/oracle/data/lmtbsb01.dbf' SIZE 50M EXTENT MANAGEMENT LOCAL UNIFORM SIZE 128K; You cannot specify the DEFAULT storage clause, MINIMUM EXTENT, or TEMPORARY when you explicitly specify EXTENT MANAGEMENT LOCAL. If you want to create a temporary locally managed tablespace, use the CREATE TEMPORARY TABLESPACE statement. Note: When you allocate a datafile for a locally managed tablespace, you should allow space for metadata used for space management (the extent bitmap or space header segment) which are part of user space. For example, if you do not specify the SIZE parameter in the extent management clause when UNIFORM is specified, the default extent size is 1MB. Therefore, in this case, the size specified for the datafile must be larger (at least one block plus space for the bitmap) than 1MB. Specifying Segment Space Management in Locally Managed Tablespaces When you create a locally managed tablespace using the CREATE TABLESPACE statement, the SEGMENT SPACE MANAGEMENT clause allows you to specify how free and used space within a segment is to be managed. Your choices are: ■ MANUAL Specifying MANUAL tells Oracle that you want to use free lists for managing free space within segments. Free lists are lists of data blocks that have space available for inserting rows. This form of managing space within segments is called manual segment-space management because of the need to specify and tune the PCTUSED, FREELISTS, and FREELISTS GROUPS storage parameters for schema objects created in the tablespace. MANUAL is the default. ■ AUTO This keyword tells Oracle that you want to use bitmaps to manage the free space within segments. A bitmap, in this case, is a map that describes the status of each data block within a segment with respect to the amount of space in the block available for inserting rows. As more or less space becomes available in a 11-8 Oracle9i Database Administrator’s Guide Creating Tablespaces data block, its new state is reflected in the bitmap. Bitmaps allow Oracle to manage free space more automatically, and thus, this form of space management is called automatic segment-space management. Automatic segment-space management is a simpler and more efficient way of managing space within a segment. It completely eliminates any need to specify and tune the PCTUSED, FREELISTS, and FREELISTS GROUPS storage parameters for schema objects created in the tablespace. If such attributes should be specified, they are ignored. Automatic segment-space management delivers better space utilization than manual segment-space management, and it is self tuning in that it scales with increasing the number of users, as well as instances. For a Real Application Clusters environment, automatic segment-space management allows for a dynamic affinity of space to instances, thus avoiding the hard partitioning of space inherent with using free list groups. For many standard workloads, application performance when using automatic segment space management is better than the performance of a well tuned application using manual segment-space management. The following statement creates tablespace lmtbsb with automatic segment-space management: CREATE TABLESPACE lmtbsb DATAFILE '/u02/oracle/data/lmtbsb01.dbf' SIZE 50M EXTENT MANAGEMENT LOCAL SEGMENT SPACE MANAGEMENT AUTO; Your specification at tablespace creation time of your method for managing available space in segments, applies to all segments subsequently created in the tablespace. Also, your choice of method cannot be subsequently altered. Only permanent, locally managed tablespaces can specify automatic segment-space management. Altering a Locally Managed Tablespace You cannot alter a locally managed tablespace to a locally managed temporary tablespace, nor can you change its method of segment space management. Some reasons for using the ALTER TABLESPACE statement for locally managed tablespaces include: ■ Adding a datafile. For example: ALTER TABLESPACE lmtbsb ADD DATAFILE '/u02/oracle/data/lmtbsb02.dbf' SIZE 1M; Managing Tablespaces 11-9 Creating Tablespaces ■ ■ ■ Altering a tablespace’s availability (ONLINE/OFFLINE). See "Altering Tablespace Availability" on page 11-21. Making a tablespace read-only or read-write. See "Using Read-Only Tablespaces" on page 11-24. Renaming a datafile, or enabling/disabling the autoextension of the size of a datafile in the tablespace. See Chapter 12, "Managing Datafiles". Coalescing free extents is unnecessary for locally managed tablespaces. Dictionary-Managed Tablespaces Starting with Oracle9i, the default for extent management when creating a tablespace is locally managed. However, you can explicitly specify that you want to create a dictionary-managed tablespace. For dictionary-managed tablespaces, Oracle updates the appropriate tables in the data dictionary whenever an extent is allocated, or freed for reuse. Creating a Dictionary-Managed Tablespace As an example, the following statement creates the tablespace tbsa, with the following characteristics: ■ ■ ■ The data of the new tablespace is contained in a single datafile, 50M in size. The tablespace is explicitly created as a dictionary-managed tablespace by specifying EXTENT MANAGEMENT DICTIONARY. The default storage parameters for any segments created in this tablespace are specified. The following statement creates the tablespace tbsb: CREATE TABLESPACE tbsb DATAFILE '/u02/oracle/data/tbsa01.dbf' SIZE 50M EXTENT MANAGEMENT DICTIONARY DEFAULT STORAGE ( INITIAL 50K NEXT 50K MINEXTENTS 2 MAXEXTENTS 50 PCTINCREASE 0); The following parameters, included in the above example, determine segment storage allocation in the tablespace. These parameters affect both how long it takes 11-10 Oracle9i Database Administrator’s Guide Creating Tablespaces to access data stored in the database and how efficiently space in the database is used. They are referred to as storage parameters. Storage Parameter Description INITIAL Defines the size in bytes (K or M) of the first extent in the segment NEXT Defines the size of the second extent in bytes (K or M) PCTINCREASE Specifies the percent by which each extent, after the second (NEXT) extent, grows MINEXTENTS Specifies the number of extents allocated when a segment is first created in the tablespace MAXEXTENTS Determines the maximum number of extents that a segment can have. Can also be specified as UNLIMITED. Another parameter on the CREATE TABLESPACE statement, MIMIMUM EXTENT, also influences segment allocation. If specified, it ensures that all free and allocated extents in the tablespace are at least as large as, and a multiple of, a specified number of bytes (K or M). This provides one means of controlling free space fragmentation in the tablespace. See Also: ■ ■ ■ "Setting Storage Parameters" on page 14-8 Oracle9i Database Performance Tuning Guide and Reference for more discussion of the effects of these parameters Oracle9i SQL Reference for a complete description of storage parameters Altering a Dictionary-Managed Tablespace One reason for using an ALTER TABLESPACE statement is to add a datafile. The following statement creates a new datafile for the tbsa tablespace: ALTER TABLESPACE tbsa ADD DATAFILE '/u02/oracle/data/tbsa02.dbf' SIZE 1M; You might also want to change the default storage parameters. You can change the default storage parameters of a tablespace using the ALTER TABLESPACE statement, as illustrated in the following example: Managing Tablespaces 11-11 Creating Tablespaces ALTER TABLESPACE users DEFAULT STORAGE ( NEXT 100K MAXEXTENTS 20 PCTINCREASE 0); New values for the default storage parameters of a tablespace affect only future objects that are created, or extents allocated for existing segments within the tablespace. Other reasons for issuing an ALTER TABLESPACE statement include, but are not limited to: ■ ■ ■ ■ Coalescing free space in a tablespace. See "Coalescing Free Space in Dictionary-Managed Tablespaces" on page 11-16. Altering a tablespace’s availability (ONLINE/OFFLINE). See "Altering Tablespace Availability" on page 11-21. Making a tablespace read-only or read-write. See "Using Read-Only Tablespaces" on page 11-24. Adding or renaming a datafile, or enabling/disabling the autoextension of the size of a datafile in the tablespace. See Chapter 12, "Managing Datafiles". Temporary Tablespaces To improve the concurrence of multiple sort operations, reduce their overhead, or avoid Oracle space management operations altogether, create temporary tablespaces. A temporary tablespace can be shared by multiple users and can be assigned to users with the CREATE USER statement when you create users in the database. Within a temporary tablespace, all sort operations for a given instance and tablespace share a single sort segment. Sort segments exist for every instance that performs sort operations within a given tablespace. The sort segment is created by the first statement that uses a temporary tablespace for sorting, after startup, and is released only at shutdown. An extent cannot be shared by multiple transactions. You can view the allocation and deallocation of space in a temporary tablespace sort segment using the V$SORT_SEGMENT view. The V$TEMPSEG_USAGE view identifies the current sort users in those segments. You cannot explicitly create objects in a temporary tablespace. 11-12 Oracle9i Database Administrator’s Guide Creating Tablespaces See Also: ■ ■ ■ Chapter 24, "Managing Users and Resources" for information about assigning temporary tablespaces to users Oracle9i Database Reference for more information about the V$SORT_SEGMENT and V$TEMPSEG_USAGE views Oracle9i Database Performance Tuning Guide and Reference for a discussion on tuning sorts Creating a Locally Managed Temporary Tablespace Because space management is much simpler and more efficient in locally managed tablespaces, they are ideally suited for temporary tablespaces. Locally managed temporary tablespaces use tempfiles, which do not modify data outside of the temporary tablespace or generate any redo for temporary tablespace data. Therefore, they can be used in standby or read-only databases. You also use different views for viewing information about tempfiles than you would for datafiles. The V$TEMPFILE and DBA_TEMP_FILES views are analogous to the V$DATAFILE and DBA_DATA_FILES views. To create a locally managed temporary tablespace, you use the CREATE TEMPORARY TABLESPACE statement, which requires that you have the CREATE TABLESPACE system privilege. The following statement creates a temporary tablespace in which each extent is 16M. Each 16M extent (which is the equivalent of 8000 blocks when the standard block size is 2K) is represented by a bit in the bitmap for the file. CREATE TEMPORARY TABLESPACE lmtemp TEMPFILE '/u02/oracle/data/lmtemp01.dbf' SIZE 20M REUSE EXTENT MANAGEMENT LOCAL UNIFORM SIZE 16M; The extent management clause is optional for temporary tablespaces because all temporary tablespaces are created with locally managed extents of a uniform size. The Oracle default for SIZE is 1M. But if you want to specify another value for SIZE, you can do so as shown in the above statement. The AUTOALLOCATE clause is not allowed for temporary tablespaces. Managing Tablespaces 11-13 Creating Tablespaces Note: On some operating systems, Oracle does not allocate space for the tempfile until the tempfile blocks are actually accessed. This delay in space allocation results in faster creation and resizing of tempfiles, but it requires that sufficient disk space is available when the tempfiles are later used. Please refer to your operating system documentation to determine whether Oracle allocates tempfile space in this way on your system. Altering a Locally Managed Temporary Tablespace Except for adding a tempfile, as illustrated in the following example, you cannot use the ALTER TABLESPACE statement for a locally managed temporary tablespace. ALTER TABLESPACE lmtemp ADD TEMPFILE '/u02/oracle/data/lmtemp02.dbf' SIZE 2M REUSE; Note: You cannot use the ALTER TABLESPACE statement, with the TEMPORARY keyword, to change a locally managed permanent tablespace into a locally managed temporary tablespace. You must use the CREATE TEMPORARY TABLESPACE statement to create a locally managed temporary tablespace. However, the ALTER DATABASE statement can be used to alter tempfiles. The following statements take offline and bring online temporary files: ALTER DATABASE TEMPFILE '/u02/oracle/data/lmtemp02.dbf' OFFLINE; ALTER DATABASE TEMPFILE '/u02/oracle/data/lmtemp02.dbf' ONLINE; The following statement resizes a temporary file: ALTER DATABASE TEMPFILE '/u02/oracle/data/lmtemp02.dbf' RESIZE 4M; The following statement drops a temporary file and deletes the operating system file: ALTER DATABASE TEMPFILE '/u02/oracle/data/lmtemp02.dbf' DROP INCLUDING DATAFILES; 11-14 Oracle9i Database Administrator’s Guide Creating Tablespaces The tablespace to which this tempfile belonged remains. A message is written to the alert file for the datafile that was deleted. If an operating system error prevents the deletion of the file, the statement still succeeds, but a message describing the error is written to the alert file. It is also possible, but not shown, to use the ALTER DATABASE statement to enable or disable the automatic extension of an existing tempfile, and to rename (RENAME FILE) a tempfile. Creating a Dictionary-Managed Temporary Tablespace To identify a tablespace as temporary during tablespace creation, specify the TEMPORARY keyword on the CREATE TABLESPACE statement. You cannot specify EXTENT MANAGEMENT LOCAL for a temporary tablespace created in this fashion. To create a locally managed temporary tablespace, use the CREATE TEMPORARY TABLESPACE statement, which is the preferred method of creating a temporary tablespace. The following statement creates a temporary dictionary-managed tablespace: CREATE TABLESPACE sort DATAFILE '/u02/oracle/data/sort01.dbf' SIZE 50M DEFAULT STORAGE ( INITIAL 2M NEXT 2M MINEXTENTS 1 PCTINCREASE 0) EXTENT MANAGEMENT DICTIONARY TEMPORARY; Altering a Dictionary-Managed Temporary Tablespace You can issue the ALTER TABLESPACE statement against a dictionary-managed temporary tablespace using many of the same keywords and clauses as for a permanent dictionary-managed tablespace. Any restrictions are noted in the Oracle9i SQL Reference. Note: When you take dictionary-managed temporary tablespaces offline with the ALTER TABLESPACE ... OFFLINE statement, returning them online does not affect their temporary status. You can change an existing permanent dictionary-managed tablespace to a temporary tablespace, using the ALTER TABLESPACE statement. For example: Managing Tablespaces 11-15 Coalescing Free Space in Dictionary-Managed Tablespaces ALTER TABLESPACE tbsa TEMPORARY; Coalescing Free Space in Dictionary-Managed Tablespaces Over time, the free space in a dictionary-managed tablespace can become fragmented, making it difficult to allocate new extents. Ways of defragmenting this free space are discussed in this section. The following topics are contained in this section: ■ How Oracle Coalesces Free Space ■ Manually Coalescing Free Space ■ Monitoring Free Space How Oracle Coalesces Free Space A free extent in a dictionary-managed tablespace is comprised of a collection of contiguous free blocks. When allocating new extents to a tablespace segment, the free extent closest in size to the required extent is used. In some cases, when segments are dropped, their extents are deallocated and marked as free, but any adjacent free extents are not immediately recombined into larger free extents. The result is fragmentation that makes allocation of larger extents more difficult. This fragmentation is addressed in several ways: ■ ■ ■ ■ When attempting to allocate a new extent for a segment, Oracle first tries to find a free extent large enough for the new extent. If no free extent that is large enough is found, Oracle then coalesces adjacent free extents in the tablespace and looks again. This coalescing is always performed by Oracle whenever it cannot find a free extent into which the new extent will fit. The SMON background process periodically coalesces neighboring free extents when the PCTINCREASE value for a tablespace in nonzero. If you set PCTINCREASE=0, no coalescing of free extents will occur. If you are concerned about the overhead of SMON’s ongoing coalescing, an alternative is to set PCTINCREASE=0, and periodically coalesce free space manually. When a segment is dropped or truncated, a limited form of coalescing is performed if the PCTINCREASE value for the segment is not zero. This is done even if PCTINCREASE=0 for the tablespace containing the segment. You can use the ALTER TABLESPACE ... COALESCE statement to manually coalesce any adjacent free extents. 11-16 Oracle9i Database Administrator’s Guide Coalescing Free Space in Dictionary-Managed Tablespaces The process of coalescing free space is illustrated in the following figure. Figure 11–1 Coalescing Free Space TABSP_2 Input U F U U F U F F U F F F U F U F U F Output F F = free extent U = used extent Note: Coalescing free space is not necessary for locally managed tablespaces because bitmaps automatically track adjacent free space. See Also: Oracle9i Database Concepts for detailed information on allocating extents and coalescing free space Manually Coalescing Free Space If you find that fragmentation of space in a tablespace is high (contiguous space on your disk appears as noncontiguous), you can coalesce any free space using the ALTER TABLESPACE ... COALESCE statement. You must have the ALTER TABLESPACE system privilege to coalesce tablespaces. You might want to use this statement if PCTINCREASE=0, or you can use it to supplement SMON and extent allocation coalescing. If all extents within the tablespace are of the same size, coalescing is not necessary. This would be the case if the default PCTINCREASE value for the tablespace were set to zero, all segments used the default storage parameters of the tablespace, and INITIAL=NEXT=MINIMUM EXTENT. The following statement coalesces free space in the tablespace tabsp_4: ALTER TABLESPACE tabsp_4 COALESCE; Managing Tablespaces 11-17 Coalescing Free Space in Dictionary-Managed Tablespaces Like other options of the ALTER TABLESPACE statement, the COALESCE option is exclusive: when specified, it must be the only option. This statement does not coalesce free extents that are separated by data extents. If you observe that there are many free extents located between data extents, you must reorganize the tablespace (for example, by exporting and importing its data) to create useful free space extents. Monitoring Free Space You can use the following views for monitoring free space in a tablespace: ■ DBA_FREE_SPACE ■ DBA_FREE_SPACE_COALESCED The following statement displays the free space in tablespace tabsp_4: SELECT BLOCK_ID, BYTES, BLOCKS FROM DBA_FREE_SPACE WHERE TABLESPACE_NAME = 'TABSP_4' ORDER BY BLOCK_ID; BLOCK_ID BYTES BLOCKS ---------- ---------- ---------2 16384 2 4 16384 2 6 81920 10 16 16384 2 27 16384 2 29 16384 2 31 16384 2 33 16384 2 35 16384 2 37 16384 2 39 8192 1 40 8192 1 41 196608 24 13 rows selected. This view shows that there is adjacent free space in tabsp_4 (for example, blocks starting with BLOCK_IDs 2, 4, 6, 16) that has not been coalesced. After coalescing the tablespace using the ALTER TABLESPACE statement shown previously, the results of this query would read: BLOCK_ID BYTES BLOCKS 11-18 Oracle9i Database Administrator’s Guide Specifying Nonstandard Block Sizes for Tablespaces ---------- ---------- ---------2 131072 16 27 311296 38 2 rows selected. The DBA_FREE_SPACE_COALESCED view displays statistics for coalescing activity. It is also useful in determining if you need to coalesce space. See Also: Oracle9i Database Reference for more information about these views Specifying Nonstandard Block Sizes for Tablespaces You can create tablespaces of different block sizes than the standard database block size specified by the DB_BLOCK_SIZE initialization parameter. This feature enables the transporting of tablespaces with unlike block sizes between databases. The BLOCKSIZE clause of the CREATE TABLESPACE statement enables you to create a tablespace with a block size other than the database’s standard block size. However, your buffer cache in SGA memory must be configured for the nonstandard block sizes. The following statement creates tablespace lmtbsb, but specifies a block size that differs from the standard database block size (as specified by the DB_BLOCK_SIZE initialization parameter): CREATE TABLESPACE lmtbsb DATAFILE '/u02/oracle/data/lmtbsb01.dbf' SIZE 50M EXTENT MANAGEMENT LOCAL UNIFORM SIZE 128K; BLOCKSIZE 8K; Note: In order for the BLOCKSIZE clause to succeed, you must have the DB_CACHE_SIZE and at least one DB_nK_CACHE_SIZE initialization parameter set, and the integer you specify in this clause must correspond with the setting of one DB_nK_CACHE_ SIZE parameter setting. Although redundant, specifying a BLOCKSIZE equal to the standard block size, as specified by the DB_BLOCK_SIZE initialization parameter, is allowed. For information about these parameters, see "Setting the Buffer Cache Initialization Parameters" on page 2-40. Managing Tablespaces 11-19 Controlling the Writing of Redo Records See Also: ■ "Specifying Database Block Sizes" on page 2-37 ■ "Transporting Tablespaces Between Databases" on page 11-34 Controlling the Writing of Redo Records For some database operations, it is possible to control whether redo records are generated. Suppressing redo generation can improve performance, and may be appropriate for easily recoverable operations. This might include a CREATE TABLE...AS SELECT statement, where the operation can be repeated if there is a database or instance failure. Without redo, no media recovery is possible. Specify the NOLOGGING clause in the CREATE TABLESPACE statement if you wish to suppress redo when these operations are performed for objects within the tablespace. If you do not include this clause, or specify LOGGING instead, then redo is generated when changes are made to objects in the tablespace. Redo is never generated for temporary segments or in temporary tablespaces, regardless of the logging attribute. The logging attribute specified at the tablespace level is the default attribute for objects created within the tablespace. You can override this default logging attribute by specifying LOGGING or NOLOGGING at the schema object level; for example, in a CREATE TABLE statement. In the case where you have a standby database, specifying NOLOGGING causes problems with the availablity and accuracy of the standby database. To overcome this problem, you can specify FORCE LOGGING mode. When you include the FORCE LOGGING clause in the CREATE TABLESPACE statement, you force the generation of redo records for all operations that make changes to objects in a tablespace. This overrides any specification made at the object level. If you transport a tablespace that is in FORCE LOGGING mode to another database, the new tablespace will not maintain the FORCE LOGGING mode. 11-20 Oracle9i Database Administrator’s Guide Altering Tablespace Availability See Also: ■ ■ ■ Oracle9i Database Concepts for additional information about NOLOGGING mode Oracle9i SQL Reference for information about operations that can be done in NOLOGGING mode "Specifying FORCE LOGGING Mode" on page 2-29 for more information about FORCE LOGGING mode and for information about the effects of the FORCE LOGGING clause used with the CREATE DATABASE statement Altering Tablespace Availability You can take an online tablespace offline so that this portion of the database is temporarily unavailable for general use. The rest of the database is open and available for users to access data. Conversely, you can bring an offline tablespace online to make the schema objects within the tablespace available to database users. The database must be open. To alter the availability of a tablespace, use the SQL statement ALTER TABLESPACE. You must have the ALTER TABLESPACE or MANAGE TABLESPACE system privilege to perform this action. You can also take all of the datafiles or tempfiles in a tablespace offline, and bring them back online, without affecting the OFFLINE or ONLINE status of the tablespace itself. Taking Tablespaces Offline You may want to take a tablespace offline for any of the following reasons: ■ ■ ■ To make a portion of the database unavailable while allowing normal access to the remainder of the database To perform an offline tablespace backup (even though a tablespace can be backed up while online and in use) To make an application and its group of tables temporarily unavailable while updating or maintaining the application When a tablespace is taken offline, Oracle takes all the associated files offline. The SYSTEM tablespace can never be taken offline. You can specify any of the following options when taking a tablespace offline: Managing Tablespaces 11-21 Altering Tablespace Availability Option Description NORMAL A tablespace can be taken offline normally if no error conditions exist for any of the datafiles of the tablespace. No datafile in the tablespace can be currently offline as the result of a write error. When OFFLINE NORMAL is specified, Oracle takes a checkpoint for all datafiles of the tablespace as it takes them offline. NORMAL is the default. TEMPORARY A tablespace can be taken offline temporarily, even if there are error conditions for one or more files of the tablespace. When OFFLINE TEMPORARY is specified, Oracle takes offline the datafiles that are not already offline, checkpointing them as it does so. If no files are offline, but you use the temporary option, media recovery is not required to bring the tablespace back online. However, if one or more files of the tablespace are offline because of write errors, and you take the tablespace offline temporarily, the tablespace requires recovery before you can bring it back online. IMMEDIATE A tablespace can be taken offline immediately, without Oracle taking a checkpoint on any of the datafiles. When you specify OFFLINE IMMEDIATE, media recovery for the tablespace is required before the tablespace can be brought online. You cannot take a tablespace offline immediately if the database is running in NOARCHIVELOG mode. FOR RECOVER Takes the database tablespaces in the recovery set offline for tablespace point-in-time recovery. For additional information, see Oracle9i User-Managed Backup and Recovery Guide. Caution: If you must take a tablespace offline, use the NORMAL option (the default) if possible. This guarantees that the tablespace will not require recovery to come back online. It will not require recovery, even if after incomplete recovery you reset the redo log sequence using an ALTER DATABASE OPEN RESETLOGS statement. Specify TEMPORARY only when you cannot take the tablespace offline normally. In this case, only the files taken offline because of errors need to be recovered before the tablespace can be brought online. Specify IMMEDIATE only after trying both the normal and temporary options. The following example takes the users tablespace offline normally: 11-22 Oracle9i Database Administrator’s Guide Altering Tablespace Availability ALTER TABLESPACE users OFFLINE NORMAL; Before taking an online tablespace offline, consider taking the following actions: ■ ■ Verify that the tablespace contains no active rollback segments. Such a tablespace cannot be taken offline. You may want to alter the tablespace allocation of any users who have been assigned the tablespace as either a default or temporary tablespace. This is advisable because they will not be able to access objects or sort areas in the tablespace while it is offline. See Also: "Taking Rollback Segments Offline" on page 13-23 Bringing Tablespaces Online You can bring any tablespace in an Oracle database online whenever the database is open. A tablespace is normally online so that the data contained within it is available to database users. Note: If a tablespace to be brought online was not taken offline "cleanly" (that is, using the NORMAL option of the ALTER TABLESPACE OFFLINE statement), you must first perform media recovery on the tablespace before bringing it online. Otherwise, Oracle returns an error and the tablespace remains offline. Depending upon your archiving strategy, refer to one of the following books for information about performing media recovery: ■ Oracle9i User-Managed Backup and Recovery Guide ■ Oracle9i Recovery Manager User’s Guide The following statement brings the users tablespace online: ALTER TABLESPACE users ONLINE; Altering the Availability of Datafiles or Tempfiles Clauses of the ALTER TABLESPACE statement enable you to change the online or offline status of all of the datafiles or tempfiles within a tablespace. Specifically, the statements that affect online/offline status are: ■ ALTER TABLESPACE ... DATAFILE {ONLINE|OFFLINE} Managing Tablespaces 11-23 Using Read-Only Tablespaces ■ ALTER TABLESPACE ... TEMPFILE {ONLINE|OFFLINE} You are required only to enter the tablespace name, not the individual datafiles or tempfiles. All of the datafiles or tempfiles are affected, but the online/offline status of the tablespace itself is not changed. In most cases the above ALTER TABLESPACE statements can be issued whenever the database is mounted, even if it is not open. The database must not be open if the tablespace is the SYSTEM tablespace, an undo tablespace, or the default temporary tablespace. The ALTER DATABASE DATAFILE and ALTER DATABASE TEMPFILE statements also have ONLINE/OFFLINE clauses, however in those statements require that you enter all of the filenames for the tablespace. The syntax is different from the ALTER TABLESPACE ... ONLINE|OFFLINE statement that alters a tablespace’s availability, because that is a different operation. The ALTER TABLESPACE statement takes datafiles offline as well as the tablespace, but it cannot be used to alter the status of a temporary tablespace or its tempfile(s). Using Read-Only Tablespaces Making a tablespace read-only prevents write operations on the datafiles in the tablespace. The primary purpose of read-only tablespaces is to eliminate the need to perform backup and recovery of large, static portions of a database, but they also provide a means of completely protecting historical data so that no one can modify the data after the fact. Making a tablespace read-only prevents updates on all tables in the tablespace, regardless of a user’s update privilege level. Note: Making a tablespace read-only cannot in itself be used to satisfy archiving or data publishing requirements, because the tablespace can only be brought online in the database in which it was created. However, you can meet such requirements by using the transportable tablespace feature. You can drop items, such as tables or indexes, from a read-only tablespace, but you cannot create or alter objects in the tablespace. You can execute statements that update the file description in the data dictionary, such as ALTER TABLE ... ADD or ALTER TABLE ... MODIFY, but you will not be able to utilize the new description until the tablespace is made read-write. Read-only tablespaces can be transported to other databases. And, since read-only tablespaces can never be updated, they can reside on CD-ROM or WORM (Write Once-Read Many) devices. 11-24 Oracle9i Database Administrator’s Guide Using Read-Only Tablespaces The following topics are discussed in this section: ■ Making a Tablespace Read-Only ■ Making a Read-Only Tablespace Writable ■ Creating a Read-Only Tablespace on a WORM Device ■ Delaying the Opening of Datafiles in Read Only Tablespaces See Also: ■ ■ Oracle9i Database Concepts for more information about read-only tablespaces "Transporting Tablespaces Between Databases" on page 11-34 Making a Tablespace Read-Only All tablespaces are initially created as read-write. Use the READ ONLY clause in the ALTER TABLESPACE statement to change a tablespace to read-only. You must have the ALTER TABLESPACE or MANAGE TABLESPACE system privilege. Before you can make a tablespace read-only, the following conditions must be met. ■ The tablespace must be online. This is necessary to ensure that there is no undo information that needs to be applied to the tablespace. ■ The tablespace must not contain any active rollback segments (this would be the normal situation, as a data tablespace should not contain rollback segments). For this reason, the SYSTEM tablespace can never be made read-only, since it contains the SYSTEM rollback segment. Additionally, because any rollback segments of a read-only tablespace would not be accessible, you would have to drop the rollback segments before you made a tablespace read-only. ■ The tablespace must not currently be involved in an online backup, since the end of a backup updates the header file of all datafiles in the tablespace. For better performance while accessing data in a read-only tablespace, you can issue a query that accesses all of the blocks of the tables in the tablespace just before making it read-only. A simple query, such as SELECT COUNT (*), executed against each table ensures that the data blocks in the tablespace can be subsequently accessed most efficiently. This eliminates the need for Oracle to check the status of the transactions that most recently modified the blocks. Managing Tablespaces 11-25 Using Read-Only Tablespaces The following statement makes the flights tablespace read-only: ALTER TABLESPACE flights READ ONLY; You do not have to wait for transactions to complete before issuing the ALTER TABLESPACE ... READ ONLY statement. When the statement is issued, the target tablespace goes into a transitional read-only mode in which no further write operations (DML statements) are allowed against the tablespace. Existing transactions that modified the tablespace are allowed to commit or rollback. Once all transactions (in the database) have completed, the tablespace becomes read-only. Note: This transitional read-only state only occurs if the value of the initialization parameter COMPATIBLE is 8.1.0 or greater. If this parameter is set to a value less than 8.1.0, the ALTER TABLESPACE ... READ ONLY statement fails if any active transactions exist. If you find it is taking a long time for the tablespace to quiesce, it is possible to identify the transactions which are preventing the read-only state from taking effect. The owners of these transactions can be notified and a decision can be made to terminate the transactions, if necessary. The following example illustrates how you might identify the blocking transactions: ■ Identify the transaction entry for the ALTER TABLESPACE ... READ ONLY statement and note its session address (saddr). SELECT SQL_TEXT, SADDR FROM V$SQLAREA,V$SESSION WHERE V$SQLAREA.ADDRESS = V$SESSION.SQL_ADDRESS AND SQL_TEXT LIKE 'alter tablespace%'; SQL_TEXT SADDR ---------------------------------------- -------alter tablespace tbs1 read only 80034AF0 ■ The start SCN of each active transaction is stored in the V$TRANSACTION view. Displaying this view sorted by ascending start SCN lists the transactions in execution order. Since you know the session address of the transaction entry for the read-only statement, it can be located in the V$TRANSACTION view. All transactions with lesser start SCN can potentially hold up the quiesce and subsequent read-only state of the tablespace. SELECT SES_ADDR, START_SCNB FROM V$TRANSACTION 11-26 Oracle9i Database Administrator’s Guide Using Read-Only Tablespaces ORDER BY START_SCNB; SES_ADDR START_SCNB -------- ---------800352A0 3621 80035A50 3623 80034AF0 3628 80037910 3629 --> --> --> --> waiting on this txn waiting on this txn this is the ALTER TABLESPACE statement don’t care about this txn After making the tablespace read-only, it is advisable to back it up immediately. As long as the tablespace remains read-only, no further backups of the tablespace are necessary since no changes can be made to it. See Also: Depending upon your backup and recovery strategy, refer to one of the following books for information about recovering a database with read-only datafiles: ■ Oracle9i User-Managed Backup and Recovery Guide ■ Oracle9i Recovery Manager User’s Guide Making a Read-Only Tablespace Writable Use the READ WRITE keywords in the ALTER TABLESPACE statement to change a tablespace to allow write operations. You must have the ALTER TABLESPACE or MANAGE TABLESPACE system privilege. A prerequisite to making the tablespace read-write is that all of the datafiles in the tablespace, as well as the tablespace itself, must be online. Use the DATAFILE ... ONLINE clause of the ALTER DATABASE statement to bring a datafile online. The V$DATAFILE view lists the current status of datafiles. The following statement makes the flights tablespace writable: ALTER TABLESPACE flights READ WRITE; Making a read-only tablespace writable updates the control file entry for the datafiles, so that you can use the read-only version of the datafiles as a starting point for recovery. Creating a Read-Only Tablespace on a WORM Device Follow these steps to create a read-only tablespace on a CD-ROM or WORM (Write Once-Read Many) device. Managing Tablespaces 11-27 Using Read-Only Tablespaces 1. Create a writable tablespace on another device. Create the objects that belong in the tablespace and insert your data. 2. Alter the tablespace to make it read-only. 3. Copy the datafiles of the tablespace onto the WORM device. Use operating system commands to copy the files. 4. Take the tablespace offline. 5. Rename the datafiles to coincide with the names of the datafiles you copied onto your WORM device. Use ALTER TABLESPACE with the RENAME DATAFILE clause. Renaming the datafiles changes their names in the control file. 6. Bring the tablespace back online. Delaying the Opening of Datafiles in Read Only Tablespaces When substantial portions of a very large database are stored in read-only tablespaces that are located on slow-access devices or hierarchical storage, you should consider setting the READ_ONLY_OPEN_DELAYED initialization parameter to TRUE. This speeds certain operations, primarily opening the database, by causing datafiles in read-only tablespaces to be accessed for the first time only when an attempt is made to read data stored within them. Setting READ_ONLY_OPEN_DELAYED=TRUE has the following side-effects: ■ ■ ■ ■ ■ ■ A missing or bad read-only file is not detected at open time. It is only discovered when there is an attempt to access it. ALTER SYSTEM CHECK DATAFILES does not check read-only files. ALTER TABLESPACE ... ONLINE and ALTER DATABASE DATAFILE ... ONLINE does not check read-only files. They are checked only upon the first access. V$RECOVER_FILE, V$BACKUP, and V$DATAFILE_HEADER do not access read-only files. Read-only files are indicated in the results list with the error "DELAYED OPEN", with zeroes for the values of other columns. V$DATAFILE does not access read-only files. Read-only files have a size of "0" listed. V$RECOVER_LOG does not access read-only files. Logs they could need for recovery are not added to the list. 11-28 Oracle9i Database Administrator’s Guide Dropping Tablespaces ■ ALTER DATABASE NOARCHIVELOG does not access read-only files.It proceeds even if there is a read-only file that requires recovery. Notes: ■ ■ RECOVER DATABASE and ALTER DATABASE OPEN RESETLOGS continue to access all read-only datafiles regardless of the parameter value. If you want to avoid accessing read-only files for these operations, those files should be taken offline. If a backup control file is used, the read-only status of some files may be inaccurate. This can cause some of these operations to return unexpected results. Care should be taken in this situation. Dropping Tablespaces You can drop a tablespace and its contents (the segments contained in the tablespace) from the database if the tablespace and its contents are no longer required. Any tablespace in an Oracle database, except the SYSTEM tablespace, can be dropped. You must have the DROP TABLESPACE system privilege to drop a tablespace. Caution: Once a tablespace has been dropped, the tablespace’s data is not recoverable. Therefore, make sure that all data contained in a tablespace to be dropped will not be required in the future. Also, immediately before and after dropping a tablespace from a database, back up the database completely. This is strongly recommended so that you can recover the database if you mistakenly drop a tablespace, or if the database experiences a problem in the future after the tablespace has been dropped. When you drop a tablespace, the file pointers in the control file of the associated database are removed. You can optionally direct Oracle to delete the operating system files (datafiles) that constituted the dropped tablespace. If you do not direct Oracle to delete the datafiles at the same time that it deletes the tablespace, you must later use the appropriate commands of your operating system to delete them. Managing Tablespaces 11-29 Diagnosing and Repairing Locally Managed Tablespace Problems You cannot drop a tablespace that contains any active segments. For example, if a table in the tablespace is currently being used or the tablespace contains an active rollback segment, you cannot drop the tablespace. The tablespace can be online or offline, but it is best to take the tablespace offline before dropping it. To drop a tablespace, use the DROP TABLESPACE statement. The following statement drops the users tablespace, including the segments in the tablespace: DROP TABLESPACE users INCLUDING CONTENTS; If the tablespace is empty (does not contain any tables, views, or other structures), you do not need to specify the INCLUDING CONTENTS option. Use the CASCADE CONSTRAINTS option to drop all referential integrity constraints from tables outside the tablespace that refer to primary and unique keys of tables inside the tablespace. To delete the datafiles associated with a tablespace at the same time that the tablespace is dropped, use the INCLUDING CONTENTS AND DATAFILES clause. The following statement drops the USER tablespace and its associated datafiles: DROP TABLESPACE users INCLUDING CONTENTS AND DATAFILES; A message is written to the alert file for each datafile that is deleted. If an operating system error prevents the deletion of a file, the DROP TABLESPACE statement still succeeds, but a message describing the error is written to the alert file. Diagnosing and Repairing Locally Managed Tablespace Problems Note: The DBMS_SPACE_ADMIN package provides administrators with defect diagnosis and repair functionality for locally managed tablespaces. It cannot be used in this capacity for dictionary-managed tablespaces. It also provides procedures for migrating from dictionarymanaged tablespaces to locally managed tablespaces, and the reverse. The DBMS_SPACE_ADMIN package contains the following procedures: Procedure Description SEGMENT_VERIFY Verifies the consistency of the extent map of the segment. 11-30 Oracle9i Database Administrator’s Guide Diagnosing and Repairing Locally Managed Tablespace Problems Procedure Description SEGMENT_CORRUPT Marks the segment corrupt or valid so that appropriate error recovery can be done. Cannot be used for a locally managed SYSTEM tablespace. SEGMENT_DROP_CORRUPT Drops a segment currently marked corrupt (without reclaiming space). Cannot be used for a locally managed SYSTEM tablespace. SEGMENT_DUMP Dumps the segment header and extent map of a given segment. TABLESPACE_VERIFY Verifies that the bitmaps and extent maps for the segments in the tablespace are in sync. TABLESPACE_REBUILD_BITMAPS Rebuilds the appropriate bitmap. Cannot be used for a locally managed SYSTEM tablespace. TABLESPACE_FIX_BITMAPS Marks the appropriate data block address range (extent) as free or used in bitmap. Cannot be used for a locally managed SYSTEM tablespace. TABLESPACE_REBUILD_QUOTAS Rebuilds quotas for given tablespace. TABLESPACE_MIGRATE_FROM_LOCAL Migrates a locally managed tablespace to dictionary-managed tablespace. Cannot be used to migrate a locally managed SYSTEM tablespace to a dictionary-managed SYSTEM tablespace. TABLESPACE_MIGRATE_TO_LOCAL Migrates a tablespace from dictionary-managed format to locally managed format. TABLESPACE_RELOCATE_BITMAPS Relocates the bitmaps to the destination specified. Cannot be used for a locally managed system tablespace. TABLESPACE_FIX_SEGMENT_STATES Fixes the state of the segments in a tablespace in which migration was aborted. The following scenarios describe typical situations in which you can use the DBMS_ SPACE_ADMIN package to diagnose and resolve problems. Note: Some of these procedures can result in lost and unrecoverable data if not used properly. You should work with Oracle Support Services if you have doubts about these procedures. Managing Tablespaces 11-31 Diagnosing and Repairing Locally Managed Tablespace Problems Oracle9i Supplied PL/SQL Packages and Types Reference for details about the DBMS_SPACE_ADMIN package See Also: Scenario 1: Fixing Bitmap When Allocated Blocks are Marked Free (No Overlap) The TABLESPACE_VERIFY procedure discovers that a segment has allocated blocks that are marked free in the bitmap, but no overlap between segments is reported. In this scenario, perform the following tasks: 1. Call the SEGMENT_DUMP procedure to dump the ranges that the administrator allocated to the segment. 2. For each range, call the TABLESPACE_FIX_BITMAPS procedure with the TABLESPACE_EXTENT_MAKE_USED option to mark the space as used. 3. Call TABLESPACE_REBUILD_QUOTAS to fix up quotas. Scenario 2: Dropping a Corrupted Segment You cannot drop a segment because the bitmap has segment blocks marked "free". The system has automatically marked the segment corrupted. In this scenario, perform the following tasks: 1. Call the SEGMENT_VERIFY procedure with the SEGMENT_VERIFY_EXTENTS_ GLOBAL option. If no overlaps are reported, then proceed with steps 2 through 5. 2. Call the SEGMENT_DUMP procedure to dump the DBA ranges allocated to the segment. 3. For each range, call TABLESPACE_FIX_BITMAPS with the TABLESPACE_ EXTENT_MAKE_FREE option to mark the space as free. 4. Call SEGMENT_DROP_CORRUPT to drop the SEG$ entry. 5. Call TABLESPACE_REBUILD_QUOTAS to fix up quotas. Scenario 3: Fixing Bitmap Where Overlap is Reported The TABLESPACE_VERIFY procedure reports some overlapping. Some of the real data must be sacrificed based on previous internal errors. After choosing the object to be sacrificed, in this case say, table t1, perform the following tasks: 11-32 Oracle9i Database Administrator’s Guide Diagnosing and Repairing Locally Managed Tablespace Problems 1. Make a list of all objects that t1 overlaps. 2. Drop table t1. If necessary, follow up by calling the SEGMENT_DROP_CORRUPT procedure. 3. Call the SEGMENT_VERIFY procedure on all objects that t1 overlapped. If necessary, call the TABLESPACE_FIX_BITMAPS procedure to mark appropriate bitmap blocks as used. 4. Rerun the TABLESPACE_VERIFY procedure to verify the problem is resolved. Scenario 4: Correcting Media Corruption of Bitmap Blocks A set of bitmap blocks has media corruption. In this scenario, perform the following tasks: 1. Call the TABLESPACE_REBUILD_BITMAPS procedure, either on all bitmap blocks, or on a single block if only one is corrupt. 2. Call the TABLESPACE_REBUILD_QUOTAS procedure to rebuild quotas. 3. Call the TABLESPACE_VERIFY procedure to verify that the bitmaps are consistent. Scenario 5: Migrating from a Dictionary-Managed to a Locally Managed Tablespace You migrate a dictionary-managed tablespace to a locally managed tablespace. You use the TABLESPACE_MIGRATE_TO_LOCAL procedure. Let us assume that the database block size is 2K, and the existing extent sizes in tablespace tbs_1 are 10, 50, and 10,000 blocks (used, used, and free). The MINIMUM EXTENT value is 20K (10 blocks). In this scenario, you allow the bitmap allocation unit to be chosen by the system. The value of 10 blocks is chosen, because it is the highest common denominator and does not exceed MINIMUM EXTENT. The statement to convert tbs_1 to a locally managed tablespace is as follows: EXEC DBMS_SPACE_ADMIN.TABLESPACE_MIGRATE_TO_LOCAL ('tbs_1'); If you choose to specify a allocation unit size, it must be a factor of the unit size calculated by the system, otherwise an error message is issued. Managing Tablespaces 11-33 Migrating the SYSTEM Tablespace to a Locally Managed Tablespace Migrating the SYSTEM Tablespace to a Locally Managed Tablespace Use the DBMS_SPACE_ADMIN package to migrate the SYSTEM tablespace from dictionary-managed to locally managed. The following statement performs the migration: SQL> EXECUTE DBMS_SPACE_ADMIN.TABLESPACE_MIGRATE_TO_LOCAL('SYSTEM'); Before performing the migration the following conditions must be met: ■ The database has a default temporary tablespace that is not SYSTEM. ■ There are no rollback segments in dictionary-managed tablespaces. ■ ■ There is at least one online rollback segment in a locally managed tablespace, or if using automatic undo management, an undo tablespace is online. All tablespaces other than the tablespace containing the undo space (that is, the tablespace containing the rollback segment or the undo tablespace) are in read-only mode. ■ There is a cold backup of the database. ■ The system is in restricted mode. All of these conditions, except for the cold backup, are enforced by the TABLESPACE_MIGRATE_TO_LOCAL procedure. Note: After the SYSTEM tablespace is migrated to locally managed, any dictionary-managed tablespaces in the database cannot be made READ WRITE. If you want to be able to use the dictionary-managed tablespaces in READ-WRITE mode, Oracle recommends that you first migrate these tablespaces to locally managed before migrating the SYSTEM tablespace. Transporting Tablespaces Between Databases This section describes how to transport tablespaces between databases, and contains the following topics: ■ Introduction to Transportable Tablespaces ■ Limitations ■ Compatibility Considerations for Transportable Tablespaces ■ Transporting Tablespaces Between Databases: A Procedure 11-34 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases ■ Object Behaviors ■ Using Transportable Tablespaces Introduction to Transportable Tablespaces Note: You must be using the Enterprise Edition of Oracle8i (or higher) to generate a transportable tablespace set. However, you can use any edition of Oracle8i (or higher) to plug a transportable tablespace set into an Oracle database. See "Compatibility Considerations for Transportable Tablespaces" on page 11-36 for a discussion of database compatibility for transporting tablespaces across release levels. You can use the transportable tablespaces feature to move a subset of an Oracle database and "plug" it in to another Oracle database, essentially moving tablespaces between the databases. The tablespaces being transported can be either dictionary managed or locally managed. Starting with Oracle9i, the transported tablespaces are not required to be of the same block size as the target database’s standard block size. Transporting tablespaces is particularly useful for: ■ Moving data from OLTP systems to data warehouse staging systems ■ Updating data warehouses and data marts from staging systems ■ Loading data marts from central data warehouses ■ Archiving OLTP and data warehouse systems efficiently ■ Data publishing to internal and external customers ■ Performing Tablespace Point-in-Time Recovery (TSPITR) Moving data using transportable tablespaces can be much faster than performing either an export/import or unload/load of the same data, because transporting a tablespace only requires the copying of datafiles and integrating the tablespace structural information. You can also use transportable tablespaces to move index data, thereby avoiding the index rebuilds you would have to perform when importing or loading table data. Managing Tablespaces 11-35 Transporting Tablespaces Between Databases See Also: ■ ■ ■ Oracle9i Database Concepts for more details about transportable tablespaces and their use in data marts and data warehousing Oracle9i Database Migration for information about transportable tablespace compatibility issues between different Oracle releases Oracle9i Recovery Manager User’s Guide for information about using RMAN to transport an RMAN tablespace backup into another database. Using this method, you are not required to make the tablespace in the original database read-only. Limitations Be aware of the following limitations as you plan for transportable tablespace use: ■ ■ ■ ■ The source and target database must be on the same hardware platform. For example, you can transport tablespaces between Sun Solaris Oracle databases, or you can transport tablespaces between Windows NT Oracle databases. However, you cannot transport a tablespace from a Sun Solaris Oracle database to an Windows NT Oracle database. The source and target database must use the same character set and national character set. You cannot transport a tablespace to a target database in which a tablespace with the same name already exists. Transportable tablespaces do not support: – Materialized views/replication – Function-based indexes – Scoped REFs – 8.0-compatible advanced queues with multiple recipients Compatibility Considerations for Transportable Tablespaces To use the transportable tablespaces feature, the COMPATIBLE initialization parameter for both the source and target databases must be set to 8.1 or higher. If the block size of any tablespace being transported is different from the standard block size for the target database, the COMPATIBLE initialization parameter must be set to 9.0 or higher for the target database. You are not required to be running the 11-36 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases same release of Oracle for both the source and target database. Oracle guarantees that the transportable tablespace set is compatible with the target database. If not, an error is signaled at the beginning of the plug-in operation. It is always possible to transport a tablespace from a database running an older release of Oracle (starting with Oracle8i) to a database running a newer release of Oracle (for example, Oracle9i). When creating a transportable tablespace set, Oracle computes the lowest compatibility level at which the target database must run. This is referred to as the compatibility level of the transportable set. When plugging the transportable set into a target database, Oracle signals an error if the compatibility level of the transportable set is greater than the compatibility level of the target database. Transporting Tablespaces Between Databases: A Procedure To move or copy a set of tablespaces, perform the following steps. These steps are illustrated more fully in succeeding sections that detail transporting tablespaces sales_1 and sales_2 between databases. 1. Pick a self-contained set of tablespaces. 2. Generate a transportable tablespace set. A transportable tablespace set consists of datafiles for the set of tablespaces being transported and a file containing structural information for the set of tablespaces. 3. Transport the tablespace set. Copy the datafiles and the export file to the target database. You can do this using any facility for copying flat files (for example, an operating system copy utility, ftp, or publishing on CDs). 4. Plug in the tablespace. Invoke the Import utility to plug the set of tablespaces into the target database. Step 1: Pick a Self-Contained Set of Tablespaces There may be logical or physical dependencies between objects in the transportable set and those outside of the set. You can only transport a set of tablespaces that is self-contained. In this context "self-contained" means that there are no references from inside the set of tablespaces pointing outside of the tablespaces. Some examples of self contained tablespace violations are: Managing Tablespaces 11-37 Transporting Tablespaces Between Databases ■ An index inside the set of tablespaces is for a table outside of the set of tablespaces. Note: It is not a violation if a corresponding index for a table is outside of the set of tablespaces. ■ A partitioned table is partially contained in the set of tablespaces. The tablespace set you want to copy must contain either all partitions of a partitioned table, or none of the partitions of a partitioned table. If you want to transport a subset of a partition table, you must exchange the partitions into tables. ■ A referential integrity constraint points to a table across a set boundary. When transporting a set of tablespaces, you can choose to include referential integrity constraints. However, doing so can affect whether or not a set of tablespaces is self-contained. If you decide not to transport constraints, then the constraints are not considered as pointers. ■ A table inside the set of tablespaces contains a LOB column that points to LOBs outside the set of tablespaces. To determine whether a set of tablespaces is self-contained, you can invoke the TRANSPORT_SET_CHECK procedure in the Oracle supplied package DBMS_TTS. You must have been granted the EXECUTE_CATALOG_ROLE role (initially signed to SYS) to execute this procedure. When you invoke the DBMS_TTS package, you specify the list of tablespaces in the transportable set to be checked for self containment. You can optionally specify if constraints must be included. For strict or full containment, you must additionally set the TTS_FULL_CHECK parameter to TRUE. The strict or full containment check is for cases that require capturing not only references going outside the transportable set, but also those coming into the set. Tablespace Point-in-Time Recovery (TSPITR) is one such case where dependent objects must be fully contained or fully outside the transportable set. For example, it is a violation to perform TSPITR on a tablespace containing a table t but not its index i because the index and data will be inconsistent after the transport. A full containment check ensures that there are no dependencies going outside or coming into the transportable set. See the example for TSPITR in the Oracle9i User-Managed Backup and Recovery Guide. 11-38 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases Note: The default for transportable tablespaces is to check for self containment rather than full containment. Here we determine whether tablespaces sales_1 and sales_2 are self-contained, with referential integrity constraints taken into consideration (indicated by TRUE). EXECUTE dbms_tts.transport_set_check('sales_1,sales_2', TRUE); After invoking this PL/SQL package, you can see all violations by selecting from the TRANSPORT_SET_VIOLATIONS view. If the set of tablespaces is self-contained, this view is empty. The following query shows a case where there are two violations: a foreign key constraint, dept_fk, across the tablespace set boundary, and a partitioned table, jim.sales, that is partially contained in the tablespace set. SELECT * FROM TRANSPORT_SET_VIOLATIONS; VIOLATIONS --------------------------------------------------------------------------Constraint DEPT_FK between table JIM.EMP in tablespace SALES_1 and table JIM.DEPT in tablespace OTHER Partitioned table JIM.SALES is partially contained in the transportable set These violations must be resolved before sales_1 and sales_2 are transportable. As noted in the next step, one choice for bypassing the integrity constrain violation is to not export the integrity constraints. Object references (such as REFs) across the tablespace set are not considered violations. REFs are not checked by the TRANSPORT_SET_CHECK routine. When a tablespace containing dangling REFs is plugged into a database, queries following that dangling REF indicate user error. See Also: ■ ■ ■ Oracle9i Application Developer’s Guide - Fundamentals for more information about REFs Oracle9i Supplied PL/SQL Packages and Types Reference for more information about the DBMS_TTS package Oracle9i User-Managed Backup and Recovery Guide for information specific to using the DBMS_TTS package for TSPITR Managing Tablespaces 11-39 Transporting Tablespaces Between Databases Step 2: Generate a Transportable Tablespace Set After ensuring you have a self-contained set of tablespaces that you want to transport, generate a transportable tablespace set by performing the following tasks: 1. Make all tablespaces in the set you are copying read-only. ALTER TABLESPACE sales_1 READ ONLY; ALTER TABLESPACE sales_2 READ ONLY; 2. Invoke the Export utility and specify which tablespaces are in the transportable set, as follows: EXP TRANSPORT_TABLESPACE=y TABLESPACES=(sales_1,sales_2) TRIGGERS=y CONSTRAINTS=n GRANTS=n FILE=expdat.dmp Note: Although the Export utility is used, only data dictionary structural information (metadata) for the tablespaces is exported. Hence, this operation goes quickly even for a large tablespace. When prompted, connect as SYS (or other administrative user) with the SYSDBA system privilege: CONNECT SYS/password AS SYSDBA You must always specify TABLESPACES. In this example, we also specify that: ■ Triggers are to be exported. If you set TRIGGERS=y, triggers are exported without a validity check. Invalid triggers cause compilation errors during the subsequent import.If you set TRIGGERS=n, triggers are not exported. ■ Referential integrity constraints are not to be exported ■ Grants are not to be exported. ■ The name of the structural information export file to be created is expdat.dmp. If you are performing TSPITR or transport with a strict containment check, use: EXP TRANSPORT_TABLESPACE=y TABLESPACES=(sales_1,sales_2) TTS_FULL_CHECK=Y FILE=expdat.dmp 11-40 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases If the tablespace sets being transported are not self-contained, export fails and indicate that the transportable set is not self-contained. You must then return to Step 1 to resolve all violations. See Also: Oracle9i Database Utilities for information about using the Export utility Step 3: Transport the Tablespace Set Transport both the datafiles and the export file of the tablespaces to a place accessible to the target database. You can use any facility for copying flat files (for example, an operating system copy utility, ftp, or publishing on CDs). Step 4: Plug In the Tablespace Set Note: If you are transporting a tablespace of a different block size than the standard block size of the database receiving the tablespace set, then you must first have a DB_nK_CACHE_SIZE initialization parameter entry in the receiving database’s parameter file. For example, if you are transporting a tablespace with an 8K block size into a database with a 4K standard block size, then you must include a DB_8K_CACHE_SIZE initialization parameter entry in the parameter file. If it is not already included in the parameter file, this parameter can be set using the ALTER SYSTEM SET statement. See Oracle9i SQL Reference for information about specifying values for the DB_nK_CACHE_SIZE initialization parameter. To plug in a tablespace set, perform the following tasks: 1. Plug in the tablespaces and integrate the structural information using the Import utility. IMP TRANSPORT_TABLESPACE=y FILE=expdat.dmp DATAFILES=('/db/sales_jan','/db/sales_feb',...) TABLESPACES=(sales_1,sales_2) TTS_OWNERS=(dcranney,jfee) FROMUSER=(dcranney,jfee) TOUSER=(smith,williams) When prompted, connect as SYS (or other administrative user) with the SYSDBA system privilege: Managing Tablespaces 11-41 Transporting Tablespaces Between Databases CONNECT SYS/password AS SYSDBA In this example we specify the following: ■ ■ ■ ■ TRANSPORT_TABLESPACE=y tells the Export utility that we are transporting a tablespace. The exported file containing the metadata for the tablespaces is expdat.dmp. DATAFILES specifies the datafiles of the transported tablespaces and must be specified. The tablespace names are sales_1 and sales_2. When you specify TABLESPACES, the supplied tablespace names are compared to those in the export file. Import returns an error if there is any mismatch. Otherwise, tablespace names are extracted from the export file. ■ TTS_OWNERS lists all users who own data in the tablespace set. When you specify TTS_OWNERS, the user names are compared to those in the export file. Import returns an error if there is any mismatch. Otherwise, owner names are extracted from the export file. ■ FROMUSER and TOUSER are specified to change the ownership of database objects. If you do not specify FROMUSER and TOUSER, all database objects (such as tables and indexes) are created under the same user as in the source database. Those users must already exist in the target database. If not, import returns an error indicating that some required users do not exist in the target database. You can use FROMUSER and TOUSER to change the owners of objects. In this example we specify FROMUSER=(dcranney,jfee) and TOUSER=(smith, williams). Objects in the tablespace set owned by dcranney in the source database will be owned by smith in the target database after the tablespace set is plugged in. Similarly, objects owned by jfee in the source database will be owned by williams in the target database. In this case, the target database is not required to have users dcranney and jfee, but must have users smith and williams. After this statement successfully executes, all tablespaces in the set being copied remain in read-only mode. Check the import logs to ensure no error has occurred. 11-42 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases When dealing with a large number of datafiles, specifying the list of datafile names in the statement line can be a laborious process. It can even exceed the statement line limit. In this situation, you can use an import parameter file. For example, you can invoke the Import utility as follows: IMP PARFILE='par.f' The file par.f file contains the following: TRANSPORT_TABLESPACE=y FILE=expdat.dmp DATAFILES=('/db/sales_jan','/db/sales_feb',...) TABLESPACES=(sales_1,sales_2) TTS_OWNERS=(dcranney,jfee) FROMUSER=(dcranney,jfee) TOUSER=(smith,williams) 2. If necessary, put the tablespaces in the copied space back into read-write mode as follows: ALTER TABLESPACE sales_1 READ WRITE ALTER TABLESPACE sales_1 READ WRITE See Also: Oracle9i Database Utilities for information about using the Import utility Object Behaviors Most objects, whether data in a tablespace or structural information associated with the tablespace, behave normally after being transported to a different database. However, the following objects are exceptions: ■ ROWIDs ■ REFs ■ Privileges ■ Partitioned Tables ■ Objects ■ Advanced Queues ■ Indexes ■ Triggers Managing Tablespaces 11-43 Transporting Tablespaces Between Databases ■ Materialized Views/Replication ROWIDs When a database contains tablespaces that have been plugged in (from other databases), the ROWIDs in that database are no longer unique. A ROWID is guaranteed unique only within a table. REFs REFs are not checked when Oracle determines if a set of tablespaces is self-contained. As a result, a plugged-in tablespace may contain dangling REFs. Any query following dangling REFs returns a user error. Privileges Privileges are transported if you specify GRANTS=y during export. During import, some grants may fail. For example, the user being granted a certain right may not exist, or a role being granted a particular right may not exist. Partitioned Tables You cannot move a partitioned table using transportable tablespaces when only a subset of the partitioned table is contained in the set of tablespaces. You must ensure that all partitions in a table are in the tablespace set, or exchange the partitions into tables before copying the tablespace set. However, you should note that exchanging partitions with tables invalidates the global index of the partitioned table. At the target database, you can exchange the tables back into partitions if there is already a partitioned table that exactly matches the column in the target database. If all partitions of that table come from the same foreign database, the exchange operation is guaranteed to succeed. If they do not, in rare cases, the exchange operation may return an error indicating that there is a data object number conflict. If you receive a data object number conflict error when exchanging tables back into partitions, you can move the offending partition using the ALTER TABLE MOVE PARTITION statement. After doing so, retry the exchange operation. If you specify the WITHOUT VALIDATION option of the exchange statement, the statement returns immediately because it only manipulates structural information. Moving partitions, however, may be slow because the data in the partition can be copied. 11-44 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases See Also: "Transporting and Attaching Partitions for Data Warehousing" on page 11-46 for an example of transporting a partitioned table Objects A transportable tablespace set can contain: ■ Tables ■ Indexes ■ Domain indexes ■ Bitmap indexes ■ Index-organized tables ■ LOBs ■ Nested tables ■ Varrays ■ Tables with user-defined type columns If the tablespace set contains a pointer to a BFILE, you must move the BFILE and set the directory correctly in the target database. Advanced Queues You can use transportable tablespaces to move or copy Oracle advanced queues, as long as these queues are not 8.0 compatible queues with multiple recipients. After a queue is transported to a target database, the queue is initially disabled. After making the transported tablespaces read-write in the target database, you can enable the queue by starting it up using the built-in PL/SQL routine DBMS_ AQADM.START_QUEUE. Indexes You can transport regular indexes, domain indexes, and bitmap indexes. When the transportable set fully contains a partitioned table, you can also transport the global index of the partitioned table. Function-based indexes are not supported. If they exist in a tablespace, you must drop them before you can transport the tablespace. Managing Tablespaces 11-45 Transporting Tablespaces Between Databases Triggers Triggers are exported without a validity check. In other words, Oracle does not verify that the trigger refers only to objects within the transportable set. Invalid triggers cause a compilation error during the subsequent import. Materialized Views/Replication Transporting materialized views or replication structural information is not supported. When transporting a tablespace, the materialized view or replication metadata associated with the tables in the tablespace is not exported and, thus, is not be available to the target database. Using Transportable Tablespaces The following are some possible applications for transportable tablespaces. Transporting and Attaching Partitions for Data Warehousing Typical enterprise data warehouses contain one or more large fact tables. These fact tables can be partitioned by date, making the enterprise data warehouse a historical database. You can build indexes to speed up star queries. In fact, Oracle recommends that you build local indexes for such historically partitioned tables to avoid rebuilding global indexes every time you drop the oldest partition from the historical database. Suppose every month you would like to load one month’s worth of data into the data warehouse. There is a large fact table in the data warehouse called sales, which has the following columns: CREATE TABLE sales (invoice_no NUMBER, sale_year INT NOT NULL, sale_month INT NOT NULL, sale_day INT NOT NULL) PARTITION BY RANGE (sale_year, sale_month, (partition jan98 VALUES LESS THAN (1998, partition feb98 VALUES LESS THAN (1998, partition mar98 VALUES LESS THAN (1998, partition apr98 VALUES LESS THAN (1998, partition may98 VALUES LESS THAN (1998, partition jun98 VALUES LESS THAN (1998, sale_day) 2, 1), 3, 1), 4, 1), 5, 1), 6, 1), 7, 1)); You create a local nonprefixed index: CREATE INDEX sales_index ON sales(invoice_no) LOCAL; 11-46 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases Initially, all partitions are empty, and are in the same default tablespace. Each month, you want to create one partition and attach it to the partitioned sales table. Suppose it is July 1998, and you would like to load the July sales data into the partitioned table. In a staging database, you create a new tablespace, ts_jul. You also create a table, jul_sales, in that tablespace with exactly the same column types as the sales table. You can create the table jul_sales using the CREATE TABLE ... AS SELECT statement. After creating and populating jul_sales, you can also create an index, jul_sale_index, for the table, indexing the same column as the local index in the sales table. After building the index, transport the tablespace ts_jul to the data warehouse. In the data warehouse, add a partition to the sales table for the July sales data. This also creates another partition for the local nonprefixed index: ALTER TABLE sales ADD PARTITION jul98 VALUES LESS THAN (1998, 8, 1); Attach the transported table jul_sales to the table sales by exchanging it with the new partition: ALTER TABLE sales EXCHANGE PARTITION jul98 WITH TABLE jul_sales INCLUDING INDEXES WITHOUT VALIDATION; This statement places the July sales data into the new partition jul98, attaching the new data to the partitioned table. This statement also converts the index jul_ sale_index into a partition of the local index for the sales table. This statement should return immediately, because it only operates on the structural information and it simply switches database pointers. If you know that the data in the new partition does not overlap with data in previous partitions, you are advised to specify the WITHOUT VALIDATION option. Otherwise, the statement goes through all the new data in the new partition in an attempt to validate the range of that partition. If all partitions of the sales table came from the same staging database (the staging database is never destroyed), the exchange statement always succeeds. In general, however, if data in a partitioned table comes from different databases, it’s possible that the exchange operation may fail. For example, if the jan98 partition of sales did not come from the same staging database, the above exchange operation can fail, returning the following error: ORA-19728: data object number conflict between table JUL_SALES and partition JAN98 in table SALES Managing Tablespaces 11-47 Transporting Tablespaces Between Databases To resolve this conflict, move the offending partition by issuing the following statement: ALTER TABLE sales MOVE PARTITION jan98; Then retry the exchange operation. After the exchange succeeds, you can safely drop jul_sales and jul_sale_ index (both are now empty). Thus you have successfully loaded the July sales data into your data warehouse. Publishing Structured Data on CDs Transportable tablespaces provide a way to publish structured data on CDs. A data provider can load a tablespace with data to be published, generate the transportable set, and copy the transportable set to a CD. This CD can then be distributed. When customers receive this CD, they can plug it into an existing database without having to copy the datafiles from the CD to disk storage. For example, suppose on a Windows NT machine D: drive is the CD drive. You can plug in a transportable set with datafile catalog.f and export file expdat.dmp as follows: IMP TRANSPORT_TABLESPACE=y DATAFILES='D:\catalog.f' FILE='D:\expdat.dmp' You can remove the CD while the database is still up. Subsequent queries to the tablespace return an error indicating that Oracle cannot open the datafiles on the CD. However, operations to other parts of the database are not affected. Placing the CD back into the drive makes the tablespace readable again. Removing the CD is the same as removing the datafiles of a read-only tablespace. If you shut down and restart the database, Oracle indicates that it cannot find the removed datafile and does not open the database (unless you set the initialization parameter READ_ONLY_OPEN_DELAYED to TRUE). When READ_ONLY_OPEN_ DELAYED is set to TRUE, Oracle reads the file only when someone queries the plugged-in tablespace. Thus, when plugging in a tablespace on a CD, you should always set the READ_ONLY_OPEN_DELAYED initialization parameter to TRUE, unless the CD is permanently attached to the database. Mounting the Same Tablespace Read-Only on Multiple Databases You can use transportable tablespaces to mount a tablespace read-only on multiple databases. In this way, separate databases can share the same data on disk instead of duplicating data on separate disks. The tablespace datafiles must be accessible by all databases. To avoid database corruption, the tablespace must remain read-only in all the databases mounting the tablespace. 11-48 Oracle9i Database Administrator’s Guide Transporting Tablespaces Between Databases You can mount the same tablespace read-only on multiple databases in either of the following ways: ■ ■ Plug the tablespace into each of the databases on which you want to mount the tablespace. Generate a transportable set in a single database. Put the datafiles in the transportable set on a disk accessible to all databases. Import the structural information into each database. Generate the transportable set in one of the databases and plug it into other databases. If you use this approach, it is assumed that the datafiles are already on the shared disk, and they belong to an existing tablespace in one of the databases. You can make the tablespace read-only, generate the transportable set, and then plug the tablespace in to other databases while the datafiles remain in the same location on the shared disk. You can make the disk accessible by multiple computers in several ways. You can use either a cluster file system or raw disk, because that is required by Oracle9i Real Application Clusters. Because Oracle reads only these type of datafiles on shared disk, you can also use NFS. Be aware, however, that if a user queries the shared tablespace while NFS is down, the database will hang until the NFS operation times out. Later, you can drop the read-only tablespace in some of the databases. Doing so does not modify the datafiles for the tablespace. Thus, the drop operation does not corrupt the tablespace. Do not make the tablespace read-write unless only one database is mounting the tablespace. Archive Historical Data Using Transportable Tablespaces Since a transportable tablespace set is a self-contained set of files that can be plugged into any Oracle database, you can archive old/historical data in an enterprise data warehouse using the transportable tablespace procedures described in this chapter. See Also: Oracle9i Data Warehousing Guide for more details Using Transportable Tablespaces to Perform TSPITR You can use transportable tablespaces to perform tablespace point-in-time recovery (TSPITR). Oracle9i User-Managed Backup and Recovery Guide for information about how to perform TSPITR using transportable tablespaces See Also: Managing Tablespaces 11-49 Viewing Tablespace Information Viewing Tablespace Information The following data dictionary and dynamic performance views provide useful information about the tablespaces of a database. View Description V$TABLESPACE Name and number of all tablespaces from the control file. DBA_TABLESPACES, USER_TABLESPACES Descriptions of all (or user accessible) tablespaces. DBA_SEGMENTS, USER_SEGMENTS Information about segments within all (or user accessible) tablespaces. DBA_EXTENTS, USER_EXTENTS Information about data extents within all (or user accessible) tablespaces. DBA_FREE_SPACE, USER_FREE_SPACE Information about free extents within all (or user accessible) tablespaces. V$DATAFILE Information about all datafiles, including tablespace number of owning tablespace. V$TEMPFILE Information about all tempfiles, including tablespace number of owning tablespace. DBA_DATA_FILES Shows files (datafiles) belonging to tablespaces. DBA_TEMP_FILES Shows files (tempfiles) belonging to temporary tablespaces. V$TEMP_EXTENT_MAP Information for all extents in all locally managed temporary tablespaces. V$TEMP_EXTENT_POOL For locally managed temporary tablespaces: the state of temporary space cached and used for by each instance. V$TEMP_SPACE_HEADER Shows space used/free for each tempfile. DBA_USERS Default and temporary tablespaces for all users. DBA_TS_QUOTAS Lists tablespace quotas for all users. V$SORT_SEGMENT Information about every sort segment in a given instance. The view is only updated when the tablespace is of the TEMPORARY type. V$SORT_USER Temporary sort space usage by user and temporary/permanent tablespace. The following are just a few examples of using some of these views. 11-50 Oracle9i Database Administrator’s Guide Viewing Tablespace Information See Also: Oracle9i Database Reference for complete description of these views Listing Tablespaces and Default Storage Parameters: Example To list the names and default storage parameters of all tablespaces in a database, use the following query on the DBA_TABLESPACES view: SELECT TABLESPACE_NAME "TABLESPACE", INITIAL_EXTENT "INITIAL_EXT", NEXT_EXTENT "NEXT_EXT", MIN_EXTENTS "MIN_EXT", MAX_EXTENTS "MAX_EXT", PCT_INCREASE FROM DBA_TABLESPACES; TABLESPACE INITIAL_EXT NEXT_EXT MIN_EXT ---------- ----------- -------- ------RBS 1048576 1048576 2 SYSTEM 106496 106496 1 TEMP 106496 106496 1 TESTTBS 57344 16384 2 USERS 57344 57344 1 MAX_EXT ------40 99 99 10 99 PCT_INCREASE -----------0 1 0 1 1 Listing the Datafiles and Associated Tablespaces of a Database: Example To list the names, sizes, and associated tablespaces of a database, enter the following query on the DBA_DATA_FILES view: SELECT FILE_NAME, BLOCKS, TABLESPACE_NAME FROM DBA_DATA_FILES; FILE_NAME -----------/U02/ORACLE/IDDB3/RBS01.DBF /U02/ORACLE/IDDB3/SYSTEM01.DBF /U02/ORACLE/IDDB3/TEMP01.DBF /U02/ORACLE/IDDB3/TESTTBS01.DBF /U02/ORACLE/IDDB3/USERS01.DBF BLOCKS ---------1536 6586 6400 6400 384 TABLESPACE_NAME ------------------RBS SYSTEM TEMP TESTTBS USERS Displaying Statistics for Free Space (Extents) of Each Tablespace: Example To produce statistics about free extents and coalescing activity for each tablespace in the database, enter the following query: Managing Tablespaces 11-51 Viewing Tablespace Information SELECT TABLESPACE_NAME "TABLESPACE", FILE_ID, COUNT(*) "PIECES", MAX(blocks) "MAXIMUM", MIN(blocks) "MINIMUM", AVG(blocks) "AVERAGE", SUM(blocks) "TOTAL" FROM DBA_FREE_SPACE GROUP BY TABLESPACE_NAME, FILE_ID; TABLESPACE ---------RBS SYSTEM TEMP TESTTBS USERS FILE_ID PIECES ------- -----2 1 1 1 4 1 5 5 3 1 MAXIMUM ------955 119 6399 6364 363 MINIMUM AVERAGE ------- ------955 955 119 119 6399 6399 3 1278 363 363 TOTAL -----955 119 6399 6390 363 PIECES shows the number of free space extents in the tablespace file, MAXIMUM and MINIMUM show the largest and smallest contiguous area of space in database blocks, AVERAGE shows the average size in blocks of a free space extent, and TOTAL shows the amount of free space in each tablespace file in blocks. This query is useful when you are going to create a new object or you know that a segment is about to extend, and you want to make sure that there is enough space in the containing tablespace. 11-52 Oracle9i Database Administrator’s Guide 12 Managing Datafiles This chapter describes the various aspects of datafile management, and contains the following topics: ■ Guidelines for Managing Datafiles ■ Creating Datafiles and Adding Datafiles to a Tablespace ■ Changing a Datafile’s Size ■ Altering Datafile Availability ■ Renaming and Relocating Datafiles ■ Dropping Datafiles ■ Verifying Data Blocks in Datafiles ■ Mapping Files to Physical Devices ■ Viewing Datafile Information See Also: Chapter 3, "Using Oracle-Managed Files" for information about creating datafiles and tempfiles that are both created and managed by the Oracle database server Managing Datafiles 12-1 Guidelines for Managing Datafiles Guidelines for Managing Datafiles Datafiles are physical files of the operating system that store the data of all logical structures in the database. They must be explicitly created for each tablespace. Oracle assigns each datafile two associated file numbers, an absolute file number and a relative file number, that are used to uniquely identify it. These numbers are described in the following table: Type of File Number Description Absolute Uniquely identifies a datafile in the database. In earlier releases of Oracle, the absolute file number may have been referred to as simply, the "file number." Relative Uniquely identifies a datafile within a tablespace. For small and medium size databases, relative file numbers usually have the same value as the absolute file number. However, when the number of datafiles in a database exceeds a threshold (typically 1023), the relative file number differs from the absolute file number. File numbers are displayed in many data dictionary views. You can optionally use file numbers instead of file names to identify datafiles or tempfiles in SQL statements. When using a file number, specify the file number that is displayed in the FILE# column of the V$DATAFILE or V$TEMPFILE view. This file number is also displayed in the FILE_ID column of the DBA_DATA_FILES or DBA_TEMP_ FILES view. This section describes aspects of managing datafiles, and contains the following topics: ■ Determine the Number of Datafiles ■ Determine the Size of Datafiles ■ Place Datafiles Appropriately ■ Store Datafiles Separate from Redo Log Files Determine the Number of Datafiles At least one datafile is required for the SYSTEM tablespace of a database. A small system might have a single datafile. The following are some guidelines to consider when determining the number of datafiles for your database. 12-2 Oracle9i Database Administrator’s Guide Guidelines for Managing Datafiles Determine the Value of the DB_FILES Initialization Parameter When starting an Oracle instance, the DB_FILES initialization parameter indicates the amount of SGA space to reserve for datafile information and thus, the maximum number of datafiles that can be created for the instance. This limit applies for the life of the instance. You can change the value of DB_FILES (by changing the initialization parameter setting), but the new value does not take effect until you shut down and restart the instance. Note: The default value of DB_FILES is operating system specific. When determining a value for DB_FILES, take the following into consideration: ■ ■ If the value of DB_FILES is too low, you cannot add datafiles beyond the DB_ FILES limit without first shutting down the database. If the value of DB_FILES is too high, memory is unnecessarily consumed. Limitations When Adding Datafiles to a Tablespace You can add datafiles to tablespaces, subject to the following limitations: ■ ■ ■ ■ ■ Operating systems often impose a limit on the number of files a process can open simultaneously. More datafiles cannot be created when the operating system limit of open files is reached. Operating systems impose limits on the number and size of datafiles. Oracle imposes a maximum limit on the number of datafiles for any Oracle database opened by any instance. This limit is operating system specific. You cannot exceed the number of datafiles specified by the DB_FILES initialization parameter. When you issue CREATE DATABASE or CREATE CONTROLFILE statements, the MAXDATAFILES parameter specifies an initial size of the datafile portion of the control file. However, if you attempt to add a new file whose number is greater than MAXDATAFILES, but less than or equal to DB_FILES, the control file will expand automatically so that the datafiles section can accommodate more files. Consider the Performance Impact The number of datafiles comprising a tablespace, and ultimately the database, can have an impact upon performance. Managing Datafiles 12-3 Guidelines for Managing Datafiles Oracle allows more datafiles in the database than the operating system defined limit. Oracle’s DBWn processes can open all online datafiles. Oracle is capable of treating open file descriptors as a cache, automatically closing files when the number of open file descriptors reaches the operating system-defined limit. This can have a negative performance impact. When possible, adjust the operating system limit on open file descriptors so that it is larger than the number of online datafiles in the database. See Also: ■ ■ Your operating system specific Oracle documentation for more information on operating system limits Oracle9i SQL Reference for more information about the MAXDATAFILES parameter of the CREATE DATABASE or CREATE CONTROLFILE statement Determine the Size of Datafiles The first datafile (in the original SYSTEM tablespace) must be at least 150M to contain the initial data dictionary and rollback segment. If you install other Oracle products, they may require additional space in the SYSTEM tablespace. See the installation instructions for these products for information about their space requirements. Place Datafiles Appropriately Tablespace location is determined by the physical location of the datafiles that constitute that tablespace. Use the hardware resources of your computer appropriately. For example, if several disk drives are available to store the database, consider placing potentially contending datafiles on separate disks.This way, when users query information, both disk drives can work simultaneously, retrieving data at the same time. Store Datafiles Separate from Redo Log Files Datafiles should not be stored on the same disk drive that stores the database’s redo log files. If the datafiles and redo log files are stored on the same disk drive and that disk drive fails, the files cannot be used in your database recovery procedures. If you multiplex your redo log files, then the likelihood of losing all of your redo log files is low, so you can store datafiles on the same drive as some redo log files. 12-4 Oracle9i Database Administrator’s Guide Creating Datafiles and Adding Datafiles to a Tablespace Creating Datafiles and Adding Datafiles to a Tablespace When creating a tablespace, you should estimate the potential size of database objects and create sufficient datafiles. Later, if needed, you can create additional datafiles and add them to a tablespace to increase the total amount of disk space allocated to it, and consequently the database. Preferably, place datafiles on multiple devices, so as to ensure that data is spread evenly across all devices. You can create datafiles and associate them with a tablespace using any of the statements listed in the following table. In all cases, you can either specify the file specifications for the datafiles being created, or you can use the Oracle Managed Files feature to create files that are created and managed by the database server. The table includes a brief description of the statement, as used to create datafiles, and references the section of this book where use of the statement is most completely described: SQL Statement Description For more information... CREATE TABLESPACE Creates a tablespace and the datafiles that comprise it "Creating Tablespaces" on page 11-3 CREATE TEMPORARY TABLESPACE Creates a locally-managed temporary tablespace and the tempfiles (tempfiles are a special kind of datafile) that comprise it "Creating a Locally Managed Temporary Tablespace" on page 11-13 ALTER TABLESPACE ... ADD DATAFILE Creates and adds a datafile to a tablespace "Altering a Dictionary-Managed Tablespace" on page 11-11 ALTER TABLESPACE ... ADD TEMPFILE Creates and adds a tempfile to a temporary tablespace "Creating a Locally Managed Temporary Tablespace" on page 11-13 CREATE DATABASE Creates a database and associated datafiles "Manually Creating an Oracle Database" on page 2-14 ALTER DATABASE ... CREATE DATAFILE Creates a new empty datafile in place of an old one--useful to re-create a datafile that was lost with no backup. Not discussed in this book. See Oracle9i User-Managed Backup and Recovery Guide. If you add new datafiles to a tablespace and do not fully specify the filenames, Oracle creates the datafiles in the default database directory or the current Managing Datafiles 12-5 Changing a Datafile’s Size directory, depending upon your operating system. Oracle recommends you always specify a fully qualified name for a datafile. Unless you want to reuse existing files, make sure the new filenames do not conflict with other files. Old files that have been previously dropped will be overwritten. If a statement that creates a datafile fails, Oracle removes any created operating system files. However, because of the large number of potential errors that can occur with file systems and storage subsystems, there can be situations where you must manually remove the files using operating system commands. Changing a Datafile’s Size This section describes the various ways to alter the size of a datafile, and contains the following topics: ■ Enabling and Disabling Automatic Extension for a Datafile ■ Manually Resizing a Datafile Enabling and Disabling Automatic Extension for a Datafile You can create datafiles or alter existing datafiles so that they automatically increase in size when more space is needed in the database. The files increase in specified increments up to a specified maximum. Setting your datafiles to extend automatically provides these advantages: ■ ■ Reduces the need for immediate intervention when a tablespace runs out of space Ensures applications will not halt because of failures to allocate extents To determine whether a datafile is auto-extensible, query the DBA_DATA_FILES view and examine the AUTOEXTENSIBLE column. You can specify automatic file extension by specifying an AUTOEXTEND ON clause when you create datafiles using the following SQL statements: ■ CREATE DATABASE ■ CREATE TABLESPACE ■ ALTER TABLESPACE You can enable or disable automatic file extension for existing datafiles, or manually resize a datafile using the ALTER DATABASE statement. 12-6 Oracle9i Database Administrator’s Guide Changing a Datafile’s Size The following example enables automatic extension for a datafile added to the users tablespace: ALTER TABLESPACE users ADD DATAFILE '/u02/oracle/rbdb1/users03.dbf' SIZE 10M AUTOEXTEND ON NEXT 512K MAXSIZE 250M; The value of NEXT is the minimum size of the increments added to the file when it extends. The value of MAXSIZE is the maximum size to which the file can automatically extend. The next example disables the automatic extension for the datafile. ALTER DATABASE DATAFILE '/u02/oracle/rbdb1/users03.dbf' AUTOEXTEND OFF; See Also: Oracle9i SQL Reference for more information about the SQL statements for creating or altering datafiles Manually Resizing a Datafile You can manually increase or decrease the size of a datafile using the ALTER DATABASE statement. Because you can change the sizes of datafiles, you can add more space to your database without adding more datafiles. This is beneficial if you are concerned about reaching the maximum number of datafiles allowed in your database. Manually reducing the sizes of datafiles enables you to reclaim unused space in the database. This is useful for correcting errors in estimates of space requirements. In the next example, assume that the datafile /u02/oracle/rbdb1/stuff01.dbf has extended up to 250M. However, because its tablespace now stores smaller objects, the datafile can be reduced in size. The following statement decreases the size of datafile /u02/oracle/rbdb1/stuff01.dbf: ALTER DATABASE DATAFILE '/u02/oracle/rbdb1/stuff01.dbf' RESIZE 100M; Note: It is not always possible to decrease the size of a file to a specific value. Managing Datafiles 12-7 Altering Datafile Availability Altering Datafile Availability You can take individual datafiles or tempfiles of a tablespace offline or similarly, bring them online. Offline datafiles are unavailable to the database and cannot be accessed until they are brought back online.You also have the option of taking all datafiles or tempfiles comprising a tablespace offline or online simply by specifying the name of a tablespace. One example of where you might be required to alter the availability of a datafile is when Oracle has problems writing to a datafile and automatically takes the datafile offline. Later, after resolving the problem, you can bring the datafile back online manually. The files of a read-only tablespace can independently be taken offline or brought online just as for read-write tablespaces. Bringing a datafile online in a read-only tablespace makes the file readable. No one can write to the file unless its associated tablespace is returned to the read-write state. To take a datafile offline, or bring it online, you must have the ALTER DATABASE system privilege. To take all datafiles or tempfiles offline using the ALTER TABLESPACE statement, you must have the ALTER TABLESPACE or MANAGE TABLESPACE system privilege. In an Oracle Real Application Clusters environment, the database must be open in exclusive mode. This section describes ways to alter datafile availability, and contains the following topics: ■ Bringing Datafiles Online or Taking Offline in ARCHIVELOG Mode ■ Taking Datafiles Offline in NOARCHIVELOG Mode ■ Altering the Availability of All Datafiles or Tempfiles in a Tablespace Note: You can make all datafiles in any tablespace, except the files in the SYSTEM tablespace, temporarily unavailable by taking the tablespace offline. You must leave these files in the tablespace to bring the tablespace back online. For more information about taking a tablespace offline, see "Taking Tablespaces Offline" on page 11-21. 12-8 Oracle9i Database Administrator’s Guide Altering Datafile Availability Bringing Datafiles Online or Taking Offline in ARCHIVELOG Mode To bring an individual datafile online, issue the ALTER DATABASE statement and include the DATAFILE clause.The following statement brings the specified datafile online: ALTER DATABASE DATAFILE '/u02/oracle/rbdb1/stuff01.dbf' ONLINE; To take the same file offline, issue the following statement: ALTER DATABASE DATAFILE '/u02/oracle/rbdb1/stuff01.dbf' OFFLINE; Note: To use this form of the ALTER DATABASE statement, the database must be in ARCHIVELOG mode. This requirement prevents you from accidentally losing the datafile, since taking the datafile offline while in NOARCHIVELOG mode is likely to result in losing the file. Taking Datafiles Offline in NOARCHIVELOG Mode To take a datafile offline when the database is in NOARCHIVELOG mode, use the ALTER DATABASE statement with both the DATAFILE and OFFLINE DROP clauses. This enables you to take the datafile offline and drop it immediately. It is useful, for example, if the datafile contains only data from temporary segments and has not been backed up and the database is in NOARCHIVELOG mode. The following statement takes the specified datafile offline: ALTER DATABASE DATAFILE '/u02/oracle/rbdb1/users03.dbf' OFFLINE DROP; Altering the Availability of All Datafiles or Tempfiles in a Tablespace Clauses of the ALTER TABLESPACE statement allow you to change the online or offline status of all of the datafiles or tempfiles within a tablespace. Specifically, the statements that affect online/offline status are: ■ ALTER TABLESPACE ... DATAFILE {ONLINE|OFFLINE} ■ ALTER TABLESPACE ... TEMPFILE {ONLINE|OFFLINE} You are required only to enter the tablespace name, not the individual datafiles or tempfiles. All of the datafiles or tempfiles are affected, but the online/offline status of the tablespace itself is not changed. Managing Datafiles 12-9 Renaming and Relocating Datafiles In most cases the above ALTER TABLESPACE statements can be issued whenever the database is mounted, even if it is not open. However, the database must not be open if the tablespace is the system tablespace, an undo tablespace, or the default temporary tablespace. The ALTER DATABASE DATAFILE and ALTER DATABASE TEMPFILE statements also have ONLINE/OFFLINE clauses, however in those statements you must enter all of the filenames for the tablespace. The syntax is different from the ALTER TABLESPACE ... ONLINE|OFFLINE statement that alters a tablespace’s availability, because that is a different operation. The ALTER TABLESPACE statement takes datafiles offline as well as the tablespace, but it cannot be used to alter the status of a temporary tablespace or its tempfile(s). Renaming and Relocating Datafiles You can rename datafiles to either change their names or relocate them. Some options, and procedures which you can follow, are described in the following sections: ■ Renaming and Relocating Datafiles for a Single Tablespace For example, renaming filename1 and filename2 in tablespace1, while the rest of the database is open. ■ Renaming and Relocating Datafiles for Multiple Tablespaces For example, renaming filename1 in tablespace1 and filename2 in tablespace2, while the database is mounted but closed. Note: To rename or relocate datafiles of the SYSTEM tablespace, you must use the second option, because you cannot take the SYSTEM tablespace offline. When you rename and relocate datafiles with these procedures, only the pointers to the datafiles, as recorded in the database’s control file, are changed. The procedures do not physically rename any operating system files, nor do they copy files at the operating system level. Renaming and relocating datafiles involves several steps. Read the steps and examples carefully before performing these procedures. 12-10 Oracle9i Database Administrator’s Guide Renaming and Relocating Datafiles Renaming and Relocating Datafiles for a Single Tablespace The section offers some procedures for renaming and relocating datafiles in a single tablespace. You must have the ALTER TABLESPACE system privilege to rename datafiles of a single tablespace. Renaming Datafiles in a Single Tablespace To rename datafiles from a single tablespace, complete the following steps: 1. Take the non-SYSTEM tablespace that contains the datafiles offline. For example: ALTER TABLESPACE users OFFLINE NORMAL; 2. Rename the datafiles using the operating system. 3. Use the ALTER TABLESPACE statement with the RENAME DATAFILE clause to change the filenames within the database. For example, the following statement renames the datafiles /u02/oracle/rbdb1/user1.dbf and /u02/oracle/rbdb1/user2.dbf to/u02/oracle/rbdb1/users01.dbf and /u02/oracle/rbdb1/users02.dbf, respectively: ALTER TABLESPACE users RENAME DATAFILE '/u02/oracle/rbdb1/user1.dbf', '/u02/oracle/rbdb1/user2.dbf' TO '/u02/oracle/rbdb1/users01.dbf', '/u02/oracle/rbdb1/users02.dbf'; The new files must already exist; this statement does not create the files. Also, always provide complete filenames (including their paths) to properly identify the old and new datafiles. In particular, specify the old datafile name exactly as it appears in the DBA_DATA_FILES view of the data dictionary. 4. Back up the database. After making any structural changes to a database, always perform an immediate and complete backup. Relocating and Renaming Datafiles in a Single Tablespace Here is an example that illustrates the steps involved for relocating a datafile. Assume the following conditions: ■ An open database has a tablespace named users that is made up of datafiles all located on the same disk. Managing Datafiles 12-11 Renaming and Relocating Datafiles ■ The datafiles of the users tablespace are to be relocated to different and separate disk drives. ■ You are currently connected with administrator privileges to the open database. ■ You have a current backup of the database. Complete the following steps: 1. Identify the datafile names of interest. The following query of the data dictionary view DBA_DATA_FILES lists the datafile names and respective sizes (in bytes) of the users tablespace: SELECT FILE_NAME, BYTES FROM DBA_DATA_FILES WHERE TABLESPACE_NAME = 'USERS'; FILE_NAME -----------------------------------------/U02/ORACLE/RBDB1/USERS01.DBF /U02/ORACLE/RBDB1/USERS02.DBF BYTES ---------------102400000 102400000 2. Take the tablespace containing the datafiles offline, or shut down the database and restart and mount it, leaving it closed. Either option closes the datafiles of the tablespace. 3. Copy the datafiles to their new locations and rename them using the operating system. Note: You can execute an operating system command to copy a file by using the SQL*Plus HOST command. 4. Rename the datafiles within Oracle. The datafile pointers for the files that make up the users tablespace, recorded in the control file of the associated database, must now be changed from the old names to the new names. If the tablespace is offline but the database is open, use the ALTER TABLESPACE ... RENAME DATAFILE statement. If the database is mounted but closed, use the ALTER DATABASE ... RENAME FILE statement. ALTER TABLESPACE users RENAME DATAFILE '/u02/oracle/rbdb1/users01.dbf', '/u02/oracle/rbdb1/users02.dbf' TO '/u03/oracle/rbdb1/users01.dbf', 12-12 Oracle9i Database Administrator’s Guide Renaming and Relocating Datafiles '/u04/oracle/rbdb1/users02.dbf'; 5. Bring the tablespace online, or open the database. If the users tablespace is offline and the database is open, bring the tablespace back online. If the database is mounted but closed, open the database. 6. Back up the database. After making any structural changes to a database, always perform an immediate and complete backup. Renaming and Relocating Datafiles for Multiple Tablespaces You can rename and relocate datafiles of one or more tablespaces using ALTER DATABASE statement with the RENAME FILE clause. This option is the only choice if you want to rename or relocate datafiles of several tablespaces in one operation, or rename or relocate datafiles of the SYSTEM tablespace. If the database must remain open, consider instead the procedure outlined in the previous section. To rename datafiles of several tablespaces in one operation or to rename datafiles of the SYSTEM tablespace, you must have the ALTER DATABASE system privilege. To rename datafiles in multiple tablespaces, follow these steps. 1. Ensure that the database is mounted but closed. 2. Copy the datafiles to be renamed to their new locations and new names, using the operating system. 3. Use ALTER DATABASE to rename the file pointers in the database’s control file. For example, the following statement renames the datafiles/u02/oracle/rbdb1/sort01.dbf and /u02/oracle/rbdb1/user3.dbf to /u02/oracle/rbdb1/temp01.dbf and /u02/oracle/rbdb1/users03.dbf, respectively: ALTER DATABASE RENAME FILE '/u02/oracle/rbdb1/sort01.dbf', '/u02/oracle/rbdb1/user3.dbf' TO '/u02/oracle/rbdb1/temp01.dbf', '/u02/oracle/rbdb1/users03.dbf; The new files must already exist; this statement does not create the files. Also, always provide complete filenames (including their paths) to properly identify the old and new datafiles. In particular, specify the old datafile name exactly as it appears in the DBA_DATA_FILES view of the data dictionary. 4. Back up the database. After making any structural changes to a database, always perform an immediate and complete backup. Managing Datafiles 12-13 Dropping Datafiles Dropping Datafiles There is no SQL statement that specifically drops a datafile. The only means of dropping a datafile is to drop the tablespace that contains the datafile. For example, if you want to remove a datafile from a tablespace, you could do the following: 1. Create a new tablespace 2. Move the data from the old tablespace to the new one 3. Drop the old tablespace You can, however, drop a tempfile using the ALTER DATABASE statement. For example: ALTER DATABASE TEMPFILE '/u02/oracle/data/lmtemp02.dbf' DROP INCLUDING DATAFILES; See Also: Dropping Tablespaces on page 11-29 Verifying Data Blocks in Datafiles If you want to configure Oracle to use checksums to verify data blocks, set the initialization parameter DB_BLOCK_CHECKSUM to TRUE. The value of this parameter can be changed dynamically, or set in the initialization parameter file. The default value of DB_BLOCK_CHECKSUM is FALSE. Regardless of the setting of this parameter, checksums are always used to verify data blocks in the system tablespace. When you enable block checking, Oracle computes a checksum for each block written to disk. Checksums are computed for all data blocks, including temporary blocks. The DBWn process calculates the checksum for each block and stores it in the block’s header. Checksums are also computed by the direct loader. The next time Oracle reads a data block, it uses the checksum to detect corruption in the block. If a corruption is detected, Oracle returns message ORA-01578 and writes information about the corruption to a trace file. Caution: Setting DB_BLOCK_CHECKSUM to TRUE can cause performance overhead. Set this parameter to TRUE only under the advice of Oracle Support personnel to diagnose data corruption problems. 12-14 Oracle9i Database Administrator’s Guide Mapping Files to Physical Devices See Also: Oracle9i Database Reference for information about checksums and the DB_BLOCK_CHECKSUM initialization parameter Mapping Files to Physical Devices In an environment where datafiles are simply file system files or are created directly on a raw device, it is relatively straight forward to see the association between a tablespace and the underlying device. Oracle provides views, such as DBA_ TABLESPACES, DBA_DATA_FILES, and V$DATAFILE, that provide a mapping of files onto devices. These mappings, along with device statistics can be used to evaluate I/O performance. However, with the introduction of host based Logical Volume Managers (LVM), and sophisticated storage subsystems that provide RAID (Redundant Array of Independent Disks) features, it is not easy to determine file to device mapping. This poses a problem because it becomes difficult to determine your "hottest" files when they are hidden behind a "black box". This section presents Oracle’s approach to resolving this problem. The following topics are contained in this section: ■ Overview of Oracle’s File Mapping Interface ■ How Oracle’s File Mapping Interface Works ■ Using Oracle’s File Mapping Interface ■ File Mapping Examples Note: This section presents an overview of Oracle’s file mapping interface and explains how to use the DBMS_STORAGE_MAP package and dynamic performance views to expose the mapping of files onto physical devices. You can more easily access this functionality through the Oracle Enterprise Manager (OEM). It provides an easy to use graphical interface for mapping files to physical devices. See the Oracle Enterprise Manager documentation set for more information. Managing Datafiles 12-15 Mapping Files to Physical Devices Overview of Oracle’s File Mapping Interface To acquire an understanding of I/O performance, one must have detailed knowledge of the storage hierarchy in which files reside. Oracle provides a mechanism to show a complete mapping of a file to intermediate layers of logical volumes to actual physical devices. This is accomplished though a set of dynamic performance views (V$ views). Using these views, you can locate the exact disk on which any block of a file resides. To build these views, storage vendors must provide mapping libraries that are responsible for mapping their particular I/O stack elements. Oracle communicates with these libraries through an external non-Oracle process that is spawned by an Oracle background process called FMON. FMON is responsible for managing the mapping information. Oracle provides a PL/SQL package, DBMS_STORAGE_MAP, that you use to invoke mapping operations that populate the mapping views. How Oracle’s File Mapping Interface Works This section describes the components of Oracle’s file mapping interface and how the interface works. It contains the following topics: ■ Components of File Mapping ■ Mapping Structures ■ Example of Mapping Structures ■ Configuration ID Components of File Mapping The following figure shows the components of the file mapping mechanism. 12-16 Oracle9i Database Administrator’s Guide Mapping Files to Physical Devices Figure 12–1 Components of File Mapping mapping lib0 Oracle Instance SGA FMON FMPUTL mapping lib1 External Process . . . mapping libn The following sections briefly describes these components and how they work together to populate the mapping views: ■ FMON ■ External Process (FMPUTL) ■ Mapping Libraries FMON FMON is a background process started by Oracle whenever the FILE_ MAPPING initialization parameter is set to TRUE. FMON is responsible for: ■ Building mapping information, which is stored in the SGA. This information is composed of the following structures: – Files – File system extents – Elements – Subelements These structures are explained in "Mapping Structures" on page 12-18. ■ ■ Refreshing mapping information when a change occurs because of: – Changes to Oracle datafiles (size) – Addition or deletion of datafiles – Changes to the storage configuration (not frequent) Saving mapping information in the data dictionary to maintain a view of the information that is persistent across startup and shutdown operations Managing Datafiles 12-17 Mapping Files to Physical Devices ■ Restoring mapping information into the SGA at instance startup. This avoids the need for a potentially expensive complete rebuild of the mapping information on every instance startup. You help control this mapping using procedures that are invoked with the DBMS_ STORAGE_MAP package. External Process (FMPUTL) FMON spawns an external non-Oracle process called FMPUTL, that communicates directly with the vendor supplied mapping libraries. This process obtains the mapping information through all levels of the I/O stack, assuming that mapping libraries exist for all levels. On some platforms the external process requires that the SETUID bit is set to ON because root privileges are needed to map through all levels of the I/O mapping stack. The external process is responsible for discovering the mapping libraries and dynamically loading them into its address space. Mapping Libraries Oracle uses mapping libraries to discover mapping information for the elements that are owned by a particular mapping library. Through these mapping libraries information about individual I/O stack elements is communicated. This information is used to populate dynamic performance views that can be queried by users. Mapping libraries need to exist for all levels of the stack for the mapping to be complete, and different libraries may own their own parts of the I/O mapping stack. For example, a VERITAS VxVM library would own the stack elements related to the VERITAS Volume Manager, and an EMC library would own all EMC storage specific layers of the I/O mapping stack. Mapping libraries are vendor supplied. However, Oracle currently supplies a mapping library for EMC storage. The mapping libraries available to a database server are identified in a special file named filemap.ora. Mapping Structures The mapping structures and Oracle’s representation of these structures are described in this section. You will need to understand this information in order to interpret the information in the mapping views. The following are the primary structures that compose the mapping information: ■ Files A file mapping structure provides a set of attributes for a file, including file size, number of file system extents that the file is composed of, and the file type. 12-18 Oracle9i Database Administrator’s Guide Mapping Files to Physical Devices ■ File system extents A file system extent mapping structure describes a contiguous chunk of blocks residing on one element. This includes the device offset, the extent size, the file offset, the type (data or parity), and the name of the element where the extent resides. Note: File system extents are not the same as Oracle extents. File system extents are physical contiguous blocks of data written to a device as managed by the file system. Oracle extents are logical structures managed by Oracle, such as tablespace extents. ■ Elements An element mapping structure is the abstract mapping structure that describes a storage component within the I/O stack. Elements may be mirrors, stripes, partitions, RAID5, concatenated elements, and disks. These structures are the mapping building blocks. ■ Subelements A subelement mapping structure describes the link between an element and the next elements in the I/O mapping stack. This structure contains the subelement number, size, the element name where the subelement exists, and the element offset. All of these mapping structures are illustrated in the following example. Example of Mapping Structures Consider an Oracle database which is composed of two data files X and Y. Both files X and Y reside on a file system mounted on volume A. File X is composed of two extents while file Y is composed of only one extent. Element A is striped over two elements B and C. Element B is a partition of element D and element C is mirrored over elements E and F. Note that elements D, E, and F are physical disks. Subelement B0 connects the parent element A to element B, subelement C1 connects A to C, .... All of the mapping structures are illustrated in Figure 12–2. Managing Datafiles 12-19 Mapping Files to Physical Devices Figure 12–2 Illustration of Mapping Structures File X File Extent 1 File Extent 2 File Extent 1 File Y Element A Sub B0 Sub C1 Element B Element C Sub D0 Element D Sub E0 Element E Sub F1 Element F Note that the mapping structures represented are sufficient to describe the entire mapping information for the Oracle instance and consequently to map every logical block within the file into a (element name, element offset) tuple (or more in case of mirroring) at each level within the I/O stack. Configuration ID The configuration ID captures the version information associated with elements or files. The vendor library provides the configuration ID and updates it whenever a change occurs. Without a configuration ID, there is no way for Oracle to tell whether the mapping has changed. There are two kinds of configuration IDs: ■ Persistent These configuration IDs are persistent across instance shutdown 12-20 Oracle9i Database Administrator’s Guide Mapping Files to Physical Devices ■ Non-persistent The configuration IDs are not persistent across instance shutdown. Oracle is only capable of refreshing the mapping information while the instance is up. Using Oracle’s File Mapping Interface This section discusses how to use Oracle’s file mapping interface. It contains the following topics: ■ Enabling File Mapping ■ Using the DBMS_STORAGE_MAP Package ■ Obtaining Information from the File Mapping Views Enabling File Mapping The following steps enable the file mapping feature: 1. Ensure that a valid filemap.ora file exists in the $ORACLE_ HOME/rdbms/filemap/etc directory. Caution: While the format and content of the filemap.ora file is discussed here, it is for informational reasons only. The filemap.ora file is created by Oracle when your system is installed. Until such time that vendors supply there own libraries, there will be only one entry in the filemap.ora file, and that is the Oracle supplied EMC library. This file should be modified manually by uncommenting this entry only if an EMC Symmetrix array is available. The filemap.ora file is the configuration file that describes all of the available mapping libraries. FMON requires that a filemap.ora file exists and that it points to a valid path to mapping libraries. Otherwise, it will not start successfully. The following row needs to be included for each library : lib=vendor_name:mapping_library_path where: – vendor_name should be Oracle for the EMC Symmetric library – mapping_library_path is the full path of the mapping library Managing Datafiles 12-21 Mapping Files to Physical Devices Note that the ordering of the libraries in this file is extremely important. The libraries are queried based on their order in the configuration file. The file mapping service can be even started even if no mapping libraries are available. The filemap.ora file still needs to be present even though it is empty. In this case, the mapping service is constrained in the sense that new mapping information cannot be discovered. Only restore and drop operations are allowed in such a configuration. 2. Set the FILE_MAPPING initialization parameter to TRUE. FILE_MAPPING=TRUE The instance does not have to be shut down to set this parameter. It can be set using an ALTER SYSTEM statement. 3. Invoke the appropriate DBMS_STORAGE_MAP mapping procedure. You have two options: ■ ■ In a cold startup scenario, the Oracle database is just started and no mapping operation has been invoked yet. You execute the DBMS_ STORAGE_MAP.MAP_ALL procedure to build the mapping information for the entire I/O subsystem associated with the Oracle database. In a warm start scenario where the mapping information is already built, you have the option to invoke the DBMS_STORAGE_MAP.MAP_SAVE procedure to save the mapping information in the data dictionary. (Note that this procedure is invoked in DBMS_STORAGE_MAP.MAP_ALL() by default.) This forces all of the mapping information in the SGA to be flushed to disk. Once you restart the database, use DBMS_STORAGE_MAP.RESTORE() to restore the mapping information into the SGA. If needed, DBMS_STORAGE_ MAP.MAP_ALL() can be called to refresh the mapping information. Using the DBMS_STORAGE_MAP Package The DBMS_STORAGE_MAP package enables you control the mapping operations. The various procedures available to you are described in the following table. Procedure Use to: MAP_OBJECT Build the mapping information for the Oracle object identified by object name, owner, and type MAP_ELEMENT Build mapping information for the specified element 12-22 Oracle9i Database Administrator’s Guide Mapping Files to Physical Devices Procedure Use to: MAP_FILE Build mapping information for the specified filename MAP_ALL Build entire mapping information for all types of Oracle files (excluding archive logs) DROP_ELEMENT Drop the mapping information for a specified element DROP_FILE Drop the file mapping information for the specified filename DROP_ALL Drop all mapping information in the SGA for this instance SAVE Save into the data dictionary the required information needed to regenerate the entire mapping RESTORE Load the entire mapping information from the data dictionary into the shared memory of the instance LOCK_MAP Lock the mapping information in the SGA for this instance UNLOCK_MAP Unlock the mapping information in the SGA for this instance See Also: ■ ■ Oracle9i Supplied PL/SQL Packages and Types Reference for a description of the DBMS_STORAGE_MAP package "File Mapping Examples" on page 12-25 for an example of using the DBMS_STORAGE_MAP package Obtaining Information from the File Mapping Views Mapping information generated by DBMS_STORAGE_MAP package is captured in dynamic performance views. Brief descriptions of these views are presented here. View Description V$MAP_LIBRARY Contains a list of all mapping libraries that have been dynamically loaded by the external process V$MAP_FILE Contains a list of all file mapping structures in the shared memory of the instance V$MAP_FILE_EXTENT Contains a list of all file system extent mapping structures in the shared memory of the instance V$MAP_ELEMENT Contains a list of all element mapping structures in the SGA of the instance Managing Datafiles 12-23 Mapping Files to Physical Devices View Description V$MAP_EXT_ELEMENT Contains supplementary information for all element mapping V$MAP_SUBELEMENT Contains a list of all subelement mapping structures in the shared memory of the instance V$MAP_COMP_LIST Contains supplementary information for all element mapping structures. V$MAP_FILE_IO_STACK The hierarchical arrangement of storage containers for the file displayed as a series of rows. Each row represents a level in the hierarchy. See Also: Oracle9i Database Reference contains complete descriptions of the dynamic performance views However, the information generated by the DBMS_STORAGE_MAP.MAP_OBJECT procedure is captured in a global temporary table named MAP_OBJECT. This table displays the hierarchical arrangement of storage containers for objects. Each row in the table represents a level in the hierarchy. A description of the MAP_OBJECT table follows. Column Datatype OBJECT_NAME VARCHAR2(2000) Name of the object OBJECT_OWNER VARCHAR2(2000) Owner of the object OBJECT_TYPE VARCHAR2(2000) Object type FILE_MAP_IDX NUMBER File index (corresponds to FILE_MAP_IDX in V$MAP_FILE) DEPTH NUMBER Element depth within the I/O stack ELEM_IDX NUMBER Index corresponding to element CU_SIZE NUMBER Contiguous set of logical blocks of the file, in HKB units, that is resident contiguously on the element STRIDE NUMBER Number of HKB between contiguous units (CU) in the file that are contiguous on this element. Used in RAID5 and striped files. 12-24 Oracle9i Database Administrator’s Guide Description Mapping Files to Physical Devices Column Datatype Description NUM_CU NUMBER Number of contiguous units that are adjacent to each other on this element that are separated by STRIDE HKB in the file. In RAID5, the number of contiguous units also include the parity stripes. ELEM_OFFSET NUMBER Element offset in HKB units FILE_OFFSET NUMBER Offset in HKB units from the start of the file to the first byte of the contiguous units DATA_TYPE VARCHAR2(2000) Datatype (DATA, PARITY, or DATA AND PARITY) PARITY_POS NUMBER PARITY_PERIOD NUMBER Position of the parity. Only for RAID5. This field is needed to distinguish the parity from the data part. Parity period. Only for RAID5. File Mapping Examples The following examples illustrates some of the powerful capabilities of Oracle’s file mapping feature. This includes : ■ The ability to map all Oracle files that span a particular device ■ The ability to map a particular file into its corresponding devices ■ The ability to map a particular Oracle object, including its block distribution at all levels within the I/O stack Consider an Oracle instance which is composed of two datafiles: ■ t_db1.f ■ t_db2.f These files are created on a Solaris UFS file system mounted on a VERITAS VxVM host based striped volume, /dev/vx/dsk/ipfdg/ipf-vol1, that consists of the following host devices as externalized from an EMC Symmetrix array: ■ /dev/vx/rdmp/c2t1d0s2 ■ /dev/vx/rdmp/c2t1d1s2 Note that the following examples require the execution of a MAP_ALL()operation. Managing Datafiles 12-25 Mapping Files to Physical Devices Example 1: Map All Oracle Files that Span a Device The following query returns all Oracle files associated with the /dev/vx/rdmp/c2t1d1s2 host device: SELECT UNIQUE me.ELEM_NAME, mf.FILE_NAME FROM V$MAP_FILE_IO_STACK fs, V$MAP_FILE mf, V$MAP_ELEMENT me WHERE mf.FILE_MAP_IDX = fs.FILE_MAP_IDX AND me.ELEM_IDX = fs.ELEM_IDX AND me.ELEM_NAME = /dev/vx/rdmp/c2t1d1s2; The query results are: ELEM_NAME -----------------------/dev/vx/rdmp/c2t1d1s2 /dev/vx/rdmp/c2t1d1s2 FILE_NAME -------------------------------/oracle/dbs/t_db1.f /oracle/dbs/t_db2.f Example 2: Map a File into Its Corresponding Devices The following query displays a topological graph of the /oracle/dbs/t_db1.f datafile: WITH fv AS (SELECT FILE_MAP_IDX, FILE_NAME FROM V$MAP_FILE WHERE FILE_NAME = /oracle/dbs/t_db1.f) SELECT fv.FILE_NAME, LPAD(' ', 4 * (LEVEL - 1)) || el.ELEM_NAME ELEM_NAME FROM V$MAP_SUBELEMENT sb, V$MAP_ELEMENT el, fv, (SELECT UNIQUE ELEM_IDX FROM V$MAP_FILE_IO_STACK io, fv WHERE io.FILE_MAP_IDX = fv.FILE_MAP_IDX) fs WHERE el.ELEM_IDX = sb.CHILD_IDX AND fs.ELEM_IDX = el.ELEM_IDX START WITH sb.PARENT_IDX IN (SELECT DISTINCT ELEM_IDX FROM V$MAP_FILE_EXTENT fe, fv WHERE fv.FILE_MAP_IDX = fe.FILE_MAP_IDX) CONNECT BY PRIOR sb.CHILD_IDX = sb.PARENT_IDX; The resulting topological graph is: FILE_NAME ----------------------/oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f 12-26 Oracle9i Database Administrator’s Guide ELEM_NAME ------------------------------------------------_sym_plex_/dev/vx/rdsk/ipfdg/ipf-vol1_-1_-1 _sym_subdisk_/dev/vx/rdsk/ipfdg/ipf-vol1_0_0_0 /dev/vx/rdmp/c2t1d0s2 _sym_symdev_000183600407_00C _sym_hyper_000183600407_00C_0 Mapping Files to Physical Devices /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f _sym_hyper_000183600407_00C_1 _sym_subdisk_/dev/vx/rdsk/ipfdg/ipf-vol1_0_1_0 /dev/vx/rdmp/c2t1d1s2 _sym_symdev_000183600407_00D _sym_hyper_000183600407_00D_0 _sym_hyper_000183600407_00D_1 Example 3: Map an Oracle Object This example displays the block distribution at all levels within the I/O stack for the scott.bonus table. A MAP_OBJECT() operation must first be executed as follows: EXECUTE DBMS_STORAGE_MAP.MAP_OBJECT('BONUS','SCOTT','TABLE'); The query is as follows: SELECT io.OBJECT_NAME o_name, io.OBJECT_OWNER o_owner, io.OBJECT_TYPE o_type, mf.FILE_NAME, me.ELEM_NAME, io.DEPTH, (SUM(io.CU_SIZE * (io.NUM_CU - DECODE(io.PARITY_PERIOD, 0, 0, TRUNC(io.NUM_CU / io.PARITY_PERIOD)))) / 2) o_size FROM MAP_OBJECT io, V$MAP_ELEMENT me, V$MAP_FILE mf WHERE io.OBJECT_NAME = 'BONUS' AND io.OBJECT_OWNER = 'SCOTT' AND io.OBJECT_TYPE = 'TABLE' AND me.ELEM_IDX = io.ELEM_IDX AND mf.FILE_MAP_IDX = io.FILE_MAP_IDX GROUP BY io.ELEM_IDX, io.FILE_MAP_IDX, me.ELEM_NAME, mf.FILE_NAME, io.DEPTH, io.OBJECT_NAME, io.OBJECT_OWNER, io.OBJECT_TYPE ORDER BY io.DEPTH; The following is the result of the query. Note that the o_size column is expressed in KB. O_NAME -----BONUS BONUS O_OWNER ------SCOTT SCOTT O_TYPE -----TABLE TABLE FILE_NAME ------------------/oracle/dbs/t_db1.f /oracle/dbs/t_db1.f BONUS SCOTT TABLE /oracle/dbs/t_db1.f BONUS SCOTT TABLE /oracle/dbs/t_db1.f BONUS SCOTT BONUS SCOTT BONUS SCOTT TABLE TABLE TABLE /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f ELEM_NAME DEPTH O_SIZE ----------------------------- ------ -----/dev/vx/dsk/ipfdg/ipf-vol1 0 20 _sym_plex_/dev/vx/rdsk/ipf 1 20 pdg/if-vol1_-1_-1 _sym_subdisk_/dev/vx/rdsk/ 2 12 ipfdg/ipf-vol1_0_1_0 _sym_subdisk_/dev/vx/rdsk/ipf 2 8 dg/ipf-vol1_0_2_0 /dev/vx/rdmp/c2t1d1s2 3 12 /dev/vx/rdmp/c2t1d2s2 3 8 _sym_symdev_000183600407_00D 4 12 Managing Datafiles 12-27 Viewing Datafile Information BONUS BONUS BONUS BONUS BONUS SCOTT SCOTT SCOTT SCOTT SCOTT TABLE TABLE TABLE TABLE TABLE /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f /oracle/dbs/t_db1.f _sym_symdev_000183600407_00E _sym_hyper_000183600407_00D_0 _sym_hyper_000183600407_00D_1 _sym_hyper_000183600407_00E_0 _sym_hyper_000183600407_00E_1 4 5 5 6 6 8 12 12 8 8 Viewing Datafile Information The following data dictionary views provide useful information about the datafiles of a database: View Description DBA_DATA_FILES Provides descriptive information about each datafile, including the tablespace to which it belongs and the file id. The file id can be used to join with other views for detail information. DBA_EXTENTS DBA view describes the extents comprising all segments in the database. Contains the file id of the datafile containing the extent. USER view describes extents of the segments belonging to objects owned by the current user. USER_EXTENTS DBA_FREE_SPACE USER_FREE_SPACE DBA view lists the free extents in all tablespaces. Includes the file id of the datafile containing the extent. USER view lists the free extents in the tablespaces accessible to the current user. V$DATAFILE Contains datafile information from the control file V$DATAFILE_HEADER Contains information from datafile headers This example illustrates the use of one of these views, V$DATAFILE. SELECT NAME, FILE#, STATUS, CHECKPOINT_CHANGE# "CHECKPOINT" FROM V$DATAFILE; NAME -------------------------------/u01/oracle/rbdb1/system01.dbf /u02/oracle/rbdb1/temp01.dbf /u02/oracle/rbdb1/users03.dbf FILE# ----1 2 3 STATUS ------SYSTEM ONLINE OFFLINE CHECKPOINT ---------3839 3782 3782 FILE# lists the file number of each datafile; the first datafile in the SYSTEM tablespace created with the database is always file 1. STATUS lists other information 12-28 Oracle9i Database Administrator’s Guide Viewing Datafile Information about a datafile. If a datafile is part of the SYSTEM tablespace, its status is SYSTEM (unless it requires recovery). If a datafile in a non-SYSTEM tablespace is online, its status is ONLINE. If a datafile in a non-SYSTEM tablespace is offline, its status can be either OFFLINE or RECOVER. CHECKPOINT lists the final SCN (system change number) written for a datafile’s most recent checkpoint. See Also: Oracle9i Database Reference for a complete descriptions of these views Managing Datafiles 12-29 Viewing Datafile Information 12-30 Oracle9i Database Administrator’s Guide 13 Managing Undo Space This chapter describes how to manage undo space, either by using undo tablespaces or by using rollback segments. It contains the following topics: ■ What is Undo? ■ Specifying the Mode for Undo Space Management ■ Managing Undo Tablespaces ■ Managing Rollback Segments See Also: ■ ■ Chapter 3, "Using Oracle-Managed Files" for information about creating an undo tablespace whose datafiles are both created and managed by the Oracle database server Oracle9i Real Application Clusters Administration for information about managing undo space in an Oracle Real Application Clusters environment. Managing Undo Space 13-1 What is Undo? What is Undo? Every Oracle database must have a method of maintaining information that is used to roll back, or undo, changes to the database. Such information consists of records of the actions of transactions, primarily before they are committed. Oracle refers to these records collectively as undo. Undo records are used to: ■ Roll back transactions when a ROLLBACK statement is issued ■ Recover the database ■ Provide read consistency When a rollback statement is issued, undo records are used to undo changes that were made to the database by the uncommitted transaction. During database recovery, undo records are used to undo any uncommitted changes applied from the redo log to the datafiles. Undo records provide read consistency by maintaining the before image of the data for users who are accessing the data at the same time that another user is changing it. Historically, Oracle has used rollback segments to store undo. Space management for these rollback segments has proven to be quite complex. Oracle now offers another method of storing undo that eliminates the complexities of managing rollback segment space, and enables DBAs to exert control over how long undo is retained before being overwritten. This method uses an undo tablespace. Both of these methods of managing undo space are discussed in this chapter. You cannot use both methods in the same database instance, although for migration purposes it is possible, for example, to create undo tablespaces in a database that is using rollback segments, or to drop rollback segments in a database that is using undo tablespaces. However, you must shut down and restart your database in order to effect the switch to another method of managing undo. Note: Oracle always uses a SYSTEM rollback segment for performing system transactions. There is only one SYSTEM rollback segment and it is created automatically at CREATE DATABASE time and is always brought online at instance startup. You are not required to perform any operations to manage the SYSTEM rollback segment. 13-2 Oracle9i Database Administrator’s Guide Specifying the Mode for Undo Space Management See Also: Oracle9i Database Concepts for more information about undo and managing undo space Specifying the Mode for Undo Space Management If you use the rollback segment method of managing undo space, you are said to be operating in the manual undo management mode. If you use the undo tablespace method, you are operating in the automatic undo management mode. You determine the mode at instance startup using the UNDO_MANAGEMENT initialization parameter. Starting an Instance in Automatic Undo Management Mode The following initialization parameter setting causes the STARTUP command to start an instance in automatic undo management mode: UNDO_MANAGEMENT = AUTO An undo tablespace must be available, into which Oracle will store undo records. The default undo tablespace is created at database creation, or an undo tablespace can be created explicitly. The methods of creating an undo tablespace are explained in "Creating an Undo Tablespace" on page 13-6 When the instance starts up, Oracle automatically selects for use the first available undo tablespace. If there is no undo tablespace available, the instance starts, but uses the SYSTEM rollback segment. This is not recommended in normal circumstances, and an alert message is written to the alert file to warn that the system is running without an undo tablespace. You can optionally specify at startup that you want an Oracle instance to use a specific undo tablespace. This is done by setting the UNDO_TABLESPACE initialization parameter. For example: UNDO_TABLESPACE = undotbs_01 In this case, if you have not already created the undo tablespace (in this example, undotbs_01), the STARTUP command will fail. The UNDO_TABLESPACE parameter can be used to assign a specific undo tablespace to an instance in an Oracle Real Application Clusters environment. The following is a summary of the initialization parameters for automatic undo management mode: Managing Undo Space 13-3 Specifying the Mode for Undo Space Management Initialization Parameter Description UNDO_MANAGEMENT If AUTO, use automatic undo management mode. If MANUAL, use manual undo management mode. UNDO_TABLESPACE A dynamic parameter specifying the name of an undo tablespace to use. UNDO_RETENTION A dynamic parameter specifying the length of time to retain undo. Default is 900 seconds. UNDO_SUPPRESS_ERRORS If TRUE, suppress error messages if manual undo management SQL statements are issued when operating in automatic undo management mode. If FALSE, issue error message. This is a dynamic parameter. If the initialization parameter file contains parameters relating to manual undo management, they are ignored. To learn how to manage undo tablespaces, see "Managing Undo Tablespaces" on page 13-5. See Also: Oracle9i Database Reference for complete descriptions of initialization parameters used in automatic undo management mode Starting an Instance in Manual Undo Management Mode The following initialization parameter setting causes the STARTUP command to start an instance in manual undo management mode: UNDO_MANAGEMENT = MANUAL If the UNDO_MANAGEMENT initialization parameter is not specified, the instance starts in manual undo management mode. If an UNDO_TABLESPACE initialization parameter is found, it is ignored. For DBAs who want to run their databases in manual undo management mode, their existing initialization parameter file can be used without any changes. When the instance starts up, it brings online a number of rollback segments as determined by either of the following: ■ ■ 13-4 The ROLLBACK_SEGMENTS initialization parameter The TRANSACTIONS and TRANSACTIONS_PER_ROLLBACK_SEGMENT initialization parameters Oracle9i Database Administrator’s Guide Managing Undo Tablespaces The following is a summary of initialization parameters that can be specified with manual undo management mode. Initialization Parameter Description ROLLBACK_SEGMENTS Specifies the rollback segments to be acquired at instance startup TRANSACTIONS Specifies the maximum number of concurrent transactions TRANSACTIONS_PER_ROLLBACK_SEGMENT Specifies the number of concurrent transactions that each rollback segment is expected to handle MAX_ROLLBACK_SEGMENTS Specifies the maximum number of rollback segments that can be online for any instance To learn how to manage rollback segments, see "Managing Rollback Segments" on page 13-13. See Also: Oracle9i Database Reference for complete descriptions of initialization parameters used in manual undo management mode Managing Undo Tablespaces Oracle strongly recommends operating in automatic undo management mode. The database server can manage undo more efficiently, and automatic undo management mode is less complex to implement and manage. The following sections guide you in the management of undo tablespaces: ■ Creating an Undo Tablespace ■ Altering an Undo Tablespace ■ Dropping an Undo Tablespace ■ Switching Undo Tablespaces ■ Establishing User Quotas for Undo Space ■ Specifying the Retention Period for Undo Information ■ Viewing Information About Undo Space See Also: Oracle9i SQL Reference for complete descriptions of the SQL statements discussed in the following sections Managing Undo Space 13-5 Managing Undo Tablespaces Creating an Undo Tablespace There are two methods of creating an undo tablespace. The first method creates the undo tablespace when the CREATE DATABASE statement is issued. This occurs when you are creating a new database, and the instance is started in automatic undo management mode (UNDO_MANAGEMENT = AUTO). The second method is used with an existing database. It uses the CREATE UNDO TABLESPACE statement. You cannot create database objects in an undo tablespace. It is reserved for system-managed undo data. Using CREATE DATABASE to Create an Undo Tablespace You can create a specific undo tablespace using the UNDO TABLESPACE clause of the CREATE DATABASE statement. But, this clause is not required. If the UNDO TABLESPACE clause is not specified and the CREATE DATABASE statement is executed in automatic undo management mode, a default undo tablespace is created with the name SYS_UNDOTBS. This tablespace is allocated from the default set of files used by the CREATE DATABASE statement and its attributes are determined by Oracle. The initial size is 10M, and it is autoextensible. This method of creating an undo tablespace is only recommended to users who do not have any specific requirements for allocation of undo space. The following statement illustrates using the UNDO TABLESPACE clause in a CREATE DATABASE statement. The undo tablespace is named undotbs_01 and one datafile, /u01/oracle/rbdb1/undo0101.dbf, is allocated for it. CREATE DATABASE rbdb1 CONTROLFILE REUSE . . . UNDO TABLESPACE undotbs_01 DATAFILE '/u01/oracle/rbdb1/undo0101.dbf'; If the undo tablespace cannot be created successfully during CREATE DATABASE, the entire CREATE DATABASE operation fails. You must clean up the database files, correct the error and retry the CREATE DATABASE operation. Using the CREATE UNDO TABLESPACE Statement The CREATE UNDO TABLESPACE statement is the same as the CREATE TABLESPACE statement, but the UNDO keyword is specified. Oracle determines most of the attributes of the undo tablespace, you can specify only the DATAFILE clause. 13-6 Oracle9i Database Administrator’s Guide Managing Undo Tablespaces This example creates the undotbs_02 undo tablespace: CREATE UNDO TABLESPACE undotbs_02 DATAFILE '/u01/oracle/rbdb1/undo0201.dbf' SIZE 2M REUSE AUTOEXTEND ON; Altering an Undo Tablespace Undo tablespaces are altered using the ALTER TABLESPACE statement. However, since most aspects of undo tablespaces are system managed, you need only be concerned with the following actions: ■ Adding a datafile ■ Renaming a datafile ■ Bringing a datafile online or taking it offline ■ Beginning or ending an open backup on a datafile These are also the only attributes you are permitted to alter. If an undo tablespace runs out of space, or you want to prevent it from doing so, you can add more files to it or resize existing datafiles. The following example adds another datafile to undo tablespace undotbs_01: ALTER TABLESPACE undotbs_01 ADD DATAFILE '/u01/oracle/rbdb1/undo0102.dbf' AUTOEXTEND ON NEXT 1M MAXSIZE UNLIMITED; You can use the ALTER DATABASE ... DATAFILE statement to resize or extend a datafile. See Also: "Changing a Datafile’s Size" on page 12-6 Dropping an Undo Tablespace Use the DROP TABLESPACE statement to drop an undo tablespace. The following example drops the undo tablespace undotbs_01: DROP TABLESPACE undotbs_01; An undo tablespace can only be dropped if it is not currently used by any instance. If the undo tablespace contains any outstanding transactions (for example, a transaction died but has not yet been recovered), the DROP TABLESPACE statement fails. However, since DROP TABLESPACE drops an undo tablespace even if it contains unexpired undo information (within retention period), you must be careful Managing Undo Space 13-7 Managing Undo Tablespaces not to drop an undo tablespace if undo information is needed by some existing queries. DROP TABLESPACE for undo tablespaces behaves like DROP TABLESPACE ... INCLUDING CONTENTS. All contents of the undo tablespace are removed. Switching Undo Tablespaces You can switch from using one undo tablespace to another. Because the UNDO_ TABLESPACE initialization parameter is a dynamic parameter, the ALTER SYSTEM SET statement can be used to assign a new undo tablespace. The following statement effectively switches to a new undo tablespace: ALTER SYSTEM SET UNDO_TABLESPACE = undotbs_02; Assuming undotbs_01 is the current undo tablespace, after this command successfully executes, the instance uses undotbs_02 in place of undotbs_01 as its undo tablespace. If any of the following conditions exist for the tablespace being switched to, an error is reported and no switching occurs: ■ The tablespace does not exist, ■ The tablespace is not an undo tablespace ■ The tablespace is already being used by another instance The database is online while the switch operation is performed, and user transactions can be executed while this command is being executed. When the switch operation completes successfully, all transactions started after the switch operation began are assigned to transaction tables in the new undo tablespace. The switch operation does not wait for transactions in the old undo tablespace to commit. If there are any pending transactions in the old undo tablespace, the old undo tablespace enters into a PENDING OFFLINE mode (status). In this mode, existing transactions can continue to execute, but undo records for new user transactions cannot be stored in this undo tablespace. An undo tablespace can exist in this PENDING OFFLINE mode, even after the switch operation completes successfully. A PENDING OFFLINE undo tablespace cannot used by another instance, nor can it be dropped. Eventually, after all active transactions have committed, the undo tablespace automatically goes from the PENDING OFFLINE mode to the OFFLINE mode. From then on, the undo 13-8 Oracle9i Database Administrator’s Guide Managing Undo Tablespaces tablespace is available for other instances (in an Oracle Real Application Cluster environment). If the parameter value for UNDO TABLESPACE is set to '' (two single quotes), the current undo tablespace will be switched out without switching in any other undo tablespace. This can be used, for example, to unassign an undo tablespace in the event that you want to revert to manual undo management mode. The following example unassigns the current undo tablespace: ALTER SYSTEM SET UNDO_TABLESPACE = ''; Establishing User Quotas for Undo Space Oracle’s Database Resource Manager can be used to establish user quotas for undo space. The Database Resource Manager directive, UNDO_POOL, allows DBAs to limit the amount of undo space consumed by a group of users (resource consumer group). You can specify an undo pool for each consumer group. An undo pool controls the amount of total undo that can be generated by a consumer group. When the total undo generated by a consumer group exceeds its undo limit, the current UPDATE transaction generating the redo is terminated. No other members of the consumer group can perform further updates until undo space is freed from the pool. When no UNDO_POOL directive is explicitly defined, users are allowed unlimited undo space. See Also: Chapter 27, "Using the Database Resource Manager" Specifying the Retention Period for Undo Information Committed undo information normally is lost when its undo space is overwritten by a newer transaction. But for consistent read purposes, long running queries might require old undo information for undoing changes and producing older images of data blocks. The initialization parameter, UNDO_RETENTION, provides a means of explicitly specifying the amount of undo information to retain. With a proper setting, long running queries can complete without risk of receiving the "snapshot too old" error. Setting the UNDO_RETENTION Initialization Parameter Retention is specified in units of seconds, for example 500 seconds. It is persistent and can survive system crashes. That is, undo generated before an instance crash, is retained until its retention time has expired even across restarting the instance. Managing Undo Space 13-9 Managing Undo Tablespaces When the instance is recovered, undo information will be retained based on the current setting of the UNDO_RETENTION initialization parameter. The UNDO_RETENTION parameter can be set initially in the initialization parameter file that is used by the STARTUP process: UNDO_RETENTION = 10 The UNDO_RETENTION parameter value can be changed dynamically at any time using the ALTER SYSTEM command: ALTER SYSTEM SET UNDO_RETENTION = 5; The effect of the UNDO_RETENTION parameter is immediate, but it can only be honored if the current undo tablespace has enough space for the active transactions. If an active transaction requires undo space and the undo tablespace does not have available space, the system starts reusing unexpired undo space. Such action can potentially cause some queries to fail with the "snapshot too old" error. If the UNDO_RETENTION initialization parameter is not specified, the default value is 900 seconds. Choosing the Retention Period for Flashback Queries The retention period for undo information is an important factor in the execution of flashback queries. Oracle’s flashback query feature enables you to see a consistent version of the database as of a specified time in the past. You can execute queries, or even applications, as of a previous time in the database. The Oracle supplied DBMS_ FLASHBACK package implements this functionality at the session level. At the object level, flashback queries use the AS OF clause of the SELECT statement to specify the previous point in time for which you wish to view data. The retention period determines how far back in time a database version can be established for flashback queries. Specifically, you must choose an undo retention interval that is long enough that it enables you to construct a snapshot of the database for the oldest version of the database that you are interested in. For example, if an application requires that a version of the database be available reflecting its content 12 hours previously, then UNDO_RETENTION must be set to 43200. When using automatic undo management, the RETENTION value for LOB columns is set to the value of UNDO_RETENTION. 13-10 Oracle9i Database Administrator’s Guide Managing Undo Tablespaces See Also: ■ ■ ■ Oracle9i Application Developer’s Guide - Fundamentals for information about using the flashback query feature Oracle9i Supplied PL/SQL Packages and Types Reference for a description of the DBMS_FLASHBACK package Oracle9i SQL Reference for a description of the AS OF clause of the SELECT statement Calculating the Space Requirements For Undo Retention Given a specific UNDO_RETENTION parameter setting and some system statistics, the amount of undo space required to satisfy the undo retention requirement can be estimated using the following formula: UndoSpace = UR * UPS + overhead where: ■ UndoSpace is the number of undo blocks ■ UR is UNDO_RETENTION in seconds ■ UPS is undo blocks for each second ■ overhead is the small overhead for metadata (transaction tables, bitmaps, and so forth) As an example, if UNDO_RETENTION is set to 2 hours, and the transaction rate (UPS) is 200 undo blocks for each second, with a 4K block size, the required undo space is computed as follows: (2 * 3600 * 200 * 4K) = 5.8GBs. Such computation can be performed by using information in the V$UNDOSTAT view. In the steady state, you can query the view to obtain the transaction rate. The overhead figure can also be obtained from the view. Viewing Information About Undo Space This section lists views that are useful for viewing information about undo space in the automatic undo management mode. In addition to views listed here, you can obtain information from the views available for viewing tablespace and datafile information. Managing Undo Space 13-11 Managing Undo Tablespaces See Also: ■ "Viewing Tablespace Information" on page 11-50 ■ "Viewing Datafile Information" on page 12-28 Undo Space Views The following views are available for obtaining undo space information: View Description V$UNDOSTAT Contains statistics for monitoring and tuning undo space. Use this view to help estimate the amount of undo space required for the current workload. Oracle also uses this information to help tune undo usage in the system. This view is available in both the automatic undo management and the manual undo management modes. V$ROLLSTAT For automatic undo management mode, information reflects behavior of the undo segments in the undo tablespace V$TRANSACTION Contains undo segment information DBA_UNDO_EXTENTS Shows the commit time for each extent in the undo tablespace. See Also: Oracle9i Database Reference for complete descriptions of the views used in automatic undo management mode Monitoring Undo Space The V$UNDOSTAT view is useful for monitoring the effects of transaction execution on undo space in the current instance. Statistics are available for undo space consumption, transaction concurrency, and length of queries in the instance. Each row in the view contains statistics collected in the instance for a ten-minute interval. The rows are in descending order by the BEGIN_TIME column value. Each row belongs to the time interval marked by (BEGIN_TIME, END_TIME). Each column represents the data collected for the particular statistic in that time interval. The first row of the view contains statistics for the (partial) current time period. The view contains a total of 1008 rows, spanning a 7 day cycle. The following example shows the results of a query on the V$UNDOSTAT view. SELECT BEGIN_TIME, END_TIME, UNDOTSN, UNDOBLKS, TXNCOUNT, MAXCONCURRENCY AS "MAXCON" 13-12 Oracle9i Database Administrator’s Guide Managing Rollback Segments FROM V$UNDOSTAT; The results are: BEGIN_TIME -------------------07/28/2000 18:26:28 07/28/2000 18:16:28 07/28/2000 14:36:28 07/28/2000 14:26:28 07/28/2000 14:16:28 ... END_TIME UNDOTSN UNDOBLKS TXNCOUNT MAXCON -------------------- ------- -------- -------- -----07/28/2000 18:32:13 2 709 55 2 07/28/2000 18:26:28 2 448 12 2 07/28/2000 18:16:28 1 0 0 0 07/28/2000 14:36:28 1 1 1 1 07/28/2000 14:26:28 1 10 1 1 The above example shows how undo space is consumed in the system for the previous 24 hours from the time 18:32:13. Managing Rollback Segments If you choose to use rollback segments to store undo, the following sections guide you in their management: ■ Guidelines for Managing Rollback Segments ■ Creating Rollback Segments ■ Altering Rollback Segments ■ Explicitly Assigning a Transaction to a Rollback Segment ■ Dropping Rollback Segments ■ Viewing Rollback Segment Information Note: The use of rollback segments for managing undo space will be deprecated in a future release. Oracle strongly recommends that you use automatic undo management and manage undo space using an UNDO_TABLESPACE. Guidelines for Managing Rollback Segments This section describes guidelines to consider before creating or managing the rollback segments of your databases, and contains the following topics: ■ Use Multiple Rollback Segments Managing Undo Space 13-13 Managing Rollback Segments ■ Choose Between Public and Private Rollback Segments ■ Specify Rollback Segments to Acquire Automatically ■ Approximate Rollback Segment Sizes ■ Create Rollback Segments with Many Equally Sized Extents ■ Set an Optimal Number of Extents for Each Rollback Segment ■ Place Rollback Segments in a Separate Tablespace See Also: Oracle9i Database Concepts for additional information about rollback segments Use Multiple Rollback Segments Using multiple rollback segment distributes rollback segment contention across many segments and improves system performance. Oracle assigns transactions to rollback segments in round-robin fashion. This results in a fairly even distribution of the number of transactions for each rollback segment. It is also possible to assign a transaction to a specific rollback segment, but this is usually not done. When a database is created, a single rollback segment named SYSTEM is created in the SYSTEM tablespace. This rollback segment is used in special ways by the Oracle database server, and is not intended for general use. Before you write to objects created in non-SYSTEM tablespaces, you must create and bring online at least one additional rollback segment in a non-SYSTEM tablespace. Note: When you are initially creating the database, and in order to create additional tablespaces and rollback segments, you must create a second rollback segment in the SYSTEM tablespace. Once these additional rollback segments are created, you should activate the new rollback segments and make the second rollback segment unavailable. At startup, an instance always acquires (brings online) the SYSTEM rollback segment in addition to any other rollback segments it needs or is directed to acquire. When there are multiple rollback segments, Oracle tries to use the SYSTEM rollback segment only for special system transactions and distributes user transactions among other rollback segments. If there are too many transactions for the non-SYSTEM rollback segments, Oracle uses the SYSTEM segment; plan your number of rollback segments to avoid this. 13-14 Oracle9i Database Administrator’s Guide Managing Rollback Segments There are a couple of options for activating multiple rollback segments when you start up an instance: ■ ■ Use public rollback segments and include the TRANSACTIONS and TRANSACTIONS_PER_ROLLBACK_SEGMENT initialization parameters in your initialization parameter file Use private or public rollback segments and specify their names in the ROLLBACK_SEGMENTS initialization parameter These options are discussed in other guidelines that follow. There is a limit on the number of rollback segments that can be open simultaneously. This limit is set by the MAX_ROLLBACK_SEGMENTS initialization parameter. Ensure that this parameter is set to a value higher than the number of rollback segments specified in the ROLLBACK_SEGMENTS initialization parameter. See Also: Oracle9i Database Reference for additional information about the TRANSACTIONS, TRANSACTIONS_PER_ROLLBACK_ SEGMENT, and ROLLBACK_SEGMENT initialization parameters Choose Between Public and Private Rollback Segments A private rollback segment must be acquired explicitly by an instance. This can occur at database startup when the rollback segments name is included in the ROLLBACK_SEGMENTS parameter in the initialization parameter file. A private rollback segment can also be acquired by specifically bringing it online by manually issuing the statement to do so. In an Oracle Real Application Clusters environment, private rollback segments allow an instance to acquire specific rollback segments. Public rollback segments form a pool of rollback segments that any instance requiring a rollback segment can use. An instance decides how many of these rollback segments to automatically acquire at instance startup based on the values of the TRANSACTIONS and TRANSACTIONS_PER_ROLLBACK_SEGMENT initialization parameters. Public rollback segments can be shared between Oracle Real Application Cluster instances. If you are not using the Oracle9i Real Application Clusters feature, private and public rollback segments function similarly. Specify Rollback Segments to Acquire Automatically When many transactions are concurrently proceeding, they simultaneously generate rollback information. A way of specifying that an appropriate number of rollback segments be acquired automatically at instance startup is to include the Managing Undo Space 13-15 Managing Rollback Segments TRANSACTIONS and TRANSACTIONS_PER_ROLLBACK_SEGMENT initialization parameters. You must also be using public rollback segments. You can indicate the number of concurrent transactions you expect for the instance with the initialization parameter TRANSACTIONS, and the number of transactions you expect each rollback segment will need to handle with the initialization parameter TRANSACTIONS_PER_ROLLBACK_SEGMENT. Then, when an instance opens a database, it attempts to acquire at least n rollback segments, where n=TRANSACTIONS/TRANSACTIONS_PER_ROLLBACK_SEGMENT. When creating your database, or subsequently, you should have created at least n public rollback segments. If you choose to use private rollback segments, these rollback segments will be acquired automatically by an instance at startup if you specify the rollback segments by name in the ROLLBACK_SEGMENTS initialization parameter in the instance’s parameter file. If you use both private and public rollback segments the following might occur. An instance acquires all the rollback segments listed in the ROLLBACK_SEGMENTS initialization parameter, even if more than TRANSACTIONS/TRANSACTIONS_PER_ ROLLBACK_SEGMENT segments are specified. Approximate Rollback Segment Sizes Total rollback segment size should be set based on the size of the most common transactions issued against a database. In general, short transactions experience better performance when the database has many smaller rollback segments, while long-running transactions, like batch jobs, perform better with larger rollback segments. Generally, rollback segments can handle transactions of any size easily. However, in extreme cases when a transaction is either very short or very long, a user might want to use an appropriately sized rollback segment. If a system is running only short transactions, rollback segments should be small so that they are always cached in main memory. If the rollback segments are small enough, they are more likely to be cached in the SGA according to the LRU algorithm, and database performance is improved because less disk I/O is necessary. The main disadvantage of small rollback segments is the increased likelihood of the error "snapshot too old" when running a long query involving records that are frequently updated by other transactions. This error occurs because the rollback entries needed for read consistency are overwritten as other update entries wrap around the rollback segment. Consider this issue when designing an application’s transactions, and make them short atomic units of work so that you can avoid this problem. 13-16 Oracle9i Database Administrator’s Guide Managing Rollback Segments In contrast, long-running transactions work better with larger rollback segments, because the rollback entries for a long-running transaction can fit in preallocated extents of a large rollback segment. When database systems applications concurrently issue a mix of very short and very long transactions, performance can be optimized if transactions are explicitly assigned to a rollback segment based on the transaction/rollback segment size. You can minimize dynamic extent allocation and truncation for rollback segments. This is not required for most systems and is intended for extremely large or small transactions. To optimize performance when issuing a mix of extremely small and large transactions, make a number of rollback segments of appropriate size for each type of transaction (such as small, medium, and large). Most rollback segments should correspond to the typical transactions, with a fewer number of rollback segments for the atypical transactions. Then set OPTIMAL for each such rollback segment so that the rollback segment returns to its intended size if it has to grow. You should tell users about the different sets of rollback segments that correspond to the different types of transactions. Often, it is not beneficial to assign a transaction explicitly to a specific rollback segment. However, you can assign an atypical transaction to an appropriate rollback segment created for such transactions. For example, you can assign a transaction that contains a large batch job to a large rollback segment. When a mix of transactions is not prevalent, each rollback segment should be 10% of the size of the database’s largest table because most SQL statements affect 10% or less of a table. A rollback segment of this size should be sufficient to store the actions performed by most SQL statements. Generally speaking, you should set a high MAXEXTENTS for rollback segments. This allows a rollback segment to allocate subsequent extents as it needs them. Create Rollback Segments with Many Equally Sized Extents Each rollback segment’s total allocated space should be divided among many equally sized extents. In general, optimal rollback I/O performance is observed if each rollback segment for an instance has 10 to 20 equally sized extents. After determining the desired total initial size of a rollback segment and the number of initial extents for the segment, use the following formula to calculate the size (s) of each extent of the rollback segment: s = T / n Managing Undo Space 13-17 Managing Rollback Segments where: s = calculated size, in bytes, of each extent initially allocated T = total initial rollback segment size, in bytes n = number of extents initially allocated After s is calculated, create the rollback segment and specify the storage parameters INITIAL and NEXT as s, and MINEXTENTS to n. PCTINCREASE cannot be specified for rollback segments and therefore defaults to 0. Also, if the size s of an extent is not an exact multiple of the data block size, it is rounded up to the next multiple. Set an Optimal Number of Extents for Each Rollback Segment You should carefully assess the kind of transactions the system runs when setting the OPTIMAL parameter for each rollback segment. For a system that executes long-running transactions frequently, OPTIMAL should be large so that Oracle does not have to shrink and allocate extents frequently. Also, for a system that executes long queries on active data, OPTIMAL should be large to avoid "snapshot too old" errors. OPTIMAL should be smaller for a system that mainly executes short transactions and queries so that the rollback segments remain small enough to be cached in memory, thus improving system performance. The V$ROLLNAME and V$ROLLSTAT dynamic performance views can be monitored to collect statistics useful in determining appropriate settings for OPTIMAL. See "Monitoring Rollback Segment Statistics" on page 13-27. Place Rollback Segments in a Separate Tablespace If possible, create one or more tablespaces specifically to hold all rollback segments. This way, all rollback segment data is stored separately from other types of data. Creating this "rollback segment" tablespace can provide the following benefits: ■ ■ ■ A tablespace holding rollback segments can always be kept online, thus maximizing the combined storage capacity of rollback segments at all times. If some rollback segments are not available, the overall database operation can be affected. Because tablespaces with active rollback segments cannot be taken offline, designating a tablespace to hold all rollback segments of a database ensures that the data stored in other tablespaces can be taken offline without concern for the database’s rollback segments. A tablespace’s free extents are likely to be more fragmented if the tablespace contains rollback segments that frequently allocate and deallocate extents. 13-18 Oracle9i Database Administrator’s Guide Managing Rollback Segments Creating Rollback Segments To create rollback segments, you must have the CREATE ROLLBACK SEGMENT system privilege. You use the CREATE ROLLBACK SEGMENT statement. The tablespace to contain the new rollback segments must be online. Rollback segments are usually created as part of the database creation script or process, but you may add more at a later time. The following topics relating to creating rollback segments are contained in this section: ■ The CREATE ROLLBACK SEGMENT Statement ■ Bringing New Rollback Segments Online ■ Setting Storage Parameters When Creating a Rollback Segment The CREATE ROLLBACK SEGMENT Statement The following statement creates a rollback segment named rbs_02 in the rbsspace tablespace, using the default storage parameters of that tablespace. Since this is not an Oracle Real Application Clusters environment, it is not necessary to specify PRIVATE or PUBLIC. The default is PRIVATE. CREATE ROLLBACK SEGMENT rbs_02 TABLESPACE rbsspace; See Also: Oracle9i SQL Reference for exact syntax, restrictions, and authorization requirements for the SQL statements used in managing rollback segments Bringing New Rollback Segments Online New rollback segments are initially offline. You must issue an ALTER ROLLBACK SEGMENT statement to bring them online and make them available for use by transactions of an instance. This is described in "Changing the ONLINE/OFFLINE Status of Rollback Segments" on page 13-22. If you create a private rollback segment, add the name of this new rollback segment to the ROLLBACK_SEGMENTS initialization parameter in the initialization parameter file for the database. Doing so enables the private rollback segment to be acquired automatically by the instance at instance startup. For example, if two new private rollback segments are created and named rbs_01 and rbs_02, then the ROLLBACK_SEGMENTS initialization parameter can be specified as follows: ROLLBACK_SEGMENTS = (rbs_01, rbs_02) Managing Undo Space 13-19 Managing Rollback Segments Setting Storage Parameters When Creating a Rollback Segment Suppose you wanted to create a rollback segment rbs_01 with storage parameters and optimal size set as follows: ■ The rollback segment is allocated an initial extent of 100K. ■ The rollback segment is allocated the second extent of 100K. ■ The optimal size of the rollback segment is 4M. ■ ■ The minimum number of extents and the number of extents initially allocated when the segment is created is 20. The maximum number of extents that the rollback segment can allocate, including the initial extent, is 100. The following statement creates a rollback segment with these characteristics: CREATE ROLLBACK SEGMENT rbs_01 TABLESPACE rbsspace STORAGE ( INITIAL 100K NEXT 100K OPTIMAL 4M MINEXTENTS 20 MAXEXTENTS 100 ); You cannot set a value for the storage parameter PCTINCREASE. It is always 0 for rollback segments. The OPTIMAL storage parameter is unique to rollback segments. For a discussion of storage parameters see "Setting Storage Parameters" on page 14-8. Oracle Corporation makes the following recommendations: ■ ■ ■ Set INITIAL and NEXT to the same value to ensure that all extents are the same size. Create a large number of initial extents to minimize the possibility of dynamic extension. MINEXTENTS = 20 is a good value. Avoid setting MAXEXTENTS = UNLIMITED as this could cause unnecessary extension of a rollback segment and possibly of data files due to a programming error. If you do specify UNLIMITED, be aware that extents for that segment must have a minimum of four data blocks. Also, if you later want to convert a rollback segment whose MAXEXTENTS are limited to UNLIMITED, that rollback segment cannot be converted if it has less than four data blocks in any extent. If you want to convert from limited to UNLIMITED, and have less than four data 13-20 Oracle9i Database Administrator’s Guide Managing Rollback Segments blocks in an extent, your only choice is to drop and re-create the rollback segment. See Also: Oracle9i SQL Reference for a detailed description of storage parameters Altering Rollback Segments This section discusses various actions you can take to maintain your rollback segments. All of these maintenance activities use the ALTER ROLLBACK SEGMENT statement. You must have the ALTER ROLLBACK SEGMENT system privilege to use this statement. The following topics are discussed: ■ Changing Rollback Segment Storage Parameters ■ Shrinking a Rollback Segment Manually ■ Changing the ONLINE/OFFLINE Status of Rollback Segments Changing Rollback Segment Storage Parameters You can change some of a rollback segment’s storage parameters after creating it. You may want to change the values of OPTIMAL or MAXEXTENTS. The following statement alters the maximum number of extents that the rbs_01 rollback segment can allocate: ALTER ROLLBACK SEGMENT rbs_01 STORAGE (MAXEXTENTS 120); You can alter the settings for the SYSTEM rollback segment, including the OPTIMAL parameter, just as you can alter those of any rollback segment. Shrinking a Rollback Segment Manually You can manually decrease the size of a rollback segment using the ALTER ROLLBACK SEGMENT statement. The rollback segment you are trying to shrink must be online. The following statement shrinks rollback segment rbs1 to 100K: ALTER ROLLBACK SEGMENT rbs1 SHRINK TO 100K; This statement attempts to reduce the size of the rollback segment to the specified size, but stops short if an extent cannot be deallocated because it is active. Managing Undo Space 13-21 Managing Rollback Segments Changing the ONLINE/OFFLINE Status of Rollback Segments This section describes aspects of bringing rollback segments online and taking them offline, and contains the following topics: ■ Bringing Rollback Segments Online Manually ■ Bringing Rollback Segment Online Automatically ■ Taking Rollback Segments Offline A rollback segment is either online and available to transactions, or offline and unavailable to transactions. Generally, rollback segments are online and available for use by transactions. You may want to take online rollback segments offline in the following situations: ■ ■ You want to take a tablespace offline, and the tablespace contains rollback segments. You cannot take a tablespace offline if it contains rollback segments that transactions are currently using. To prevent associated rollback segments from being used, you can take them offline before taking the tablespace offline. You want to drop a rollback segment, but cannot because transactions are currently using it. To prevent the rollback segment from being used, you can take it offline before dropping it. Note: You cannot take the SYSTEM rollback segment offline. You might later want to bring an offline rollback segment back online so that transactions can use it. When a rollback segment is created, it is initially offline, and you must explicitly bring a newly created rollback segment online before it can be used by an instance’s transactions. You can bring an offline rollback segment online using any instance accessing the database that contains the rollback segment. Bringing Rollback Segments Online Manually You can only bring a rollback segment online if its current status (as shown in the DBA_ROLLBACK_SEGS data dictionary view) is OFFLINE or PARTLY AVAILABLE. To bring an offline rollback segment online, use the ALTER ROLLBACK SEGMENT statement with the ONLINE option. The following statement brings the rollback segment user_rs_2 online: ALTER ROLLBACK SEGMENT user_rs_2 ONLINE; 13-22 Oracle9i Database Administrator’s Guide Managing Rollback Segments After you bring a rollback segment online, its status in the data dictionary view DBA_ROLLBACK_SEGS is ONLINE. To see a query for checking rollback segment status, see "Displaying Rollback Segment Information" on page 13-26. A rollback segment in the PARTLY AVAILABLE state contains data for an in-doubt or recovered distributed transaction, or for yet to be recovered transactions. You can view its status in the data dictionary view DBA_ROLLBACK_SEGS as PARTLY AVAILABLE. The rollback segment usually remains in this state until the transaction is resolved either automatically by RECO, or manually by a DBA. You might find that all rollback segments are PARTLY AVAILABLE. In this case, you can bring the PARTLY AVAILABLE segment online. Some resources used by the rollback segment for the in-doubt transaction remain inaccessible until the transaction is resolved. As a result, the rollback segment may have to grow if other transactions assigned to it need additional space. As an alternative to bringing a PARTLY AVAILABLE segment online, you might find it more efficient to create a new rollback segment temporarily, until the in-doubt transaction is resolved. Bringing Rollback Segment Online Automatically If you would like a rollback segment to be automatically brought online whenever you start up the database, add the segment’s name to the ROLLBACK_SEGMENTS parameter in the database’s parameter file. Or, you can use public rollback segments and use the TRANSACTIONS and TRANSACTIONS_PER_ROLLBACK_SEGMENT initialization parameters. These options are discussed in "Specify Rollback Segments to Acquire Automatically" on page 13-15. Taking Rollback Segments Offline To take an online rollback segment offline, use the ALTER ROLLBACK SEGMENT statement with the OFFLINE option. The rollback segment’s status in the DBA_ROLLBACK_SEGS data dictionary view must be ONLINE, and the rollback segment must be acquired by the current instance. The following example takes the rollback segment user_rs_2 offline: ALTER ROLLBACK SEGMENT user_rs_2 OFFLINE; If you attempt to take a rollback segment that does not contain active rollback entries offline, Oracle immediately takes the segment offline and changes its status to OFFLINE. In contrast, if you try to take a rollback segment that contains rollback data for active transactions (local, remote, or distributed) offline, Oracle makes the rollback Managing Undo Space 13-23 Managing Rollback Segments segment unavailable to future transactions and takes it offline after all the active transactions using the rollback segment complete. Until the transactions complete, the rollback segment cannot be brought online by any instance other than the one that was trying to take it offline. During this period that the rollback segment is waiting to go offline, the rollback segment’s status in the view DBA_ROLLBACK_SEGS remains ONLINE. However, the rollback segment’s status in the view V$ROLLSTAT is PENDING OFFLINE. For information on viewing rollback segment status, see "Displaying Rollback Segment Information" on page 13-26. The instance that tried to take a rollback segment offline and caused it to change to PENDING OFFLINE can bring it back online at any time. If the rollback segment is brought back online, it functions normally. After you take a public or private rollback segment offline, it remains offline until you explicitly bring it back online or you restart the instance. Explicitly Assigning a Transaction to a Rollback Segment A transaction can be explicitly assigned to a specific rollback segment. Reasons for doing this include: ■ ■ ■ You can predict the amount of rollback information generated by a transaction. You can assign the transaction to a rollback segment where you know that the rollback information will fit in the current extents of the segment. Thus, you can reduce the overhead of additional extents being dynamically allocated, and subsequently truncated. You know that no long running queries are concurrently reading the same tables, so if you assign small transactions to small rollback segments, those segments will most likely remain in memory. You have transactions that modify tables that are concurrently being read by long-running queries. You can assign these transactions to large rollback segments so that the rollback information needed for the read-consistent queries is not overwritten. To assign a transaction to a rollback segment explicitly, use the SET TRANSACTION statement with the USE ROLLBACK SEGMENT clause. The rollback segment must be online for the current instance, and the SET TRANSACTION USE ROLLBACK SEGMENT statement must be the first statement of the transaction. If a specified rollback segment is not online or a SET TRANSACTION USE ROLLBACK SEGMENT clause is not the first statement in a transaction, an error is returned. 13-24 Oracle9i Database Administrator’s Guide Managing Rollback Segments For example, if you are about to begin a transaction that contains a significant amount of work (more than most transactions), you can assign the transaction to a large rollback segment, as follows: SET TRANSACTION USE ROLLBACK SEGMENT large_rs1; After the transaction is committed, Oracle automatically assigns the next transaction to any available rollback segment unless the new transaction is explicitly assigned to a specific rollback segment by the user. Dropping Rollback Segments You can drop rollback segments when the extents of a segment become too fragmented on disk, or the segment needs to be relocated in a different tablespace. Before dropping a rollback segment, make sure that the status of the rollback segment is OFFLINE. If the rollback segment that you want to drop is any other status, you cannot drop it. If the status is INVALID, the segment has already been dropped. To drop a rollback segment, use the DROP ROLLBACK SEGMENT statement. You must have the DROP ROLLBACK SEGMENT system privilege. The following statement drops the rbs1 rollback segment: DROP ROLLBACK SEGMENT rbs1; Note: If a rollback segment specified in ROLLBACK_SEGMENTS is dropped, be sure to edit the parameter files of the database to remove the name of the dropped rollback segment from the list in the ROLLBACK_SEGMENTS parameter. If this step is not performed before the next instance startup, startup fails because it cannot acquire the dropped rollback segment. After a rollback segment is dropped, its status changes to INVALID. The next time a rollback segment is created, it takes the row vacated by a dropped rollback segment, if one is available, and the dropped rollback segment’s row no longer appears in the DBA_ROLLBACK_SEGS view. Viewing Rollback Segment Information This section presents views that can be used to obtain and monitor rollback segment information, and provides information and examples relating to their use. Managing Undo Space 13-25 Managing Rollback Segments The following topics are included: ■ Rollback Segment Views ■ Displaying Rollback Segment Information ■ Monitoring Rollback Segment Statistics ■ Displaying All Rollback Segments ■ Displaying Whether a Rollback Segment Has Gone Offline See Also: Oracle9i Database Reference for more information about the data dictionary views discussed in this chapter Rollback Segment Views The following views are useful for displaying information about rollback segments: View Description DBA_ROLLBACK_SEGS Describes the rollback segments, including names and tablespaces DBA_SEGMENTS Identifies a segment as a rollback segment and contains additional segment information V$ROLLNAME Lists the names of all online rollback segments V$ROLLSTAT Contains rollback segment statistics V$TRANSACTION Contains undo segment information Displaying Rollback Segment Information The DBA_ROLLBACK_SEGS data dictionary view stores information about the rollback segments of a database. For example, the following query lists the name, associated tablespace, and status of each rollback segment in a database: SELECT SEGMENT_NAME, TABLESPACE_NAME, STATUS FROM DBA_ROLLBACK_SEGS; SEGMENT_NAME ------------SYSTEM PUBLIC_RS USERS_RS TABLESPACE_NAME ---------------SYSTEM SYSTEM USERS 13-26 Oracle9i Database Administrator’s Guide STATUS -----ONLINE ONLINE ONLINE Managing Rollback Segments In addition, the following data dictionary views contain information about the segments of a database, including rollback segments: ■ USER_SEGMENTS ■ DBA_SEGMENTS Monitoring Rollback Segment Statistics The V$ROLLSTAT dynamic performance view can be queried to monitor rollback segment statistics. It must be joined with the V$ROLLNAME view to map its segment number to its name. Some specific columns of interest in the V$ROLLSTAT view include: Name Description USN Rollback segment number. If this view is joined with the V$ROLLNAME view, the rollback segment name can be determined. WRITES The number of bytes of entries written to the rollback segment. XACTS The number of active transactions. GETS The number of rollback segment header requests. WAITS The number of rollback segment header requests that resulted in waits. OPTSIZE The value of the optimal parameter for the rollback segment. HWMSIZE The highest value (high water mark), in bytes, of the rollback segment size reached during usage. SHRINKS The number of shrinks that the rollback segment has had to perform in order to stay at the optimal size. WRAPS The number of times a rollback segment entry has wrapped from one extent to another. EXTENDS The number of times that the rollback segment had to acquire a new extent. AVESHRINK The average number of bytes freed during a shrink. AVEACTIVE The average number of bytes in active extents in the rollback segment, measured over time. These statistics are reset at system startup. Managing Undo Space 13-27 Managing Rollback Segments Ad hoc querying of this view can help in determining the most advantageous setting for the OPTIMAL parameter. Assuming that an instance has equally sized rollback segments with comparably sized extents, OPTIMAL for a given rollback segment should be set slightly higher than AVEACTIVE. The following chart provides additional information on how to interpret the statistics given in this view. SHRINKS AVESHRINK Analysis and Recommendation Low Low If AVEACTIVE is close to OPTSIZE, then the OPTIMAL setting is correct. Otherwise, OPTIMAL is too large (not many shrinks are being performed.) Low High Excellent: a good setting for OPTIMAL. High Low OPTIMAL is too small: too many shrinks are being performed. High High Periodic long transactions are probably causing these statistics. Set the OPTIMAL parameter higher until SHRINKS is low. Displaying All Rollback Segments The following query returns the name of each rollback segment, the tablespace that contains it, and its size: SELECT SEGMENT_NAME, TABLESPACE_NAME, BYTES, BLOCKS, EXTENTS FROM DBA_SEGMENTS WHERE SEGMENT_TYPE = 'ROLLBACK'; SEGMENT_NAME TABLESPACE_NAME ------------ --------------SYSTEM SYSTEM RB_TEMP SYSTEM RB1 RBS RB2 RBS RB3 RBS RB4 RBS RB5 RBS RB6 RBS RB7 RBS RB8 RBS 10 rows selected. 13-28 Oracle9i Database Administrator’s Guide BYTES ------409600 1126400 614400 614400 614400 614400 614400 614400 614400 614400 BLOCKS -----200 550 300 300 300 300 300 300 300 300 EXTENTS ------8 11 3 3 3 3 3 3 3 3 Managing Rollback Segments Displaying Whether a Rollback Segment Has Gone Offline When you take a rollback segment offline, it does not actually go offline until all active transactions in it have completed. Between the time when you attempt to take it offline and when it actually is offline, its status in V$ROLLSTAT is PENDING OFFLINE and it is not used for new transactions. To determine whether any rollback segments for an instance are in this state, use the following query: SELECT NAME, XACTS "ACTIVE TRANSACTIONS" FROM V$ROLLNAME, V$ROLLSTAT WHERE STATUS = 'PENDING OFFLINE' AND V$ROLLNAME.USN = V$ROLLSTAT.USN; NAME ---------RS2 ACTIVE TRANSACTIONS -------------------3 If your instance is part of an Oracle Real Application Clusters configuration, this query displays information for rollback segments of the current instance only, not those of other instances. Managing Undo Space 13-29 Managing Rollback Segments 13-30 Oracle9i Database Administrator’s Guide Part III Schema Objects Part III describes the creation and maintenace of schema objects in the Oracle database. It includes the following chapters: ■ Chapter 14, "Managing Space for Schema Objects" ■ Chapter 15, "Managing Tables" ■ Chapter 16, "Managing Indexes" ■ Chapter 17, "Managing Partitioned Tables and Indexes" ■ Chapter 18, "Managing Clusters" ■ Chapter 19, "Managing Hash Clusters" ■ Chapter 20, "Managing Views, Sequences, and Synonyms" ■ Chapter 21, "General Management of Schema Objects" ■ Chapter 22, "Detecting and Repairing Data Block Corruption" 14 Managing Space for Schema Objects This chapter offers guidelines for managing space for schema objects. It contains the following topics: ■ Managing Space in Data Blocks ■ Setting Storage Parameters ■ Managing Resumable Space Allocation ■ Deallocating Space ■ Understanding Space Use of Datatypes You should familiarize yourself with the concepts in this chapter before attempting to manage specific schema objects as described in later chapters. Managing Space for Schema Objects 14-1 Managing Space in Data Blocks Managing Space in Data Blocks This section describes aspects of managing space in data blocks. Data blocks are the finest level of granularity of the structure in which database data is stored on disk. The size of a data block is specified (or defaulted) at database creation. The PCTFREE and PCTUSED parameters are physical attributes that can be specified when a schema object is created or altered. These parameters allow you to control the use of the free space within a data block. This free space is available for inserts and updates of rows of data. The PCTFREE and PCTUSED parameters allow you to: ■ Improve performance when writing and retrieving data ■ Decrease the amount of unused space in data blocks ■ Decrease the amount of row chaining between data blocks The INITRANS and MAXTRANS parameters are also physical attributes that can be specified when schema objects are created or altered. These parameters control the number of concurrent update transactions allocated for data blocks of a schema object, which in turn affects space usage in data block headers and can have an impact upon data block free space. The following topics are contained in this section: ■ Specifying the PCTFREE Parameter ■ Specifying the PCTUSED Parameter ■ Selecting Associated PCTUSED and PCTFREE Values ■ Specifying the Transaction Entry Parameters: INITRANS and MAXTRANS See Also: ■ ■ Oracle9i Database Concepts for more information on data blocks Oracle9i SQL Reference for syntax and other details of the PCTFREE, PCTUSED, INITRANS, and MAXTRANS physical attributes parameters Specifying the PCTFREE Parameter The PCTFREE parameter is used to set the percentage of a block to be reserved for possible updates to rows that already are contained in that block. For example, 14-2 Oracle9i Database Administrator’s Guide Managing Space in Data Blocks assume that you specify the following parameter within a CREATE TABLE statement: PCTFREE 20 This indicates that 20% of each data block used for this table’s data segment will be kept free and available for possible updates to the existing rows already within each block. Figure 14–1 illustrates PCTFREE. Figure 14–1 PCTFREE Database Block PCTFREE = 20 20% Free Space Block allows row inserts until 80% is occupied, leaving 20% free for updates to existing rows in the block Notice that before the block reaches PCTFREE, the free space of the data block is filled by both the insertion of new rows and by the growth of the data block header. Ensure that you understand the nature of a table or index data before setting PCTFREE. Updates can cause rows to grow. New values might not be the same size as values they replace. If there are many updates in which data values get larger, PCTFREE should be increased. If updates to rows do not affect the total row width, PCTFREE can be low. Your goal is to find a satisfactory trade-off between densely packed data and good update performance. Managing Space for Schema Objects 14-3 Managing Space in Data Blocks The default for PCTFREE is 10 percent. You can use any integer between 0 and 99, inclusive, as long as the sum of PCTFREE and PCTUSED does not exceed 100. Effects of Specifying a Smaller PCTFREE A smaller PCTFREE has the following effects: ■ Reserves less room for updates to expand existing table rows ■ Allows inserts to fill the block more completely ■ May save space, because the total data for a table or index is stored in fewer blocks (more rows or entries for each block) A small PCTFREE might be suitable, for example, for a segment that is rarely changed. Effects of Specifying a Larger PCTFREE A larger PCTFREE has the following effects: ■ ■ ■ Reserves more room for future updates to existing table rows May require more blocks for the same amount of inserted data (inserting fewer rows for each block) May improve update performance, because Oracle does not need to chain row pieces as frequently, if ever A large PCTFREE is suitable, for example, for segments that are frequently updated. PCTFREE for Nonclustered Tables If the data in the rows of a nonclustered table is likely to increase in size over time, reserve some space for these updates. Otherwise, updated rows are likely to be chained among blocks. PCTFREE for Clustered Tables The discussion for nonclustered tables also applies to clustered tables. However, if PCTFREE is reached, new rows from any table contained in the same cluster key go into a new data block that is chained to the existing cluster key. PCTFREE for Indexes You can specify PCTFREE only when initially creating an index. 14-4 Oracle9i Database Administrator’s Guide Managing Space in Data Blocks Specifying the PCTUSED Parameter Note: The PCTUSED parameter is ignored for objects created in locally managed tablespaces with segment space management specified as AUTO. This form of segment space management is discussed in "Specifying Segment Space Management in Locally Managed Tablespaces" on page 11-8. After a data block becomes full as determined by PCTFREE, Oracle does not consider the block for the insertion of new rows until the percentage of the block being used falls below the parameter PCTUSED. Before this value is achieved, Oracle uses the free space of the data block only for updates to rows already contained in the data block. For example, assume that you specify the following parameter within a CREATE TABLE statement: PCTUSED 40 In this case, a data block used for this table’s data segment is not considered for the insertion of any new rows until the amount of used space in the block falls to 39% or less (assuming that the block’s used space has previously reached PCTFREE). Figure 14–2 illustrates this. Managing Space for Schema Objects 14-5 Managing Space in Data Blocks Figure 14–2 PCTUSED Database Block PCTUSED = 40 60% unused space No new rows are inserted until amount of used space falls below 40% The default value for PCTUSED is 40 percent. After the free space in a data block reaches PCTFREE, no new rows are inserted in that block until the percentage of space used falls below PCTUSED. The percent value is for the block space available for data after overhead is subtracted from total space. You can specify any integer between 0 and 99 (inclusive) for PCTUSED, as long as the sum of PCTUSED and PCTFREE does not exceed 100. Effects of Specifying a Smaller PCTUSED A smaller PCTUSED has the following effects: ■ ■ Reduces processing costs incurred during UPDATE and DELETE statements for moving a block to the free list when it has fallen below that percentage of usage Increases the unused space in a database Effects of Specifying a Larger PCTUSED A larger PCTUSED has the following effects: ■ 14-6 Improves space efficiency Oracle9i Database Administrator’s Guide Managing Space in Data Blocks Increases processing cost during INSERT and UPDATE ■ Selecting Associated PCTUSED and PCTFREE Values If you decide not to use the default values for PCTFREE or PCTUSED, keep the following guidelines in mind: The sum of PCTFREE and PCTUSED must be equal to or less than 100. ■ If the sum equals 100, then Oracle attempts to keep no more than PCTFREE free space, and processing costs are highest. ■ The smaller the difference between 100 and the sum of PCTFREE and PCTUSED (as in PCTUSED of 75, PCTFREE of 20), the more efficient space usage is, at some performance cost. ■ The following table contains examples that show how and why specific values for PCTFREE and PCTUSED are specified for tables. Example Scenario Settings Explanation 1 Common activity includes UPDATE statements that increase the size of the rows. PCTFREE=20 PCTFREE is set to 20 to allow enough room for rows that increase in size as a result of updates. PCTUSED is set to 40 so that less processing is done during high update activity, thus improving performance. Most activity includes INSERT and DELETE statements, and UPDATE statements that do not increase the size of affected rows. PCTFREE=5 The table is very large and storage is a primary concern. Most activity includes read-only transactions. PCTFREE=5 2 3 PCTUSED=40 PCTUSED=60 PCTUSED=40 PCTFREE is set to 5 because most UPDATE statements do not increase row sizes. PCTUSED is set to 60 so that space freed by DELETE statements is used soon, yet processing is minimized. PCTFREE is set to 5 because this is a large table and you want to completely fill each block. Managing Space for Schema Objects 14-7 Setting Storage Parameters Specifying the Transaction Entry Parameters: INITRANS and MAXTRANS INITRANS specifies the number of DML transaction entries for which space is initially reserved in the data block header. Space is reserved in the headers of all data blocks in the associated segment. As multiple transactions concurrently access the rows of the same data block, space is allocated for each DML transaction’s entry in the block. Once the space reserved by INITRANS is depleted, space for additional transaction entries is allocated out of the free space in a block, if available. Once allocated, this space effectively becomes a permanent part of the block header. The MAXTRANS parameter limits the number of transaction entries that can concurrently use data in a data block. Therefore, you can limit the amount of free space that can be allocated for transaction entries in a data block using MAXTRANS. The INITRANS and MAXTRANS parameters for the data blocks allocated to a specific schema object should be set individually for each schema object based on the following criteria: ■ ■ The space you would like to reserve for transaction entries compared to the space you would reserve for database data The number of concurrent transactions that are likely to touch the same data blocks at any given time For example, if a table is very large and only a small number of users simultaneously access the table, the chances of multiple concurrent transactions requiring access to the same data block is low. Therefore, INITRANS can be set low, especially if space is at a premium in the database. Alternatively, assume that a table is usually accessed by many users at the same time. In this case, you might consider preallocating transaction entry space by using a high INITRANS. This eliminates the overhead of having to allocate transaction entry space, as required when the object is in use. Also, allow a higher MAXTRANS so that no user has to wait to access necessary data blocks. Setting Storage Parameters This section describes the storage parameters that you can set for various data structures. These storage parameters apply to the following types of structures and schema objects: ■ 14-8 Tablespaces (used as storage parameter defaults for all segments) Oracle9i Database Administrator’s Guide Setting Storage Parameters ■ Tables, partitions, clusters, materialized views, and materialized view logs (data segments) ■ Indexes (index segments) ■ Rollback segments The following topics are discussed: ■ Identifying the Storage Parameters ■ Setting Default Storage Parameters for Segments in a Tablespace ■ Setting Storage Parameters for Data Segments ■ Setting Storage Parameters for Index Segments ■ Setting Storage Parameters for LOBs, Varrays, and Nested Tables ■ Changing Values for Storage Parameters ■ Understanding Precedence in Storage Parameters ■ Example of How Storage Parameters Effect Space Allocation Identifying the Storage Parameters Storage parameters determine space allocation for objects when they are created in a dictionary-managed tablespace. Locally managed tablespaces provide a simpler means of space allocation, and most storage parameters have no meaning in their context. When you create a dictionary-managed tablespace you can specify default storage parameters. These values override the system defaults to become the defaults for objects created in that tablespace only. You specify the default storage values in the DEFAULT STORAGE clause of a CREATE or ALTER TABLESPACE statement. Furthermore, for objects created in dictionary-managed tablespaces, you can specify storage parameters for each individual schema object. These parameter settings override any default storage settings. Use the STORAGE clause of the CREATE or ALTER statement for specifying storage parameters for the individual object. The following example illustrates specifying storage parameters when a table is being created: CREATE TABLE players (code NUMBER(10) PRIMARY KEY, lastname VARCHAR(20), firstname VARCHAR(15), Managing Space for Schema Objects 14-9 Setting Storage Parameters position VARCHAR2(20), team VARCHAR2(20)) PCTFREE 10 PCTUSED 40 STORAGE (INITIAL 25K NEXT 10K MAXEXTENTS 10 MINEXTENTS 3); Not all storage parameters can be specified for every type of database object, and not all storage parameters can be specified in both the CREATE and ALTER statements. The following table contains a brief description of each storage parameter. For a complete description of these parameters, including their default, minimum, and maximum settings, see the Oracle9i SQL Reference. Parameter Description INITIAL The size, in bytes, of the first extent allocated when a segment is created. This parameter cannot be specified in an ALTER statement. NEXT The size, in bytes, of the next incremental extent to be allocated for a segment. The second extent is equal to the original setting for NEXT. From there forward, NEXT is set to the previous size of NEXT multiplied by (1 + PCTINCREASE/100). PCTINCREASE The percentage by which each incremental extent grows over the last incremental extent allocated for a segment. If PCTINCREASE is 0, then all incremental extents are the same size. If PCTINCREASE is greater than zero, then each time NEXT is calculated, it grows by PCTINCREASE. PCTINCREASE cannot be negative. The new NEXT equals 1 + PCTINCREASE/100, multiplied by the size of the last incremental extent (the old NEXT) and rounded up to the next multiple of a block size. MINEXTENTS The total number of extents to be allocated when the segment is created. This allows for a large allocation of space at creation time, even if contiguous space is not available. MAXEXTENTS The total number of extents, including the first, that can ever be allocated for the segment. 14-10 Oracle9i Database Administrator’s Guide Setting Storage Parameters Parameter Description FREELIST GROUPS The number of groups of free lists for the database object you are creating. Oracle uses the instance number of Oracle Real Application Cluster instances to map each instance to one free list group. For information on the use of this parameter, see Oracle9i Real Application Clusters Administration. Note: This parameter is ignored for objects created in locally managed tablespaces with segment space management specified as AUTO. FREELISTS Specifies the number of free lists for each of the free list groups for the schema object. Not valid for tablespaces.The use of this parameter is discussed in Oracle9i Database Performance Tuning Guide and Reference. Note: This parameter is ignored for objects created in locally managed tablespaces with segment space management specified as AUTO. OPTIMAL Relevant only to rollback segments. See Chapter 13, "Managing Undo Space" for information on the use of this parameter. BUFFER POOL Defines a default buffer pool (cache) for a schema object. Not valid for tablespaces or rollback segments. For information on the use of this parameter, see Oracle9i Database Performance Tuning Guide and Reference. Setting Default Storage Parameters for Segments in a Tablespace You can set default storage parameters for each tablespace of a database. Any storage parameter that you do not explicitly set when creating or subsequently altering a segment in a tablespace automatically is set to the corresponding default storage parameter for the tablespace in which the segment resides. When specifying MINEXTENTS at the tablespace level, any extent allocated in the tablespace is rounded to a multiple of the number of minimum extents. Setting Storage Parameters for Data Segments You set the storage parameters for the data segment of a nonclustered table, materialized view, or materialized view log using the STORAGE clause of the CREATE or ALTER statement for tables, materialized views, or materialized view logs. In contrast, you set the storage parameters for the data segments of a cluster using the STORAGE clause of the CREATE CLUSTER or ALTER CLUSTER statement, Managing Space for Schema Objects 14-11 Setting Storage Parameters rather than the individual CREATE or ALTER statements that put tables and materialized views into the cluster. Storage parameters specified when creating or altering a clustered table or materialized view are ignored. The storage parameters set for the cluster override the table’s storage parameters. With partitioned tables, you can set default storage parameters at the table level. When creating a new partition of the table, the default storage parameters are inherited from the table level (unless you specify them for the individual partition). If no storage parameters are specified at the table level, then they are inherited from the tablespace. Setting Storage Parameters for Index Segments Storage parameters for an index segment created for a table index can be set using the STORAGE clause of the CREATE INDEX or ALTER INDEX statement. Storage parameters of an index segment created for the index used to enforce a primary key or unique key constraint can be set in either of the following ways: ■ ■ In the ENABLE ... USING INDEX clause of the CREATE TABLE or ALTER TABLE statement In the STORAGE clause of the ALTER INDEX statement Setting Storage Parameters for LOBs, Varrays, and Nested Tables A table or materialized view can contain LOB, varray, or nested table column types. These entities can be stored in their own segments. LOBs and varrays are stored in LOB segments, while a nested table is stored in a storage table. You can specify a STORAGE clause for these segments that will override storage parameters specified at the table level. See Also: ■ Oracle9i Application Developer’s Guide - Large Objects (LOBs) ■ Oracle9i Application Developer’s Guide - Fundamentals ■ Oracle9i SQL Reference All of the above books contain more information about creating tables containing LOBs, varrays, and nested tables. 14-12 Oracle9i Database Administrator’s Guide Setting Storage Parameters Changing Values for Storage Parameters You can alter default storage parameters for tablespaces and specific storage parameters for individual segments if you so choose. Default storage parameters can be reset for a tablespace. However, changes affect only new objects created in the tablespace, or new extents allocated for a segment. The INITIAL and MINEXTENTS storage parameters cannot be altered for an existing table, cluster, index, or rollback segment. If only NEXT is altered for a segment, the next incremental extent is the size of the new NEXT, and subsequent extents can grow by PCTINCREASE as usual. If both NEXT and PCTINCREASE are altered for a segment, the next extent is the new value of NEXT, and from that point forward, NEXT is calculated using PCTINCREASE as usual. Understanding Precedence in Storage Parameters The storage parameters in effect at a given time are determined by the following types of SQL statements, listed in order of precedence (where higher numbers take precedence over lower numbers): 1. ALTER [TABLE|CLUSTER|MATERIALIZED VIEW|MATERIALIZED VIEW LOG|INDEX|ROLLBACK] SEGMENT statement 2. CREATE [TABLE|CLUSTER|MATERIALIZED VIEW|MATERIALIZED VIEW LOG|INDEX|ROLLBACK] SEGMENT statement 3. ALTER TABLESPACE statement 4. CREATE TABLESPACE statement 5. Oracle default values Any storage parameter specified at the object level overrides the corresponding option set at the tablespace level. When storage parameters are not explicitly set at the object level, they default to those at the tablespace level. When storage parameters are not set at the tablespace level, Oracle system defaults apply. If storage parameters are altered, the new options apply only to the extents not yet allocated. Note: The storage parameters for temporary segments always use the default storage parameters set for the associated tablespace. Managing Space for Schema Objects 14-13 Managing Resumable Space Allocation Example of How Storage Parameters Effect Space Allocation Assume the following statement has been executed: CREATE TABLE test_storage ( . . . ) STORAGE (INITIAL 100K NEXT 100K MINEXTENTS 2 MAXEXTENTS 5 PCTINCREASE 50); Also assume that the initialization parameter DB_BLOCK_SIZE is set to 2K. The following table shows how extents are allocated for the TEST_STORAGE table. Also shown is the value for the incremental extent, as can be seen in the NEXT column of the USER_SEGMENTS or DBA_SEGMENTS data dictionary views: Table 14–1 Extent Allocations Extent# Extent Size Value for NEXT 1 50 blocks or 102400 bytes 50 blocks or 102400 bytes 2 50 blocks or 102400 bytes 75 blocks or153600 bytes 3 75 blocks or 153600 bytes 113 blocks or 231424 bytes 4 115 blocks or 235520 bytes 170 blocks or 348160 bytes 5 170 blocks or 348160 bytes No next value, MAXEXTENTS=5 If you change the NEXT or PCTINCREASE storage parameters with an ALTER statement (such as ALTER TABLE), the specified value replaces the current value stored in the data dictionary. For example, the following statement modifies the NEXT storage parameter of the test_storage table before the third extent is allocated for the table: ALTER TABLE test_storage STORAGE (NEXT 500K); As a result, the third extent is 500K when allocated, the fourth is (500K*1.5)=750K, and so forth. Managing Resumable Space Allocation Oracle provides a means for suspending, and later resuming, the execution of large database operations in the event of space allocation failures. This enables you to take corrective action instead of the Oracle database server returning an error to the user. After the error condition is corrected, the suspended operation automatically 14-14 Oracle9i Database Administrator’s Guide Managing Resumable Space Allocation resumes. This feature is called resumable space allocation. The statements that are affected are called resumable statements. This section contains the following topics: ■ Resumable Space Allocation Overview ■ Enabling and Disabling Resumable Space Allocation ■ Detecting Suspended Statements ■ Resumable Space Allocation Example: Registering an AFTER SUSPEND Trigger Resumable Space Allocation Overview This section provides an overview of resumable space allocation. It describes how resumable statements work, and specifically defines qualifying statements and error conditions. How Resumable Statements Work The following is an overview of how resumable statements work. Details are contained in later sections. 1. A statement executes in a resumable mode only when the client explicitly enables resumable semantics for the session using the ALTER SESSION statement. 2. A resumable statement is suspended when one of the following conditions occur (these conditions result in corresponding errors being signalled for nonresumable statements): 3. ■ Out of space condition ■ Maximum extents reached condition ■ Space quota exceeded condition. On suspending a resumable statement’s execution, there are mechanisms to perform user supplied operations, log errors, and to query the status of the statement execution. When a resumable statement is suspended the following actions are taken: ■ ■ The error is reported in the alert log. If the user registered a trigger on the AFTER SUSPEND system event, the user trigger is executed. A user supplied PL/SQL procedure can access the Managing Space for Schema Objects 14-15 Managing Resumable Space Allocation error message data using the DBMS_RESUMABLE package and DBA/USER_ RESUMABLE view. 4. Suspending a statement automatically results in suspending the transaction. Thus all transactional resources are held through a statement suspend and resume. 5. When the error condition disappears (for example, as a result of user intervention or perhaps sort space released by other queries), the suspended statement automatically resumes execution. 6. A suspended statement can be forced to throw the exception using the DBMS_ RESUMABLE.ABORT() procedure. This procedure can be called by a DBA, or by the user who issued the statement. 7. A suspension time out interval is associated with resumable statements. A resumable statement that is suspended for the timeout interval (the default is two hours) wakes up and returns the exception to the user. 8. A resumable statement can be suspended and resumed multiple times during execution. What Operations are Resumable? Note: Resumable space allocation is fully supported when using locally managed tablespaces. There are certain limitations when using dictionary-managed tablespaces. See "Resumable Space Allocation Limitations for Dictionary-Managed Tablespaces" on page 14-18 for details. The following operations are resumable: ■ Queries SELECT statements that run out of temporary space (for sort areas) are candidates for resumable execution. When using OCI, the calls LNOCIStmtExecute() and LNOCIStmtFetch() are candidates. ■ DML INSERT, UPDATE, and DELETE statements are candidates. The interface used to execute them does not matter; it can be OCI, JSQL, PL/SQL, or another interface. Also, INSERT INTO ... SELECT from external tables can be resumable. 14-16 Oracle9i Database Administrator’s Guide Managing Resumable Space Allocation ■ Import/Export As for SQL*Loader, a command line parameter controls whether statements are resumable after recoverable errors. ■ DDL The following statements are candidates for resumable execution: – CREATE TABLE ... AS SELECT – CREATE INDEX – ALTER INDEX ... REBUILD – ALTER TABLE ... MOVE PARTITION – ALTER TABLE ... SPLIT PARTITION – ALTER INDEX ... REBUILD PARTITION – ALTER INDEX ... SPLIT PARTITION – CREATE MATERIALIZED VIEW – CREATE MATERIALIZED VIEW LOG What Errors are Correctable? There are three classes of correctable errors: ■ Out of space condition The operation cannot acquire any more extents for a table/index/temporary segment/rollback segment/undo segment/cluster/LOB/table partition/index partition in a tablespace. For example, the following errors fall in this category: ORA-1650 unable to extend rollback segment ... in tablespace ... ORA-1653 unable to extend table ... in tablespace ... ORA-1654 unable to extend index ... in tablespace ... ■ Maximum extents reached condition The number of extents in a table/index/temporary segment/rollback segment/undo segment/cluster/LOB/table partition/index partition equals the maximum extents defined on the object. For example, the following errors fall in this category: ORA-1628 max # extents ... reached for rollback segment ... ORA-1631 max # extents ... reached in table ... ORA-1654 max # extents ... reached in index ... Managing Space for Schema Objects 14-17 Managing Resumable Space Allocation ■ Space quota exceeded condition The user has exceeded his assigned space quota in the tablespace. Specifically, this is noted by the following error: ORA-1536 space quote exceeded for tablespace string Resumable Space Allocation Limitations for Dictionary-Managed Tablespaces There are certain limitations of resumable space allocation when using dictionary-managed tablespaces. These limitations are listed below: 1. If a DDL operation such as CREATE TABLE or CREATE INDEX is executed with an explicit MAXEXTENTS setting which causes an out of space error during its execution, the operation will not be suspended. Instead, it will be aborted. This error is treated as not repairable because the properties of an object (for example, MAXEXTENTS) cannot be altered before its creation. However if a DML operation causes an already existing table or index to reach the MAXEXTENTS limit, it will be suspended and can be resumed later. This restriction can be overcome either by setting the MAXEXTENTS clause to UNLIMITED or by using locally managed tablespaces. 2. If rollback segments are located in dictionary managed tablespaces, then space allocation for rollback segments is not resumable. However, space allocation for user objects(tables, indexes, and the likes) would still be resumable. To workaround the limitation, we recommend using automatic undo management or placing the rollback segments in locally managed tablespaces. Resumable Statements and Distributed Operations Remote operations are not supported in resumable mode. Parallel Execution and Resumable Statements In parallel execution, if one of the parallel execution server processes encounters a correctable error, that server process suspends its execution. Other parallel execution server processes will continue executing their respective tasks, until either they encounter an error or are blocked (directly or indirectly) by the suspended server process. When the correctable error is resolved, the suspended process resumes execution and the parallel operation continues execution. If the suspended operation is terminated, the parallel operation aborts, throwing the error to the user. Different parallel execution server processes may encounter one or more correctable errors. This may result in firing an AFTER SUSPEND trigger multiple times, in 14-18 Oracle9i Database Administrator’s Guide Managing Resumable Space Allocation parallel. Also, if a parallel execution server process encounters a noncorrectable error while another parallel execution server process is suspended, the suspended statement is immediately aborted. For parallel execution, every parallel execution coordinator and server process has its own entry in DBA/USER_RESUMABLE view. Enabling and Disabling Resumable Space Allocation Resumable space allocation is only possible when statements are executed within a session that has resumable mode enabled. To enable resumable mode for a session, use the following SQL statement: ALTER SESSION ENABLE RESUMABLE; Because suspended statements can hold up some system resources, users must be granted the RESUMABLE system privilege before they are allowed to enable and execute resumable statements. To disable resumable mode, issue the following statement: ALTER SESSION DISABLE RESUMABLE; The default for a new session is resumable mode disabled. You can also specify a timeout interval, and you can provide a name used to identify a resumable statement. These are discussed separately in following sections. See Also: "Setting Default Resumable Mode" on page 14-20 Specifying a Timeout Interval When you enable resumable mode for a session, you can also specify a timeout interval, after which a suspended statement will error if no intervention has taken place. The following statement specifies that resumable transactions will time out and error after 3600 seconds: ALTER SESSION ENABLE RESUMABLE TIMEOUT 3600; The value of TIMEOUT remains in effect until it is changed by another ALTER SESSION ENABLE RESUMABLE statement, it is changed by another means, or the session ends. The default timeout interval is 7200 seconds. Managing Space for Schema Objects 14-19 Managing Resumable Space Allocation See Also: "Changing the Timeout Interval" on page 14-20 for other methods of changing the timeout interval for resumable statements Naming Resumable Statements Resumable statements can be identified by name. The following statement assigns a name to resumable statements: ALTER SESSION ENABLE RESUMABLE TIMEOUT 3600 NAME 'insert into table'; The NAME value remains in effect until it is changed by another ALTER SESSION ENABLE RESUMABLE statement, or the session ends. The default value for NAME is: User USERNAME(USERID), Session SESSIONID, Instance INSTANCEID The name of the statement is used to identify the resumable statement in the DBA_ RESUMABLE and USER_RESUMABLE views. Setting Default Resumable Mode To set default resumable mode, a DBA can register a database level LOGON trigger to alter a user’s session to enable resumable and set a timeout interval. Note: If there are multiple triggers registered that change default mode and timeout for resumable statements, the result will be unspecified because Oracle does not guarantee the order of trigger invocation. Changing the Timeout Interval In addition to the ALTER SESSION ENABLE RESUMABLE statement, there are other methods for setting or changing the timeout interval. The DBMS_RESUMABLE package contains procedures for setting the timeout period for a specific session or for the current session. A DBA can change the default system timeout by creating a system wide AFTER SUSPEND trigger that calls DBMS_RESUMABLE to set it. For example, the following code sample sets a system wide default timeout to one hour: CREATE OR REPLACE TRIGGER resumable_default_timeout AFTER SUSPEND ON DATABASE BEGIN DBMS_RESUMABLE.SET_TIMEOUT(3600); 14-20 Oracle9i Database Administrator’s Guide Managing Resumable Space Allocation END; Detecting Suspended Statements When a resumable statement is suspended, the error is not raised to the client. In order for corrective action to be taken, Oracle provides alternative methods for notifying users of the error and for providing information about the circumstances. AFTER SUSPEND System Event and Trigger When a resumable statement encounter a correctable error, the system internally generates the AFTER SUSPEND system event. Users can register triggers for this event at both the database and schema level. If a user registers a trigger to handle this system event, the trigger is executed after a SQL statement has been suspended. SQL statements executed within a AFTER SUSPEND trigger are always nonresumable and are always autonomous. Transactions started within the trigger use the SYSTEM rollback segment. These conditions are imposed to overcome deadlocks and reduce the chance of the trigger experiencing the same error condition as the statement. Users can use the USER_RESUMABLE or DBA_RESUMABLE views, or the DBMS_ RESUMABLE.SPACE_ERROR_INFO function, within triggers to get information about the resumable statements. Triggers can also call the DBMS_RESUMABLE package to abort suspended statements and modify resumable timeout values. See Also: Oracle9i Application Developer’s Guide - Fundamentals for information about system events, triggers, and attribute functions Views Containing Information About Resumable Statements The following views can be queried to obtain information about the status of resumable statements: View Description DBA_RESUMABLE These views contain rows for all currently executing or suspended resumable statements. They can be used by a DBA, AFTER SUSPEND trigger, or another session to monitor the progress of, or obtain specific information about, resumable statements. USER_RESUMABLE Managing Space for Schema Objects 14-21 Managing Resumable Space Allocation View Description V$SESSION_WAIT When a statement is suspended the session invoking the statement is put into a wait state. A row is inserted into this view for the session with the EVENT column containing "statement suspended, wait error to be cleared". See Also: Oracle9i Database Reference for specific information about the columns contained in these views DBMS_RESUMABLE Package The DBMS_RESUMABLE package helps control resumable statements. The following procedures are available: Procedure Description ABORT(sessionID) This procedure aborts a suspended resumable statement. The parameter sessionID is the session ID in which the statement is executing. For parallel DML/DDL, sessionID is any session ID which participates in the parallel DML/DDL. Oracle guarantees that the ABORT operation always succeeds. It may be called either inside or outside of the AFTER SUSPEND trigger. The caller of ABORT must be the owner of the session with sessionID, have ALTER SYSTEM privilege, or have DBA privileges. GET_SESSION_ TIMEOUT(sessionID) This function returns the current timeout value of resumable statements for the session with sessionID. This returned timeout is in seconds. If the session does not exist, this function returns -1. SET_SESSION_ TIMEOUT(sessionID, timeout) This procedure sets the timeout interval of resumable statements for the session with sessionID. The parameter timeout is in seconds. The new timeout setting will applies to the session immediately. If the session does not exist, no action is taken. GET_TIMEOUT() This function returns the current timeout value of resumable statements for the current session. The returned value is in seconds. SET_ TIMEOUT(timeout) This procedure sets a timeout value for resumable statements for the current session. The parameter timeout is in seconds. The new timeout setting applies to the session immediately. 14-22 Oracle9i Database Administrator’s Guide Managing Resumable Space Allocation See Also: Oracle9i Supplied PL/SQL Packages and Types Reference Resumable Space Allocation Example: Registering an AFTER SUSPEND Trigger In the following example, a system wide AFTER SUSPEND trigger is created and registered as user SYS at the database level. Whenever a resumable statement is suspended in any session, this trigger can have either of two effects: ■ ■ If the rollback segment has reached its space limit, then a message is sent to the DBA and the statement is aborted. If any other recoverable error has occurred, the timeout interval is reset to 8 hours. Here are the statements for this example: CREATE OR REPLACE TRIGGER resumable_default AFTER SUSPEND ON DATABASE DECLARE /* declare transaction in this trigger is autonomous */ /* this is not required because transactions within a trigger are always autonomous */ PRAGMA AUTONOMOUS_TRANSACTION; cur_sid NUMBER; cur_inst NUMBER; errno NUMBER; err_type VARCHAR2; object_owner VARCHAR2; object_type VARCHAR2; table_space_name VARCHAR2; object_name VARCHAR2; sub_object_name VARCHAR2; error_txt VARCHAR2; msg_body VARCHAR2; ret_value BOOLEAN; mail_conn UTL_SMTP.CONNECTION; BEGIN -- Get session ID SELECT DISTINCT(SID) INTO cur_SID FROM V$MYSTAT; -- Get instance number cur_inst := userenv('instance'); Managing Space for Schema Objects 14-23 Managing Resumable Space Allocation -- Get space error information ret_value := DBMS_RESUMABLE.SPACE_ERROR_INFO(err_type,object_type,object_owner, table_space_name,object_name, sub_object_name); /* -- If the error is related to rollback segments, log error, send email -- to DBA, and abort the statement. Otherwise, set timeout to 8 hours. --- sys.rbs_error is created by DBA manually and defined as -- sql_text VARCHAR2(1000), error_msg VARCHAR2(4000), -- suspend_time DATE) */ IF OBJECT_TYPE = 'ROLLBACK SEGMENT' THEN /* LOG ERROR */ INSERT INTO sys.rbs_error ( SELECT SQL_TEXT, ERROR_MSG, SUSPEND_TIME FROM DBMS_RESUMABLE WHERE SESSION_ID = cur_sid AND INSTANCE_ID = cur_inst ); SELECT ERROR_MSG INTO error_txt FROM DBMS_RESUMABLE WHERE SESSION_ID = cur_sid and INSTANCE_ID = cur_inst; -- Send email to receipient via UTL_SMTP package msg_body:='Subject: Space Error Occurred Space limit reached for rollback segment ' || object_name || on ' || TO_CHAR(SYSDATE, 'Month dd, YYYY, HH:MIam') || '. Error message was ' || error_txt; mail_conn := UTL_SMTP.OPEN_CONNECTION('localhost', 25); UTL_SMTP.HELO(mail_conn, 'localhost'); UTL_SMTP.MAIL(mail_conn, 'sender@localhost'); UTL_SMTP.RCPT(mail_conn, 'recipient@localhost'); UTL_SMTP.DATA(mail_conn, msg_body); UTL_SMTP.QUIT(mail_conn); -- Abort the statement DBMS_RESUMABLE.ABORT(cur_sid); ELSE -- Set timeout to 8 hours DBMS_RESUMABLE.SET_TIMEOUT(28800); END IF; /* commit autonomous transaction */ 14-24 Oracle9i Database Administrator’s Guide Deallocating Space COMMIT; END; Deallocating Space It is not uncommon to allocate space to a segment, only to find out later that it is not being used. For example, you can set PCTINCREASE to a high value, which could create a large extent that is only partially used. Or, you could explicitly overallocate space by issuing the ALTER TABLE ... ALLOCATE EXTENT statement. If you find that you have unused or overallocated space, you can release it so that the unused space can be used by other segments. This section describes aspects of deallocating unused space. Viewing the High Water Mark Prior to deallocation, you can use the DBMS_SPACE package, which contains a procedure (UNUSED_SPACE) that returns information about the position of the high water mark and the amount of unused space in a segment. Within a segment, the high water mark indicates the amount of used space, or space that had been formatted to receive data.You cannot release space below the high water mark (even if there is no data in the space you want to deallocate). However, if the segment is completely empty, you can release space using the TRUNCATE ... DROP STORAGE statement. For segments in locally managed tablespaces with segment space management specified as AUTO, the following output parameters still determine the high water mark, put their meaning is somewhat altered: ■ LAST_USED_EXTENT_FILE_ID ■ LAST_USED_EXTENT_BLOCK_ID ■ LAST_USED_BLOCK Specifically, it is possible for some blocks below the high water mark to be unformatted. Neither the UNUSED_SPACE nor the FREE_SPACE procedure of DBMS_SPACE accurately accounts for unused space when segment space management is specified as AUTO. Use the SPACE_USAGE procedure instead. See Also: Oracle9i Supplied PL/SQL Packages and Types Reference contains the description of the DBMS_SPACE package Managing Space for Schema Objects 14-25 Deallocating Space Issuing Space Deallocation Statements The following statements deallocate unused space in a segment (table, index or cluster). The KEEP clause is optional. ALTER TABLE table DEALLOCATE UNUSED KEEP integer; ALTER INDEX index DEALLOCATE UNUSED KEEP integer; ALTER CLUSTER cluster DEALLOCATE UNUSED KEEP integer; When you explicitly identify an amount of unused space to KEEP, this space is retained while the remaining unused space is deallocated. If the remaining number of extents becomes smaller than MINEXTENTS, the MINEXTENTS value changes to reflect the new number. If the initial extent becomes smaller, the INITIAL value changes to reflect the new size of the initial extent. If you do not specify the KEEP clause, all unused space (everything above the high water mark) is deallocated, as long as the size of the initial extent and MINEXTENTS are preserved. Thus, even if the high water mark occurs within the MINEXTENTS boundary, MINEXTENTS remains and the initial extent size is not reduced. You can verify the deallocated space is freed by examining the DBA_FREE_SPACE view. See Also: ■ ■ Oracle9i SQL Reference for details on the syntax and options associated with deallocating unused space Oracle9i Database Reference for more information about the DBA_ FREE_SPACE view Examples of Deallocating Space This section provides some space deallocation examples. Deallocating Space Example 1: A table consists of three extents. The first extent is 10K, the second is 20K, and the third is 30K. The high water mark is in the middle of the second extent, and there is 40K of unused space. Figure 14–3 illustrates the effect of issuing the following statement: ALTER TABLE dquon DEALLOCATE UNUSED; All unused space is deallocated, leaving table dquon with two remaining extents. The third extent disappears, and the second extent size is 10K. 14-26 Oracle9i Database Administrator’s Guide Deallocating Space Figure 14–3 Deallocating All Unused Space Unused space = 40K Table DQUON Extent 1 Extent 2 Extent 3 10K 20K 30K High water mark Before ALTER TABLE dquon DEALLOCATE UNUSED; After Table DQUON Extent 1 Extent 2 10K 10K But, if you had issued the following statement specifying the KEEP keyword, then 10K above the high water mark would be kept, and the rest of the unused space would be deallocated from dquon. ALTER TABLE dquon DEALLOCATE UNUSED KEEP 10K; In effect, the third extent is deallocated and the second extent remains intact. Figure 14–4 illustrates this situation. Managing Space for Schema Objects 14-27 Deallocating Space Figure 14–4 Deallocating Unused Space, KEEP 10K Unused space = 40K Table DQUON Extent 1 Extent 2 Extent 3 10K 20K 30K High water mark ALTER TABLE dquon DEALLOCATE UNUSED KEEP 10K; Before After Table DQUON Extent 1 Extent 2 10K 20K High water mark Further, if you deallocate all unused space from dquon and keep 20K, as specified in the following statement, the third extent is cut to 10K, and the size of the second extent remains the same. ALTER TABLE dquon DEALLOCATE UNUSED KEEP 20K; Deallocating Space Example 2: Consider the situation illustrated by Figure 14–3. Extent 3 is completely deallocated, and the second extent is left with 10K. Further, the size of the next allocated extent defaults to the size of the last completely deallocated extent, which in this case, is 30K. If this is not what you want, you can explicitly set the size of the next extent using the ALTER TABLE statement, specifying a new value for NEXT in the storage clause. The following statement sets the next extent size for table dquon to 20K: ALTER TABLE dquon STORAGE (NEXT 20K); 14-28 Oracle9i Database Administrator’s Guide Understanding Space Use of Datatypes Deallocating Space Example 3: To preserve the MINEXTENTS number of extents, DEALLOCATE can retain extents that were originally allocated to a segment. This capacity is influenced by the KEEP parameter and was explained earlier. If table dquon has a MINEXTENTS value of 2, the statements illustrated in Figure 14–3 and Figure 14–4 still yield the same results as shown, and further, the initial value of MINEXTENTS is preserved. However, if the MINEXTENTS value is 3, then the statement illustrated in Figure 14–4 produces the same result as shown (the third extent is removed), but the value of MINEXTENTS is changed to 2. However, the statement illustrated in Figure 14–3 does not produce the same result. In this case, the statement has no effect. Understanding Space Use of Datatypes When creating tables and other data structures, you need to know how much space they will require. Each datatype has different space requirements. The PL/SQL User’s Guide and Reference and Oracle9i SQL Reference contain extensive descriptions of datatypes and their space requirements. Managing Space for Schema Objects 14-29 Understanding Space Use of Datatypes 14-30 Oracle9i Database Administrator’s Guide 15 Managing Tables This chapter describes the various aspects of managing tables, and includes the following topics: ■ Guidelines for Managing Tables ■ Creating Tables ■ Altering Tables ■ Redefining Tables Online ■ Dropping Tables ■ Managing Index-Organized Tables ■ Managing External Tables ■ Viewing Information About Tables See Also: ■ ■ ■ Chapter 14, "Managing Space for Schema Objects" is recommended reading before attempting tasks in this chapter. Chapter 21, "General Management of Schema Objects" presents additional aspects of managing tables, such as specifying integrity constraints and analyzing tables. Chapter 17, "Managing Partitioned Tables and Indexes" discusses partitioned tables. Managing Tables 15-1 Guidelines for Managing Tables Guidelines for Managing Tables This section describes guidelines to follow when managing tables. Following these guidelines can make the management of your tables easier, and improve performance both when creating the table and later querying or updating it. The following topics are discussed: ■ Design Tables Before Creating Them ■ Specify How Data Block Space Is to Be Used ■ Specify the Location of Each Table ■ Consider Parallelizing Table Creation ■ Consider Using NOLOGGING When Creating Tables ■ Estimate Table Size and Set Storage Parameters ■ Plan for Large Tables ■ Table Restrictions Design Tables Before Creating Them Usually, the application developer is responsible for designing the elements of an application, including the tables. Database administrators are responsible for setting storage parameters and defining clusters for tables, based on information from the application developer about how the application works and the types of data expected. Working with your application developer, carefully plan each table so that the following occurs: ■ Tables are normalized. ■ Each column is of the proper datatype. ■ Columns that allow nulls are defined last, to conserve storage space. ■ Tables are clustered whenever appropriate, to conserve storage space and optimize performance of SQL statements. Clustered tables are the subject of Chapter 18, "Managing Clusters". Specify How Data Block Space Is to Be Used By specifying the PCTFREE and PCTUSED parameters during the creation of each table, you can affect the efficiency of space utilization and amount of space reserved 15-2 Oracle9i Database Administrator’s Guide Guidelines for Managing Tables for updates to the current data in the data blocks of a table’s data segment. The PCTFREE and PCTUSED parameters are discussed in "Managing Space in Data Blocks" on page 14-2. Note: When you create a table in a locally managed tablespace for which automatic segment-space management is enabled, the need to specify the PCTFREE (or FREELISTS) parameter is eliminated. Automatic segment-space management is specified at the tablespace level. The Oracle database server automatically and efficiently manages free and used space within objects created in such tablespaces. Locally managed tablespaces and automatic segment space management are discussed in "Locally Managed Tablespaces" on page 15-2. Specify the Location of Each Table If you have the proper privileges and tablespace quota, you can create a new table in any tablespace that is currently online. It is advisable to specify the TABLESPACE clause in a CREATE TABLE statement to identify the tablespace that is to store the new table. If you do not specify a tablespace in a CREATE TABLE statement, the table is created in your default tablespace. When specifying the tablespace to contain a new table, make sure that you understand implications of your selection. By properly specifying a tablespace during the creation of each table, you can: ■ Increase the performance of the database system ■ Decrease the time needed for database administration The following situations illustrate how specifying incorrect storage locations for schema objects can affect a database: ■ ■ If users’ objects are created in the SYSTEM tablespace, the performance of Oracle can suffer, since both data dictionary objects and user objects must contend for the same datafiles. If an application’s associated tables are arbitrarily stored in various tablespaces, the time necessary to complete administrative operations (such as backup and recovery) for that application’s data can be increased. Managing Tables 15-3 Guidelines for Managing Tables Chapter 24, "Managing Users and Resources" contains information about assigning default tablespaces and tablespace quotas to users. Consider Parallelizing Table Creation You can utilize parallel execution when creating tables using a subquery (AS SELECT) in the CREATE TABLE statement. Because multiple processes work together to create the table, performance of the table creation operation is improved. Parallelizing table creation is discussed in the section "Parallelizing Table Creation" on page 15-8. Consider Using NOLOGGING When Creating Tables To create a table most efficiently use the NOLOGGING clause in the CREATE TABLE ... AS SELECT statement. The NOLOGGING clause causes minimal redo information to be generated during the table creation. This has the following benefits: ■ Space is saved in the redo log files. ■ The time it takes to create the table is decreased. ■ Performance improves for parallel creation of large tables. The NOLOGGING clause also specifies that subsequent direct loads using SQL*Loader and direct load INSERT operations are not logged. Subsequent DML statements (UPDATE, DELETE, and conventional path insert) are unaffected by the NOLOGGING attribute of the table and generate redo. If you cannot afford to lose the table after you have created it (for example, you will no longer have access to the data used to create the table) you should take a backup immediately after the table is created. In some situations, such as for tables that are created for temporary use, this precaution may not be necessary. In general, the relative performance improvement of specifying NOLOGGING is greater for larger tables than for smaller tables. For small tables, NOLOGGING has little effect on the time it takes to create a table. However, for larger tables the performance improvement can be significant, especially when you are also parallelizing the table creation. Estimate Table Size and Set Storage Parameters Estimating the sizes of tables before creating them is useful for the following reasons: 15-4 Oracle9i Database Administrator’s Guide Guidelines for Managing Tables ■ ■ You can use the combined estimated size of tables, along with estimates for indexes, undo space, and redo log files, to determine the amount of disk space that is required to hold an intended database. From these estimates, you can make correct hardware purchases and other decisions. You can use the estimated size of an individual table to better manage the disk space that the table will use. When a table is created, you can set appropriate storage parameters and improve I/O performance of applications that use the table. For example, assume that you estimate the maximum size of a table before creating it. If you then set the storage parameters when you create the table, fewer extents are allocated for the table’s data segment, and all of the table’s data is stored in a relatively contiguous section of disk space. This decreases the time necessary for disk I/O operations involving this table. Whether or not you estimate table size before creation, you can explicitly set storage parameters when creating each table. (Clustered tables, discussed in Chapter 18, "Managing Clusters", automatically use the storage parameters of the cluster.) Any storage parameter that you do not explicitly set when creating or subsequently altering a table automatically uses the corresponding default storage parameter set for the tablespace in which the table resides. Storage parameters are discussed in "Setting Storage Parameters" on page 14-8. If you explicitly set the storage parameters for the extents of a table’s data segment, try to store the table’s data in a small number of large extents rather than a large number of small extents. Plan for Large Tables There are no limits on the physical size of tables and extents. You can specify the keyword UNLIMITED for MAXEXTENTS, thereby simplifying your planning for large objects, reducing wasted space and fragmentation, and improving space reuse. However, when the number of extents in a table grows very large, you can see an impact on performance when performing any operation requiring that table. Note: You cannot alter data dictionary tables to have MAXEXTENTS greater than the allowed block maximum. If you have large tables in your database, consider the following recommendations: ■ Separate the table from its indexes. Managing Tables 15-5 Creating Tables Place indexes in separate tablespaces from other objects, and on separate disks if possible. If you ever must drop and re-create an index on a very large table (such as when disabling and enabling a constraint, or re-creating the table), indexes isolated into separate tablespaces can often find contiguous space more easily than those in tablespaces that contain other objects. ■ Allocate sufficient temporary space. If applications that access the data in a very large table perform large sorts, ensure that enough space is available for large temporary segments (temporary segments always use the default STORAGE settings for their tablespaces). Table Restrictions Here are some restrictions to be aware of before you create tables: ■ ■ ■ ■ Tables containing object types cannot be imported into a pre-Oracle8 database. You cannot move types and extent tables to a different schema when the original data still exists in the database. You cannot merge an exported table into a preexisting table having the same name in a different schema. Oracle has a limit on the total number of columns that a table (or attributes that an object type) can have. See Oracle9i Database Reference for this limit. Further, when you create a table that contains user-defined type data, Oracle maps columns of user-defined type to relational columns for storing the user-defined type data. This causes additional relational columns to be created. This results in "hidden" relational columns that are not visible in a DESCRIBE table statement and are not returned by a SELECT * statement. Therefore, when you create an object table, or a relational table with columns of REF, varray, nested table, or object type, be aware that the total number of columns that Oracle actually creates for the table can be more than those you specify. See Also: Oracle9i Application Developer’s Guide - Object-Relational Features for more information about user-defined types Creating Tables To create a new table in your schema, you must have the CREATE TABLE system privilege. To create a table in another user’s schema, you must have the CREATE ANY TABLE system privilege. Additionally, the owner of the table must have a 15-6 Oracle9i Database Administrator’s Guide Creating Tables quota for the tablespace that contains the table, or the UNLIMITED TABLESPACE system privilege. Create tables using the SQL statement CREATE TABLE. This section contains the following topics: ■ Creating a Table ■ Creating a Temporary Table ■ Parallelizing Table Creation ■ Automatically Collecting Statistics on Tables See Also: Oracle9i SQL Reference for exact syntax of the CREATE TABLE and other SQL statements discussed in this chapter Creating a Table When you issue the following statement, you create a table named admin_emp in the hr schema and store it in the admin_tbs tablespace: CREATE TABLE empno ename job mgr hiredate sal comm deptno hr.admin_emp ( NUMBER(5) PRIMARY KEY, VARCHAR2(15) NOT NULL, VARCHAR2(10), NUMBER(5), DATE DEFAULT (sysdate), NUMBER(7,2), NUMBER(7,2), NUMBER(3) NOT NULL CONSTRAINT admin_dept_fkey REFERENCES hr.departments (department_id)) TABLESPACE admin_tbs STORAGE ( INITIAL 50K NEXT 50K MAXEXTENTS 10 PCTINCREASE 25 ); In this example, integrity constraints are defined on several columns of the table. Integrity constraints are discussed in "Managing Integrity Constraints" on page 21-14. Several segment attributes are also explicitly specified for the table. These are explained in Chapter 14, "Managing Space for Schema Objects". Managing Tables 15-7 Creating Tables Creating a Temporary Table It is also possible to create a temporary table. The definition of a temporary table is visible to all sessions, but the data in a temporary table is visible only to the session that inserts the data into the table. You use the CREATE GLOBAL TEMPORARY TABLE statement to create a temporary table. The ON COMMIT keywords indicate if the data in the table is transaction-specific (the default) or session-specific: ■ ■ ON COMMIT DELETE ROWS specifies that the temporary table is transaction specific and Oracle truncates the table (delete all rows) after each commit. ON COMMIT PRESERVE ROWS specifies that the temporary table is session specific and Oracle truncates the table when you terminate the session. This example creates a temporary table that is transaction specific: CREATE GLOBAL TEMPORARY TABLE admin_work_area (startdate DATE, enddate DATE, class CHAR(20)) ON COMMIT DELETE ROWS; Indexes can be created on temporary tables. They are also temporary and the data in the index has the same session or transaction scope as the data in the underlying table. See Also: ■ ■ Oracle9i Database Concepts for more information about temporary tables Oracle9i Application Developer’s Guide - Fundamentals for more examples of temporary table use Parallelizing Table Creation When you specify the AS SELECT clause when creating a table, you can utilize parallel execution. The CREATE TABLE ... AS SELECT statement contains two parts: a CREATE part (DDL) and a SELECT part (query). Oracle can parallelize both parts of the statement. The CREATE part is parallelized if one of the following is true: ■ ■ A PARALLEL clause is included in the CREATE TABLE ... AS SELECT statement An ALTER SESSION FORCE PARALLEL DDL statement is specified The query part is parallelized if all of the following are true: 15-8 Oracle9i Database Administrator’s Guide Creating Tables ■ ■ The query includes a parallel hint specification (PARALLEL or PARALLEL_ INDEX) or the CREATE part includes the PARALLEL clause or the schema objects referred to in the query have a PARALLEL declaration associated with them. At least one of the tables specified in the query requires either a full table scan or an index range scan spanning multiple partitions. If you parallelize the creation of a table, that table then has a parallel declaration (the PARALLEL clause) associated with it. Any subsequent DML or queries on the table, for which parallelization is possible, will attempt to use parallel execution. The following simple example parallelizes the creation of a table: CREATE TABLE hr.admin_emp_dept PARALLEL AS SELECT * FROM hr.employees WHERE department_id = 10; In this example the PARALLEL clause tells Oracle to select an optimum number of parallel execution servers when creating the table. See Also: ■ ■ ■ Oracle9i Database Concepts for more information about parallel execution Oracle9i Data Warehousing Guide for a more detailed discussion about using parallel execution "Managing Processes for Parallel Execution" on page 5-18 Automatically Collecting Statistics on Tables The PL/SQL package DBMS_STATS lets you generate and manage statistics for cost-based optimization. You can use this package to gather, modify, view, export, import, and delete statistics. You can also use this package to identify or name statistics that have been gathered. You enable DBMS_STATS to automatically gather statistics for a table by specifying the MONITORING clause in the CREATE (or ALTER) TABLE statement. Then, you can effect automated statistics gathering by, for example, setting up a recurring job (perhaps by using job queues) that invokes DBMS_STATS.GATHER_TABLE_STATS with the GATHER STALE option at an appropriate interval for your application. Monitoring tracks the approximate number of INSERT, UPDATE, and DELETE operations for the table since the last time statistics were gathered. Information Managing Tables 15-9 Altering Tables about how many rows are affected is maintained in the SGA, until periodically (about every three hours) SMON incorporates the data into the data dictionary. This data dictionary information is made visible through the DBA_TAB_ MODIFICATIONS,ALL_TAB_MODIFICATIONS, or USER_TAB_MODIFICATIONS views. Oracle uses these views to identify tables with stale statistics. Using the MONITORING clause and the DBMS_STATS package enables the optimizer to generate accurate execution plans. To disable monitoring of a table, specify the NOMONITORING clause. See Also: Oracle9i Database Performance Tuning Guide and Reference for a discussion of the exact mechanism for using the MONITORING clause and the DBMS_STATS package for gathering statistics Altering Tables You alter a table using the ALTER TABLE statement. To alter a table, the table must be contained in your schema, or you must have either the ALTER object privilege for the table or the ALTER ANY TABLE system privilege. The following are many of the reasons for altering a table: ■ To modify physical characteristics (PCTFREE, PCTUSED, INITRANS, MAXTRANS, or storage parameters) ■ To move the table to a new segment or tablespace ■ To explicitly allocate an extent or deallocate unused space ■ To add, drop, or rename columns, or modify an existing column’s definition (datatype, length, default value, and NOT NULL integrity constraint) ■ To modify the logging attributes of the table ■ To modify the CACHE/NOCACHE attributes ■ To add, modify or drop integrity constraints associated with the table ■ To enable or disable integrity constraints or triggers associated with the table ■ To modify the degree of parallelism for the table ■ To enable or disable statistics collection (MONITORING/NOMONITORING) ■ To rename a table ■ To add or modify index-organized table characteristics 15-10 Oracle9i Database Administrator’s Guide Altering Tables ■ To alter the characteristics of an external table ■ To add or modify LOB columns ■ To add or modify object type, nested table, or varray columns Some of the usages of the ALTER TABLE statement are presented in the following sections: ■ Altering Physical Attributes of a Table ■ Moving a Table to a New Segment or Tablespace ■ Manually Allocating Storage for a Table ■ Modifying an Existing Column’s Definition ■ Adding Table Columns ■ Renaming Table Columns ■ Dropping Table Columns Caution: Before altering a table, familiarize yourself with the consequences of doing so. The Oracle9i SQL Reference lists many of these consequences in the descriptions of the ALTER TABLE clauses. If a view, materialized view, trigger, domain index, function-based index, check constraint, function, procedure of package depends on a base table, the alteration of the base table or its columns can affect the dependent object. See "Managing Object Dependencies" on page 21-23 for information about how Oracle manages dependencies. Altering Physical Attributes of a Table When altering the data block space usage parameters (PCTFREE and PCTUSED) of a table, note that new settings apply to all data blocks used by the table, including blocks already allocated and subsequently allocated for the table. However, the blocks already allocated for the table are not immediately reorganized when space usage parameters are altered, but as necessary after the change. The data block storage parameters are described in "Managing Space in Data Blocks" on page 14-2. When altering the transaction entry settings (INITRANS, MAXTRANS) of a table, note that a new setting for INITRANS applies only to data blocks subsequently allocated Managing Tables 15-11 Altering Tables for the table, while a new setting for MAXTRANS applies to all blocks (already and subsequently allocated blocks) of a table. To better understand these transaction entry setting parameters, see "Specifying the Transaction Entry Parameters: INITRANS and MAXTRANS" on page 14-8. The storage parameters INITIAL and MINEXTENTS cannot be altered. All new settings for the other storage parameters (for example, NEXT, PCTINCREASE) affect only extents subsequently allocated for the table. The size of the next extent allocated is determined by the current values of NEXT and PCTINCREASE, and is not based on previous values of these parameters. Storage parameters are discussed in "Setting Storage Parameters" on page 14-8. Moving a Table to a New Segment or Tablespace The ALTER TABLE ... MOVE statement enables you to relocate data of a nonpartitioned table into a new segment, and optionally into a different tablespace for which you have quota. This statement also allows you to modify any of the table’s storage attributes, including those which cannot be modified using ALTER TABLE. The following statement moves the hr.admin_emp table to a new segment, specifying new storage parameters: ALTER TABLE hr.admin_emp MOVE STORAGE ( INITIAL 20K NEXT 40K MINEXTENTS 2 MAXEXTENTS 20 PCTINCREASE 0 ); If the table includes LOB column(s), this statement can be used to move the table along with LOB data and LOB index segments (associated with this table) which the user explicitly specifies. If not specified, the default is to not move the LOB data and LOB index segments. Manually Allocating Storage for a Table Oracle dynamically allocates additional extents for the data segment of a table, as required. However, perhaps you want to allocate an additional extent for a table explicitly. For example, in an Oracle Real Application Clusters environment, an extent of a table can be allocated explicitly for a specific instance. A new extent can be allocated for a table using the ALTER TABLE ... ALLOCATE EXTENT clause. 15-12 Oracle9i Database Administrator’s Guide Altering Tables You can also explicitly deallocate unused space using the DEALLOCATE UNUSED clause of ALTER TABLE. This is described in "Deallocating Space" on page 14-25. See Also: Oracle9i Real Application Clusters Administration for information about using the ALLOCATE EXTENT clause in an Oracle Real Application Clusters environment Modifying an Existing Column’s Definition Use the ALTER TABLE ... MODIFY statement to modify an existing column’s definition. You can modify a column’s datatype, default value, or column constraint. You can increase the length of an existing column, or decrease it, if all existing data satisfies the new length. You can change a column from byte semantics to CHAR semantics or vice versa. You must set the initialization parameter BLANK_ TRIMMING=TRUE to decrease the length of a nonempty CHAR column. If you are modifying a table to increase the length of a column of datatype CHAR, realize that this can be a time consuming operation and can require substantial additional storage, especially if the table contains many rows. This is because the CHAR value in each row must be blank-padded to satisfy the new column length. Oracle9i SQL Reference for additional information about modifying table columns and additional restrictions See Also: Adding Table Columns To add a column to an existing table, use the ALTER TABLE ... ADD statement. The following statement alters the hr.admin_emp table to add a new column named bonus: ALTER TABLE hr.admin_emp ADD (bonus NUMBER (7,2)); If a new column is added to a table, the column is initially NULL unless you specify the DEFAULT clause. When you specify a default value, Oracle updates each row in the new column with the values specified. You can add a column with a NOT NULL constraint to a table only if the table does not contain any rows, or you specify a default value. Oracle9i SQL Reference for additional information about adding table columns and additional restrictions See Also: Managing Tables 15-13 Altering Tables Renaming Table Columns Oracle allows you to rename existing columns in a table. Use the RENAME COLUMN clause of the ALTER TABLE statement to rename a column. The new name must not conflict with the name of any existing column in the table. No other clauses are allowed in conjunction with the RENAME COLUMN clause. The following statement renames the comm column of the hr.admin_emp table. ALTER TABLE hr.admin_emp RENAME COLUMN comm TO commission; As noted earlier, altering a table’s column can invalidate dependent objects. However, when you rename a column, Oracle updates associated data dictionary tables to ensure that function-based indexes and check constraints remain valid. Oracle also allows you to rename column constraints. This is discussed in "Renaming Constraints" on page 21-19. Note: The RENAME TO clause of ALTER TABLE appears similar in syntax to the RENAME COLUMN clause, but is used for renaming the table itself. Dropping Table Columns You can drop columns that are no longer needed from a table, including an index-organized table. This provides a convenient means to free space in a database, and avoids your having to export/import data then re-create indexes and constraints. You cannot drop all columns from a table, nor can you drop columns from a table owned by SYS. Any attempt to do so results in an error. Oracle9i SQL Reference for information about additional restrictions and options for dropping columns from a table See Also: Removing Columns from Tables When you issue an ALTER TABLE ... DROP COLUMN statement, the column descriptor and the data associated with the target column are removed from each row in the table. You can drop multiple columns with one statement. The following statements are examples of dropping columns from the hr.admin_emp table. This statement drops only the sal column: 15-14 Oracle9i Database Administrator’s Guide Altering Tables ALTER TABLE hr.admin_emp DROP COLUMN sal; The following statement drops both the bonus and comm columns: ALTER TABLE hr.admin_emp DROP (bonus, commission); Marking Columns Unused If you are concerned about the length of time it could take to drop column data from all of the rows in a large table, you can use the ALTER TABLE ... SET UNUSED statement. This statement marks one or more columns as unused, but does not actually remove the target column data or restore the disk space occupied by these columns. However, a column that is marked as unused is not displayed in queries or data dictionary views, and its name is removed so that a new column can reuse that name. All constraints, indexes, and statistics defined on the column are also removed. To mark the hiredate and mgr columns as unused, execute the following statement: ALTER TABLE hr.admin_emp SET UNUSED (hiredate, mgr); You can later remove columns that are marked as unused by issuing an ALTER TABLE ... DROP UNUSED COLUMNS statement. Unused columns are also removed from the target table whenever an explicit drop of any particular column or columns of the table is issued. The data dictionary views USER_UNUSED_COL_TABS, ALL_UNUSED_COL_TABS, or DBA_UNUSED_COL_TABS can be used to list all tables containing unused columns. The COUNT field shows the number of unused columns in the table. SELECT * FROM DBA_UNUSED_COL_TABS; OWNER TABLE_NAME COUNT --------------------------- --------------------------- ----HR ADMIN_EMP 2 Removing Unused Columns The ALTER TABLE ... DROP UNUSED COLUMNS statement is the only action allowed on unused columns. It physically removes unused columns from the table and reclaims disk space. In the example that follows the optional keyword CHECKPOINT is specified. This option causes a checkpoint to be applied after processing the specified number of rows, in this case 250. Checkpointing cuts down on the amount of undo logs Managing Tables 15-15 Redefining Tables Online accumulated during the drop column operation to avoid a potential exhaustion of undo space. ALTER TABLE hr.admin_emp DROP UNUSED COLUMNS CHECKPOINT 250; Redefining Tables Online In highly available systems, it is occasionally necessary to redefine large "hot" tables to improve the performance of queries or DML performed against these tables. Oracle provide a mechanism to redefine tables online. This mechanism provides a significant increase in availability compared to traditional methods of redefining tables that require tables to be taken offline. When a table is redefined online, it is accessible to DML during much of the redefinition process. The table is locked in the exclusive mode only during a very small window which is independent of the size of the table and the complexity of the redefinition. This section contains the following topics: ■ Features of Online Table Redefinition ■ The DBMS_REDEFINITION Package ■ Steps for Online Redefinition of Tables ■ Intermediate Synchronization ■ Abort and Cleanup After Errors ■ Example of Online Table Redefinition ■ Restrictions Features of Online Table Redefinition Online table redefinition enables you to: ■ Modify the storage parameters of the table ■ Move the table to a different tablespace in the same schema ■ Add support for parallel queries ■ Add or drop partitioning support ■ Re-create the table to reduce fragmentation 15-16 Oracle9i Database Administrator’s Guide Redefining Tables Online ■ ■ Change the organization of a normal table (heap organized) to an index-organized table and vice versa Add or drop a column The DBMS_REDEFINITION Package The mechanism for performing online redefinition is the PL/SQL package DBMS_ REDEFINITION. Execute privileges on this package is granted to EXECUTE_ CATALOG_ROLE. In addition to having execute privileges on this package, you must be granted the following privileges: ■ CREATE ANY TABLE ■ ALTER ANY TABLE ■ DROP ANY TABLE ■ LOCK ANY TABLE ■ SELECT ANY TABLE See Also: Oracle9i Supplied PL/SQL Packages and Types Reference Steps for Online Redefinition of Tables In order to perform an online redefinition of a table the user must perform the following steps. 1. Choose one of the following two methods of redefinition: ■ ■ 2. The first method of redefinition, and the preferred method, is to use the primary keys to perform the redefinition. For this method, the pre-redefinition and the post-redefinition versions of the tables should have the same primary key columns. This is the default method of redefinition. The second method of redefinition is to use ROWIDs. For this method, the table to be redefined should not be an index organized table. Also, in this method of redefinition, a hidden column (M_ROW$$) is added to the post-redefined version of the table and it is recommended that this column be marked as unused or dropped after the redefinition is completed. Verify that the table can be online redefined by invoking the DBMS_ REDEFINITION.CAN_REDEF_TABLE() procedure and specifying the method of redefinition to be used. If the table is not a candidate for online redefinition, Managing Tables 15-17 Redefining Tables Online then this procedure raises an error indicating why the table cannot be online redefined. 3. Create an empty interim table (in the same schema as the table to be redefined) with all of the desired attributes. If columns are to be dropped, do not include them in the definition of the interim table. If a column is to be added, then add the column definition to the interim table. It is possible to perform table redefinition in parallel. If you specify a degree of parallelism on both of the tables and you ensure that parallel execution is enabled for the session, Oracle will use parallel execution whenever possible to perform the redefinition. 4. Start the redefinition process by calling DBMS_REDEFINITION.START_ REDEF_TABLE(), providing the following: ■ The table to be redefined ■ The interim table name ■ The column mapping ■ The method of redefinition If the column mapping information is not supplied, then it is assumed that all the columns (with their names unchanged) are to be included in the interim table. If the column mapping is supplied, then only those columns specified explicitly in the column mapping are considered. If the method of redefinition is not specified, then the default method of redefinition using primary keys is assumed. 5. Create any triggers, indexes, grants and constraints on the interim table. Any referential constraints involving the interim table (that is, the interim table is either a parent or a child table of the referential constraint) must be created disabled. Until the redefinition process is either completed or aborted, any trigger defined on the interim table will not execute. When the redefinition is completed, the triggers, constraints, indexes and grants associated with the interim table replace those on the table being redefined. The referential constraints involving the interim table (created disabled) transfer to the table being redefined and become enabled after the redefinition is complete. 6. Execute the DBMS_REDEFINITION.FINISH_REDEF_TABLE() procedure to complete the redefinition of the table. During this procedure, the original table is locked in the exclusive mode for a very small window. This window is independent of the amount of data in the original table. Also, as part of this procedure, the following occurs: 15-18 Oracle9i Database Administrator’s Guide Redefining Tables Online 7. a. The original table is redefined such that it has all the attributes, indexes, constraints, grants and triggers of the interim table b. The referential constraints involving the interim table now involve the post redefined table and are enabled. Optionally, rename any indexes, triggers, and constraints that were created on the interim table and that are now defined on the redefined table. If the redefinition was done using ROWIDs, the post-redefined table will have a hidden column (M_ROW$$) and it is recommended that the user set this hidden column to unused as follows: ALTER TABLE table_name SET UNUSED (M_ROW$$) 8. The following is the end result of the redefinition process: ■ ■ ■ ■ The original table is redefined with the attributes and features of the interim table. The triggers, grants, indexes and constraints defined on the interim table after START_REDEF_TABLE() and before FINISH_REDEF_TABLE() are now defined on the post-redefined table. Any referential constraints involving the interim table before the redefinition process was finished now involve the post-redefinition table and are enabled. Any indexes, triggers, grants and constraints defined on the original table (prior to redefinition) are transferred to the interim table and are dropped when the user drops the interim table. Any referential constraints involving the original table before the redefinition now involve the interim table and are disabled. Any PL/SQL procedures and cursors defined on the original table (prior to redefinition) are invalidated. They are automatically revalidated (this revalidation can fail if the shape of the table was changed as a result of the redefinition process) whenever they are used next. Intermediate Synchronization After the redefinition process has been started by calling START_REDEF_TABLE() and before FINISH_REDEF_TABLE() has been called, it is possible that a large number of DML statements have been executed on the original table. If you know this is the case, it is recommended that you periodically synchronize the interim table with the original table. This is done by calling the DBMS_ REDEFINITION.SYNC_INTERIM_TABLE() procedure. Calling this procedure Managing Tables 15-19 Redefining Tables Online reduces the time taken by FINISH_REDEF_TABLE() to complete the redefinition process. The small amount of time that the original table is locked during FINISH_REDEF_ TABLE() is independent of whether SYNC_INTERIM_TABLE() has been called. Abort and Cleanup After Errors In the event that an error is raised during the redefinition process, or if you choose to abort the redefinition process, call DBMS_REDEFINITION.ABORT_REDEF_ TABLE(). This procedure drops temporary logs and tables associated with the redefinition process. After this procedure is called, the user can drop the interim table and its associated objects. Example of Online Table Redefinition This example illustrates online redefinition of the previously created table hr.admin_emp, which at this point only contains columns: empno, ename, job, deptno. The table is redefined as follows: ■ New columns mgr, hiredate, sal, and bonus (these existed in the original table but were dropped in previous examples) are added. ■ The new column bonus is initialized to 0 ■ The column deptno has it’s value increased by 10. ■ The redefined table is partitioned by range on empno. The steps in this redefinition are illustrated below. 1. Verify that the table is a candidate for online redefinition. BEGIN DBMS_REDEFINITION.CAN_REDEF_TABLE('hr','admin_emp', dbms_redefinition.cons_use_pk); END; / 2. Create an interim table hr.int_admin_emp. CREATE TABLE hr.int_admin_emp (empno NUMBER(5) PRIMARY KEY, ename VARCHAR2(15) NOT NULL, job VARCHAR2(10), mgr NUMBER(5), hiredate DATE DEFAULT (sysdate), 15-20 Oracle9i Database Administrator’s Guide Redefining Tables Online sal NUMBER(7,2), deptno NUMBER(3) NOT NULL, bonus NUMBER (7,2) DEFAULT(1000)) PARTITION BY RANGE(empno) (PARTITION emp1000 VALUES LESS THAN (1000) TABLESPACE admin_tbs, PARTITION emp2000 VALUES LESS THAN (2000) TABLESPACE admin_tbs2); 3. Start the redefinition process. BEGIN DBMS_REDEFINITION.START_REDEF_TABLE('hr', 'admin_emp','int_admin_emp', 'empno empno, ename ename, job job, deptno+10 deptno, 0 bonus', dbms_redefinition.cons_use_pk); END; / 4. Create any triggers, indexes and constraints on hr.int_admin_emp. During the final step of redefinition, these are transferred back to the original table. Any referential constraints involved on hr.int_admin_emp should be disabled. You can define any grants associated with the interim table. These replace the grants on the original table after the redefinition. ALTER TABLE hr.int_admin_emp ADD CONSTRAINT admin_dept_fkey2 FOREIGN KEY (deptno) REFERENCES hr.departments (department_id); ALTER TABLE hr.int_admin_emp MODIFY CONSTRAINT admin_dept_fkey2 DISABLE KEEP INDEX; The disabled constraint, admin_dept_fkey2, will be enabled automatically as part of the finish redefinition process and will then involve the newly redefined admin_emp table. 5. Optionally, synchronize the interim table hr.int_admin_emp. BEGIN DBMS_REDEFINITION.SYNC_INTERIM_TABLE('hr', 'admin_emp', 'int_admin_emp'); END; / 6. Complete the redefinition. BEGIN DBMS_REDEFINITION.FINISH_REDEF_TABLE('hr', 'admin_emp', 'int_admin_emp'); END; / Managing Tables 15-21 Redefining Tables Online The table hr.admin_emp is locked in the exclusive mode only for a small window toward the end of this step. After this call the table hr.admin_emp is redefined such that it has all the attributes of the hr.int_admin_emp table. 7. Drop the interim table. Restrictions The following restrictions apply to the online redefinition of tables: ■ ■ ■ ■ ■ ■ ■ If the table is to be redefined using primary keys, then the table to be redefined and the post-redefinition table must have the same primary key columns. If the table is to be redefined using ROWIDs, then the table must not be an index-organized table. Tables that have materialized views and materialized view logs defined on them cannot be online redefined. Tables that are materialized view container tables and Advanced Queuing tables cannot be online redefined. The overflow table of an index-organized table cannot be online redefined. Tables with user-defined types (objects, REFs, collections, typed tables) cannot be online redefined. Tables with BFILE columns cannot be online redefined. Tables with LONG columns cannot be online redefined. Tables with LOB columns are acceptable. ■ The table to be redefined cannot be part of a cluster. ■ Tables in the SYS and SYSTEM schema cannot be online redefined. ■ Temporary tables cannot be redefined. ■ There is no horizontal subsetting support. ■ ■ ■ Only simple deterministic expressions can be used when mapping the columns in the interim table to those of the original table. For example, subqueries are not allowed. If new columns (which are not instantiated with existing data for the original table) are being added as part of the redefinition, then they must not be declared NOT NULL until the redefinition is complete. There cannot be any referential constraints between the table being redefined and the interim table. 15-22 Oracle9i Database Administrator’s Guide Dropping Tables ■ Table redefinition cannot be done NOLOGGING. Dropping Tables To drop a table, the table must be contained in your schema or you must have the DROP ANY TABLE system privilege. To drop a table that is no longer needed, use the DROP TABLE statement. The following statement drops the hr.int_admin_emp table: DROP TABLE hr.int_admin_emp; If the table to be dropped contains any primary or unique keys referenced by foreign keys of other tables and you intend to drop the FOREIGN KEY constraints of the child tables, include the CASCADE clause in the DROP TABLE statement, as shown below: DROP TABLE hr.admin_emp CASCADE CONSTRAINTS; Caution: Before dropping a table, familiarize yourself with the consequences of doing so: ■ ■ ■ ■ ■ Dropping a table removes the table definition from the data dictionary. All rows of the table are no longer accessible. All indexes and triggers associated with a table are dropped. All views and PL/SQL program units dependent on a dropped table remain, yet become invalid (not usable). See "Managing Object Dependencies" on page 21-23 for information about how Oracle manages dependencies. All synonyms for a dropped table remain, but return an error when used. All extents allocated for a table that is dropped are returned to the free space of the tablespace and can be used by any other object requiring new extents or new objects. All rows corresponding to a clustered table are deleted from the blocks of the cluster. Clustered tables are the subject of Chapter 18, "Managing Clusters". Perhaps instead of dropping a table, you want to truncate it. The TRUNCATE statement provides a fast, efficient method for deleting all rows from a table, but it Managing Tables 15-23 Managing Index-Organized Tables does not affect any structures associated with the table being truncated (column definitions, constraints, triggers, and so forth) or authorizations. The TRUNCATE statement is discussed in "Truncating Tables and Clusters" on page 21-9. Managing Index-Organized Tables This section describes aspects of managing index-organized tables, and includes the following topics: ■ What are Index-Organized Tables ■ Creating Index-Organized Tables ■ Maintaining Index-Organized Tables ■ Analyzing Index-Organized Tables ■ Using the ORDER BY Clause with Index-Organized Tables ■ Converting Index-Organized Tables to Regular Tables What are Index-Organized Tables An index-organized table has a storage organization that is a variant of a primary B-tree. Unlike an ordinary (heap-organized) table whose data is stored as an unordered collection (heap), data for an index-organized table is stored in a B-tree index structure in a primary key sorted manner. Besides storing the primary key column values of an index-organized table row, each index entry in the B-tree stores the nonkey column values as well. Why use Index-Organized Tables Index-organized tables provide fast key-based access to table data for queries involving exact match and range searches. Changes to the table data (such as adding new rows, updating rows, or deleting rows) result only in updating the index structure (because there is no separate table storage area). Also, storage requirements are reduced because key columns are not duplicated in the table and index. The remaining nonkey columns are stored in the index structure. Index-organized tables are particularly useful when you are using applications that must retrieve data based on a primary key. Index-organized tables are also suitable for modeling application-specific index structures. For example, content-based 15-24 Oracle9i Database Administrator’s Guide Managing Index-Organized Tables information retrieval applications containing text, image and audio data require inverted indexes that can be effectively modeled using index-organized tables. Differences Between Index Organized and Regular Tables As shown in Figure 15–1, the index-organized table is somewhat similar to a configuration consisting of an ordinary table and an index on one or more of the table columns, but instead of maintaining two separate storage structures, one for the table and one for the B-tree index, the database system maintains only a single B-tree index. Also, rather than having a row's rowid stored in the index entry, the nonkey column values are stored. Thus, each B-tree index entry contains: primary_key_value, non_primary_key_column_values Figure 15–1 Structure of Regular Table versus an Index-Organized Table Regular Table and Index Index-Organized Table Table Index Finance ROWID Invest ROWID Finance Invest 5543 6879 Index Finance 5543 Invest 6879 Table Data Stored in Index Applications manipulate the index-organized table just like an ordinary table, using SQL statements. However, the database system performs all operations by manipulating the corresponding B-tree index. See Also: ■ ■ Oracle9i Database Concepts for more details about index-organized tables Oracle9i SQL Reference for details of the syntax involved in creating index-organized tables Creating Index-Organized Tables You use the CREATE TABLE statement to create index-organized tables, but you must provide the following additional information: Managing Tables 15-25 Managing Index-Organized Tables ■ ■ ■ ■ An ORGANIZATION INDEX qualifier, which indicates that this is an index-organized table A primary key, specified through a column constraint clause (for a single column primary key) or a table constraint clause (for a multiple-column primary key). A primary key must be specified for index-organized tables. An optional row overflow specification clause (OVERFLOW), which preserves dense clustering of the B-tree index by storing the row column values exceeding a specified threshold in a separate overflow data segment. An INCLUDING clause can also be specified to specify what (nonkey) columns are to be stored in the overflow data segment. A PCTTHRESHOLD value which defines the percentage of space reserved in the index block for an index-organized table. Any portion of the row that exceeds the specified threshold is stored in the overflow segment. In other words, the row is broken at a column boundary into two pieces, a head piece and tail piece. The head piece fits in the specified threshold and is stored along with the key in the index leaf block. The tail piece is stored in the overflow area as one or more row pieces. Thus, the index entry contains the key value, the nonkey column values that fit the specified threshold, and a pointer to the rest of the row. The following example creates an index-organized table: CREATE TABLE admin_docindex( token char(20), doc_id NUMBER, token_frequency NUMBER, token_offsets VARCHAR2(512), CONSTRAINT pk_admin_docindex PRIMARY KEY (token, doc_id)) ORGANIZATION INDEX TABLESPACE admin_tbs PCTTHRESHOLD 20 OVERFLOW TABLESPACE admin_tbs2; The above example shows that the ORGANIZATION INDEX qualifier specifies an index-organized table, where the key columns and nonkey columns reside in an index defined on columns that designate the primary key (token, doc_id) for the table. Index-organized tables can store object types. The following example creates object type admin_typ, then creates an index-organized table containing a column of object type admin_typ: CREATE OR REPLACE TYPE admin_typ AS OBJECT (col1 NUMBER, col2 VARCHAR2(6)); 15-26 Oracle9i Database Administrator’s Guide Managing Index-Organized Tables CREATE TABLE admin_iot (c1 NUMBER primary key, c2 admin_typ) ORGANIZATION INDEX; You can also create an index-organized table of object types. For example: CREATE TABLE admin_iot2 OF admin_typ (col1 PRIMARY KEY) ORGANIZATION INDEX; See Also: "Creating Partitioned Index-Organized Tables" on page 17-19 for information about creating partitioned index-organized tables Using the AS Subquery You can create an index-organized table using the AS subquery. Creating an index-organized table in this manner enables you to load the table in parallel by using the PARALLEL option. The following statement creates an index-organized table (in parallel) by selecting rows from the conventional table hr.jobs: CREATE TABLE admin_iot3(i PRIMARY KEY, j, k, l) ORGANIZATION INDEX PARALLEL (DEGREE 2) AS SELECT * FROM hr.jobs; Using the Overflow Clause The overflow clause specified in the earlier example indicates that any nonkey columns of rows exceeding 20% of the block size are placed in a data segment stored in the admin_tbs2 tablespace. The key columns should fit the specified threshold. If an update of a nonkey column causes the row to decrease in size, Oracle identifies the row piece (head or tail) to which the update is applicable and rewrites that piece. If an update of a nonkey column causes the row to increase in size, Oracle identifies the piece (head or tail) to which the update is applicable and rewrites that row piece. If the update’s target turns out to be the head piece, note that this piece can again be broken into 2 to keep the row size below the specified threshold. The nonkey columns that fit in the index leaf block are stored as a row head-piece that contains a ROWID field linking it to the next row piece stored in the overflow data segment. The only columns that are stored in the overflow area are those that do not fit. Managing Tables 15-27 Managing Index-Organized Tables Choosing and Monitoring a Threshold Value You should choose a threshold value that can accommodate your key columns, as well as the first few nonkey columns (if they are frequently accessed). After choosing a threshold value, you can monitor tables to verify that the value you specified is appropriate. You can use the ANALYZE TABLE ... LIST CHAINED ROWS statement to determine the number and identity of rows exceeding the threshold value. See Also: Oracle9i SQL Reference for details about this use of the ANALYZE statement Using the INCLUDING clause In addition to specifying PCTTHRESHOLD, you can use the INCLUDING clause to control which nonkey columns are stored with the key columns. Oracle accommodates all nonkey columns up to the column specified in the INCLUDING clause in the index leaf block, provided it does not exceed the specified threshold. All nonkey columns beyond the column specified in the INCLUDING clause are stored in the overflow area. Note: Oracle moves all primary key columns of an indexed-organized table to the beginning of the table (in their key order), in order to provide efficient primary key based access. As an example: CREATE TABLE admin_iot4(a INT, b INT, c INT, d INT, primary key(c,b)) ORGANIZATION INDEX; The stored column order is: c b a d (instead of: a b c d). The last primary key column is b, based on the stored column order. The INCLUDING column can be the last primary key column (b in this example), or any nonkey column (that is, any column after b in the stored column order). The example presented earlier can be modified to create an index-organized table where the token_offsets column value is always stored in the overflow area: CREATE TABLE admin_docindex2( token CHAR(20), doc_id NUMBER, token_frequency NUMBER, token_offsets VARCHAR2(512), CONSTRAINT pk_admin_docindex2 PRIMARY KEY (token, doc_id)) 15-28 Oracle9i Database Administrator’s Guide Managing Index-Organized Tables ORGANIZATION INDEX TABLESPACE admin_tbs PCTTHRESHOLD 20 INCLUDING token_frequency OVERFLOW TABLESPACE admin_tbs2; Here, only nonkey columns prior to token_offsets (in this case a single column only) are stored with the key column values in the index leaf block. Using Key Compression Creating an index-organized table using key compression enables you to eliminate repeated occurrences of key column prefix values. Key compression breaks an index key into a prefix and a suffix entry. Compression is achieved by sharing the prefix entries among all the suffix entries in an index block. This sharing can lead to huge savings in space, allowing you to store more keys in each index block while improving performance. You can enable key compression using the COMPRESS clause while: ■ creating an index-organized table ■ moving an index-organized table You can also specify the prefix length (as the number of key columns), which identifies how the key columns are broken into a prefix and suffix entry. CREATE TABLE admin_iot5(i INT, j INT, k INT, l INT, PRIMARY KEY (i, j, k)) ORGANIZATION INDEX COMPRESS; The preceding statement is equivalent to the following statement: CREATE TABLE admin_iot6(i INT, j INT, k INT, l INT, PRIMARY KEY(i, j, k)) ORGANIZATION INDEX COMPRESS 2; For the list of values (1,2,3), (1,2,4), (1,2,7), (1,3,5), (1,3,4), (1,4,4) the repeated occurrences of (1,2), (1,3) are compressed away. You can also override the default prefix length used for compression as follows: CREATE TABLE admin_iot7(i INT, j INT, k INT, l INT, PRIMARY KEY (i, j, k)) ORGANIZATION INDEX COMPRESS 1; For the list of values (1,2,3), (1,2,4), (1,2,7), (1,3,5), (1,3,4), (1,4,4), the repeated occurrences of 1 are compressed away. You can disable compression as follows: Managing Tables 15-29 Managing Index-Organized Tables ALTER TABLE admin_iot5 MOVE NOCOMPRESS; Oracle9i Database Concepts for more details about key compression See Also: Maintaining Index-Organized Tables Index-organized tables differ from regular tables only in physical organization; logically, they are manipulated in the same manner. You can use an index-organized table in place of a regular table in INSERT, SELECT, DELETE, and UPDATE statements. Altering Index-Organized Tables You can use the ALTER TABLE statement to modify physical and storage attributes for both primary key index and overflow data segments. All the attributes specified prior to the OVERFLOW keyword are applicable to the primary key index segment. All attributes specified after the OVERFLOW key word are applicable to the overflow data segment. For example, you can set the INITRANS of the primary key index segment to 4 and the overflow of the data segment INITRANS to 6 as follows: ALTER TABLE admin_docindex INITRANS 4 OVERFLOW INITRANS 6; You can also alter PCTTHRESHOLD and INCLUDING column values. A new setting is used to break the row into head and overflow tail pieces during subsequent operations. For example, the PCTHRESHOLD and INCLUDING column values can be altered for the admin_docindex table as follows: ALTER TABLE admin_docindex PCTTHRESHOLD 15 INCLUDING doc_id; By setting the INCLUDING column to doc_id, all the columns that follow token_ frequency and token_offsets, are stored in the overflow data segment. For index-organized tables created without an overflow data segment, you can add an overflow data segment by using the ADD OVERFLOW clause. For example, you can add an overflow segment to table admin_iot3 as follows: ALTER TABLE admin_iot3 ADD OVERFLOW TABLESPACE admin_tbs2; Moving (Rebuilding) Index-Organized Tables Because index-organized tables are primarily stored in a B-tree index, you can encounter fragmentation as a consequence of incremental updates. However, you can use the ALTER TABLE ... MOVE statement to rebuild the index and reduce this fragmentation. 15-30 Oracle9i Database Administrator’s Guide Managing Index-Organized Tables The following statement rebuilds the index-organized table admin_docindex: ALTER TABLE admin_docindex MOVE; You can rebuild index-organized tables online using the ONLINE keyword. The overflow data segment, if present, is rebuilt when the OVERFLOW keyword is specified. For example, to rebuild the admin_docindex table but not the overflow data segment, perform a move online as follows: ALTER TABLE admin_docindex MOVE ONLINE; To rebuild the admin_docindex table along with its overflow data segment perform the move online as shown in the following statement. This statement also illustrates moving both the table and overflow data segment to new tablespaces. ALTER TABLE admin_docindex MOVE TABLESPACE admin_tbs2 OVERFLOW TABLESPACE admin_tbs3; In this last example, an index organized table with a LOB column (CLOB) is built. Then the table is moved while the LOB index and data segment are rebuilt and moved to a new tablespace. CREATE TABLE admin_iot_lob (c1 number (6) primary key, admin_lob CLOB) ORGANIZATION INDEX LOB (admin_lob) STORE AS (TABLESPACE admin_tbs2); ALTER TABLE admin_iot_lob MOVE LOB (admin_lob) STORE AS (TABLESPACE admin_tbs3); Updating the Key Column A key column update is logically equivalent to deleting the row with the old key value and inserting the row with the new key value at the appropriate place to maintain the primary key order. Logically, in the following example, the admin_docindex table row for token='coins' and doc_id=10 is deleted and a new row for token='medals' and doc_id=10 is inserted: UPDATE admin_docindex SET token='medals' WHERE token='coins' and doc_id=10; Managing Tables 15-31 Managing Index-Organized Tables Analyzing Index-Organized Tables Just like conventional tables, index-organized tables are analyzed using the ANALYZE statement. For example, the following statement gathers statistics for the admin_docindex table: ANALYZE TABLE admin_docindex COMPUTE STATISTICS; Note: Oracle recommends that the DBMS_STATS package be used for collecting optimizer statistics. See "Analyzing Tables, Indexes, and Clusters" on page 21-3 for information about collecting optimizer statistics, and for information about using the ANALYZE statement to collect non-optimizer statistics, validate object structure, and list chained rows. The ANALYZE statement analyzes both the primary key index segment and the overflow data segment, and computes logical as well as physical statistics for the table. ■ ■ The logical statistics can be queried using USER_TABLES, ALL_TABLES or DBA_TABLES. You can query the physical statistics of the primary key index segment using USER_INDEXES, ALL_INDEXES or DBA_INDEXES (and using the primary key index name). For example, you can obtain the primary key index segment’s physical statistics for the table admin_docindex as follows: SELECT LAST_ANALYZED, BLEVEL,LEAF_BLOCKS, DISTINCT_KEYS FROM DBA_INDEXES WHERE INDEX_NAME= 'PK_ADMIN_DOCINDEX'; ■ You can query the physical statistics for the overflow data segment using the USER_TABLES, ALL_TABLES or DBA_TABLES. You can identify the overflow entry by searching for IOT_TYPE = 'IOT_OVERFLOW'. For example, you can obtain overflow data segment physical attributes associated with the admin_ docindex table as follows: SELECT LAST_ANALYZED, NUM_ROWS, BLOCKS, EMPTY_BLOCKS FROM DBA_TABLES WHERE IOT_TYPE='IOT_OVERFLOW' and IOT_NAME= 'ADMIN_DOCINDEX'; 15-32 Oracle9i Database Administrator’s Guide Managing External Tables Using the ORDER BY Clause with Index-Organized Tables If an ORDER BY clause only references the primary key column or a prefix of it, then the optimizer avoids the sorting overhead as the rows are returned sorted on the primary key columns. The following queries avoid sorting overhead because the data is already sorted on the primary key: SELECT * FROM admin_docindex2 ORDER BY token, doc_id; SELECT * FROM admin_docindex2 ORDER BY token; If, however, you have an ORDER BY clause on a suffix of the primary key column or non-primary key columns, additional sorting is required (assuming no other secondary indexes are defined). SELECT * FROM admin_docindex2 ORDER BY doc_id; SELECT * FROM admin_docindex2 ORDER BY token_frequency Converting Index-Organized Tables to Regular Tables You can convert index-organized tables to regular tables using the Oracle IMPORT or EXPORT utilities, or the CREATE TABLE ... AS SELECT statement. To convert an index-organized table to a regular table: ■ Export the index-organized table data using conventional path. ■ Create a regular table definition with the same definition. ■ Import the index-organized table data, making sure IGNORE=y (ensures that object exists error is ignored). Note: Before converting an index-organized table to a regular table, be aware that index-organized tables cannot be exported using pre-Oracle8 versions of the Export utility. See Also: Oracle9i Database Utilities for more details about using the IMPORT and EXPORT utilities Managing External Tables Oracle allows you read-only access to data in external tables. External tables are defined as tables that do not reside in the database, and can be in any format for Managing Tables 15-33 Managing External Tables which an access driver is provided. By providing Oracle with metadata describing an external table, Oracle is able to expose the data in the external table as if it were data residing in a regular database table. The external data can be queried directly and in parallel using SQL. You can, for example, select, join, or sort external table data. You can also create views and synonyms for external tables. However, no DML operations (UPDATE, INSERT, or DELETE) are possible, and no indexes can be created, on external tables. Note: The DBMS_STATS package can be used for gathering statistics for external tables. The ANALYZE statement is not supported for gathering statistics for external tables. For information about using the DBMS_STATS package, see Oracle9i Database Performance Tuning Guide and Reference The means of defining the metadata for external tables is through the CREATE TABLE ... ORGANIZATION EXTERNAL statement. This external table definition can be thought of as a view that allows running any SQL query against external data without requiring that the external data first be loaded into the database. An access driver is the actual mechanism used to read the external data in the table. Oracle provides an access driver for external tables. It allows the reading of data from external files using the Oracle loader technology. The ORACLE_LOADER access driver provides data mapping capabilities which are a subset of the control file syntax of SQL*Loader utility. Oracle’s external tables feature provides a valuable means for performing basic extraction, transformation, and transportation (ETT) tasks that are common for datawarehousing. These following sections discuss the DDL statements that are supported for external tables. Only DDL statements discussed are supported, and not all clauses of these statements are supported. ■ Creating External Tables ■ Altering External Tables ■ Dropping External Tables ■ System and Object Privileges for External Tables 15-34 Oracle9i Database Administrator’s Guide Managing External Tables See Also: ■ ■ Oracle9i Database Utilities contains more information about external tables and describes the access driver and its access parameters Oracle9i Data Warehousing Guide for information about using external tables in a datawarehousing environment Creating External Tables You create external tables using the ORGANIZATION EXTERNAL clause of the CREATE TABLE statement. You are not in fact creating a table; that is, an external table does not have any extents associated with it. Rather, you are creating metadata in the data dictionary that enables you to access external data. The following example creates an external table, then uploads the data to a database table. EXAMPLE: Creating an External Table and Loading Data The file empxt1.dat contains the following sample data: 360,Jane,Janus,ST_CLERK,121,17-MAY-2001,3000,0,50,jjanus 361,Mark,Jasper,SA_REP,145,17-MAY-2001,8000,.1,80,mjasper 362,Brenda,Starr,AD_ASST,200,17-MAY-2001,5500,0,10,bstarr 363,Alex,Alda,AC_MGR,145,17-MAY-2001,9000,.15,80,aalda The file empxt2.dat contains the following sample data: 401,Jesse,Cromwell,HR_REP,203,17-MAY-2001,7000,0,40,jcromwel 402,Abby,Applegate,IT_PROG,103,17-MAY-2001,9000,.2,60,aapplega 403,Carol,Cousins,AD_VP,100,17-MAY-2001,27000,.3,90,ccousins 404,John,Richardson,AC_ACCOUNT,205,17-MAY-2001,5000,0,110,jrichard The following SQL statements create an external table in the hr schema named admin_ext_employees and load its data into the hr.employees table. CONNECT / AS SYSDBA; -- Set up directories and grant access to hr CREATE OR REPLACE DIRECTORY admin_dat_dir AS '/net/dlsun301/private6/examples/submitted/ADMIN/flatfiles/data'; CREATE OR REPLACE DIRECTORY admin_log_dir AS '/net/dlsun301/private6/examples/submitted/ADMIN/flatfiles/log'; CREATE OR REPLACE DIRECTORY admin_bad_dir AS '/net/dlsun301/private6/examples/submitted/ADMIN/flatfiles/bad'; Managing Tables 15-35 Managing External Tables GRANT READ ON DIRECTORY admin_dat_dir TO hr; GRANT WRITE ON DIRECTORY admin_log_dir TO hr; GRANT WRITE ON DIRECTORY admin_bad_dir TO hr; -- hr connects CONNECT hr/hr -- create the external table CREATE TABLE admin_ext_employees (employee_id NUMBER(4), first_name VARCHAR2(20), last_name VARCHAR2(25), job_id VARCHAR2(10), manager_id NUMBER(4), hire_date DATE, salary NUMBER(8,2), commission_pct NUMBER(2,2), department_id NUMBER(4), email VARCHAR2(25) ) ORGANIZATION EXTERNAL ( TYPE ORACLE_LOADER DEFAULT DIRECTORY admin_dat_dir ACCESS PARAMETERS ( records delimited by newline badfile admin_bad_dir:'empxt%a_%p.bad' logfile admin_log_dir:'empxt%a_%p.log' fields terminated by ',' missing field values are null ( employee_id, first_name, last_name, job_id, manager_id, hire_date char date_format date mask "dd-mon-yyyy", salary, commission_pct, department_id, email ) ) LOCATION ('empxt1.dat', 'empxt2.dat') ) PARALLEL REJECT LIMIT UNLIMITED; -- enable parallel for loading (good if lots of data to load) ALTER SESSION ENABLE PARALLEL DML; -- load the data in hr employees table INSERT INTO employees (employee_id, first_name, last_name, job_id, manager_id, hire_date, salary, commission_pct, department_id, email) SELECT * FROM admin_ext_employees; 15-36 Oracle9i Database Administrator’s Guide Managing External Tables The following paragraphs contain descriptive information about this example. The first few statements in this example create the directory objects for the operating system directories that contain the data sources, and for the bad record and log files specified in the access parameters. You must also grant READ or WRITE directory object privileges, as appropriate. Note: When creating a directory object or BFILEs, ensure that the following conditions are met: ■ ■ ■ The operating system file must not be a symbolic or hard link. The operating system directory path named in the Oracle DIRECTORY object must be an existing OS directory path. The operating system directory path named in the Oracle DIRECTORY object should not contain any symbolic links in its components. The TYPE specification is given only to illustrate its use. If not specified, ORACLE_ LOADER is the default access driver. The access parameters, specified in the ACCESS PARAMETERS clause, are opaque to Oracle. These access parameters are defined by the access driver, and are provided to the access driver by Oracle when the external table is accessed. See Oracle9i Database Utilities for a description of the ORACLE_ LOADER access parameters. The PARALLEL clause enables parallel query on the data sources. The granule of parallelism is by default a data source, but parallel access within a data source is implemented whenever possible. For example, if PARALLEL=3 were specified, then more than one parallel execution server could be working on a data source. But, parallel access within a data source is provided by the access driver only if all of the following conditions are met: ■ The media allows random positioning within a data source ■ It is possible to find a record boundary from a random position ■ The data files are large enough to make it worthwhile to break up into multiple chunks Note: Specifying a PARALLEL clause is of value only when dealing with large amounts of data. Otherwise, it is not advisable to specify a PARALLEL clause, and doing so can be detrimental. Managing Tables 15-37 Managing External Tables The REJECT LIMIT clause specifies that there is no limit on the number of errors that can occur during a query of the external data. For parallel access, this limit applies to each parallel execution server independently. For example, if REJECT LIMIT 10 is specified, each parallel query process is allowed 10 rejections. Hence, the only precisely enforced values for REJECT LIMIT on parallel query are 0 and UNLIMITED. In this example, the INSERT INTO TABLE statement generates a dataflow from the external data source to the Oracle SQL engine where data is processed. As data is parsed by the access driver from the external table sources and provided to the external table interface, the external data is converted from its external representation to its Oracle internal data type. See Also: Oracle9i SQL Reference provides details of the syntax of the CREATE TABLE statement for creating external tables and specifies restrictions on the use of clauses Altering External Tables You can use any of the following ALTER TABLE clauses to change the characteristics of an external table. No other clauses are permitted. ALTER TABLE Clause Description Example REJECT LIMIT Changes the reject limit ALTER TABLE admin_ext_employees REJECT LIMIT 100; DEFAULT DIRECTORY Changes the default directory specification ALTER TABLE admin_ext_employees DEFAULT DIRECTORY admin_dat2_dir; ACCESS PARAMETERS Allows access parameters to be changed without dropping and re-creating the external table metadata ALTER TABLE admin_ext_employees ACCESS PARAMETERS (FIELDS TERMINATED BY ';'); LOCATION Allows data sources to be changed without dropping and re-creating the external table metadata ALTER TABLE admin_ext_employees LOCATION ('empxt3.txt', 'empxt4.txt'); PARALLEL No difference from regular tables. Allows degree of parallelism to be changed. No new syntax ADD COLUMN No difference from regular tables. Allows a column to be added to an external table. No new syntax 15-38 Oracle9i Database Administrator’s Guide Managing External Tables ALTER TABLE Clause Description Example MODIFY COLUMN No difference from regular tables. Allows an external table column to be modified. No new syntax DROP COLUMN No difference from regular tables. Allows an external table column to be dropped. No new syntax RENAME TO No difference from regular tables. Allows external table to be renamed. No new syntax Dropping External Tables For an external table, the DROP TABLE statement removes only the table metadata in the database. It has no affect on the actual data, which resides outside of the database. System and Object Privileges for External Tables System and object privileges for external tables are a subset of those for regular table. Only the following system privileges are applicable to external tables: ■ CREATE ANY TABLE ■ ALTER ANY TABLE ■ DROP ANY TABLE ■ SELECT ANY TABLE Only the following object privileges are applicable to external tables: ■ ALTER ■ SELECT However, object privileges associated with a directory are: ■ READ ■ WRITE For external tables, READ privileges are required on directory objects that contain data sources, while WRITE privileges are required for directory objects containing bad, log, or discard files. Managing Tables 15-39 Viewing Information About Tables Viewing Information About Tables The following views allow you to access information about tables. View Description DBA_TABLES DBA view describes all relational tables in the database. ALL view describes all tables accessible to the user. USER view is restricted to tables owned by the user. Some columns in these views contain statistics that are generated by the DBMS_STATS package or ANALYZE statement. ALL_TABLES USER_TABLES DBA_TAB_COLUMNS ALL_TAB_COLUMNS These views describe the columns of tables, views, and clusters in the database. Some columns in these views contain statistics that are generated by the DBMS_STATS package or ANALYZE statement. USER_TAB_COLUMNS DBA_ALL_TABLES ALL_ALL_TABLES These views describe all relational and object tables in the database. Object tables are not specifically discussed in this book. USER_ALL_TABLES DBA_TAB_COMMENTS ALL_TAB_COMMENTS These views display comments for tables and views. Comments are entered using the COMMENT statement. USER_TAB_COMMENTS DBA_COL_COMMENTS ALL_COL_COMMENTS These views display comments for table and view columns. Comments are entered using the COMMENT statement. USER_COL_COMMENTS DBA_EXTERNAL_TABLES These views list the specific attributes of external tables in the database. ALL_EXTERNAL_TABLES USER_EXTERNAL_TABLES DBA_EXTERNAL_LOCATIONS These views list the data sources for external tables. ALL_EXTERNAL_LOCATIONS USER_EXTERNAL_LOCATIONS DBA_TAB_HISTOGRAMS These views describe histograms on tables and views. ALL_TAB_HISTOGRAMS USER_TAB_HISTOGRAMS DBA_TAB_COL_STATISTICS ALL_TAB_COL_STATISTICS These views provide column statistics and histogram information extracted from the related TAB_COLUMNS views. USER_TAB_COL_STATISTICS 15-40 Oracle9i Database Administrator’s Guide Viewing Information About Tables View Description DBA_TAB_MODIFICATIONS These views describe tables that have been modified since the last time table statistics were gathered on them. The views are populated only for tables with the MONITORING attribute. They are not populated immediately, but after a time lapse (usually 3 hours). ALL_TAB_MODIFICATIONS USER_TAB_MODIFICATIONS These views list tables with unused columns, as marked by the ALTER TABLE ... SET UNUSED statement. DBA_UNUSED_COL_TABS ALL_UNUSED_COL_TABS USER_UNUSED_COL_TABS DBA_PARTIAL_DROP_TABS ALL_PARTIAL_DROP_TABS These views list tables that have partially completed DROP COLUMN operations. These operations could be incomplete because the operation was interrupted by the user or a system crash. USER_PARTIAL_DROP_TABS See Also: ■ ■ ■ ■ ■ "Viewing Information About Tables" on page 15-40 Oracle9i Database Reference for complete descriptions of these views Oracle9i Application Developer’s Guide - Object-Relational Features for information about object tables Oracle9i Database Performance Tuning Guide and Reference for information about histograms and generating statistics for tables "Analyzing Tables, Indexes, and Clusters" on page 21-3 Managing Tables 15-41 Viewing Information About Tables 15-42 Oracle9i Database Administrator’s Guide 16 Managing Indexes This chapter discusses the management of indexes, and contains the following topics: ■ Guidelines for Managing Indexes ■ Creating Indexes ■ Altering Indexes ■ Monitoring Space Use of Indexes ■ Dropping Indexes ■ Viewing Index Information See Also: Chapter 14, "Managing Space for Schema Objects" is recommended reading before attempting tasks described in this chapter. Managing Indexes 16-1 Guidelines for Managing Indexes Guidelines for Managing Indexes Indexes are optional structures associated with tables and clusters that allow SQL statements to execute more quickly against a table. Just as the index in this manual helps you locate information faster than if there were no index, an Oracle index provides a faster access path to table data. You can use indexes without rewriting any queries. Your results are the same, but you see them more quickly. Oracle provides several indexing schemes that provide complementary performance functionality. These are: ■ B-tree indexes—the default and the most common ■ B-tree cluster indexes—defined specifically for cluster ■ Hash cluster indexes—defined specifically for a hash cluster ■ Global and local indexes—relate to partitioned tables and indexes ■ ■ ■ ■ Reverse key indexes—most useful for Oracle Real Application Cluster applications Bitmap indexes—compact; work best for columns with a small set of values Function-based indexes—contain the precomputed value of a function/expression Domain indexes—specific to an application or cartridge. Indexes are logically and physically independent of the data in the associated table. Being independent structures, they require storage space. You can create or drop an index without affecting the base tables, database applications, or other indexes. Oracle automatically maintains indexes when you insert, update, and delete rows of the associated table. If you drop an index, all applications continue to work. However, access to previously indexed data might be slower. This section discusses guidelines for managing indexes and contains the following topics: 16-2 ■ Create Indexes After Inserting Table Data ■ Index the Correct Tables and Columns ■ Order Index Columns for Performance ■ Limit the Number of Indexes for Each Table ■ Drop Indexes That Are No Longer Required ■ Specify Index Block Space Use Oracle9i Database Administrator’s Guide Guidelines for Managing Indexes ■ Estimate Index Size and Set Storage Parameters ■ Specify the Tablespace for Each Index ■ Consider Parallelizing Index Creation ■ Consider Creating Indexes with NOLOGGING ■ Consider Costs and Benefits of Coalescing or Rebuilding Indexes ■ Consider Cost Before Disabling or Dropping Constraints See Also: ■ ■ ■ Oracle9i Database Concepts for conceptual information about indexes and indexing, including descriptions of the various indexing schemes offered by Oracle Oracle9i Database Performance Tuning Guide and Reference and Oracle9i Data Warehousing Guide for information about bitmap indexes Oracle9i Data Cartridge Developer’s Guide for information about defining domain-specific operators and indexing schemes and integrating them into the Oracle database server Create Indexes After Inserting Table Data Data is often inserted or loaded into a table using the either the SQL*Loader or Import utility. It is more efficient to create an index for a table after inserting or loading the data. If you create one or more indexes before loading data, Oracle then must update every index as each row is inserted. Creating an index on a table that already has data requires sort space. Some sort space comes from memory allocated for the index’s creator. The amount for each user is determined by the initialization parameter SORT_AREA_SIZE. Oracle also swaps sort information to and from temporary segments that are only allocated during the index creation in the users temporary tablespace. Under certain conditions, data can be loaded into a table with SQL*Loader’s direct path load and an index can be created as data is loaded. See Also: Oracle9i Database Utilities for information about using SQL*Loader for direct path load Managing Indexes 16-3 Guidelines for Managing Indexes Index the Correct Tables and Columns Use the following guidelines for determining when to create an index: ■ ■ Create an index if you frequently want to retrieve less than 15% of the rows in a large table. The percentage varies greatly according to the relative speed of a table scan and how clustered the row data is about the index key. The faster the table scan, the lower the percentage; the more clustered the row data, the higher the percentage. To improve performance on joins of multiple tables, index columns used for joins. Note: Primary and unique keys automatically have indexes, but you might want to create an index on a foreign key. ■ Small tables do not require indexes. If a query is taking too long, then the table might have grown from small to large. Some columns are strong candidates for indexing. Columns with one or more of the following characteristics are candidates for indexing: ■ Values are relatively unique in the column. ■ There is a wide range of values (good for regular indexes). ■ There is a small range of values (good for bitmap indexes). ■ The column contains many nulls, but queries often select all rows having a value. In this case, use the following phrase: WHERE COL_X > -9.99 * power(10,125) Using the above phrase is preferable to: WHERE COL_X IS NOT NULL This is because the first uses an index on COL_X (assuming that COL_X is a numeric column). Columns with the following characteristics are less suitable for indexing: ■ There are many nulls in the column and you do not search on the non-null values. LONG and LONG RAW columns cannot be indexed. 16-4 Oracle9i Database Administrator’s Guide Guidelines for Managing Indexes The size of a single index entry cannot exceed roughly one-half (minus some overhead) of the available space in the data block. Order Index Columns for Performance The order of columns in the CREATE INDEX statement can affect query performance. In general, specify the most frequently used columns first. If you create a single index across columns to speed up queries that access, for example, col1, col2, and col3; then queries that access just col1, or that access just col1 and col2, are also speeded up. But a query that accessed just col2, just col3, or just col2 and col3 does not use the index. Limit the Number of Indexes for Each Table A table can have any number of indexes. However, the more indexes there are, the more overhead is incurred as the table is modified. Specifically, when rows are inserted or deleted, all indexes on the table must be updated as well. Also, when a column is updated, all indexes that contain the column must be updated. Thus, there is a trade-off between the speed of retrieving data from a table and the speed of updating the table. For example, if a table is primarily read-only, having more indexes can be useful; but if a table is heavily updated, having fewer indexes could be preferable. Drop Indexes That Are No Longer Required Consider dropping an index if: ■ It does not speed up queries. The table could be very small, or there could be many rows in the table but very few index entries. ■ The queries in your applications do not use the index. ■ The index must be dropped before being rebuilt. See Also: "Monitoring Index Usage" on page 16-21 Specify Index Block Space Use When an index is created for a table, data blocks of the index are filled with the existing values in the table up to PCTFREE. The space reserved by PCTFREE for an index block is only used when a new row is inserted into the table and the Managing Indexes 16-5 Guidelines for Managing Indexes corresponding index entry must be placed in the correct index block (that is, between preceding and following index entries). If no more space is available in the appropriate index block, the indexed value is placed where it belongs (based on the lexical set ordering). Therefore, if you plan on inserting many rows into an indexed table, PCTFREE should be high to accommodate the new index values. If the table is relatively static without many inserts, PCTFREE for an associated index can be low so that fewer blocks are required to hold the index data. PCTUSED cannot be specified for indexes. See Also: "Managing Space in Data Blocks" on page 14-2 for information about the PCTFREE parameter Estimate Index Size and Set Storage Parameters Estimating the size of an index before creating one can facilitate better disk space planning and management. You can use the combined estimated size of indexes, along with estimates for tables, rollback segments, and redo log files, to determine the amount of disk space that is required to hold an intended database. From these estimates, you can make correct hardware purchases and other decisions. Use the estimated size of an individual index to better manage the disk space that the index uses. When an index is created, you can set appropriate storage parameters and improve I/O performance of applications that use the index. For example, assume that you estimate the maximum size of an index before creating it. If you then set the storage parameters when you create the index, fewer extents are allocated for the table’s data segment, and all of the index’s data is stored in a relatively contiguous section of disk space. This decreases the time necessary for disk I/O operations involving this index. The maximum size of a single index entry is approximately one-half the data block size. See Also: "Setting Storage Parameters" on page 14-8 for specific information about storage parameters Specify the Tablespace for Each Index Indexes can be created in any tablespace. An index can be created in the same or different tablespace as the table it indexes. If you use the same tablespace for a table and its index, it can be more convenient to perform database maintenance (such as 16-6 Oracle9i Database Administrator’s Guide Guidelines for Managing Indexes tablespace or file backup) or to ensure application availability. All the related data is always online together. Using different tablespaces (on different disks) for a table and its index produces better performance than storing the table and index in the same tablespace. Disk contention is reduced. But, if you use different tablespaces for a table and its index and one tablespace is offline (containing either data or index), then the statements referencing that table are not guaranteed to work. Consider Parallelizing Index Creation You can parallelize index creation, much the same as you can parallelize table creation. Because multiple processes work together to create the index, Oracle can create the index more quickly than if a single server process created the index sequentially. When creating an index in parallel, storage parameters are used separately by each query server process. Therefore, an index created with an INITIAL value of 5M and a parallel degree of 12 consumes at least 60M of storage during index creation. See Also: ■ ■ Oracle9i Database Concepts for more information about parallel execution Oracle9i Data Warehousing Guide for information about utilizing parallel execution in a datawarehousing environment Consider Creating Indexes with NOLOGGING You can create an index and generate minimal redo log records by specifying NOLOGGING in the CREATE INDEX statement. Note: Because indexes created using NOLOGGING are not archived, perform a backup after you create the index. Creating an index with NOLOGGING has the following benefits: ■ Space is saved in the redo log files. ■ The time it takes to create the index is decreased. ■ Performance improves for parallel creation of large indexes. Managing Indexes 16-7 Guidelines for Managing Indexes In general, the relative performance improvement is greater for larger indexes created without LOGGING than for smaller ones. Creating small indexes without LOGGING has little affect on the time it takes to create an index. However, for larger indexes the performance improvement can be significant, especially when you are also parallelizing the index creation. Consider Costs and Benefits of Coalescing or Rebuilding Indexes Improper sizing or increased growth can produce index fragmentation. To eliminate or reduce fragmentation, you can rebuild or coalesce the index. But before you perform either task weigh the costs and benefits of each option and choose the one that works best for your situation. Table 16–1 is a comparison of the costs and benefits associated with rebuilding and coalescing indexes. Table 16–1 To Rebuild or Coalesce ... That Is the Question Rebuild Index Coalesce Index Quickly moves index to another tablespace Cannot move index to another tablespace Higher costs: requires more disk space Lower costs: does not require more disk space Creates new tree, shrinks height if applicable Coalesces leaf blocks within same branch of tree Enables you to quickly change storage and tablespace parameters without having to drop the original index. Quickly frees up index leaf blocks for use. In situations where you have B-tree index leaf blocks that can be freed up for reuse, you can merge those leaf blocks using the following statement: ALTER INDEX vmoore COALESCE; Figure 16–1 illustrates the effect of an ALTER INDEX COALESCE on the index vmoore. Before performing the operation, the first two leaf blocks are 50% full. This means you have an opportunity to reduce fragmentation and completely fill the first block, while freeing up the second. In this example, assume that PCTFREE=0. 16-8 Oracle9i Database Administrator’s Guide Creating Indexes Figure 16–1 Coalescing Indexes B-tree Index Before ALTER INDEX vmoore COALESCE; B-tree Index After ALTER INDEX vmoore COALESCE; Consider Cost Before Disabling or Dropping Constraints Because unique and primary keys have associated indexes, you should factor in the cost of dropping and creating indexes when considering whether to disable or drop a UNIQUE or PRIMARY KEY constraint. If the associated index for a UNIQUE key or PRIMARY KEY constraint is extremely large, you can save time by leaving the constraint enabled rather than dropping and re-creating the large index. You also have the option of explicitly specifying that you want to keep or drop the index when dropping or disabling a UNIQUE or PRIMARY KEY constraint. See Also: "Managing Integrity Constraints" on page 21-14 Creating Indexes This section describes how to create indexes. To create an index in your own schema, at least one of the following conditions must be true: ■ The table or cluster to be indexed is in your own schema. ■ You have INDEX privilege on the table to be indexed. ■ You have CREATE ANY INDEX system privilege. To create an index in another schema, all of the following conditions must be true: ■ You have CREATE ANY INDEX system privilege. Managing Indexes 16-9 Creating Indexes ■ The owner of the other schema has a quota for the tablespaces to contain the index or index partitions, or UNLIMITED TABLESPACE system privilege. This section contains the following topics: ■ Creating an Index Explicitly ■ Creating a Unique Index Explicitly ■ Creating an Index Associated with a Constraint ■ Collecting Incidental Statistics when Creating an Index ■ Creating a Large Index ■ Creating an Index Online ■ Creating a Function-Based Index ■ Creating a Key-Compressed Index See Also: Oracle9i SQL Reference for syntax and restrictions on the use of the CREATE INDEX, ALTER INDEX, and DROP INDEX statements Creating an Index Explicitly You can create indexes explicitly (outside of integrity constraints) using the SQL statement CREATE INDEX. The following statement creates an index named emp_ ename for the ename column of the emp table: CREATE INDEX emp_ename ON emp(ename) TABLESPACE users STORAGE (INITIAL 20K NEXT 20k PCTINCREASE 75) PCTFREE 0; Notice that several storage settings and a tablespace are explicitly specified for the index. If you do not specify storage options (such as INITIAL and NEXT) for an index, the default storage options of the default or specified tablespace are automatically used. 16-10 Oracle9i Database Administrator’s Guide Creating Indexes Creating a Unique Index Explicitly Indexes can be unique or nonunique. Unique indexes guarantee that no two rows of a table have duplicate values in the key column (or columns). Nonunique indexes do not impose this restriction on the column values. Use the CREATE UNIQUE INDEX statement to create a unique index. The following example creates a unique index: CREATE UNIQUE INDEX dept_unique_index ON dept (dname) TABLESPACE indx; Alternatively, you can define UNIQUE integrity constraints on the desired columns. Oracle enforces UNIQUE integrity constraints by automatically defining a unique index on the unique key. This is discussed in the following section. However, it is advisable that any index that exists for query performance, including unique indexes, be created explicitly See Also: Oracle9i Database Performance Tuning Guide and Reference for more information about creating an index for performance Creating an Index Associated with a Constraint Oracle enforces a UNIQUE key or PRIMARY KEY integrity constraint on a table by creating a unique index on the unique key or primary key. This index is automatically created by Oracle when the constraint is enabled. No action is required by you when you issue the CREATE TABLE or ALTER TABLE statement to create the index, but you can optionally specify a USING INDEX clause to exercise control over its creation. This includes both when a constraint is defined and enabled, and when a defined but disabled constraint is enabled. To enable a UNIQUE or PRIMARY KEY constraint, thus creating an associated index, the owner of the table must have a quota for the tablespace intended to contain the index, or the UNLIMITED TABLESPACE system privilege. A constraint’s associated index always assumes the name of the constraint, unless you optionally specify otherwise. Specifying Storage Options for an Index Associated with a Constraint You can set the storage options for the indexes associated with UNIQUE and PRIMARY KEY constraints using the USING INDEX clause. The following CREATE TABLE statement enables a PRIMARY KEY constraint and specifies the associated index’s storage options: CREATE TABLE emp ( Managing Indexes 16-11 Creating Indexes empno NUMBER(5) PRIMARY KEY, age INTEGER) ENABLE PRIMARY KEY USING INDEX TABLESPACE users PCTFREE 0; Specifying the Index Associated with a Constraint If you require more explicit control over the indexes associated with UNIQUE and PRIMARY KEY constraints, Oracle allows you to: ■ ■ Specify an existing index that Oracle is to use to enforce the constraint Specify a create index statement that Oracle is to use to create the index and enforce the constraint These options are specified using the USING INDEX clause. The following statements present some examples. Example 1: CREATE TABLE a ( a1 INT PRIMARY KEY USING INDEX (create index ai on a (a1))); Example 2: CREATE TABLE b( b1 INT, b2 INT, CONSTRAINT bu1 UNIQUE (b1, b2) USING INDEX (create unique index bi on b(b1, b2)), CONSTRAINT bu2 UNIQUE (b2, b1) USING INDEX bi); Example 3: CREATE TABLE c(c1 INT, c2 INT); CREATE INDEX ci ON c (c1, c2); ALTER TABLE c ADD CONSTRAINT cpk PRIMARY KEY (c1) USING INDEX ci; If a single statement creates an index with one constraint and also uses that index for another constraint, the system will attempt to rearrange the clauses to create the index before reusing it. See Also: "Managing Integrity Constraints" on page 21-14 16-12 Oracle9i Database Administrator’s Guide Creating Indexes Collecting Incidental Statistics when Creating an Index Oracle provides you with the opportunity to collect statistics at very little resource cost during the creation or rebuilding of an index. These statistics are stored in the data dictionary for ongoing use by the optimizer in choosing a plan for the execution of SQL statements. The following statement computes index, table, and column statistics while building index emp_ename on column ename of table emp: CREATE INDEX emp_ename ON emp(ename) COMPUTE STATISTICS; See Also: ■ ■ Oracle9i Database Performance Tuning Guide and Reference for information about collecting statistics and their use by the optimizer "Analyzing Tables, Indexes, and Clusters" on page 21-3 Creating a Large Index When creating an extremely large index, consider allocating a larger temporary tablespace for the index creation using the following procedure: 1. Create a new temporary tablespace using the CREATE TABLESPACE or CREATE TEMPORARY TABLESPACE statement. 2. Use the TEMPORARY TABLESPACE option of the ALTER USER statement to make this your new temporary tablespace. 3. Create the index using the CREATE INDEX statement. 4. Drop this tablespace using the DROP TABLESPACE statement. Then use the ALTER USER statement to reset your temporary tablespace to your original temporary tablespace. Using this procedure can avoid the problem of expanding your usual, and usually shared, temporary tablespace to an unreasonably large size that might affect future performance. Creating an Index Online You can create and rebuild indexes online. This enables you to update base tables at the same time you are building or rebuilding indexes on that table. You can perform DML operations while the index build is taking place, but DDL operations are not Managing Indexes 16-13 Creating Indexes allowed. Parallel execution is not supported when creating or rebuilding an index online. The following statements illustrate online index build operations: CREATE INDEX emp_name ON emp (mgr, emp1, emp2, emp3) ONLINE; Note: While you can perform DML operations during an online index build, Oracle recommends that you do not perform major/large DML operations during this procedure. This is because while the DML on the base table is taking place it holds a lock on that resource. The DDL to build the index cannot proceed until the transaction acting on the base table commits or rolls back, thus releasing the lock. For example, if you want to load rows that total up to 30% of the size of an existing table, you should perform this load before the online index build. See Also: Rebuilding an Existing Index on page 16-20 Creating a Function-Based Index Function-based indexes facilitate queries that qualify a value returned by a function or expression. The value of the function or expression is precomputed and stored in the index. See Also: ■ Oracle9i Database Concepts ■ Oracle9i Data Warehousing Guide These books provide additional information about function-based indexes. Features of Function-Based Indexes Function-based indexes allow you to: ■ Create more powerful sorts You can perform case-insensitive sorts with the UPPER and LOWER functions, descending order sorts with the DESC keyword, and linguistic-based sorts with the NLSSORT function. 16-14 Oracle9i Database Administrator’s Guide Creating Indexes ■ Precompute the value of a computationally intensive function and store it in the index An index can store computationally intensive expression that you access often. When you need to access a value, it is already computed, greatly improving query execution performance. ■ Increase the number of situations where the optimizer can perform a range scan instead of a full table scan For example, consider the expression in the WHERE clause below: CREATE INDEX idx ON Example_tab(column_a + column_b); SELECT * FROM example_tab WHERE column_a + column_b < 10; The optimizer can use a range scan for this query because the index is built on (column_a + column_b). Range scans typically produce fast response times if the predicate selects less than 15% of the rows of a large table. The optimizer can estimate how many rows are selected by expressions more accurately if the expressions are materialized in a function-based index. (Expressions of function-based indexes are represented as virtual columns and analyze operation using the DBMS_STATS package can build histograms on such columns.) ■ Enable true descending order indexes They are treated as a special case of function-based indexes. Note: Oracle sorts columns with the DESC keyword in descending order. Such indexes are treated as function-based indexes. Descending indexes cannot be bitmapped or reverse, and cannot be used in bitmapped optimizations. To get the pre-Oracle 8.1 release DESC behavior, remove the DESC keyword from the CREATE INDEX statement. ■ Create indexes on object columns and REF columns Methods that describe objects can be used as functions on which to build indexes. For example, you can use the MAP method to build indexes on an object type column. Managing Indexes 16-15 Creating Indexes See Also: ■ ■ ■ Oracle9i Database Globalization Support Guide for information about the NLSSORT function Oracle9i Database Performance Tuning Guide and Reference for information about the optimizer Oracle9i Application Developer’s Guide - Object-Relational Features for information about object and REF columns How Function-Based Indexes Work For the creation of a function-based index in your own schema, you must be granted the QUERY REWRITE system privileges. To create the index in another schema or on another schema’s tables, you must have the CREATE ANY INDEX and GLOBAL QUERY REWRITE privileges. You must have the following initialization parameters defined to create a function-based index: ■ QUERY_REWRITE_INTEGRITY set to TRUSTED ■ QUERY_REWRITE_ENABLED set to TRUE ■ COMPATIBLE set to 8.1.0.0.0 or a greater value Additionally, to use a function-based index: ■ ■ The table must be analyzed after the index is created. The query must be guaranteed not to need any NULL values from the indexed expression, since NULL values are not stored in indexes. Note: CREATE INDEX stores the timestamp of the most recent function used in the function-based index. This timestamp is updated when the index is validated. When performing tablespace point-in-time recovery of a function-based index, if the timestamp on the most recent function used in the index is newer than the timestamp stored in the index, then the index is marked invalid. You must use the ANALYZE INDEX ... VALIDATE STRUCTURE statement to validate this index. To illustrate a function-based index, lets consider the following statement that defines a function-based index (area_index) defined on the function area(geo): 16-16 Oracle9i Database Administrator’s Guide Creating Indexes CREATE INDEX area_index ON rivers (area(geo)); In the following SQL statement, when area(geo) is referenced in the WHERE clause, the optimizer considers using the index area_index. SELECT id, geo, area(geo), desc FROM rivers WHERE Area(geo) >5000; Table owners should have EXECUTE privileges on the functions used in function-based indexes. Because a function-based index depends upon any function it is using, it can be invalidated when a function changes. If the function is valid, you can use an ALTER INDEX ... ENABLE statement to enable a function-based index that has been disabled. The ALTER INDEX ... DISABLE statement allows you to disable the use of a function-based index. Consider doing this if you are working on the body of the function. Examples of Function-Based Indexes Some examples of using function-based indexes follow. Example: Function-Based Index for Case-Insensitive Searches The following statement creates function-based index idx on table emp based on an uppercase evaluation of the ename column: CREATE INDEX idx ON emp (UPPER(ename)); Now the SELECT statement uses the function-based index on UPPER(ename) to retrieve all employees with names that start with JOH: SELECT * FROM emp WHERE UPPER(ename) LIKE 'JOH%'; This example also illustrates a case-insensitive search. Example: Precomputing Arithmetic Expressions with a Function-Based Index This statement creates a function-based index on an expression: CREATE INDEX idx ON t (a + b * (c - 1), a, b); SELECT statements can use either an index range scan (in the following SELECT statement the expression is a prefix of the index) or index full scan (preferable when the index specifies a high degree of parallelism). SELECT a FROM t WHERE a + b * (c - 1) < 100; Managing Indexes 16-17 Creating Indexes Examples: Function-Based Index for Language-Dependent Sorting You can use function-based indexes to support a linguistic sort index. NLSSORT is a function that returns a sort key that has been given a string. Thus, if you want to build an index on name using NLSSORT, issue the following statement: CREATE INDEX nls_index ON t_table (NLSSORT(name, 'NLS_SORT = German')); This statement creates index nls_index on table t_table with the collation sequence German. Now, the following statement selects from t_table using the NLS_SORT index: SELECT * FROM t_table ORDER BY name; Rows are ordered using the collation sequence in German. The following example combines a case-insensitive sort and a language sort: CREATE INDEX empi ON emp UPPER ((ename), NLSSORT(ename)); Here, an NLS_SORT specification does not appear in the NLSSORT argument because NLSSORT looks at the session setting for the language of the linguistic sort key. The previous example illustrated a case where NLS_SORT was specified. Creating a Key-Compressed Index Creating an index using key compression enables you to eliminate repeated occurrences of key column prefix values. Key compression breaks an index key into a prefix and a suffix entry. Compression is achieved by sharing the prefix entries among all the suffix entries in an index block. This sharing can lead to huge savings in space, allowing you to store more keys for each index block while improving performance. Key compression can be useful in the following situations: ■ ■ You have a non-unique index where ROWID is appended to make the key unique. If you use key compression here, the duplicate key is stored as a prefix entry on the index block without the ROWID. The remaining rows become suffix entries consisting of only the ROWID. You have a unique multi-column index. You enable key compression using the COMPRESS clause. The prefix length (as the number of key columns) can also be specified to identify how the key columns are 16-18 Oracle9i Database Administrator’s Guide Altering Indexes broken into a prefix and suffix entry. For example, the following statement compresses duplicate occurrences of a key in the index leaf block: CREATE INDEX emp_ename ON emp(ename) TABLESPACE users COMPRESS 1; The COMPRESS clause can also be specified during rebuild. For example, during rebuild you can disable compression as follows: ALTER INDEX emp_ename REBUILD NOCOMPRESS; See Also: Oracle9i Database Concepts for a more detailed discussion of key compression Altering Indexes To alter an index, your schema must contain the index or you must have the ALTER ANY INDEX system privilege. Among the actions allowed by the ALTER INDEX statement are: ■ Rebuild or coalesce an existing index ■ Deallocate unused space or allocate a new extent ■ Specify parallel execution (or not) and alter the degree of parallelism ■ Alter storage parameters or physical attributes ■ Specify LOGGING or NOLOGGING ■ Enable or disable key compression ■ Mark the index unusable ■ Start or stop the monitoring of index usage You cannot alter an index’s column structure. More detailed discussions of some of these operations are contained in the following sections: ■ Altering Storage Characteristics of an Index ■ Rebuilding an Existing Index ■ Monitoring Index Usage Managing Indexes 16-19 Altering Indexes Altering Storage Characteristics of an Index Alter the storage parameters of any index, including those created by Oracle to enforce primary and unique key integrity constraints, using the ALTER INDEX statement. For example, the following statement alters the emp_ename index: ALTER INDEX emp_ename STORAGE (PCTINCREASE 50); The storage parameters INITIAL and MINEXTENTS cannot be altered. All new settings for the other storage parameters affect only extents subsequently allocated for the index. For indexes that implement integrity constraints, you can choose to adjust storage parameters by issuing an ALTER TABLE statement that includes the USING INDEX subclause of the ENABLE clause. For example, the following statement changes the storage options of the index created on table emp to enforce the primary key constraint: ALTER TABLE emp ENABLE PRIMARY KEY USING INDEX PCTFREE 5; Rebuilding an Existing Index Before rebuilding an existing index, compare the costs and benefits associated with rebuilding to those associated with coalescing indexes as described in Table 16–1 on page 16-8. When you rebuild an index, you use an existing index as the data source. Creating an index in this manner enables you to change storage characteristics or move to a new tablespace. Rebuilding an index based on an existing data source removes intra-block fragmentation. Compared to dropping the index and using the CREATE INDEX statement, re-creating an existing index offers better performance. The following statement rebuilds the existing index emp_name: ALTER INDEX emp_name REBUILD; The REBUILD clause must immediately follow the index name, and precede any other options. It cannot be used in conjunction with the DEALLOCATE UNUSED clause. If have the option of rebuilding the index online. The following statement rebuilds the emp_name index online: 16-20 Oracle9i Database Administrator’s Guide Monitoring Space Use of Indexes ALTER INDEX REBUILD ONLINE; If you do not have the space required to rebuild an index, you can choose instead to coalesce the index. Coalescing an index can also be done online. See Also: ■ "Creating an Index Online" on page 16-13 ■ "Monitoring Space Use of Indexes" on page 16-21 Monitoring Index Usage Oracle provides a means of monitoring indexes to determine if they are being used or not used. If it is determined that an index is not being used, then it can be dropped, thus eliminating unnecessary statement overhead. To start monitoring an index’s usage, issue this statement: ALTER INDEX index MONITORING USAGE; Later, issue the following statement to stop the monitoring: ALTER INDEX index NOMONITORING USAGE; The view V$OBJECT_USAGE can be queried for the index being monitored to see if the index has been used. The view contains a USED column whose value is YES or NO, depending upon if the index has been used within the time period being monitored. The view also contains the start and stop times of the monitoring period, and a MONITORING column (YES/NO) to indicate if usage monitoring is currently active. Each time that you specify MONITORING USAGE, the V$OBJECT_USAGE view is reset for the specified index. The previous usage information is cleared or reset, and a new start time is recorded. When you specify NOMONITORING USAGE, no further monitoring is performed, and the end time is recorded for the monitoring period. Until the next ALTER INDEX ... MONITORING USAGE statement is issued, the view information is left unchanged. Monitoring Space Use of Indexes If key values in an index are inserted, updated, and deleted frequently, the index can lose its acquired space efficiently over time. Monitor an index’s efficiency of space usage at regular intervals by first analyzing the index’s structure, using the Managing Indexes 16-21 Dropping Indexes ANALYZE INDEX ... VALIDATE STRUCTURE statement, and then querying the INDEX_STATS view: SELECT PCT_USED FROM INDEX_STATS WHERE NAME = 'index'; The percentage of an index’s space usage varies according to how often index keys are inserted, updated, or deleted. Develop a history of an index’s average efficiency of space usage by performing the following sequence of operations several times: ■ Analyzing statistics ■ Validating the index ■ Checking PCTUSED ■ Dropping and rebuilding (or coalescing) the index When you find that an index’s space usage drops below its average, you can condense the index’s space by dropping the index and rebuilding it, or coalescing it. See Also: "Analyzing Tables, Indexes, and Clusters" on page 21-3 Dropping Indexes To drop an index, the index must be contained in your schema, or you must have the DROP ANY INDEX system privilege. Some reasons for dropping an index include: ■ ■ The index is no longer required. The index is not providing anticipated performance improvements for queries issued against the associated table. For example, the table might be very small, or there might be many rows in the table but very few index entries. ■ Applications do not use the index to query the data. ■ The index has become invalid and must be dropped before being rebuilt. ■ The index has become too fragmented and must be dropped before being rebuilt. When you drop an index, all extents of the index’s segment are returned to the containing tablespace and become available for other objects in the tablespace. How you drop an index depends on whether you created the index explicitly with a CREATE INDEX statement, or implicitly by defining a key constraint on a table. If you created the index explicitly with the CREATE INDEX statement, then you can 16-22 Oracle9i Database Administrator’s Guide Viewing Index Information drop the index with the DROP INDEX statement. The following statement drops the emp_ename index: DROP INDEX emp_ename; You cannot drop only the index associated with an enabled UNIQUE key or PRIMARY KEY constraint. To drop a constraint’s associated index, you must disable or drop the constraint itself. Note: If a table is dropped, all associated indexes are dropped automatically. See Also: "Managing Integrity Constraints" on page 21-14 Viewing Index Information The following views display information about indexes: View Description DBA_INDEXES DBA view describes indexes on all tables in the database. ALL view describes indexes on all tables accessible to the user. USER view is restricted to indexes owned by the user. Some columns in these views contain statistics that are generated by the DBMS_STATS package or ANALYZE statement. ALL_INDEXES USER_INDEXES DBA_IND_COLUMNS ALL_IND_COLUMNS These views describe the columns of indexes on tables. Some columns in these views contain statistics that are generated by the DBMS_STATS package or ANALYZE statement. USER_IND_COLUMNS DBA_IND_EXPRESSIONS These views describe the expressions of function-based indexes on tables. ALL_IND_EXPRESSIONS USER_IND_EXPRESSIONS INDEX_STATS Stores information from the last ANALYZE INDEX ... VALIDATE STRUCTURE statement. INDEX_HISTOGRAM Stores information from the last ANALYZE INDEX ... VALIDATE STRUCTURE statement. V$OBJECT_USAGE Contains index usage information produced by the ALTER INDEX ... MONITORING USAGE functionality. Managing Indexes 16-23 Viewing Index Information See Also: Oracle9i Database Reference for a complete description of these views 16-24 Oracle9i Database Administrator’s Guide 17 Managing Partitioned Tables and Indexes This chapter describes various aspects of managing partitioned tables and indexes, and contains the following topics: ■ What Are Partitioned Tables and Indexes? ■ Partitioning Methods ■ Creating Partitioned Tables ■ Maintaining Partitioned Tables ■ Partitioned Tables and Indexes Examples ■ Viewing Information About Partitioned Tables and Indexes See Also: Chapter 14, "Managing Space for Schema Objects" is recommended reading before attempting tasks described in this chapter. Managing Partitioned Tables and Indexes 17-1 What Are Partitioned Tables and Indexes? What Are Partitioned Tables and Indexes? Today’s enterprises frequently run mission critical databases containing upwards of several hundred gigabytes and, in many cases, several terabytes of data. These enterprises are challenged by the support and maintenance requirements of very large databases (VLDB), and must devise methods to meet those challenges. One way to meet VLDB demands is to create and use partitioned tables and indexes. Partitioned tables allow your data to be broken down into smaller, more manageable pieces called partitions, or even subpartitions. Indexes can be partitioned in similar fashion. Each partition is stored in its own segment and can be managed individually. It can function independently of the other partitions, thus providing a structure that can be better tuned for availability and performance. If you are using parallel execution, partitions provide another means of parallelization. Operations on partitioned tables and indexes are performed in parallel by assigning different parallel execution servers to different partitions of the table or index. Partitions and subpartitions of a table or index all share the same logical attributes. For example, all partitions (or subpartitions) in a table share the same column and constraint definitions, and all partitions (or subpartitions) of an index share the same index options. They can, however, have different physical attributes (such as TABLESPACE). Although you are not required to keep each table or index partition (or subpartition) in a separate tablespace, it is to your advantage to do so. Storing partitions in separate tablespaces enables you to: ■ Reduce the possibility of data corruption in multiple partitions ■ Back up and recover each partition independently ■ ■ Control the mapping of partitions to disk drives (important for balancing I/O load) Improve manageability, availability, and performance Partitioning is transparent to existing applications and standard DML statements run against partitioned tables. However, an application can be programmed to take advantage of partitioning by using partition-extended table or index names in DML. You can use the SQL*Loader, Import, and Export utilities to load or unload data stored in partitioned tables. These utilities are all partition and subpartition aware. 17-2 Oracle9i Database Administrator’s Guide Partitioning Methods See Also: ■ ■ ■ Oracle9i Database Concepts contains more information about partitioning. Before the first time you attempt to create a partitioned table or index, or perform maintenance operations on any partitioned table, it is recommended that you review the information contained in that book. Oracle9i Data Warehousing Guide and Oracle9i Database Concepts contain information about parallel execution Oracle9i Database Utilities describes the SQL*Loader, Import, and Export utilities. Partitioning Methods There are several partitioning methods offered by Oracle: ■ Range partitioning ■ Hash partitioning ■ List partitioning ■ Composite range-hash partitioning ■ Composite range-list partitioning Indexes, as well as tables, can be partitioned. A global index can only be partitioned by range, but it can be defined on any type of partitioned, or nonpartitioned, table. It can require more maintenance than a local index. A local index is constructed so that it reflects the structure of the underlying table. It is equipartitioned with the underlying table, meaning that it is partitioned on the same columns as the underlying table, creates the same number of partitions or subpartitions, and gives them the same partition bounds as corresponding partitions of the underlying table. For local indexes, index partitioning is maintained automatically when partitions are affected by maintenance activity. This ensures that the index remains equipartitioned with the underlying table. The following sections can help you decide on a partitioning method appropriate for your needs: ■ When to Use the Range Partitioning Method ■ When to Use the Hash Partitioning Method ■ When to Use the List Partitioning Method Managing Partitioned Tables and Indexes 17-3 Partitioning Methods ■ When to Use the Composite Range-Hash Partitioning Method ■ When to Use the Composite Range-List Partitioning Method When to Use the Range Partitioning Method Use range partitioning to map rows to partitions based on ranges of column values. This type of partitioning is useful when dealing with data that has logical ranges into which it can be distributed; for example, months of the year. Performance is best when the data evenly distributes across the range. If partitioning by range causes partitions to vary dramatically in size because of unequal distribution, you may want to consider one of the other methods of partitioning. When creating range partitions, you must specify: ■ Partitioning method: range ■ Partitioning column(s) ■ Partition descriptions identifying partition bounds The example below creates a table of four partitions, one for each quarter’s sales. The columns sale_year, sale_month, and sale_day are the partitioning columns, while their values constitute a specific row’s partitioning key. The VALUES LESS THAN clause determines the partition bound: rows with partitioning key values that compare less than the ordered list of values specified by the clause are stored in the partition. Each partition is given a name (sales_q1, sales_q2, ...), and each partition is contained in a separate tablespace (tsa, tsb, ...). CREATE TABLE sales ( invoice_no NUMBER, sale_year INT NOT NULL, sale_month INT NOT NULL, sale_day INT NOT NULL ) PARTITION BY RANGE (sale_year, sale_month, sale_day) ( PARTITION sales_q1 VALUES LESS THAN (1999, 04, 01) TABLESPACE tsa, PARTITION sales_q2 VALUES LESS THAN (1999, 07, 01) TABLESPACE tsb, PARTITION sales_q3 VALUES LESS THAN (1999, 10, 01) TABLESPACE tsc, PARTITION sales_q4 VALUES LESS THAN (2000, 01, 01) TABLESPACE tsd ); 17-4 Oracle9i Database Administrator’s Guide Partitioning Methods A row with sale_year=1999, sale_month=8, and sale_day=1 has a partitioning key of (1999, 8, 1) and would be stored in partition sales_q3. When to Use the Hash Partitioning Method Use hash partitioning if your data does not easily lend itself to range partitioning, but you would like to partition for performance and manageability reasons. Hash partitioning provides a method of evenly distributing data across a specified number of partitions. Rows are mapped into partitions based on a hash value of the partitioning key. Creating and using hash partitions gives you a highly tunable method of data placement, because you can influence availability and performance by spreading these evenly sized partitions across I/O devices (striping). To create hash partitions you specify the following: ■ Partitioning method: hash ■ Partitioning columns(s) ■ Number of partitions or individual partition descriptions The following example creates a hash-partitioned table. The partitioning column is id, four partitions are created and assigned system generated names, and they are placed in four named tablespaces (gear1, gear2, ...). CREATE TABLE scubagear (id NUMBER, name VARCHAR2 (60)) PARTITION BY HASH (id) PARTITIONS 4 STORE IN (gear1, gear2, gear3, gear4); When to Use the List Partitioning Method Use list partitioning when you require explicit control over how rows map to partitions. You can specify a list of discrete values for the partitioning column in the description for each partition. This is different from range partitioning, where a range of values is associated with a partition, and from hash partitioning, where the user has no control of the row to partition mapping. The list partitioning method is specifically designed for modeling data distributions that follow discrete values. This cannot be easily done by range or hash partitioning because: ■ Range partitioning assumes a natural range of values for the partitioning column. It is not possible to group together out-of-range values partitions. Managing Partitioned Tables and Indexes 17-5 Partitioning Methods ■ Hash partitioning allows no control over the distribution of data because the data is distributed over the various partitions using the system hash function. Again, this makes it impossible to logically group together discrete values for the partitioning columns into partitions. Further, list partitioning allows unordered and unrelated sets of data to be grouped and organized together very naturally. Unlike the range and hash partitioning methods, multi-column partitioning is not supported for list partitioning. If a table is partitioned by list, the partitioning key can consist only of a single column of the table. Otherwise all columns that can be partitioned by the range or hash methods can be partitioned by the list partitioning method. When creating list partitions, you must specify: ■ Partitioning method: list ■ Partitioning column ■ Partition descriptions, each specifying a list of literal values (a value list), which are the discrete values of the partitioning column that qualify a row to be included in the partition The following example creates a list-partitioned table. It creates table q1_sales_ by_region which is partitioned by regions consisting of groups of states. CREATE TABLE q1_sales_by_region (deptno number, deptname varchar2(20), quarterly_sales number(10, 2), state varchar2(2)) PARTITION BY LIST (state) (PARTITION q1_northwest VALUES ('OR', 'WA'), PARTITION q1_southwest VALUES ('AZ', 'UT', 'NM'), PARTITION q1_northeast VALUES ('NY', 'VM', 'NJ'), PARTITION q1_southeast VALUES ('FL', 'GA'), PARTITION q1_northcentral VALUES ('SD', 'WI'), PARTITION q1_southcentral VALUES ('OK', 'TX')); A row is mapped to a partition by checking whether the value of the partitioning column for a row matches a value in the value list that describes the partition. For example, some sample rows are inserted as follows: 17-6 ■ (10, 'accounting', 100, 'WA') maps to partition q1_northwest ■ (20, 'R&D', 150, 'OR') maps to partition q1_northwest Oracle9i Database Administrator’s Guide Partitioning Methods ■ (30, 'sales', 100, 'FL') maps to partition q1_southeast ■ (40, 'HR', 10, 'TX') maps to partition q1_southwest ■ (50, 'systems engineering', 10, 'CA') does not map to any partition in the table and returns an error One of the interesting things to note about list partitioning is that there is no apparent sense of ordering between partitions (unlike range partitioning). You can also specify a default partition into which rows that do not map to any other partition are mapped. If a default partition were specified in the above example, the state CA would map to that partition. When to Use the Composite Range-Hash Partitioning Method Range-hash partitioning partitions data using the range method, and within each partition, subpartitions it using the hash method. These composite partitions are ideal for both historical data and striping, and provide improved manageability of range partitioning and data placement, as well as the parallelism advantages of hash partitioning. When creating range-hash partitions, you specify the following: ■ Partitioning method: range ■ Partitioning column(s) ■ Partition descriptions identifying partition bounds ■ Subpartitioning method: hash ■ Subpartitioning column(s) ■ Number of subpartitions for each partition or descriptions of subpartitions The following statement creates a range-hash partitioned table. In this example, three range partitions are created, each containing eight subpartitions. Because the subpartitions are not named, system generated names are assigned, but the STORE IN clause distributes them across the 4 specified tablespaces (ts1, ...,ts4). CREATE TABLE scubagear (equipno NUMBER, equipname VARCHAR(32), price NUMBER) PARTITION BY RANGE (equipno) SUBPARTITION BY HASH(equipname) SUBPARTITIONS 8 STORE IN (ts1, ts2, ts3, ts4) (PARTITION p1 VALUES LESS THAN (1000), PARTITION p2 VALUES LESS THAN (2000), PARTITION p3 VALUES LESS THAN (MAXVALUE)); Managing Partitioned Tables and Indexes 17-7 Partitioning Methods The partitions of a range-hash partitioned table are logical structures only, as their data is stored in the segments of their subpartitions. As with partitions, these subpartitions share the same logical attributes. Unlike range partitions in a range-partitioned table, the subpartitions cannot have different physical attributes from the owning partition, although they are not required to reside in the same tablespace. When to Use the Composite Range-List Partitioning Method Like the composite range-hash partitioning method, the composite range-list partitioning method provides for partitioning based on a two level hierarchy. The first level of partitioning is based on a range of values, as for range partitioning; the second level is based on discrete values, as for list partitioning. This form of composite partitioning is well suited for historical data, but allows you to further group the rows of data based on unordered or unrelated column values. When creating range-list partitions, you specify the following: ■ Partitioning method: range ■ Partitioning column(s) ■ Partition descriptions identifying partition bounds ■ Subpartitioning method: list ■ Subpartitioning column ■ Subpartition descriptions, each specifying a list of literal values (a value list), which are the discrete values of the subpartitioning column that qualify a row to be included in the subpartition The following example illustrates how range-list partitioning might be used. The example tracks sales data of products by quarters and within each quarter, groups it by specified states. CREATE TABLE quarterly_regional_sales (deptno number, item_no varchar2(20), txn_date date, txn_amount number, state varchar2(2)) TABLESPACE ts4 PARTITION BY RANGE (txn_date) SUBPARTITION BY LIST (state) (PARTITION q1_1999 VALUES LESS THAN (TO_DATE(’1-APR-1999’,’DD-MON-YYYY’)) (SUBPARTITION q1_1999_northwest VALUES (’OR’, ’WA’), SUBPARTITION q1_1999_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q1_1999_northeast VALUES (’NY’, ’VM’, ’NJ’), SUBPARTITION q1_1999_southeast VALUES (’FL’, ’GA’), 17-8 Oracle9i Database Administrator’s Guide Partitioning Methods SUBPARTITION q1_1999_northcentral VALUES (’SD’, ’WI’), SUBPARTITION q1_1999_southcentral VALUES (’OK’, ’TX’) ), PARTITION q2_1999 VALUES LESS THAN ( TO_DATE(’1-JUL-1999’,’DD-MON-YYYY’)) (SUBPARTITION q2_1999_northwest VALUES (’OR’, ’WA’), SUBPARTITION q2_1999_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q2_1999_northeast VALUES (’NY’, ’VM’, ’NJ’), SUBPARTITION q2_1999_southeast VALUES (’FL’, ’GA’), SUBPARTITION q2_1999_northcentral VALUES (’SD’, ’WI’), SUBPARTITION q2_1999_southcentral VALUES (’OK’, ’TX’) ), PARTITION q3_1999 VALUES LESS THAN (TO_DATE(’1-OCT-1999’,’DD-MON-YYYY’)) (SUBPARTITION q3_1999_northwest VALUES (’OR’, ’WA’), SUBPARTITION q3_1999_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q3_1999_northeast VALUES (’NY’, ’VM’, ’NJ’), SUBPARTITION q3_1999_southeast VALUES (’FL’, ’GA’), SUBPARTITION q3_1999_northcentral VALUES (’SD’, ’WI’), SUBPARTITION q3_1999_southcentral VALUES (’OK’, ’TX’) ), PARTITION q4_1999 VALUES LESS THAN ( TO_DATE(’1-JAN-2000’,’DD-MON-YYYY’)) (SUBPARTITION q4_1999_northwest VALUES (’OR’, ’WA’), SUBPARTITION q4_1999_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q4_1999_northeast VALUES (’NY’, ’VM’, ’NJ’), SUBPARTITION q4_1999_southeast VALUES (’FL’, ’GA’), SUBPARTITION q4_1999_northcentral VALUES (’SD’, ’WI’), SUBPARTITION q4_1999_southcentral VALUES (’OK’, ’TX’) ) ); A row is mapped to a partition by checking whether the value of the partitioning column for a row falls within a specific partition range. The row is then mapped to a subpartition within that partition by identifying the subpartition whose descriptor value list contains a value matching the subpartition column value. For example, some sample rows are inserted as follows: ■ ■ ■ ■ (10, 4532130, ’23-Jan-1999’, 8934.10, ’WA’) maps to subpartition q1_1999_ northwest (20, 5671621, ’15-May-1999’, 49021.21, ’OR’) maps to subpartition q2_1999_ northeast (30, 9977612, ,’07-Sep-1999’, 30987.90, ’FL’) maps to subpartition q3_1999_ southeast (40, 9977612, ’29-Nov-1999’, 67891.45, ’TX’) maps to subpartition q4_1999_ southwest Managing Partitioned Tables and Indexes 17-9 Creating Partitioned Tables ■ ■ (40, 4532130, ’5-Jan-2000’, 897231.55, ’TX’) does not map to any partition in the table and raises an error (50, 5671621, ’17-Dec-1999’, 76123.35, ’CA’) does not map to any subpartition in the table and raises an error The partitions of a range-list partitioned table are logical structures only, as their data is stored in the segments of their subpartitions. The list subpartitions have the same characteristics as list partitions. You can specify a default subpartition, just as you specify a default partition for list partitioning. Creating Partitioned Tables Creating a partitioned table or index is very similar to creating a non-partitioned table or index (as described in Chapter 15, "Managing Tables"), but you include a partitioning clause. The partitioning clause, and subclauses, that you include depend upon the type of partitioning you want to achieve. You can partition both regular (heap organized) tables and index-organized tables, including those containing LOB columns. You can create nonpartitioned global indexes, range-partitioned global indexes, and local indexes on partitioned tables. When you create (or alter) a partitioned table, a row movement clause, either ENABLE ROW MOVEMENT or DISABLE ROW MOVEMENT can be specified. This clause either enables or disables the migration of a row to a new partition if its key is updated. The default is DISABLE ROW MOVEMENT. The following sections present details and examples of creating partitions for the various types of partitioned tables and indexes: ■ Creating Range-Partitioned Tables ■ Creating Hash-Partitioned Tables ■ Creating List-Partitioned Tables ■ Creating Composite Range-Hash Partitioned Tables ■ Creating Composite Range-List Partitioned Tables ■ Using Subpartition Templates to Describe Composite Partitioned Tables ■ Creating Partitioned Index-Organized Tables ■ Partitioning Restrictions for Multiple Block Sizes 17-10 Oracle9i Database Administrator’s Guide Creating Partitioned Tables See Also: ■ ■ Oracle9i SQL Reference for the exact syntax of the partitioning clauses for creating and altering partitioned tables and indexes, any restrictions on their use, and specific privileges required for creating and altering tables Oracle9i Application Developer’s Guide - Large Objects (LOBs) and Oracle9i Application Developer’s Guide - Fundamentals for information about creating partitioned tables containing columns with LOBs or other objects stored as LOBs Creating Range-Partitioned Tables The PARTITION BY RANGE clause of the CREATE TABLE statement specifies that the table is to be range-partitioned. The PARTITION clauses identify the individual partition ranges, and optional subclauses of a PARTITION clause can specify physical and other attributes specific to a partition’s segment. If not overridden at the partition level, partitions inherit the attributes of their underlying table. In this example, more complexity is added to the example presented earlier for a range-partitioned table. Storage parameters and a LOGGING attribute are specified at the table level. These replace the corresponding defaults inherited from the tablespace level for the table itself, and are inherited by the range partitions. However, since there was little business in the first quarter, the storage attributes for partition sales_q1 are made smaller. The ENABLE ROW MOVEMENT clause is specified to allow the migration of a row to a new partition if an update to a key value is made that would place the row in a different partition. CREATE TABLE sales ( invoice_no NUMBER, sale_year INT NOT NULL, sale_month INT NOT NULL, sale_day INT NOT NULL ) STORAGE (INITIAL 100K NEXT 50K) LOGGING PARTITION BY RANGE ( sale_year, sale_month, sale_day) ( PARTITION sales_q1 VALUES LESS THAN ( 1999, 04, 01 TABLESPACE tsa STORAGE (INITIAL 20K, NEXT 10K), PARTITION sales_q2 VALUES LESS THAN ( 1999, 07, 01 TABLESPACE tsb, PARTITION sales_q3 VALUES LESS THAN ( 1999, 10, 01 TABLESPACE tsc, PARTITION sales q4 VALUES LESS THAN ( 2000, 01, 01 TABLESPACE tsd) ) ) ) ) Managing Partitioned Tables and Indexes 17-11 Creating Partitioned Tables ENABLE ROW MOVEMENT; The rules for creating range-partitioned global indexes are similar to those for creating range-partitioned tables. The following is an example of creating a range-partitioned global index on sales_month for the above table. Each index partition is named but is stored in the default tablespace for the index. CREATE INDEX month_ix ON sales(sales_month) GLOBAL PARTITION BY RANGE(sales_month) (PARTITION pm1_ix VALUES LESS THAN (2) PARTITION pm2_ix VALUES LESS THAN (3) PARTITION pm3_ix VALUES LESS THAN (4) PARTITION pm4_ix VALUES LESS THAN (5) PARTITION pm5_ix VALUES LESS THAN (6) PARTITION pm6_ix VALUES LESS THAN (7) PARTITION pm7_ix VALUES LESS THAN (8) PARTITION pm8_ix VALUES LESS THAN (9) PARTITION pm9_ix VALUES LESS THAN (10) PARTITION pm10_ix VALUES LESS THAN (11) PARTITION pm11_ix VALUES LESS THAN (12) PARTITION pm12_ix VALUES LESS THAN (MAXVALUE)); Note: If your enterprise has or will have databases using different character sets, use caution when partitioning on character columns, because the sort sequence of characters is not identical in all character sets. For more information, see Oracle9i Database Globalization Support Guide. Creating Hash-Partitioned Tables The PARTITION BY HASH clause of the CREATE TABLE statement identifies that the table is to be hash-partitioned. The PARTITIONS clause can then be used to specify the number of partitions to create, and optionally, the tablespaces to store them in. Alternatively, you can use PARTITION clauses to name the individual partitions and their tablespaces. The only attribute you can specify for hash partitions is TABLESPACE. All of the hash partitions of a table must share the same segment attributes (except TABLESPACE), which are inherited from the table level. The following examples illustrate two methods of creating a hash-partitioned table named dept. In the first example the number of partitions is specified, but system 17-12 Oracle9i Database Administrator’s Guide Creating Partitioned Tables generated names are assigned to them and they are stored in the default tablespace of the table. CREATE TABLE dept (deptno NUMBER, deptname VARCHAR(32)) PARTITION BY HASH(deptno) PARTITIONS 16; In this second example, names of individual partitions, and tablespaces in which they are to reside, are specified. The initial extent size for each hash partition (segment) is also explicitly stated at the table level, and all partitions inherit this attribute. CREATE TABLE dept (deptno NUMBER, deptname VARCHAR(32)) STORAGE (INITIAL 10K) PARTITION BY HASH(deptno) (PARTITION p1 TABLESPACE ts1, PARTITION p2 TABLESPACE ts2, PARTITION p3 TABLESPACE ts1, PARTITION p4 TABLESPACE ts3); If you create a local index for the above table, Oracle constructs the index so that it is equipartitioned with the underlying table. Oracle also ensures that the index is maintained automatically when maintenance operations are performed on the underlying table. The following is an example of creating a local index on the table dept: CREATE INDEX loc_dept_ix ON dept(deptno) LOCAL; You can optionally name the hash partitions and tablespaces into which the local index partitions are to be stored, but if you do not do so, Oracle uses the name of the corresponding base partition as the index partition name, and stores the index partition in the same tablespace as the table partition. Creating List-Partitioned Tables The semantics for creating list partitions are very similar to those for creating range partitions. However, to create list partitions, you specify a PARTITION BY LIST clause in the CREATE TABLE statement, and the PARTITION clauses specify lists of literal values, which are the discrete values of the partitioning columns that qualify rows to be included in the partition. For list partitioning, the partitioning key can only be a single column name from the table. Available only with list partitioning, you can use the keyword DEFAULT to describe the value list for a partition. This identifies a partition that will accommodate rows that do not map into any of the other partitions. Managing Partitioned Tables and Indexes 17-13 Creating Partitioned Tables Like for range partitions, optional subclauses of a PARTITION clause can specify physical and other attributes specific to a partition’s segment. If not overridden at the partition level, partitions inherit the attributes of their underlying table. The following example creates table sales_by_region and partitions it using the list method. The first two PARTITION clauses specify physical attributes, which override the table-level defaults. The remaining PARTITION clauses do not specify attributes and those partitions inherit their physical attributes from table-level defaults. A default partition is specified. CREATE TABLE sales_by_region (item# INTEGER, qty INTEGER, store_name VARCHAR(30), state_code VARCHAR(2), sale_date DATE) STORAGE(INITIAL 10K NEXT 20K) TABLESPACE tbs5 PARTITION BY LIST (state_code) ( PARTITION region_east VALUES ('MA','NY','CT','NH','ME','MD','VA','PA','NJ') STORAGE (INITIAL 20K NEXT 40K PCTINCREASE 50) TABLESPACE tbs8, PARTITION region_west VALUES ('CA','AZ','NM','OR','WA','UT','NV','CO') PCTFREE 25 NOLOGGING, PARTITION region_south VALUES ('TX','KY','TN','LA','MS','AR','AL','GA'), PARTITION region_central VALUES ('OH','ND','SD','MO','IL','MI','IA'), PARTITION region_null VALUES (NULL), PARTITION region_unknown VALUES (DEFAULT) ); Creating Composite Range-Hash Partitioned Tables To create a range-hash partitioned table, you start by using the PARTITION BY RANGE clause of a CREATE TABLE statement. Next, you specify a SUBPARTITION BY HASH clause that follows similar syntax and rules as the PARTITION BY HASH clause. The individual PARTITION and SUBPARTITION or SUBPARTITIONS clauses, and optionally a SUBPARTITION TEMPLATE clause, follow. Attributes specified for a range partition apply to all subpartitions of that partition. You can specify different attributes for each range partition, and you can specify a STORE IN clause at the partition level if the list of tablespaces across which that 17-14 Oracle9i Database Administrator’s Guide Creating Partitioned Tables partition’s subpartitions should be spread is different from those of other partitions. All of this is illustrated in the following example. CREATE TABLE emp (deptno NUMBER, empname VARCHAR(32), grade NUMBER) PARTITION BY RANGE(deptno) SUBPARTITION BY HASH(empname) SUBPARTITIONS 8 STORE IN (ts1, ts3, ts5, ts7) (PARTITION p1 VALUES LESS THAN (1000) PCTFREE 40, PARTITION p2 VALUES LESS THAN (2000) STORE IN (ts2, ts4, ts6, ts8), PARTITION p3 VALUES LESS THAN (MAXVALUE) (SUBPARTITION p3_s1 TABLESPACE ts4, SUBPARTITION p3_s2 TABLESPACE ts5)); To learn how using a subpartition template can simplify the specification of a composite partitioned table, see "Using Subpartition Templates to Describe Composite Partitioned Tables" on page 17-17. The following statement is an example of creating a local index on the emp table where the index segments are spread across tablespaces ts7, ts8, and ts9. CREATE INDEX emp_ix ON emp(deptno) LOCAL STORE IN (ts7, ts8, ts9); This local index is equipartitioned with the base table as follows: ■ ■ ■ It consists of as many partitions as the base table. Each index partition consists of as many subpartitions as the corresponding base table partition. Index entries for rows in a given subpartition of the base table are stored in the corresponding subpartition of the index. Creating Composite Range-List Partitioned Tables The concept of range-list partitioning is similar to that of the other composite partitioning method, range-hash, but this time you specify that the subpartitions are to be list rather than hash. Specifically, after the CREATE TABLE ... PARTITION BY RANGE clause, you include a SUBPARTITION BY LIST clause that follows similar syntax and rules as the PARTITION BY LIST clause. The individual PARTITION and SUBPARTITION clauses, and optionally a SUBPARTITION TEMPLATE clause, follow. The range partitions of the composite partitioned table are described as for noncomposite range partitioned tables. This allows that optional subclauses of a PARTITION clause can specify physical and other attributes, including tablespace, Managing Partitioned Tables and Indexes 17-15 Creating Partitioned Tables specific to a partition’s segment. If not overridden at the partition level, partitions inherit the attributes of their underlying table. The list subpartition’s descriptions, in the SUBPARTITION clauses, are described as for noncomposite list partitions, except the only physical attribute that can be specified is a tablespace (optional). Subpartitions inherit all other physical attributes from the partition description. The following example of creates a table that specifies a tablespace at the partition and subpartition levels. The number of subpartitions within each partition varies, and default subpartitions are specified. CREATE TABLE sample_regional_sales (deptno number, item_no varchar2(20), txn_date date, txn_amount number, state varchar2(2)) PARTITION BY RANGE (txn_date) SUBPARTITION BY LIST (state) (PARTITION q1_1999 VALUES LESS THAN (TO_DATE(’1-APR-1999’,’DD-MON-YYYY’)) TABLESPACE tbs_1 (SUBPARTITION q1_1999_northwest VALUES (’OR’, ’WA’), SUBPARTITION q1_1999_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q1_1999_northeast VALUES (’NY’, ’VM’, ’NJ’), SUBPARTITION q1_1999_southeast VALUES (’FL’, ’GA’), SUBPARTITION q1_others VALUES (DEFAULT) TABLESPACE tbs_4 ), PARTITION q2_1999 VALUES LESS THAN ( TO_DATE(’1-JUL-1999’,’DD-MON-YYYY’)) TABLESPACE tbs_2 (SUBPARTITION q2_1999_northwest VALUES (’OR’, ’WA’), SUBPARTITION q2_1999_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q2_1999_northeast VALUES (’NY’, ’VM’, ’NJ’), SUBPARTITION q2_1999_southeast VALUES (’FL’, ’GA’), SUBPARTITION q2_1999_northcentral VALUES (’SD’, ’WI’), SUBPARTITION q2_1999_southcentral VALUES (’OK’, ’TX’) ), PARTITION q3_1999 VALUES LESS THAN (TO_DATE(’1-OCT-1999’,’DD-MON-YYYY’)) TABLESPACE tbs_3 (SUBPARTITION q3_1999_northwest VALUES (’OR’, ’WA’), SUBPARTITION q3_1999_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q3_others VALUES (DEFAULT) TABLESPACE tbs_4 ), PARTITION q4_1999 VALUES LESS THAN ( TO_DATE(’1-JAN-2000’,’DD-MON-YYYY’)) TABLESPACE tbs_4 ); This example results in the following subpartition descriptions: 17-16 Oracle9i Database Administrator’s Guide Creating Partitioned Tables ■ ■ ■ ■ ■ All subpartitions inherit their physical attributes, other than tablespace, from tablespace level defaults. This is because the only physical attribute that has been specified for partitions or subpartitions is tablespace. There are no table level physical attributes specified, thus tablespace level defaults are inherited at all levels. The first 4 subpartitions of partition q1_1999 are all contained in tbs_1, except for the subpartition q1_others, which is stored in tbs_4 and contains all rows that do not map to any of the other partitions. The 6 subpartitions of partition q2_1999 are all stored in tbs_2. The first 2 subpartitions of partition q3_1999 are all contained in tbs_3, except for the subpartition q3_others, which is stored in tbs_4 and contains all rows that do not map to any of the other partitions. There is no subpartition description for partition q4_1999. This results in one default subpartition being created and stored in tbs_4. The subpartition’s name is system generated in the form SYS_SUBPn. To learn how using a subpartition template can simplify the specification of a composite partitioned table, see "Using Subpartition Templates to Describe Composite Partitioned Tables". Using Subpartition Templates to Describe Composite Partitioned Tables You can create subpartitions in a composite partitioned table using a subpartition template. A subpartition template simplifies the specification of subpartitions by not requiring that a subpartition descriptor be specified for every partition in the table. Instead, you describe subpartitions only once in a template, then apply that subpartition template to every partition in the table. The subpartition template is used whenever a subpartition descriptor is not specified for a partition. If a subpartition descriptor is specified, then it is used instead of the subpartition template for that partition. If no subpartition template is specified, and no subpartition descriptor is supplied for a partition, then a single default subpartition is created. Specifying a Subpartition Template for a Range-Hash Partitioned Table In the case of range-hash partitioned tables, the subpartition template can describe the subpartitions in detail, or it can specify just the number of hash subpartitions. The following example creates a range-hash partitioned table using a subpartition template: Managing Partitioned Tables and Indexes 17-17 Creating Partitioned Tables CREATE TABLE emp_sub_template (deptno NUMBER, empname VARCHAR(32), grade NUMBER) PARTITION BY RANGE(deptno) SUBPARTITION BY HASH(empname) SUBPARTITION TEMPLATE (SUBPARTITION a TABLESPACE ts1, SUBPARTITION b TABLESPACE ts2, SUBPARTITION c TABLESPACE ts3, SUBPARTITION d TABLESPACE ts4 ) (PARTITION p1 VALUES LESS THAN (1000), PARTITION p2 VALUES LESS THAN (2000), PARTITION p3 VALUES LESS THAN (MAXVALUE) ); This example produces the following table description: ■ ■ ■ Every partition has four subpartitions as described in the subpartition template. Each subpartition has a tablespace specified. It is required that if a tablespace is specified for one subpartition in a subpartition template, then one must be specified for all. The names of the subpartitions are generated by concatenating the partition name with the subpartition name in the form: partition name_subpartition name The following query displays the subpartition names and tablespaces: SQL> SELECT TABLESPACE_NAME, PARTITION_NAME, SUBPARTITION_NAME 2 FROM DBA_TAB_SUBPARTITIONS WHERE TABLE_NAME=’EMP_SUB_TEMPLATE’ 3 ORDER BY TABLESPACE_NAME; TABLESPACE_NAME --------------TS1 TS1 TS1 TS2 TS2 TS2 TS3 TS3 TS3 TS4 TS4 TS4 PARTITION_NAME --------------P1 P2 P3 P1 P2 P3 P1 P2 P3 P1 P2 P3 17-18 Oracle9i Database Administrator’s Guide SUBPARTITION_NAME -----------------P1_A P2_A P3_A P1_B P2_B P3_B P1_C P2_C P3_C P1_D P2_D P3_D Creating Partitioned Tables 12 rows selected. Specifying a Subpartition Template for a Range-List Partitioned Table The following example, for a range-list partitioned table, illustrates how using a subpartition template can help you stripe data across tablespaces. In this example a table is created where the table subpartitions are vertically striped, meaning that subpartition n from every partition is in the same tablespace. CREATE TABLE stripe_regional_sales ( deptno number, item_no varchar2(20), txn_date date, txn_amount number, state varchar2(2)) PARTITION BY RANGE (txn_date) SUBPARTITION BY LIST (state) SUBPARTITION TEMPLATE (SUBPARTITION northwest VALUES (’OR’, ’WA’) TABLESPACE tbs_1, SUBPARTITION southwest VALUES (’AZ’, ’UT’, ’NM’) TABLESPACE tbs_2, SUBPARTITION northeast VALUES (’NY’, ’VM’, ’NJ’) TABLESPACE tbs_3, SUBPARTITION southeast VALUES (’FL’, ’GA’) TABLESPACE tbs_4, SUBPARTITION midwest VALUES (’SD’, ’WI’) TABLESPACE tbs_5, SUBPARTITION south VALUES (’AL’, ’AK’) TABLESPACE tbs_6, SUBPARTITION others VALUES (DEFAULT ) TABLESPACE tbs_7 ) (PARTITION q1_1999 VALUES LESS THAN ( TO_DATE(’01-APR-1999’,’DD-MON-YYYY’)), PARTITION q2_1999 VALUES LESS THAN ( TO_DATE(’01-JUL-1999’,’DD-MON-YYYY’)), PARTITION q3_1999 VALUES LESS THAN ( TO_DATE(’01-OCT-1999’,’DD-MON-YYYY’)), PARTITION q4_1999 VALUES LESS THAN ( TO_DATE(’1-JAN-2000’,’DD-MON-YYYY’)) ); If you specified the tablespaces at the partition level (for example, tbs_1 for partition q1_1999, tbs_2 for partition q1_1999, tbs_3 for partition q3_1999, and tbs_4 for partition q4_1999) and not in the subpartition template, then the table would be horizontally striped. All subpartitions would be in the tablespace of the owning partition. Creating Partitioned Index-Organized Tables For index-organized tables, you can use the range or hash partitioning method. However, only range partitioned index-organized tables can contain columns with LOBs. The semantics for creating range or hash-partitioned index-organized tables is similar to that for regular tables with these differences: ■ When you create the table you specify the ORGANIZATION INDEX clause, and INCLUDING and OVERFLOW clauses as necessary. Managing Partitioned Tables and Indexes 17-19 Creating Partitioned Tables ■ The PARTITION or PARTITIONS clauses can have OVERFLOW subclauses that allow you to specify attributes of the overflow segments at the partition level. Specifying an OVERFLOW clause results in the overflow data segments themselves being equi-partitioned with the primary key index segments. Thus, for partitioned index-organized tables with overflow, each partition has an index segment and an overflow data segment. For index-organized tables, the set of partitioning columns must be a subset of the primary key columns. Since rows of an index-organized table are stored in the primary key index for the table, the partitioning criterion has an effect on the availability. By choosing the partition key to be a subset of the primary key, an insert operation only needs to verify uniqueness of the primary key in a single partition, thereby maintaining partition independence. Support for secondary indexes on index-organized tables is similar to the support for regular tables, however, certain maintenance operations do not mark global indexes UNUSABLE, as is the case for regular tables. See Also: ■ "Managing Index-Organized Tables" on page 15-24 ■ "Maintaining Partitioned Tables" on page 17-22 ■ Oracle9i Application Developer’s Guide - Fundamentals and Oracle9i Database Concepts for more information about index-organized tables Creating Range-Partitioned Index-Organized Tables You can partition index-organized tables, and their secondary indexes, by the range method. In the following example, a range-partitioned index-organized table sales is created. The INCLUDING clause specifies all columns after week_no are stored in an overflow segment. There is one overflow segment for each partition, all stored in the same tablespace (overflow_here). Optionally, OVERFLOW TABLESPACE could be specified at the individual partition level, in which case some or all of the overflow segments could have separate TABLESPACE attributes. CREATE TABLE sales(acct_no NUMBER(5), acct_name CHAR(30), amount_of_sale NUMBER(6), week_no INTEGER, sale_details VARCHAR2(1000), PRIMARY KEY (acct_no, acct_name, week_no)) ORGANIZATION INDEX 17-20 Oracle9i Database Administrator’s Guide Creating Partitioned Tables INCLUDING week_no OVERFLOW TABLESPACE overflow_here PARTITION BY RANGE (week_no) (PARTITION VALUES LESS THAN (5) TABLESPACE ts1, PARTITION VALUES LESS THAN (9) TABLESPACE ts2 OVERFLOW TABLESPACE overflow_ts2, ... PARTITION VALUES LESS THAN (MAXVALUE) TABLESPACE ts13); Creating Hash-Partitioned Index-Organized Tables The other option for partitioning index-organized tables is to use the hash method. In the following example the index-organized table, sales, is partitioned by the hash method. CREATE TABLE sales(acct_no NUMBER(5), acct_name CHAR(30), amount_of_sale NUMBER(6), week_no INTEGER, sale_details VARCHAR2(1000), PRIMARY KEY (acct_no, acct_name, week_no)) ORGANIZATION INDEX INCLUDING week_no OVERFLOW PARTITION BY HASH (week_no) PARTITIONS 16 STORE IN (ts1, ts2, ts3, ts4) OVERFLOW STORE IN (ts3, ts6, ts9); Note: Since a well designed hash function is supposed to distribute rows in a well balanced fashion among the partitions, updating the primary key column(s) of a row is very likely to move that row to a different partition. Therefore it is recommended that a hash-partitioned index-organized table with a changeable partitioning key be created with the ROW MOVEMENT ENABLE clause explicitly specified. The default is that ROW MOVEMENT ENABLE is disabled. Managing Partitioned Tables and Indexes 17-21 Maintaining Partitioned Tables Partitioning Restrictions for Multiple Block Sizes Use caution when creating partitioned objects in a database with tablespaces of multiple block size. The storage of partitioned objects in such tablespaces is subject to some restrictions. Specifically, all partitions of the following entities must reside in tablespaces of the same block size: ■ Conventional tables ■ Indexes ■ Primary key index segments of index-organized tables ■ Overflow segments of index-organized tables ■ LOB columns stored out of line Therefore: ■ ■ ■ ■ For each conventional table, all partitions of that table must be stored in tablespaces with the same block size. For each index-organized table, all primary key index partitions must reside in tablespaces of the same block size, and all overflow partitions of that table must reside in tablespaces of the same block size. However, index partitions and overflow partitions can reside in tablespaces of different block size. For each index (global or local), each partition of that index must reside in tablespaces of the same block size. However, partitions of different indexes defined on the same object can reside in tablespaces of different block sizes. For each LOB column, each partition of that column must be stored in tablespaces of equal block sizes. However, different LOB columns can be stored in tablespaces of different block sizes. When you create or alter a partitioned table or index, all tablespaces you explicitly specify for the partitions and subpartitions of each entity must be of the same block size. If you do not explicitly specify tablespace storage for an entity, the tablespaces Oracle uses by default must be of the same block size. Therefore you must be aware of the default tablespaces at each level of the partitioned object. Maintaining Partitioned Tables This section describes how to perform partition and subpartition maintenance operations for both tables and indexes. 17-22 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables Table 17–1 lists maintenance operations that can be performed on table partitions (or subpartitions) and, for each type of partitioning, lists the specific clause of the ALTER TABLE statement that is used to perform that maintenance operation. Table 17–1 ALTER TABLE Maintenance Operations for Table Partitions Maintenance Operation Composite: Range/Hash Composite: Range/List ADD PARTITION ADD PARTITION ADD PARTITION MODIFY PARTITION...ADD SUBPARTITION MODIFY PARTITION...ADD SUBPARTITION COALESCE PARTITION n/a MODIFY PARTITION... COALESCE SUBPARTITION n/a DROP PARTITION n/a DROP PARTITION DROP PARTITION EXCHANGE PARTITION EXCHANGE PARTITION EXCHANGE PARTITION EXCHANGE PARTITION EXCHANGE PARTITION EXCHANGE SUBPARTITION EXCHANGE SUBPARTITION MERGE PARTITIONS MERGE PARTITIONS MERGE PARTITIONS Range Hash List ADD PARTITION ADD PARTITION Coalescing Partitions n/a Dropping Partitions Adding Partitions Exchanging Partitions Merging Partitions (Page 1 of 2) DROP PARTITION DROP SUBPARTITION MERGE PARTITIONS n/a MODIFY DEFAULT ATTRIBUTES MODIFY DEFAULT ATTRIBUTES MODIFY DEFAULT ATTRIBUTES MODIFY DEFAULT ATTRIBUTES MODIFY DEFAULT ATTRIBUTES MODIFY DEFAULT ATTRIBUTES FOR PARTITION MODIFY DEFAULT ATTRIBUTES FOR PARTITION Modifying Real Attributes of Partitions MODIFY PARTITION MODIFY PARTITION MODIFY PARTITION MODIFY PARTITION MODIFY PARTITION MODIFY SUBPARTITION MODIFY SUBPARTITION Modifying List Partitions: Adding Values n/a n/a MODIFY PARTITION... ADD VALUES n/a MODIFY SUBPARTITION... ADD VALUES Modifying List Partitions: Dropping Values n/a n/a MODIFY PARTITION... DROP VALUES n/a MODIFY SUBPARTITION... DROP VALUES Modifying a Subpartition Template n/a n/a n/a SET SUBPARTITION TEMPLATE SET SUBPARTITION TEMPLATE Modifying Default Attributes MERGE SUBPARTITIONS Managing Partitioned Tables and Indexes 17-23 Maintaining Partitioned Tables Table 17–1 ALTER TABLE Maintenance Operations for Table Partitions Maintenance Operation (Page 2 of 2) Composite: Range/Hash Composite: Range/List Range Hash List Moving Partitions MOVE PARTITION MOVE PARTITION MOVE PARTITION MOVE SUBPARTITION MOVE SUBPARTITION Renaming Partitions RENAME PARTITION RENAME PARTITION RENAME PARTITION RENAME PARTITION RENAME PARTITION RENAME SUBPARTITION RENAME SUBPARTITION SPLIT PARTITION n/a SPLIT PARTITION SPLIT PARTITION TRUNCATE PARTITION TRUNCATE PARTITION TRUNCATE PARTITION TRUNCATE PARTITION TRUNCATE PARTITION TRUNCATE SUBPARTITION TRUNCATE SUBPARTITION Splitting Partitions Truncating Partitions SPLIT PARTITION SPLIT SUBPARTITION Note: The first time you introduce a compressed partition into a partitioned table that has bitmap indexes and that currently contains only uncompressed partitions, you must do the following: ■ Either drop all existing bitmap indexes and bitmap index partitions, or mark them UNUSABLE. ■ Set the compression attribute. ■ Rebuild the indexes. These actions are independent of whether any partitions contain data and of the operation that introduces the compressed partition. This does not apply partitioned tables with B-tree indexes. For more information, see the Oracle9i Data Warehousing Guide. Table 17–2 lists maintenance operations that can be performed on index partitions, and indicates on which type of index (global or local) they can be performed. The ALTER INDEX clause used for the maintenance operation is shown. Global indexes do not reflect the structure of the underlying table, and if partitioned, they can only be partitioned by range. Range-partitioned indexes share some, but not all, of the partition maintenance operations that can be performed on range-partitioned tables. 17-24 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables Because local indexes reflect the underlying structure of the table, partitioning is maintained automatically when table partitions and subpartitions are affected by maintenance activity. Therefore, partition maintenance on local indexes is less necessary and there are fewer options. Table 17–2 ALTER INDEX Maintenance Operations for Index Partitions Type of Index Range Hash and List Composite Dropping Index Partitions Global DROP PARTITION - - Local n/a n/a n/a Modifying Default Attributes of Index Partitions Global MODIFY DEFAULT ATTRIBUTES - - Local MODIFY DEFAULT ATTRIBUTES MODIFY DEFAULT ATTRIBUTES MODIFY DEFAULT ATTRIBUTES Maintenance Operation Type of Index Partitioning MODIFY DEFAULT ATTRIBUTES FOR PARTITION Modifying Real Attributes of Index Partitions Global MODIFY PARTITION - - Local MODIFY PARTITION MODIFY PARTITION MODIFY PARTITION MODIFY SUBPARTITION Rebuilding Index Partitions Global REBUILD PARTITION - - Local REBUILD PARTITION REBUILD PARTITION REBUILD SUBPARTITION Renaming Index Partitions Global RENAME PARTITION - - Local RENAME PARTITION RENAME PARTITION RENAME PARTITION Splitting Index Partitions Global SPLIT PARTITION - - Local n/a n/a n/a RENAME SUBPARTITION Managing Partitioned Tables and Indexes 17-25 Maintaining Partitioned Tables Note: The following sections discuss maintenance operations on partitioned tables. Where the usability of indexes or index partitions affected by the maintenance operation is discussed, consider the following: ■ ■ Only indexes and index partitions that are not empty are candidates for being marked UNUSABLE. If they are empty, the USABLE/UNUSABLE status is left unchained. Only indexes or index partitions with USABLE status are updated by subsequent DML. Updating Global Indexes Automatically Before discussing the individual maintenance operations for partitioned tables and indexes, it is important to discuss the effects of the UPDATE GLOBAL INDEXES clause that can be specified in the ALTER TABLE statement. By default, many table maintenance operations on partitioned tables invalidate (mark UNUSABLE) global indexes. You must then rebuild the entire global index or, if partitioned, all of its partitions. Oracle enables you to override this default behavior if you specify UPDATE GLOBAL INDEXES in your ALTER TABLE statement for the maintenance operation. Specifying this clause tells Oracle to update the global index at the time it executes the maintenance operation DDL statement. This provides the following benefits: ■ ■ ■ The global index is updated in conjunction with the base table operation. You are not required to later and independently rebuild the global index. There is higher availability for global indexes, since they do not get marked UNUSABLE. The index remains available even while the partition DDL is executing and it can be used to access other partitions in the table. You avoid having to look up the names of all invalid global indexes used for rebuilding them. But also consider the following performance implications when you specify UPDATE GLOBAL INDEXES: ■ The partition DDL statement takes longer to execute since indexes which were previously marked UNUSABLE are updated. However, this must be compared against the time it takes to execute DDL without updating indexes, and then rebuilding all indexes. A rule of thumb is that it is faster to update indexes if the size of the partition is less that 5% of the size of the table. 17-26 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables ■ ■ ■ The DROP, TRUNCATE, and EXCHANGE operations are no longer fast operations. Again, one must compare the time it takes to do the DDL and then rebuild all global indexes. Updates to the index are logged, and redo and undo records are generated. If the entire index is being rebuilt, it can optionally be done NOLOGGING. Rebuilding the entire index creates a more efficient index, since it is more compact with space better utilized. Further rebuilding the index allows you change storage options. Note: The UPDATE GLOBAL INDEXES clause is not supported for partitioned index-organized tables. The following operations support the UPDATE GLOBAL INDEXES clause: ■ ADD PARTITION|SUBPARTITION (hash only) ■ COALESCE PARTITION|SUBPARTITION ■ DROP PARTITION ■ EXCHANGE PARTITION|SUBPARTITIO ■ MERGE PARTITION ■ MOVE PARTITION|SUBPARTITION ■ SPLIT PARTITION ■ TRUNCATE PARTITION|SUBPARTITION Adding Partitions This section describes how to add new partitions to a partitioned table and explains why partitions cannot be specifically added to global partitioned or local indexes. Adding a Partition to a Range-Partitioned Table Use the ALTER TABLE ... ADD PARTITION statement to add a new partition to the "high" end (the point after the last existing partition). To add a partition at the beginning or in the middle of a table, use the SPLIT PARTITION clause. For example, consider the table, sales, which contains data for the current month in addition to the previous 12 months. On January 1, 1999, you add a partition for January, which is stored in tablespace tsx. Managing Partitioned Tables and Indexes 17-27 Maintaining Partitioned Tables ALTER TABLE sales ADD PARTITION jan96 VALUES LESS THAN ( '01-FEB-1999' ) TABLESPACE tsx; Local and global indexes associated with the range-partitioned table remain usable. Adding a Partition to a Hash-Partitioned Table When you add a partition to a hash-partitioned table, Oracle populates the new partition with rows rehashed from an existing partition (selected by Oracle) as determined by the hash function. The following statements show two ways of adding a hash partition to table scubagear. Choosing the first statement adds a new hash partition whose partition name is system generated, and which is placed in the table’s default tablespace. The second statement also adds a new hash partition, but that partition is explicitly named p_named and is created in tablespace gear5. ALTER TABLE scubagear ADD PARTITION; ALTER TABLE scubagear ADD PARTITION p_named TABLESPACE gear5; Indexes may be marked UNUSABLE as explained in the following table: Table Type Index Behavior Regular (Heap) ■ ■ Index-organized ■ ■ The local indexes for the new partition, and for the existing partition from which rows were redistributed, are marked UNUSABLE and must be rebuilt. Unless you specify UPDATE GLOBAL INDEXES, all global indexes, or all partitions of partitioned global indexes, are marked UNUSABLE and must be rebuilt. For local indexes, the behavior is the same as for heap tables. All global indexes remain usable. Adding a Partition to a List-Partitioned Table The following statement illustrates adding a new partition to a list-partitioned table. In this example physical attributes and NOLOGGING are specified for the partition being added. ALTER TABLE q1_sales_by_region 17-28 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables ADD PARTITION q1_nonmainland VALUES ('HI', 'PR') STORAGE (INITIAL 20K NEXT 20K) TABLESPACE tbs_3 NOLOGGING; Any value in the set of literal values that describe the partition being added must not exist in any of the other partitions of the table. You cannot add a partition to a list-partitioned table that has a default partition, but you can split the default partition. By doing so, you effectively create a new partition defined by the values that you specify, and a second partition that remains the default partition. Local and global indexes associated with the list-partitioned table remain usable. Adding Partitions to a Range-Hash Partitioned Table Partitions can be added at both the range partition level and the hash subpartition level. Adding a Partition to a Range-Hash Partitioned Table Adding a new range partition to a range-hash partitioned table is as described previously in "Adding a Partition to a Range-Partitioned Table". However, you can specify a SUBPARTITIONS clause that allows you to add a specified number of subpartitions, or a SUBPARTITION clause for naming specific subpartitions. If no SUBPARTITIONS or SUBPARTITION clause is specified, the partition inherits table level defaults for subpartitions. This example adds a range partition q1_2000 to table sales, which will be populated with data for the first quarter of the year 2000. There are eight subpartitions stored in tablespace tbs5. ALTER TABLE sales ADD PARTITION q1_2000 VALUES LESS THAN (2000, 04, 01) SUBPARTITIONS 8 STORE IN tbs5; Adding a Subpartition to a Range-Hash Partitioned Table You use the MODIFY PARTITION ... ADD SUBPARTITION clause of the ALTER TABLE statement to add a hash subpartition to a range-hash partitioned table. The newly added subpartition is populated with rows rehashed from other subpartitions of the same partition as determined by the hash function. In the following example, a new hash subpartition us_loc5, stored in tablespace us1, is added to range partition locations_us in table diving. ALTER TABLE diving MODIFY PARTITION locations_us ADD SUBPARTITION us_locs5 TABLESPACE us1; Managing Partitioned Tables and Indexes 17-29 Maintaining Partitioned Tables Local index subpartitions corresponding to the added and rehashed subpartitions must be rebuilt. Unless you specify UPDATE GLOBAL INDEXES, all global indexes, or all partitions of partitioned global indexes, are marked UNUSABLE and must be rebuilt. Adding Partitions to a Range-List Partitioned Table Partitions can be added at both the range partition level and the list subpartition level. Adding a Partition to a Range-List Partitioned Table Adding a new range partition to a range-list partitioned table is as described previously in "Adding a Partition to a Range-Partitioned Table". However, you can specify SUBPARTITION clauses for naming and providing value lists for the subpartitions. If no SUBPARTITION clauses are specified, then the partition inherits the subpartition template. If there is no subpartition template, then a single default subpartition is created. This following statement statements adds a new partition to the quarterly_ regional_sales table that is partitioned by the range-list method. Some new physical attributes are specified for this new partition while table-level defaults are inherited for those that are not specified. ALTER TABLE quarterly_regional_sales ADD PARTITION q1_2000 VALUES LESS THAN (TO_DATE(’1-APR-2000’,’DD-MON-YYYY’)) STORAGE (INITIAL 20K NEXT 20K) TABLESPACE ts3 NOLOGGING ( SUBPARTITION q1_2000_northwest VALUES (’OR’, ’WA’), SUBPARTITION q1_2000_southwest VALUES (’AZ’, ’UT’, ’NM’), SUBPARTITION q1_2000_northeast VALUES (’NY’, ’VM’, ’NJ’), SUBPARTITION q1_2000_southeast VALUES (’FL’, ’GA’), SUBPARTITION q1_2000_northcentral VALUES (’SD’, ’WI’), SUBPARTITION q1_2000_southcentral VALUES (’OK’, ’TX’) ); Adding a Subpartition to a Range-List Partitioned Table You use the MODIFY PARTITION ... ADD SUBPARTITION clause of the ALTER TABLE statement to add a list subpartition to a range-list partitioned table. The following statement adds a new subpartition to the existing set of subpartitions in range-list partitioned table quarterly_regional_sales. The new subpartition is created in tablespace ts2. ALTER TABLE quarterly_regional_sales MODIFY PARTITION q1_1999 17-30 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables ADD SUBPARTITION q1_1999_south VALUES (’AR’,’MS’,’AL’) tablespace ts2; Adding Index Partitions You cannot explicitly add a partition to a local index. Instead, a new partition is added to a local index only when you add a partition to the underlying table. Specifically, when there is a local index defined on a table and you issue the ALTER TABLE statement to add a partition, a matching partition is also added to the local index. Oracle assigns names and default physical storage attributes to the new index partitions, but you can rename or alter them after the ADD PARTITION operation is complete. You can effectively specify a new tablespace for an index partition in an ADD PARTITION operation by first modifying the default attributes for the index. For example, assume that a local index, q1_sales_by_region_locix, was created for list partitioned table q1_sales_by_region. If before adding the new partition q1_nonmainland, as shown in "Adding a Partition to a List-Partitioned Table" on page 17-28, you had issued the following statement, then the corresponding index partition would be created in tablespace tbs_4. ALTER INDEX q1_sales_by_region_locix MODIFY DEFAULT ATTRIBUTES TABLESPACE tbs_4; Otherwise, it would be necessary for you to use the following statement to move the index partition to tbs_4 after adding it: ALTER INDEX q1_sales_by_region_locix REBUILD PARTITION q1_nonmainland TABLESPACE tbs_4; You cannot add a partition to a global index because the highest partition always has a partition bound of MAXVALUE. If you want to add a new highest partition, use the ALTER INDEX ... SPLIT PARTITION statement. Coalescing Partitions Coalescing partitions is a way of reducing the number of partitions in a hash-partitioned table, or the number of subpartitions in a range-hash partitioned table. When a hash partition is coalesced, its contents are redistributed into one or more remaining partitions determined by the hash function. The specific partition that is coalesced is selected by Oracle, and is dropped after its contents have been redistributed. Indexes may be marked UNUSABLE as explained in the following table: Managing Partitioned Tables and Indexes 17-31 Maintaining Partitioned Tables Table Type Index Behavior Regular (Heap) ■ ■ Index-organized Any local index partition corresponding to the selected partition is also dropped. Local index partitions corresponding to the one or more absorbing partitions are marked UNUSABLE and must be rebuilt. Unless you specify UPDATE GLOBAL INDEXES, all global indexes, or all partitions of partitioned global indexes, are marked UNUSABLE and must be rebuilt. ■ Some local indexes are marked UNUSABLE as noted above. ■ All global indexes remain usable. Coalescing a Partition in a Hash-Partitioned Table The ALTER TABLE ... COALESCE PARTITION statement is used to coalesce a partition in a hash-partitioned table. The following statement reduces by one the number of partitions in a table by coalescing a partition. ALTER TABLE ouu1 COALESCE PARTITION; Coalescing a Subpartition in a Range-Hash Partitioned Table The following statement distributes the contents of a subpartition of partition us_ locations into one or more remaining subpartitions (determined by the hash function) of the same partition. Basically, this operation is the inverse of the MODIFY PARTITION ... ADD SUBPARTITION clause discussed in "Adding a Subpartition to a Range-Hash Partitioned Table" on page 17-29. ALTER TABLE diving MODIFY PARTITION us_locations COALESCE SUBPARTITION; Dropping Partitions You can drop partitions from range, composite, list, or composite range-list partitioned tables. For hash-partitioned tables, or hash subpartitions of range-hash partitioned tables, you must perform a coalesce operation instead. Dropping a Table Partition Use one of the following statements to drop a table partition or subpartition: ■ ALTER TABLE ... DROP PARTITION to drop a table partition 17-32 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables ■ ALTER TABLE ... DROP SUBPARTITION to drop a subpartition of a range-list partitioned table If you want to preserve the data in the partition, use the MERGE PARTITION statement instead of the DROP PARTITION statement. If there are local indexes defined for the table, this statement also drops the matching partition or subpartitions from the local index. All global indexes, or all partitions of partitioned global indexes, are marked UNUSABLE unless either of the following are true: ■ ■ You specify UPDATE GLOBAL INDEXES (cannot be specified for index-organized tables) The partition being dropped or its subpartitions are empty Note: You cannot drop the only partition in a table. Instead, you must drop the table. The following sections contain some scenarios for dropping table partitions. Dropping a Partition from a Table that Contains Data and Global Indexes If the partition contains data and one or more global indexes are defined on the table, use one of the following methods to drop the table partition. Method 1: Leave the global indexes in place during the ALTER TABLE ... DROP PARTITION statement. Afterward, you must rebuild any global indexes (whether partitioned or not) because the index (or index partitions) will have been marked UNUSABLE. The following statements provide and example of dropping partition dec98 from the sales table, then rebuilding its global nonpartitioned index. ALTER TABLE sales DROP PARTITION dec98; ALTER INDEX sales_area_ix REBUILD; If index sales_area_ix were a range-partitioned global index, then all partitions of the index would require rebuilding. Further, it is not possible to rebuild all partitions of an index in one statement. You must write a separate REBUILD statement for each partition in the index. The following statements rebuild the index partitions jan99_ix, feb99_ix, mar99_ix, ..., dec99_ix. ALTER INDEX sales_area_ix REBUILD PARTITION jan99_ix; Managing Partitioned Tables and Indexes 17-33 Maintaining Partitioned Tables ALTER INDEX sales_area_ix REBUILD PARTITION feb99_ix; ALTER INDEX sales_area_ix REBUILD PARTITION mar99_ix; ... ALTER INDEX sales_area_ix REBUILD PARTITION nov99_ix; This method is most appropriate for large tables where the partition being dropped contains a significant percentage of the total data in the table. Method 2: Issue the DELETE statement to delete all rows from the partition before you issue the ALTER TABLE ... DROP PARTITION statement. The DELETE statement updates the global indexes, and also fires triggers and generates redo and undo logs. For example, to drop the first partition, which has a partition bound of 10000, issue the following statements: DELETE FROM sales WHERE TRANSID < 10000; ALTER TABLE sales DROP PARTITION dec98; This method is most appropriate for small tables, or for large tables when the partition being dropped contains a small percentage of the total data in the table. Method 3: Specify UPDATE GLOBAL INDEXES in the ALTER TABLE statement. This causes the global index to be updated at the time the partition is dropped. ALTER TABLE sales DROP PARTITION dec98 UPDATE GLOBAL INDEXES; Dropping a Partition Containing Data and Referential Integrity Constraints If a partition contains data and the table has referential integrity constraints, choose either of the following methods to drop the table partition. This table has a local index only, so it is not necessary to rebuild any indexes. Method 1: Disable the integrity constraints, issue the ALTER TABLE ... DROP PARTITION statement, then enable the integrity constraints: ALTER TABLE sales DISABLE CONSTRAINT dname_sales1; ALTER TABLE sales DROP PARTITTION dec98; ALTER TABLE sales 17-34 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables ENABLE CONSTRAINT dname_sales1; This method is most appropriate for large tables where the partition being dropped contains a significant percentage of the total data in the table. Method 2: Issue the DELETE statement to delete all rows from the partition before you issue the ALTER TABLE ... DROP PARTITION statement. The DELETE statement enforces referential integrity constraints, and also fires triggers and generates redo and undo log. DELETE FROM sales WHERE TRANSID < 10000; ALTER TABLE sales DROP PARTITION dec94; This method is most appropriate for small tables or for large tables when the partition being dropped contains a small percentage of the total data in the table. Dropping Index Partitions You cannot explicitly drop a partition of a local index. Instead, local index partitions are dropped only when you drop a partition from the underlying table. If a global index partition is empty, you can explicitly drop it by issuing the ALTER INDEX ... DROP PARTITION statement. But, if a global index partition contains data, dropping the partition causes the next highest partition to be marked UNUSABLE. For example, you would like to drop the index partition P1, and P2 is the next highest partition. You must issue the following statements: ALTER INDEX npr DROP PARTITION P1; ALTER INDEX npr REBUILD PARTITION P2; Note: You cannot drop the highest partition in a global index. Exchanging Partitions You can convert a partition (or subpartition) into a nonpartitioned table, and a nonpartitioned table into a partition (or subpartition) of a partitioned table by exchanging their data segments. You can also convert a hash-partitioned table into a partition of a range-hash partitioned table, or convert the partition of the range-hash partitioned table into a hash-partitioned table. Similarly, you can convert a list-partitioned table into a partition of a range-list partitioned table, or convert the partition of the range-list partitioned table into a list-partitioned table Managing Partitioned Tables and Indexes 17-35 Maintaining Partitioned Tables Exchanging table partitions is most useful when you have an application using nonpartitioned tables that you want to convert to partitions of a partitioned table. For example, you could already have partition views that you want to migrate into partitioned tables. Exchanging partitions also facilitates high-speed data loading when used with transportable tablespaces. When you exchange partitions, logging attributes are preserved. You can optionally specify if local indexes are also to be exchanged (INCLUDING INDEXES clause), and if rows are to be validated for proper mapping (WITH VALIDATION clause). Note: When you specify WITHOUT VALIDATION for the exchange partition operation, this is normally a fast operation because it involves only data dictionary updates. However, if the table or partitioned table involved in the exchange operation has a primary key or unique constraint enabled, then the exchange operation will be performed as if WITH VALIDATION were specified. This is in order to maintain the integrity of the constraints. To avoid the overhead of this validation activity, issue the following statement for each constraint before doing the exchange partition operation: ALTER TABLE table_name DISABLE CONSTRAINT constraint_name KEEP INDEX Then, enable the constraints after the exchange. Unless you specify UPDATE GLOBAL INDEXES (this cannot be specified for index-organized tables), Oracle marks UNUSABLE the global indexes, or all global index partitions, on the table whose partition is being exchanged. Any global indexes, or global index partitions, on the table being exchanged are marked UNUSABLE. See Also: ■ ■ "Converting a Partition View into a Partitioned Table" on page 17-62 "Using Transportable Tablespaces" on page 11-46 for information about transportable tablespaces 17-36 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables Exchanging a Range, Hash, or List Partition To exchange a partition of a range, hash, or list-partitioned table with a nonpartitioned table, or the reverse, use the ALTER TABLE ... EXCHANGE PARTITION statement. An example of converting a partition into a nonpartitioned table follows. In this example, table stocks can be range, hash, or list partitioned. ALTER TABLE stocks EXCHANGE PARTITION p3 WITH stock_table_3; Exchanging a Hash-Partitioned Table with a Range-Hash Partition In this example, you are exchanging a whole hash-partitioned table, with all of its partitions, with a range-hash partitioned table’s range partition and all of its hash subpartitions. This is illustrated in the following example. First, create a hash-partitioned table: CREATE TABLE t1 (i NUMBER, j NUMBER) PARTITION BY HASH(i) (PARTITION p1, PARTITION p2); Populate the table, then create a range-hash partitioned table as shown: CREATE TABLE t2 (i NUMBER, j NUMBER) PARTITION BY RANGE(j) SUBPARTITION BY HASH(i) (PARTITION p1 VALUES LESS THAN (10) SUBPARTITION t2_pls1 SUBPARTITION t2_pls2, PARTITION p2 VALUES LESS THAN (20) SUBPARTITION t2_p2s1 SUBPARTITION t2_p2s2)); It is important that the partitioning key in table t1 is the same as the subpartitioning key in table t2. To migrate the data in t1 to t2, and validate the rows, use the following statement: ALTER TABLE t1 EXCHANGE PARTITION p1 WITH TABLE t2 WITH VALIDATION; Exchanging a Subpartition of a Range-Hash Partitioned Table Use the ALTER TABLE ... EXCHANGE SUBPARTITION statement to convert a hash subpartition of a range-hash partitioned table into a nonpartitioned table, or the reverse. The following example converts the subpartition q3_1999_s1 of table Managing Partitioned Tables and Indexes 17-37 Maintaining Partitioned Tables sales into the nonpartitioned table q3_1999. Local index partitions are exchanged with corresponding indexes on q3_1999. ALTER TABLE sales EXCHANGE SUBPARTITION q3_1999_s1 WITH TABLE q3_1999 INCLUDING INDEXES; Exchanging a List-Partitioned Table with a Range-List Partition The semantics of the ALTER TABLE ... EXCHANGE PARTITION statement are the same as described previously in "Exchanging a Hash-Partitioned Table with a Range-Hash Partition". In the example shown there, the syntax of the CREATE TABLE statements would only need to be modified to create a list-partitioned table and a range-list partitioned table, respectively. The actions involved remain the same. Exchanging a Subpartition of a Range-List Partitioned Table The semantics of the ALTER TABLE ... EXCHANGE SUBPARTITION are the same as described previously in "Exchanging a Subpartition of a Range-Hash Partitioned Table". Merging Partitions Use the ALTER TABLE ... MERGE PARTITIONS statement to merge the contents of two partitions into one partition. The two original partitions are dropped, as are any corresponding local indexes. You cannot use this statement for a hash-partitioned table or for hash subpartitions of a range-hash partitioned table. Unless the involved partitions or subpartitions are empty, indexes may be marked UNUSABLE as explained in the following table: Table Type Index Behavior Regular (Heap) ■ ■ Index-organized ■ ■ 17-38 Oracle9i Database Administrator’s Guide Oracle marks UNUSABLE all resulting corresponding local index partitions or subpartitions. Unless you specify UPDATE GLOBAL INDEXES, all global indexes, or all partitions of partitioned global indexes, are marked UNUSABLE and must be rebuilt. Oracle marks UNUSABLE all resulting corresponding local index partitions or subpartitions. All global indexes remain usable. Maintaining Partitioned Tables Merging Range Partitions You are allowed to merge the contents of two adjacent range partitions into one partition. Non adjacent range partitions cannot be merged. The resulting partition inherits the higher upper bound of the two merged partitions. One reason for merging range partitions is to keep historical data online in larger partitions. For example, you can have daily partitions, with the oldest partition rolled up into weekly partitions, which can then be rolled up into monthly partitions, and so on. The following scripts create an example of merging range partitions. First, create a partitioned table and create local indexes. -- Create a Table with four partitions each on its own tablespace -- Partitioned by range on the data column. -CREATE TABLE four_seasons ( one DATE, two VARCHAR2(60), three NUMBER ) PARTITION BY RANGE ( one ) ( PARTITION quarter_one VALUES LESS THAN ( TO_DATE('01-apr-1998','dd-mon-yyyy')) TABLESPACE quarter_one, PARTITION quarter_two VALUES LESS THAN ( TO_DATE('01-jul-1998','dd-mon-yyyy')) TABLESPACE quarter_two, PARTITION quarter_three VALUES LESS THAN ( TO_DATE('01-oct-1998','dd-mon-yyyy')) TABLESPACE quarter_three, PARTITION quarter_four VALUES LESS THAN ( TO_DATE('01-jan-1999','dd-mon-yyyy')) TABLESPACE quarter_four ); --- Create local PREFIXED index on Four_Seasons -- Prefixed because the leftmost columns of the index match the -- Partition key -CREATE INDEX i_four_seasons_l ON four_seasons ( one,two ) LOCAL ( Managing Partitioned Tables and Indexes 17-39 Maintaining Partitioned Tables PARTITION PARTITION PARTITION PARTITION ); i_quarter_one TABLESPACE i_quarter_one, i_quarter_two TABLESPACE i_quarter_two, i_quarter_three TABLESPACE i_quarter_three, i_quarter_four TABLESPACE i_quarter_four Next, merge partitions. --- Merge the first two partitions -ALTER TABLE four_seasons MERGE PARTITIONS quarter_one, quarter_two INTO PARTITION quarter_two; Then, rebuild the local index for the affected partition. -- Rebuild index for quarter_two, which has been marked unusable -- because it has not had all of the data from Q1 added to it. -- Rebuilding the index will correct this. -ALTER TABLE four_seasons MODIFY PARTITION quarter_two REBUILD UNUSABLE LOCAL INDEXES; Merging List Partitions When you merge list partitions, the partitions being merged can be any two partitions. They do not need to be adjacent, as for range partitions, since list partitioning does not assume any order for partitions. The resulting partition consists of all of the data from the original two partitions. If you merge a default list partition with any other partition, the resulting partition will be the default partition. The statement below merges two partitions of a table partitioned using the list method into a partition that inherits all of its attributes from the table-level default attributes, except for PCTFREE and MAXEXTENTS, which are specified in the statement. ALTER TABLE q1_sales_by_region MERGE PARTITIONS q1_northcentral, q1_southcentral INTO PARTITION q1_central PCTFREE 50 STORAGE(MAXEXTENTS 20); The value lists for the two original partitions were specified as: PARTITION q1_northcentral VALUES ('SD','WI') PARTITION q1_southcentral VALUES ('OK','TX') 17-40 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables The resulting sales_west partition’s value list comprises the set that represents the union of these two partition value lists, or specifically: ■ ('SD','WI','OK','TX') Merging Range-Hash Partitions When you merge range-hash partitions, the subpartitions are rehashed into either the number of subpartitions specified in a SUBPARTITIONS or SUBPARTITION clause, or, if no such clause is included, table-level defaults are used. Note that the inheritance of properties is different when a range-hash partition is split (discussed in "Splitting a Range-Hash Partition" on page 17-54), verses when two range-hash partitions are merged. When a partition is split, the new partitions can inherit properties from the original partition since there is only one parent. However, when partitions are merged, properties must be inherited from table level defaults because there are two parents and the new partition cannot inherit from either at the expense of the other. The following example merges two range-hash partitions: ALTER TABLE all_seasons MERGE PARTITIONS quarter_1, quarter_2 INTO PARTITION quarter_2 SUBPARTITIONS 8; Merging Range-List Partitions Partitions can be merged at the range partition level and subpartitions can be merged at the list subpartition level. Merging Partitions in a Range-List Partitioned Table Merging range partitions in a range-list partitioned table is as described previously in "Merging Range Partitions" on page 17-39. However, when you merge two range-list partitions, the resulting new partition inherits the subpartition descriptions from the subpartition template, if one exists. If no subpartition template exists, then a single default subpartition is created for the new partition. This following statement merges two partitions in the range-list partitioned stripe_regional_sales table. A subpartition template exists for the table. ALTER TABLE stripe_regional_sales MERGE PARTITIONS q1_1999, q2_1999 INTO PARTITION q1_q2_1999 PCTFREE 50 STORAGE(MAXEXTENTS 20); Managing Partitioned Tables and Indexes 17-41 Maintaining Partitioned Tables Some new physical attributes are specified for this new partition while table-level defaults are inherited for those that are not specified. The new resulting partition q1_q2_1999 inherits the high-value bound of the partition q2_1999 and the subpartition value-list descriptions from the subpartition template description of the table. The data in the resulting partitions consists of data from both the partitions. However, there may be cases where Oracle returns an error. This can occur because data may map out of the new partition when both of the following conditions exist: ■ ■ Some of the merged subpartitions’ literal values were not included in the subpartition template The subpartition template does not contain a default partition definition. This error condition can be eliminated by always specifying a default partition in the default subpartition template. Merging Subpartitions in a Range-List Partitioned Table You can merge the contents of any two arbitrary list subpartitions belonging to the same range partition. The resulting subpartition’s value-list descriptor includes all of the literal values in the value lists for the partitions being merged. The following statement merges two subpartitions of a table partitioned using range-list method into a new subpartition located in tablespace ts4: ALTER TABLE quarterly_regional_sales MERGE SUBPARTITIONS q1_1999_northwest, q1_1999_southwest INTO SUBPARTITION q1_1999_west TABLESPACE ts4; The value lists for the original two partitions were: ■ Subpartition q1_1999_northwest was described as (’WA’,’OR’) ■ Subpartition q1_1999_southwest was described as (’AZ’,’NM’,’UT’) The resulting subpartition’s value list comprises the set that represents the union of these two subpartition value lists: ■ Subpartition q1_1999_west has a value list described as (’WA’,’OR’,’AZ’,’NM’,’UT’) The tablespace in which the resulting subpartition is located and the subpartition’s attributes are determined by the partition-level default attributes, except for those specified explicitly. If any of the existing subpartition names are being reused, then 17-42 Oracle9i Database Administrator’s Guide Maintaining Partitioned Tables the new subpartition inherits the subpartition attributes of the subpartition whose name is being reused. Modifying Default Attributes You can modify the default attributes of a table, or for a partition of a composite partitioned table. When you modify default attributes, the new attributes affect only future partitions, or subpartitions, that are created. The default values can still be specifically overridden when creating a new partition or subpartition. Modifying Default Attributes of a Table You modify the default attributes that will be inherited for range, list, or hash partitions using the MODIFY DEFAULT ATTRIBUTES clause of ALTER TABLE. The following example changes the default value of PCTFREE in table emp for any new partitions that are created. ALTER TABLE emp MODIFY DEFAULT ATTRIBUTES PCTFREE 25; For hash-partitioned tables, only the TABLESPACE attribute can be modified. Modifying Default Attributes of a Partition To modify the default attributes inherited when creating subpartitions, use the ALTER TABLE ... MODIFY DEFAULT ATTRIBUTES FOR PARTITION. The following statement modifies the TABLESPACE in which future subpartitions of partition p1 in range-hash partitioned table emp will reside. ALTER TABLE emp MODIFY DEFAULT ATTRIBUTES FOR PARTITION p1 TABLESPACE ts1; Since all subpartitions of a range-hash partitioned table must share the same attributes, except TABLESPACE, it is the only attribute that can be changed. Modifying Default Attributes of Index Partitions In similar fashion to table partitions, you can alter the default attributes that will be inherited by partitions of a range-partitioned global index, or local index partitions of partitioned tables. For this you use the ALTER INDEX ... MODIFY DEFAULT ATTRIBUTES statement. Use the ALTER INDEX ... MODIFY DEFAULT ATTRIBUTES FOR PARTITION statement if you are altering default attributes to be inherited by subpartitions of a composite partitioned table. Managing Partitioned Tables and Indexes 17-43 Maintaining Partitioned Tables Modifying Real Attributes of Partitions It is possible to modify attributes of an existing partition of a table or index. You cannot change the TABLESPACE attribute. Use ALTER TABLESPACE ... MOVE PARTITION/SUBPARTITION to move a partition or subpartition to a new tablespace. Modifying Real Attributes for a Range or List Partition Use the ALTER TABLE ... MODIFY PARTITION statement to modify existing attributes of a range partition or list partition. You can modify segment attributes (except TABLESPACE), or you can allocate and deallocate extents, mark local index partitions UNUSABLE, or rebuild local indexes that have been marked UNUSABLE. If this is a range partition of a range-hash partitioned table, note the following: ■ ■ If you allocate or deallocate an extent, this action is performed for every subpartition of the specified partition. Likewise, changing any other attributes results in corresponding changes to those attributes of all the subpartitions for that partition. The partition level default attributes are changed as well. To avoid changing attributes of existing subpartitions, use the FOR PARTITION clause of the MODIFY DEFAULT ATTRIBUTES statement. The following are some examples of modifying the real attributes of a partition. This example modifies the MAXEXTENTS storage attribute for the range partition sales_q1 of table sales: ALTER TABLE sales MODIFY PARTITION sales_Q1 STORAGE (MAXEXTENTS 10); All of the local index subpartitions of partition ts1 in range-hash partitioned table scubagear are marked UNUSABLE