oracle 10g new features for administrators vol ii

340
Oracle Database 10g: New Features for Administrators Volume II Student Guide D17079GC10 Edition 1.0 February 2004 D39100 ®

Upload: rajaduraia

Post on 27-Nov-2014

214 views

Category:

Documents


10 download

TRANSCRIPT

Page 1: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators

Volume II • Student Guide

D17079GC10

Edition 1.0

February 2004

D39100

®

Page 2: Oracle 10g New Features for Administrators Vol II

Copyright © 2004, Oracle. All rights reserved.

This documentation contains proprietary information of Oracle Corporation. It is provided under a license agreement containing restrictions on use and disclosure and is also protected by copyright law. Reverse engineering of the software is prohibited. If this documentation is delivered to a U.S. Government Agency of the Department of Defense, then it is delivered with Restricted Rights and the following legend is applicable:

Restricted Rights Legend

Use, duplication or disclosure by the Government is subject to restrictions for commercial computer software and shall be deemed to be Restricted Rights software under Federal law, as set forth in subparagraph (c)(1)(ii) of DFARS 252.227-7013, Rights in Technical Data and Computer Software (October 1988).

This material or any portion of it may not be copied in any form or by any means without the express prior written permission of Oracle Corporation. Any other copying is a violation of copyright law and may result in civil and/or criminal penalties.

If this documentation is delivered to a U.S. Government Agency not within the Department of Defense, then it is delivered with “Restricted Rights,” as defined in FAR 52.227-14, Rights in Data-General, including Alternate III (June 1987).

The information in this document is subject to change without notice. If you find any problems in the documentation, please report them in writing to Education Products, Oracle Corporation, 500 Oracle Parkway, Redwood Shores, CA 94065. Oracle Corporation does not warrant that this document is error-free.

Oracle and all references to Oracle Products are trademarks or registered trademarks of Oracle Corporation.

All other products or company names are used for identification purposes only, and may be trademarks of their respective owners.

Authors

Ric Van DykeLex de Haan Christine Jeal Janet SternJean-Francois Verrier

Technical Contributors and Reviewers

Tammy BednarJoel GoodmanDaniela HansellMagnus IsakssonSushil KumarRuss LowenthalPaul Manning Jose Marco-DominguezMughees MinhasSrinivas PutrevuMark RamacherLeng Leng TanS. Matt TaylorSabine TeuberJenny TsaiAmir ValianiHarald van BreederodeJohn Watson

Publisher

Nita K. Brozowski

Page 3: Oracle 10g New Features for Administrators Vol II

Introduction Overview I-2How DBAs Spend Their Time I-3Oracle Database 10g Manageability Goals I-4Database Management Challenges I-5Oracle Database 10g Solution: Self-Managing Database I-6How Oracle Database 10g DBAs Spend Their Time I-7Today’s IT Infrastructure I-8Grid Computing I-9Oracle Database 10g: The Database for the Grid I-10Further Information I-11Suggested Schedule I-12Student Preface I-13

1 Installation Objectives 1-2Installation New Feature Support 1-3Performance Enhancements to Installation 1-4Checking the Pre-Install Requirements 1-5Miscellaneous Installation Enhancements 1-6CD Pack Contents 1-7Management Options 1-8File Storage Options 1-9Backup and Recovery Options 1-10File Storage Options 1-9Backup and Recovery Options 1-10Passwords 1-11Summary 1-12

2 Server Configuration Objectives 2-2Database Configuration Assistant (DBCA) Enhancements 2-3Using Database Control for Management 2-5SYSAUX and DBCA 2-6Using Enterprise Manager 2-7Database Cloning 2-8MetaLink Integration 2-9Database Feature Usage: Statistics Collection 2-10Database Feature Usage: EM Interface 2-11Database Feature Usage: HWM Page 2-12Policy Framework 2-13Policy Framework in EM 2-14Policy Violations Page 2-15Managing Policies 2-16Simplified Initialization Parameters 2-17Viewing Initialization Parameters 2-18Irreversible Data File Compatibility 2-19

Contents

iii

Page 4: Oracle 10g New Features for Administrators Vol II

Response File Improvements 2-20Summary 2-21Practice 2 Overview 2-22

3 Load and Unload Data Objectives 3-2Cross-Platform Transportable Tablespaces 3-3Minimum Compatibility Level 3-4Transportable Tablespace Procedure 3-5Determining the Endian Format of a Platform 3-6Data File Conversion: Examples 3-7CLOB Exception 3-8Dynamic Performance View Changes 3-9Data Pump: Overview 3-10Data Pump: General Architecture 3-11Data Pump Export and Import: Overview 3-12Data Pump Export and Import: Benefits 3-13General Implementation: Overview 3-14Data Pump Direct Path Considerations 3-15Data Pump File Locations 3-16Data Pump File Naming and Size 3-17Data Pump Utility: Interfaces and Modes 3-18Data Pump and Filtering 3-19Data Pump Import Transformations 3-20Data Pump Job Monitoring Views 3-21Database Control and Data Pump 3-22Parallel Full Export and Import: Example 3-23Limited Schema Export: Example 3-24Network Mode Import: Example 3-25Attaching to Existing Job: Example 3-26Restarting Stopped Job: Example 3-27Data-Only Unload: Example 3-28External Table Population: Overview 3-29External Table Population Operation 3-30External Table Parallel Populate Operation 3-31External Table Population: Example 3-32External Table Projected Columns 3-33External Table Projected Column: Examples 3-34Summary 3-35Practice 3 Overview 3-36

iv

Page 5: Oracle 10g New Features for Administrators Vol II

4 Automatic Management Objectives 4-2Oracle Database 10g Solution: Self-Managing Database 4-3Automatic Database Diagnostic Monitor: Overview 4-4ADDM Performance Monitoring 4-5ADDM Methodology 4-6Top Performance Issues Detected 4-7Database Control and ADDM Findings 4-8ADDM Analysis Results 4-9ADDM Recommendations 4-10Database Control and ADDM Task 4-11Changing ADDM Attributes 4-12Retrieving ADDM Reports Using SQL 4-13Automatic Shared Memory Management: Overview 4-14SGA Tuning Principles 4-15Benefits of Automatic Shared Memory Management 4-16Database Control and Automatic Shared Memory Management 4-17Manual Configuration 4-18Behavior of Auto-Tuned SGA Parameters 4-19Behavior of Manually Tuned SGA Parameters 4-20Using the V$PARAMETER View 4-21Resizing SGA_TARGET 4-22Disable Automatic Shared Memory Management 4-23Manually Resizing Dynamic SGA Parameters 4-24Automatic Optimizer Statistics Collection: Overview 4-25GATHER_STATS_JOB 4-26Changing the GATHER_STATS_JOB Schedule 4-27Locking Statistics 4-28Using the DBMS_STATS Package 4-29Automatic Statistics Collection: Considerations 4-30History of Optimizer Statistics 4-31Managing Historical Optimizer Statistics 4-32Automatic Undo Retention Tuning 4-33Automatic Checkpoint Tuning 4-34Summary 4-35Practice 4 Overview 4-36

5 Manageability Infrastructure Objectives 5-2Oracle Database 10g Solution: Self-Managing Database 5-3Automatic Workload Repository 5-4Automatic Workload Repository: Overview 5-5Automatic Workload Repository Data 5-6Active Session History 5-7Base Statistics and Metrics 5-8

v

Page 6: Oracle 10g New Features for Administrators Vol II

Workload Repository 5-9Statistic Levels 5-10AWR Snapshot Baselines 5-11AWR Snapshot Purging Policy 5-12Database Control and AWR 5-13AWR Reports 5-14Statspack and AWR 5-15Server-Generated Alerts 5-16Server-Generated Alerts: Overview 5-17Alert Models Architecture 5-18Server-Generated Alert Types 5-19Out-of-Box Server-Generated Alerts 5-20Database Control Usage Model 5-21Database Control Interface to Alerts 5-22Setting Alert Thresholds 5-23Alerts Notification 5-24Metric Details Severity History 5-25Metric and Alert Views 5-26PL/SQL Interface for Threshold Settings 5-27Alert Consumption: Manual Configuration 5-28Automatic Routine Administration Tasks 5-29Job Scheduler Concepts 5-30DBCA and Automated Tasks 5-31Adding New Tasks Using EM 5-32Adding a New Task Using PL/SQL 5-33Common Manageability Infrastructure: Advisory Framework 5-34Advisory Framework: Overview 5-35Typical Advisor Tuning Session 5-36Database Control and Advisors 5-37DBMS_ADVISOR Package 5-38Dictionary Changes 5-39Using PL/SQL: Example 5-40Summary 5-41Practice 5 Overview 5-42

6 Application TuningObjectives 6-2Oracle Database 10g Solution: Self-Managing Database 6-3Automatic Statistics Gathering 6-4Enhanced Query Optimization 6-5Statistics on Dictionary Objects 6-6Dictionary Statistics: Best Practices 6-7Miscellaneous Statistics-Related Changes 6-8DML Table Monitoring Changes 6-9

vi

Page 7: Oracle 10g New Features for Administrators Vol II

Rule-Based Optimizer Obsolescence 6-10Automatic SQL Tuning: Overview 6-11Application Tuning Challenges 6-12SQL Tuning Advisor: Overview 6-13Stale or Missing Object Statistics 6-14SQL Statement Profiling 6-15Plan Tuning Flow and SQL Profile Creation 6-16SQL Tuning Loop 6-17Access Path Analysis 6-18SQL Structure Analysis 6-19SQL Tuning Advisor: Usage Model 6-20Database Control and SQL Tuning Advisor 6-21SQL Tuning Advisor: Options and Recommendations 6-22DBMS_SQLTUNE Package 6-23DBMS_SQLTUNE: Examples 6-24Automatic SQL Tuning Categories 6-25SQL Access Advisor: Overview 6-26SQL Access Advisor: Usage Model 6-27Possible Recommendations 6-28Typical SQL Access Advisor Session 6-29Recommendation Options 6-30Review Recommendations 6-31SQL Access Advisor: Procedure Flow 6-32Performance Monitoring Solutions 6-33Performance Management Approach 6-34Database Home Page 6-35Database Performance Page 6-36Concurrency Wait Class: Drill Down 6-37Top SQL by Waits: Drill Down 6-38Summary 6-39Practice 6: Overview 6-40

7 Support for Analytical ApplicationsObjectives 7-2MERGE Command Enhancements 7-3Conditional UPDATE and INSERT Statements 7-4Optional DELETE Clause 7-5Partitioned Outer Join: Introduction 7-6Partitioned Outer Join Syntax 7-8Time Series Calculations on Densified Data 7-9Time Series Calculations: Results 7-10

vii

Page 8: Oracle 10g New Features for Administrators Vol II

Integrating Interrow Calculations in SQL 7-11Partitions, Measures, and Dimensions 7-12Interrow Calculations: Conceptual Overview 7-13SQL MODEL: Example 7-16Materialized Join View (MJV) Enhancements 7-18REWRITE_OR_ERROR Hint 7-19REWRITE_TABLE: New Columns 7-20Partition Maintenance Operations (PMOPs) 7-21MV Execution Plans 7-22Tuning Manually Created MVs 7-23Making MVs Fast-Refreshable 7-24MV Decomposition Example 7-25TUNE_MVIEW Usage: Example 7-27MV Refresh Using Trusted Constraints 7-29Partition Change Tracking (PCT) 7-30PCT Using List Partitioning 7-31PCT Using Join Dependency 7-32PCT Using TRUNCATE PARTITION 7-33Forcing PCT-Based Refresh 7-34Summary 7-35Practice 7 Overview 7-36

8 System Resource ManagementObjectives 8-2Oracle Database 10g Solution: Self-Managing Database 8-3Database Resource Manager 8-4Setting Idle Timeouts 8-5Switching Back to the Initial Consumer Group at End of Call 8-6Creating a Mapping Using Database Control 8-7Creating a Mapping Using DBMS_RESOURCE_MANAGER 8-8Assigning Priorities Using DBMS_RESOURCE_MANAGER 8-9Changes to DBMS_RESOURCE_MANAGER Package 8-11Using the RATIO Allocation Method 8-12Monitoring the Resource Manager 8-13Summary 8-14

9 Automating Tasks with the SchedulerObjectives 9-2Scheduling Needs 9-3Scheduler Concepts 9-4Privileges for Scheduler Components 9-6Creating a Scheduler Job 9-8Creating a Scheduler Job: Example 9-9

viii

Page 9: Oracle 10g New Features for Administrators Vol II

Setting the Repeat Interval for a Job 9-10Calendaring Expressions 9-11Using Scheduler Programs 9-12Creating a Program Using EM 9-13Specifying Schedules for a Job 9-14Creating and Using Schedules 9-15Using EM to Create Schedules: Schedule 9-16Advanced Scheduler Concepts 9-17Creating a Job Class 9-18Creating a Job Class Using Enterprise Manager 9-19Job Logging 9-20Creating a Window 9-21Prioritizing Jobs Within a Window 9-23Enabling and Disabling Scheduler Components 9-25Managing Jobs 9-26Managing Programs 9-27Managing Programs with EM 9-28Managing Schedules 9-29Managing Windows 9-30Window Priority 9-32Managing Attributes of Scheduler Components 9-33Managing Attributes of the Scheduler 9-35Viewing Job Execution Details 9-36Viewing Job Logs 9-37Purging Job Logs 9-38Data Dictionary Views 9-40Summary 9-41Practice 9: Overview 9-42

10 Space ManagementObjectives 10-2Oracle Database 10g Solution: Self-Managing Database 10-3Proactive Tablespace Monitoring Overview 10-4Tablespace Space Usage Monitoring 10-5Edit Tablespace Space Usage Thresholds 10-6Edit Tablespace Page 10-7PL/SQL and Tablespace Space Usage Thresholds 10-8Proactive Undo Tablespace Monitoring 10-10Shrinking Segments: Overview 10-11Shrinking Segments: Considerations 10-12Shrinking Segments Using SQL 10-13Segment Shrink: Basic Execution 10-14Segment Shrink: Execution Considerations 10-15

ix

Page 10: Oracle 10g New Features for Administrators Vol II

Database Control and Segment Shrink 10-16Segment Advisor: Overview 10-17Segment Advisor 10-18Growth Trend Report 10-19Segment Resource Estimation 10-20Undo Management Page 10-21Undo Advisor Page 10-22Fast Ramp-Up 10-23Sorted Hash Cluster: Overview 10-24Sorted Hash Cluster: Example 10-25Sorted Hash Cluster: Basic Architecture 10-26Sorted Hash Cluster: Considerations 10-27Summary 10-28Practice 10: Overview 10-29

11 Improved VLDB SupportObjectives 11-2Bigfile Tablespaces: Overview 11-3Bigfile Tablespace Benefits 11-4Bigfile Tablespace Usage Model 11-5Creating Bigfile Tablespaces 11-6SQL Statement Changes and Additions 11-7BFTs and SQL Statements: Examples 11-8Data Dictionary Changes and Additions 11-9Bigfile Tablespaces and DBVERIFY 11-10Configuration Parameters and BFTs 11-11DBMS_UTILITY Package and BFTs 11-12Migration and Bigfile Tablespaces 11-13Extended ROWID Format and BFTs 11-14DBMS_ROWID Package Changes 11-15Temporary Tablespace Group: Overview 11-16Temporary Tablespace Group: Benefits 11-17Creating Temporary Tablespace Groups 11-18Maintaining Temporary Tablespace Groups 11-19Temporary Tablespace Group SQL: Examples 11-20Data Dictionary Changes 11-22Database Control: Creating a Partition 11-23Database Control: Partition Maintenance 11-24Partitioned IOT Enhancements 11-25Local Partitioned Index Enhancements 11-26Skipping Unusable Indexes 11-27Hash-Partitioned Global Indexes: Overview 11-28Contention Scenario 11-29Hash-Partitioned Global Indexes: Benefits 11-30Creating Hash-Partitioned Global Indexes 11-31Adding and Coalescing Partitions 11-32

x

Page 11: Oracle 10g New Features for Administrators Vol II

Range and Hash Global Index Commands 11-33Operations Not Supported 11-34Usage Example 11-35Bitmap Index Storage Enhancements 11-36Summary 11-37Practice 11: Overview 11-38

12 Backup and Recovery EnhancementsObjectives 12-2Oracle Database 10g Solution: Self-Managing Database 12-3New Backup and Recovery Strategy 12-4Flash Backup and Recovery 12-5Defining Flash Recovery Area Using Database Control 12-6Defining a Flash Recovery Area Using SQL 12-7Flash Recovery Area Space Management 12-8Backing Up Data Files to a Flash Recovery Area 12-9Modifying the Flash Recovery Area 12-10Backing Up the Flash Recovery Area 12-11New Flash Recovery Area View 12-12New Flash Recovery Area Columns 12-13Best Practices for the Database and Flash Recovery Area 12-14Changes in SQL Statement Behavior 12-15Recovering with Incrementally Updated Backups 12-17Fast Incremental Backup 12-18Enabling Fast Incremental Backup Using Database Control 12-19Enabling Fast Incremental Backup Using SQL 12-20Monitoring Block Change Tracking 12-21Oracle-Suggested Strategy 12-22RMAN Command Changes 12-23Backup Type Enhancements Using Database Control 12-24Backup Maintenance 12-25Backing Up the Entire Database 12-26Backing Up Individual Tablespaces 12-27Backing Up Data Files and Control Files 12-28Implementing Fast Recovery 12-29Automated Instance Creation and TSPITR 12-30Auxiliary Location in EM 12-31Creating Compressed Backups 12-32Monitoring Compressed Backups 12-33Simplified Recovery Through RESETLOGS 12-34Recovery Through RESETLOGS: Changes 12-35Recovering Data Files Not Backed Up 12-36Dropping a Database 12-37Automatic Channel Failover 12-38

xi

Page 12: Oracle 10g New Features for Administrators Vol II

Enhanced RMAN Scripts 12-39Setting Duration and Throttling Option 12-40Placing All Files in Online Backup Mode 12-41How Does File Status Affect BEGIN BACKUP? 12-42Changes to the END BACKUP Command 12-44How Does File Status Affect END BACKUP? 12-45Summary 12-46Practice 12 Overview 12-47

13 Flashback Any ErrorObjectives 13-2Flashback Time Navigation 13-3Flashback Error Correction 13-4Flashback Database: Overview 13-5Flashback Database Eliminates Restore Time 13-6Flashback Database Architecture 13-7Configuring Flashback Database Using EM 13-8Flashback Your Database Using EM 13-9Manually Configuring Flashback Database 13-10Flashback Database: Examples 13-11Monitoring Flashback Database 13-12Excluding Tablespaces from Flashback Database 13-13Flashback Database Considerations 13-14Flashback Drop: Overview 13-15Recycle Bin 13-16Flash Back Dropped Tables Using EM 13-17Querying the Recycle Bin 13-18Restoring Tables from the Recycle Bin 13-19Recycle Bin Automatic Space Reclamation 13-20Recycle Bin Manual Space Reclamation 13-21Bypassing the Recycle Bin 13-22Querying Dropped Tables 13-23Flashback Drop Considerations 13-24Flashback Versions Query: Overview 13-25Flashback Versions Query Using EM 13-26Flashback Versions Query Syntax 13-27Flashback Versions Query: Example 13-28Flashback Versions Query: Considerations 13-29Flashback Transaction Query: Overview 13-30Flashback Transaction Query Using EM 13-31Querying FLASHBACK_TRANSACTION_QUERY 13-32Using Flashback Versions Query and Flashback Transaction Query 13-33Flashback Transaction Query: Considerations 13-34Flashback Table: Overview 13-35Using EM to Flash Back Tables 13-36

xii

Page 13: Oracle 10g New Features for Administrators Vol II

Flashback Table: Example 13-37Rolling Back a Flashback Table Operation 13-38Flashback Table: Considerations 13-39Guaranteed Undo Retention 13-40SCN and Time Mapping Enhancements 13-41Granting Flashback Privileges 13-42When to Use Flashback Technology 13-43Flashback Technology: Benefits 13-44Summary 13-45Practice 13: Overview 13-46

14 General Storage EnhancementsObjectives 14-2Oracle Database 10g Solution: Self-Managing Database 14-3SYSAUX Tablespace: Overview 14-4SYSAUX Tablespace: Benefits 14-5SYSAUX Occupants 14-6SYSAUX and DBCA 14-7CREATE DATABASE 14-8ALTER TABLESPACE SYSAUX 14-9SYSAUX Tablespace: General Usage 14-10SYSAUX Occupants: Visualization 14-11SYSAUX Occupants: Relocation 14-12SYSAUX Occupants: Relocation Using SQL 14-13Tablespace Rename: Overview 14-14Tablespace Rename: Usage Example 14-15Tablespace Rename: Considerations 14-16Tablespace Rename: Best Practices 14-17Default Permanent Tablespace: Overview 14-18Designating a Default Permanent Tablespace 14-19Default Permanent Tablespace: SQL Examples 14-20Copying Files Using the Database Server 14-21Local Copy: Example 14-22Transferring Files: Example 14-23Copying Files: Considerations 14-24Redo Logfile Size Advisor 14-25Redo Logfile Size Advisor 14-26Summary 14-27Practice 14: Overview 14-28

xiii

Page 14: Oracle 10g New Features for Administrators Vol II

15 Automatic Storage Management (ASM)Objectives 15-2What Is Automatic Storage Management? 15-3ASM: Key Features and Benefits 15-4ASM: New Concepts 15-5ASM: General Architecture 15-6ASM Administration 15-8ASM Instance Functionalities 15-9ASM Instance Creation 15-10ASM Instance Initialization Parameters 15-11Accessing an ASM Instance 15-12Dynamic Performance View Additions 15-13ASM Home Page 15-14ASM Performance Page 15-15Starting Up an ASM Instance 15-17Shutting Down an ASM Instance 15-18ASM Administration 15-19ASM Disk Group 15-20Failure Group 15-21Disk Group Mirroring 15-22Disk Group Dynamic Rebalancing 15-23ASM Administration Page 15-24Create DiskGroup Page 15-25Create or Delete Disk Groups 15-26Adding Disks to Disk Groups 15-27Miscellaneous Alter Commands 15-28Monitoring Long-Running Operations Using V$ASM_OPERATION 15-30ASM Administration 15-31ASM Files 15-32ASM File Names 15-33ASM File Name Syntax 15-34ASM File Name Mapping 15-36ASM File Templates 15-37Template and Alias Examples 15-38Retrieving Aliases 15-39SQL Commands and File Naming 15-40DBCA and Storage Options 15-41Database Instance Parameter Changes 15-42Migrate Your Database to ASM 15-43Summary 15-44Practice 15 Overview 15-45

16 Maintaining SoftwareObjectives 16-2Oracle Database 10g Upgrade Paths 16-3

xiv

Page 15: Oracle 10g New Features for Administrators Vol II

Choose an Upgrade Method 16-4DBUA Advantages 16-5Manual Upgrade: Advantages and Disadvantages 16-6New Pre-Upgrade Information Utility 16-7Oracle Database 10g: Simplified Upgrade 16-8New Post-Upgrade Status Utility 16-9Properly Prepared Upgrade 16-10Creating SYSAUX Tablespace 16-11Recompiling Invalid Objects 16-12Backing Up the Database Before Upgrade 16-13Selecting Database Control 16-14Specifying a Flash Recovery Area 16-15Selecting Passwords 16-16Upgrade Summary 16-17Upgrade Results 16-18Performing the Manual Upgrade 16-19Summary 16-22

17 SecurityObjectives 17-2Virtual Private Database: Overview 17-3Virtual Private Database: Enhancements 17-4Column-Level VPD: Example 17-5Creating a Column-Level Policy 17-6Policy Types: Overview 17-7Static Policies 17-8Context-Sensitive Policies 17-9Sharing Policy Functions 17-10Auditing Mechanisms: Overview 17-11Uniform Audit Trails 17-12Enhanced Enterprise User Auditing 17-13Fine-Grained Auditing Enhancements 17-14Fine-Grained Auditing Policy: Example 17-15Audited DML Statement Considerations 17-16Summary 17-17Practice 17: Overview 17-18

xv

Page 16: Oracle 10g New Features for Administrators Vol II

18 Miscellaneous New FeaturesObjectives 18-2Transaction Monitoring 18-3Dynamic Performance View Changes 18-4V$FAST_START_TRANSACTIONS view 18-5Session-Based Tracing 18-6End-to-End Tracing 18-7New Statistic Aggregation Dimensions 18-8Using Enterprise Manager to Enable Statistics Aggregation 18-9Using DBMS_MONITOR to Enable Statistics Aggregation 18-10Generalized Trace Enabling 18-11Using Enterprise Manager to Enable and View SQL Tracing 18-12Enabling and Disabling Tracing 18-13Configurationless Client Connect 18-14Simplified Shared Server Configuration 18-16Viewing the Dispatcher Configuration 18-18Resumable Space Allocation Enhancements 18-19Flushing the Buffer Cache 18-20MAXTRANS and Maximum Concurrency 18-21Large Object (LOB) Data Type Changes 18-22Implicit Conversion Between CLOB and NCLOB 18-23Regular Expression Support 18-24Matching Mechanism 18-25Syntax: Example 18-26Using REGEXP_LIKE in SQL 18-27Case- and Accent-Insensitive Query and Sort 18-28Changes in Configuration Parameters 18-29Support in SQL and Functions 18-30Quote Operator q 18-31UTL_MAIL Package 18-32UTL_MAIL Examples 18-33UTL_COMPRESS Package 18-34LogMiner Enhancements 18-35Summary 18-36Practice 18 Overview 18-37

A Practices

B Solutions

xvi

Page 17: Oracle 10g New Features for Administrators Vol II

Copyright © 2004, Oracle. All rights reserved.

Automatic Storage Management(ASM)

Page 18: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-2

Copyright © 2004, Oracle. All rights reserved.15-2

Objectives

After completing this lesson, you should be able to do the following:• Understand what Automatic Storage Management

(ASM) is• Install ASM software• Set up initialization parameter files for ASM and

database instances• Execute SQL commands with ASM file names• Start up and shut down ASM instances• Administer ASM disk groups• Use RMAN to migrate your database to ASM

Page 19: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-3

Copyright © 2004, Oracle. All rights reserved.15-3

What Is Automatic Storage Management?

• Portable and high-performancecluster file system

• Manages Oracle database files• Data spread across disks

to balance load• Integrated mirroring across

disks• Solves many storage

management challenges

ASM

Filesystem

Volumemanager

Operating System

Application

Database

What Is Automatic Storage Management?Automatic Storage Management (ASM) is a new feature in Oracle Database 10g. It provides a vertical integration of the file system and the volume manager that is specifically built for Oracle database files. ASM can provide management for single SMP machines or across multiple nodes of a cluster for Oracle Real Application Clusters (RAC) support.

ASM distributes I/O load across all available resources to optimize performance while removing the need for manual I/O tuning. ASM helps DBAs manage a dynamic database environment by allowing them to grow the database size without having to shut down the database to adjust the storage allocation.

ASM can maintain redundant copies of data to provide fault tolerance, or it can be built on top of vendor-supplied reliable storage mechanisms. Data management is done by selecting the desired reliability and performance characteristics for classes of data rather than with human interaction on a per-file basis.

ASM capabilities save DBAs time by automating manual storage and thereby increasing their ability to manage larger databases (and more of them) with increased efficiency.

Page 20: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-4

Copyright © 2004, Oracle. All rights reserved.15-4

ASM: Key Features and Benefits

• Stripes files rather than logical volumes• Online disk reconfiguration and dynamic

rebalancing• Adjustable rebalancing speed• Provides redundancy on a file basis• ASM supports only Oracle database files• Cluster-aware• Automatically installed

ASM: Key Features and BenefitsASM divides files into extents and spreads the extents for each file evenly across all of the disks. ASM uses an index technique to track the placement of each extent. Traditional striping techniques use mathematical functions to stripe complete logical volumes.When your storage capacity changes, ASM does not restripe all of the data, but moves an amount of data proportional to the amount of storage added or removed to evenly redistribute the files and maintain a balanced I/O load across the disks. This is done while the database is active.You can adjust the speed of a rebalance operation to increase its speed or to lower the impact on the I/O subsystem.ASM includes mirroring protection without the need to purchase a third-party Logical Volume Manager. One unique advantage of ASM is that the mirroring is applied on a file basis, rather than on a volume basis. Hence, the same disk group can contain a combination of files protected by mirroring, or not protected at all.ASM supports data files, log files, control files, archive logs, RMAN backup sets, and other Oracle database file types. ASM supports Real Application Clusters and eliminates the need for a Cluster Logical Volume Manager or a Cluster File System.ASM is shipped with the database and does not show up as a separate option in the custom tree installation. It is available in both the Enterprise Edition and Standard Edition installations.

Page 21: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-5

Copyright © 2004, Oracle. All rights reserved.15-5

ASM: New Concepts

Database

Tablespace

Segment

Extent

Oracleblock

Data file

Physicalblock

ASMdisk group

ASM disk

ASM file

Allocation unitFile system

fileor

raw device

ASM: New ConceptsASM does not eliminate any existing database functionality. Existing databases are able to operate as they always have. New files may be created as ASM files, while existing ones are administered in the old way or can be migrated to ASM.The diagram depicts the relationships that exist between the various storage components inside an Oracle database. On the left and center parts of the diagram, you can find the relationships that exist in previous releases. The right part of the diagram shows you the new concepts introduced by ASM in Oracle Database 10g. However, these new concepts are only used to describe file storage, and do not replace any existing concepts like segments and tablespaces.With ASM, database files can now be stored as ASM files. At the top of the new hierarchy you can find what are called ASM disk groups. Any single ASM file is contained in only one disk group. However, a disk group may contain files belonging to several databases, and a single database may use storage from multiple disk groups. As you can see, one disk group is made up of ASM disks, and each ASM disk belongs to only one disk group. Also, ASM files are always spread across all the ASM disks in the disk group. ASM disks are partitioned in allocation units (AU) of one megabyte each. An AU is the smallest contiguous disk space that ASM allocates. ASM does not allow physical blocks to be split across AUs.Note: The graphic deals with only one type of ASM file: data file. However, ASM can be used to store other database file types.

Page 22: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-6

Copyright © 2004, Oracle. All rights reserved.15-6

ASM: General Architecture

ASM InstanceSID=ant

ASM InstanceSID=bee

ASM Disks ASM Disks ASM Disks ASM Disks ASM Disks ASM Disks

ASM Diskgroup Tom ASM Diskgroup Dick ASM Diskgroup Harry

DB InstanceSID=sales

DB InstanceSID=test

DB InstanceSID=sales

DB InstanceSID=test

ASMB

ASMB

FG

FG FG

FG

Node2Node1 Group Servicestom=antdick=antharry=ant

Group Servicestom=beedick=beeharry=bee

DBW0

DBW0DBW0

DBW0ASMB

RBAL RBAL

ARB0

ARBA

…ARB0

ARBA

ASMB

RBAL

RBAL RBAL

RBAL

ASM: General ArchitectureTo use ASM, you must start a special instance called an ASM instance before you start your database instance. ASM instances do not mount databases, but instead manage the metadata needed to make ASM files available to ordinary database instances. Both ASM instances and database instances have access to a common set of disks called disk groups. Database instances access the contents of ASM files directly, communicating with an ASM instance only to get information about the layout of these files.

An ASM instance contains two new background processes. One coordinates rebalance activity for disk groups. It is called RBAL. The second one performs the actual rebalance data extent movements. There can be many of these at a time, and they are called ARB0, ARB1, and so forth. An ASM instance also has most of the same background processes as a database instance (SMON, PMON, LGWR, and so on).

Each database instance using ASM has two new background processes called ASMB and RBAL. RBAL performs global opens of the disks in the disk groups. At database instance startup, ASMB connects as a foreground process into the ASM instance. All communication between the database and the ASM instance is performed via this bridge. This includes physical file changes such as data file creation and deletion. Over this connection, periodic messages are exchanged to update statistics and to verify that both instances are healthy.

Page 23: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-7

ASM: General Architecture (continued)Group Services is used to register the connection information needed by the database instances to find ASM instances. When an ASM instance mounts a disk group, it registers the disk group and connect string with Group Services. The database instance knows the name of the disk group, and can therefore use it to look up connect information for the correct ASM instance.

Like RAC, the ASM instances themselves may be clustered, using the existing Global Cache Services (GCS) infrastructure. There is one ASM instance per node on a cluster. As with existing RAC configurations, ASM requires that the Operating System makes the disks globally visible to all of the ASM instances, irrespective of the node. If there are several database instances for different databases on the same node, they share the same single ASM instance on that node. If the ASM instance on one node fails, all the database instance connected to it also fail. As with RAC, the ASM and database instances on other nodes recover the dead instances and continue operations.

Note: A disk group can contain files for many different Oracle databases. Thus multiple database instances serving different databases can access the same disk group even on a single system without RAC.

Page 24: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-8

Copyright © 2004, Oracle. All rights reserved.15-8

ASM Administration

• ASM instance

• Disk groups and disks

• Files 00100010

Page 25: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-9

Copyright © 2004, Oracle. All rights reserved.15-9

ASM Instance Functionalities

CREATE DISKGROUP

ALTER DISKGROUP DROP DISKGROUP

ALTER SYSTEM RESTRICTED SESSION

ASMinstance

Databaseinstance

ASM Instance FunctionalitiesThe main goal of an ASM instance is to manage disk groups and protect their data. ASM instances also communicate file layout to database instances. In this way, database instances can directly access files stored in disk groups.

There are several new disk group administrative commands. They all require the SYSDBAprivilege and must be issued from an ASM instance.You can add new disk groups. You can also modify existing disk groups to add new disks, remove existing ones, and many other operations. You can remove existing disk groups.

Finally, you can prevent database instances from connecting to an ASM instance. When the command ALTER SYSTEM ENABLE RESTRICTED SESSION is issued to an ASM instance, database instances cannot connect to that ASM instance. Conversely, ALTER SYSTEM DISABLE RESTRICTED SESSION enables connections from database instances. This command permits an ASM instance to start up and mount disk groups for purposes of maintenance without allowing database instances to access the disk groups.

Page 26: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-10

Copyright © 2004, Oracle. All rights reserved.15-10

ASM Instance Creation

ASM Instance CreationWhile creating an ASM-enabled database, DBCA determines if an ASM instance already exists on your host. If there is one, it gives you the list of managed disk groups. You can then make a selection of whose managed disk groups are used for ASM-enabled database storage.

When ASM instance discovery returns an empty list, DBCA creates a new ASM instance.

As part of the ASM instance creation process, DBCA automatically creates an entry in the oratab file on supported platforms. This entry is used for discovery purposes. On Windows platforms where a services mechanism is used, DBCA automatically creates an Oracle Service and the appropriate registry entry to facilitate the discovery of ASM instances.

The following configuration files are also automatically created by DBCA at the time of ASM instance creation: ASM instance parameter file and ASM instance password file.

Before creating the ASM instance, you have the possibility to specify some initialization parameters for the ASM instance. Once the ASM instance is created, DBCA allows you to create new disk groups that you can use to store your database into.

Note: The footprint of an ASM instance is around 100 MB.

Page 27: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-11

Copyright © 2004, Oracle. All rights reserved.15-11

ASM Instance Initialization Parameters

INSTANCE_TYPE = ASM

DB_UNIQUE_NAME = +ASM

ASM_POWER_LIMIT = 1

ASM_DISKSTRING = ’/dev/rdsk/*s2’, ’/dev/rdsk/c1*’

ASM_DISKGROUPS = dgroupA, dgroupB

LARGE_POOL_SIZE = 8MB

ASM Instance Initialization Parameters• INSTANCE_TYPE should be set to ASM for ASM instances.• DB_UNIQUE_NAME specifies the service provider name for which this ASM instance

manages disk groups.The default value of +ASM should be valid for you.• ASM_POWER_LIMIT controls the speed for a rebalance operation. Possible values

range from 1 to 11, with 11 being the fastest. If omitted, this value defaults to 1. The number of slaves for a rebalance operation is derived from the parallelization level specified in a manual rebalance command (POWER), or by the ASM_POWER_LIMITparameter.

• ASM_DISKSTRING is an operating system–dependent value used by ASM to limit the set of disks considered for discovery. When a new disk is added to a disk group, each ASM instance that has the disk group mounted must be able to discover the new disk using its ASM_DISKSTRING. If not specified, it is assumed to be NULL and ASM disk discovery finds all disks to which the ASM instance has read and write access.

• ASM_DISK_GROUPS is the list of names of disk groups to be mounted by an ASM instance at startup, or when the ALTER DISKGROUP ALL MOUNT command is used.

Note: The internal packages used by ASM instances are executed from the LARGE POOL; therefore, you should set the value of the initialization parameter LARGE_POOL_SIZE to a value greater than 8 MB. For other buffer parameters, you can use their default values.

Page 28: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-12

Copyright © 2004, Oracle. All rights reserved.15-12

Accessing an ASM Instance

Disk group Disk group

Storage system

AS SYSDBA AS SYSOPERASM

instance

All operations Nondestructiveoperations

Accessing an ASM InstanceASM instances do not have a data dictionary, so the only way to connect to one is by using OS authentication, that is, SYSDBA or SYSOPER. To connect remotely, a password file must be used.Normally, the SYSDBA privilege is granted through the use of an operating system group. On Unix, this is typically the dba group. By default, members of the dba group have SYSDBA privilege on all instances on the node, including the ASM instance. Users who connect to the ASM instance with the SYSDBA privilege have complete administrative access to all disk groups in the system. The SYSOPER privilege is supported in ASM instances and limits the set of allowable SQL commands to the minimum required for basic operation of an already-configured system. The following commands are available to SYSOPER users:• STARTUP/SHUTDOWN• ALTER DISKGROUP MOUNT/DISMOUNT• ALTER DISKGROUP ONLINE/OFFLINE DISK• ALTER DISKGROUP REBALANCE• ALTER DISKGROUP CHECK• Access to all V$ASM_* views

All other commands, such as CREATE DISKGROUP, ADD/DROP/RESIZE DISK, and so on, require the SYSDBA privilege and are not allowed with the SYSOPER privilege.

Page 29: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-13

Copyright © 2004, Oracle. All rights reserved.15-13

Dynamic Performance View Additions

Storage system

V$ASM_DISKGROUPV$ASM_CLIENT

V$ASM_DISK

V$ASM_FILE

V$ASM_TEMPLATE

V$ASM_ALIAS

V$ASM_OPERATION

Disk group A Disk group B

Dynamic Performance View AdditionsIn an ASM instance, V$ASM_CLIENT contains one row for every database instance using a disk group managed by the ASM instance. In a database instance, it has one row for each disk group with the database name and ASM instance name.In an ASM instance, V$ASM_DISKGROUP contains one row for every disk group discovered by the ASM instance. In a database instance, V$ASM_DISKGROUP has a row for all disk groups mounted or dismounted.In an ASM instance, V$ASM_TEMPLATE contains one row for every template present in every disk group mounted by the ASM instance. In a database instance, it has rows for all templates in mounted disk groups.In an ASM instance, V$ASM_DISK contains one row for every disk discovered by the ASM instance, including disks which are not part of any disk group. In a database instance, it has rows for disks in the disk groups in use by the database instance.In an ASM instance, V$ASM_OPERATION contains one row for every active ASM long-running operation executing in the ASM instance. In a database instance, it contains no rows.In an ASM instance, V$ASM_FILE contains one row for every ASM file in every disk group mounted by the ASM instance. In a database instance, it contains no rows.In an ASM instance, V$ASM_ALIAS contains one row for every alias present in every disk group mounted by the ASM instance. In a database instance, it contains no rows.

Page 30: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-14

Copyright © 2004, Oracle. All rights reserved.15-14

ASM Home Page

ASM Home PageEnterprise Manager provides a user-friendly graphical interface to Oracle database management, administration, and monitoring tasks. Oracle Database 10g extends the existing functionality to transparently support the management, administration, and monitoring of Oracle databases using ASM storage. It also adds support for the new management tasks required for administration of ASM instance and ASM disk groups.

This home page shows the status of the ASM instance along with the metrics and alerts generated by the collection mechanisms. This page also provides the startup and shutdown functionality. Clicking the Alerts link takes the user to an alert details page. The DiskGroup Usage chart shows space used by each client database along with free space.

Page 31: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-15

Copyright © 2004, Oracle. All rights reserved.15-15

ASM Performance Page

ASM Performance PageThe Performance tab of the ASM home page shows the I/O response time and throughput for each disk group.

You can further drill down to view disk-level performance metrics.

Page 32: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-16

Copyright © 2004, Oracle. All rights reserved.15-16

ASM Configuration Page

ASM Configuration PageThe Configuration tab of the ASM home page lets you view or modify the initialization parameters of the ASM instance.

Page 33: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-17

Copyright © 2004, Oracle. All rights reserved.15-17

Starting Up an ASM Instance

$ sqlplus /nolog

SQL> CONNECT / AS sysdba

Connected to an idle instance.

SQL> STARTUP;

ASM instance started

Total System Global Area 147936196 bytes

Fixed Size 324548 bytes

Variable Size 96468992 bytes

Database Buffers 50331648 bytes

Redo Buffers 811008 bytes

ASM diskgroups mounted

Starting Up an ASM InstanceASM instances are started similarly to database instances except that the initialization parameter file contains an entry like INSTANCE_TYPE=ASM. This parameter sets to the ASM value signals the Oracle executable that an ASM instance is starting, and not a database instance.

Furthermore, for ASM instances, the mount option during startup tries to mount the disk groups specified by the ASM_DISKGROUPS initialization parameter. No database is mounted in this case.

Other STARTUP clauses for ASM instances are similar to those for database instances. For example, RESTRICT prevents database instances from connecting to this ASM instance. OPEN is invalid for an ASM instance. NOMOUNT starts up an ASM instance without mounting any disk group.

Page 34: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-18

Copyright © 2004, Oracle. All rights reserved.15-18

Shutting Down an ASM Instance

SHUTDOWN NORMAL

ASM instance

Database instance A Database instance B

1 1

2

3

Shutting Down an ASM InstanceUpon receiving the shutdown command, the ASM instance forwards the shutdown command with the same shutdown mode (NORMAL, IMMEDIATE, TRANSACTIONAL) to all database instances dependent on the ASM instance. Except for the case of SHUTDOWNABORT issued to ASM, the ASM instance waits for all dependent databases to complete their shutdown before ASM shuts down. In the case of ASM SHUTDOWN ABORT, the ASM instance immediately aborts operation. As a result of ASM aborting, it will immediately terminate any open connections, and all dependent databases will immediately abort as a consequence.In a single ASM instance configuration, if the ASM instance fails while disk groups are open for update, then after the ASM instance reinitializes, it reads the disk group’s log and recovers all transient changes. With multiple ASM instances sharing disk groups, if one ASM instance should fail, another ASM instance automatically recovers transient ASM metadata changes caused by the failed instance.The failure of a database instance does not affect ASM instances.An ASM instance is expected to be always up and running on the host. An ASM instance should be brought up automatically whenever the host is rebooted. An ASM instance is expected to use the auto-startup mechanism supported by the underlying operating system. For example, it should run as a Service under Windows.Note: File system failure usually crashes a node.

Page 35: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-19

Copyright © 2004, Oracle. All rights reserved.15-19

ASM Administration

• ASM instance

• Disk groups and disks

• Files 00100010

Page 36: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-20

Copyright © 2004, Oracle. All rights reserved.15-20

ASM Disk Group

• A pool of disks managed asa logical unit

• Partitions total disk space into uniform-sized units

• Spreads each file evenly across all disks

• Coarse- or fine-grain striping based on file type

• Administers disk groups not files

Disk group

ASMinstance

ASM Disk GroupA disk group is a collection of disks managed as a logical unit. Storage is added and removed from disk groups in units of ASM disks. Every ASM disk has an ASM disk name, which is a name common to all nodes in a cluster. The ASM disk name abstraction is required because different hosts can use different operating system names to refer to the same disk.ASM always evenly spreads files in 1 MB allocation-unit chunks across all of the disks in a disk group. This is called COARSE striping. In this way, ASM eliminates the need for manual disk tuning. However, disks in a disk group should have similar size and performance characteristics to obtain optimal I/O tuning.For most installations, there is only a small number of disk groups: for example, one disk group for a work area and one for a recovery area.For files (such as log files) that require low latency, ASM provides fine-grained (128 KB) striping. FINE striping stripes each allocation unit. FINE striping breaks up medium-sized I/O operations into multiple smaller I/O operations that execute in parallel.While the number of files and disks increases, you have to manage only a constant number of disk groups. From a database perspective, disk groups can be specified as the default location for files created in the database.Note: Each disk group is self-describing, containing its own file directory, disk directory, and other directories.

Page 37: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-21

Copyright © 2004, Oracle. All rights reserved.15-21

Failure Group

Controller 1 Controller 2

Failure group 1 Failure group 2

Disk group A

Controller 3

Failure group 3

1 7 131 7 131 7 13

1 7 131 7 131 7 13

1 7 131 7 131 7 13

2

3

4

5

6

Failure GroupA failure group is a set of disks, inside one particular disk group, sharing a common resource whose failure needs to be tolerated. An example of a failure group is a string of SCSI disks connected to a common SCSI controller. A failure of the controller leads to all of the disks on its SCSI bus becoming unavailable, although each of the individual disks is still functional.

What constitutes a failure group is site-specific. It is largely based upon failure modes that a site is willing to tolerate. By default, ASM assigns each disk to its own failure group. When creating a disk group or adding a disk to a disk group, administrators may specify their own grouping of disks into failure groups. After failure groups are identified, ASM can optimize file layout to reduce the unavailability of data due to the failure of a shared resource.

Page 38: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-22

Copyright © 2004, Oracle. All rights reserved.15-22

Disk Group Mirroring

• Mirror at extent level• Mix primary and mirror

extents on each disk• External redundancy:

Defers to hardwaremirroring

• Normal redundancy: – Two-way mirroring– At least two failure groups

• High redundancy: – Three-way mirroring– At least three failure groups

Disk Group MirroringASM has three disk group types that support different types of mirroring: external redundancy, normal redundancy, and high redundancy. External-redundancy disk groups do not provide mirroring. Use an external-redundancy disk group if you use hardware mirroring or if you can tolerate data loss as the result of a disk failure. Normal-redundancy disk groups support two-way mirroring. High-redundancy disk groups provide triple mirroring.ASM uses a unique mirroring algorithm. ASM does not mirror disks; rather, it mirrors extents. As a result, you only need spare capacity in your disk group. When a disk fails, ASM automatically reconstructs the contents of the failed disk on the surviving disks in the disk group by reading the mirrored contents from the surviving disks. In this way, the I/O hit from a disk failure is spread across several disks rather than on a single disk that mirrors the failed drive.When ASM allocates a primary extent of a file to one disk in a disk group, it allocates a mirror copy of that extent to another disk in the disk group. Primary extents on a given disk can have their respective mirror extents on one of several partner disks in the disk group. Each disk in a disk group has the same ratio of primary and mirror extents. ASM ensures that a primary extent and its mirror copy never reside in the same failure group. If you define failure groups for your disk group, ASM can tolerate the simultaneous failure of multiple disks in a single failure group.Note: For disk groups with external redundancy, failure groups are not used because disks in an external-redundancy disk group are presumed to be highly available.

Page 39: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-23

Copyright © 2004, Oracle. All rights reserved.15-23

Disk Group Dynamic Rebalancing

• Automatic online rebalance wheneverstorage configurationchanges

• Only move data proportional to storage added

• No need for manual I/O tuning

• Online migration tonew storage

Disk Group Dynamic Rebalancing• With ASM, the rebalance process is very easy and happens without any intervention

from the DBA or system administrator. ASM automatically rebalances a disk group whenever disks are added or dropped.

• By using index techniques to spread extents on the available disks, ASM does not need to restripe all of the data, but instead only needs to move an amount of data proportional to the amount of storage added or removed to evenly redistribute the files and maintain a balanced I/O load across the disks in a disk group.

• With the I/O balanced whenever files are allocated and whenever the storage configuration changes, the DBA never needs to search for hot spots in a disk group and manually move data to restore a balanced I/O load.

• It is more efficient to add or drop multiple disks at the same time so that they are rebalanced as a single operation. This avoids unnecessary movement of data. With this technique it is easy to achieve online migration of your data. All you need to do is add the new disks in one operation and drop the old ones in one operation.

Page 40: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-24

Copyright © 2004, Oracle. All rights reserved.15-24

ASM Administration Page

ASM Administration PageThe Administration tab of the ASM home page shows the enumeration of disk groups from V$ASM_DISKGROUP.

On this page, you can Create/Edit/Drop a disk group. You can also perform disk group operations like Mount, Dismount, and Rebalance on a selected disk group.

By clicking a particular disk group, you can view all existing disks pertaining to the disk group, and you can add or delete disks as well as checking or resizing disks.

From the Disk Group page you also have access to the Performance page, as well as Templates and Files. You can define your templates and aliases.

Page 41: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-25

Copyright © 2004, Oracle. All rights reserved.15-25

Create DiskGroup Page

Create DiskGroup PageClicking the Create button on the Administration page brings you to this page. You can input disk group name, redundancy mechanism, and the list of disks that you would like to include in the new disk group.

The list of disks is obtained from the V$ASM_DISK fixed view. By default, only the disks with header status of CANDIDATE are shown in the list.

Page 42: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-26

Copyright © 2004, Oracle. All rights reserved.15-26

Create or Delete Disk Groups

CREATE DISKGROUP dgroupA NORMAL REDUNDANCY

FAILGROUP controller1 DISK

’/devices/A1’ NAME diskA1 SIZE 120G FORCE,

’/devices/A2’,

’/devices/A3’

FAILGROUP controller2 DISK

’/devices/B1’,

’/devices/B2’,

’/devices/B3’;

DROP DISKGROUP dgroupA INCLUDING CONTENTS;

Create or Delete Disk GroupsAssume that ASM disk discovery identified the following disks in the directory /devices: A1, A2, A3, A4, B1, B2, B3, and B4. Suppose that disks A1, A2, A3, and A4 are on a separate SCSI controller from disks B1, B2, B3, and B4. The first example illustrates how to set up a disk group called DGROUPA with two failure groups: CONTROLLER1 and CONTROLLER2.The example also uses NORMAL REDUNDANCY for the disk group. This is the default redundancy characteristic. As shown by the example, you can provide an optional disk name. If not supplied, ASM creates a default name of the form <group>_n, where <group> is the disk group name and n is the disk number. Optionally, you can also provide the size for the disk. If not supplied, ASM attempts to determine the size of the disk. If the size cannot be determined, an error is returned. Over-specification of capacity also returns an error. Under-specification of capacity limits what ASM uses. FORCE indicates that a specified disk should be added to the specified disk group even though the disk is already formatted as a member of an ASM disk group. Using the FORCE option for a disk that is not formatted as a member of an ASM disk group returns an error. As shown by the second statement, you can delete a disk group along with all its files. To avoid accidental deletions, the INCLUDING CONTENTS option must be specified if the disk group still contains any files besides internal ASM metadata. The disk group must be mounted. After ensuring that none of the disk group files are open, the group and all its drives are removed from the disk group. Then the header of each disk is overwritten to eliminate the ASM formatting information.

Page 43: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-27

Copyright © 2004, Oracle. All rights reserved.15-27

Adding Disks to Disk Groups

ALTER DISKGROUP dgroupA ADD DISK

’/dev/rdsk/c0t4d0s2’ NAME A5,

’/dev/rdsk/c0t5d0s2’ NAME A6,

’/dev/rdsk/c0t6d0s2’ NAME A7,

’/dev/rdsk/c0t7d0s2’ NAME A8;

ALTER DISKGROUP dgroupA ADD DISK ’/devices/A*’;

Disk formatting

Disk group rebalancing

Adding Disks to Disk GroupsThis example shows how to add disks to a disk group. You execute an ALTER DISKGROUP ADD DISK command to add the disks. The first statement adds four new disks to the DGROUPA disk group.

The second statement demonstrates the interactions of discovery strings. Consider the following configuration:/devices/A1 is a member of disk group DGROUPA./devices/A2 is a member of disk group DGROUPA./devices/A3 is a member of disk group DGROUPA./devices/A4 is a candidate disk.The second command adds A4 to the DGROUPA disk group. It ignores the other disks, even though they match the discovery string, because they are already part of the DGROUPA disk group. As shown by the diagram, when you add a disk to a disk group, the ASM instance ensures that the disk is addressable and usable. The disk is then formatted and rebalanced. The rebalance process is time-consuming as it moves extents from every file onto the new disk.

Note: Rebalance does not block any database operations. The main impact that rebalance has is on the I/O load on the system. The higher the power of the rebalance, the more I/O load it puts on the system. Thus less I/O bandwidth is available for database I/Os.

Page 44: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-28

Copyright © 2004, Oracle. All rights reserved.15-28

Miscellaneous Alter Commands

ALTER DISKGROUP dgroupA DROP DISK A5;

ALTER DISKGROUP dgroupA DROP DISK A6

ADD FAILGROUP fredDISK ’/dev/rdsk/c0t8d0s2’ NAME A9;

ALTER DISKGROUP dgroupB REBALANCE POWER 5;

ALTER DISKGROUP dgroupA UNDROP DISKS;

ALTER DISKGROUP dgroupA DISMOUNT;

ALTER DISKGROUP dgroupA CHECK ALL;

Miscellaneous Alter CommandsThe first statement shows how to remove one of the disks from disk group DGROUPA. The second statement shows how you can add and drop a disk in a single command. The big advantage in this case is that rebalancing is not started until the command completes. The third statement shows how to cancel the drop of the disk dropped in a previous example. The UNDROP command operates only on pending drops of disks, not after drop completion.

The fourth statement rebalances disk group DGROUPB if necessary. This command is generally not necessary because it is automatically done as disks are added, dropped, or resized. However, it is useful if you want to use the POWER clause to override the default and maximum speed defined by the initialization parameter ASM_POWER_LIMIT. You can change the power level of an ongoing rebalance operation by reentering the command with a new level. A power level of zero causes rebalancing to halt until the command is either implicitly or explicitly reinvoked.

The fifth statement dismounts DGROUPA. The MOUNT and DISMOUNT options allow you to make one or more disk groups available or unavailable to the database instances.

Page 45: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-29

Miscellaneous Alter Commands (continued)The sixth statement shows how to verify the internal consistency of disk group metadata and to repair any error found. It is also possible to use the NOREPAIR clause if you just want to be alerted about errors. While the example requests a check across all disks in the disk group, checking can be specified on a file or an individual disk. This command requires that the disk group be mounted. If any error is found, a summary error message is displayed and the details of the detected error are reported in the alert log.

Note: Except for the last two statements, the examples trigger a disk group rebalancing.

Page 46: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-30

Copyright © 2004, Oracle. All rights reserved.15-30

Monitoring Long-Running Operations Using V$ASM_OPERATION

Estimated amount of time (in minutes) for operation termination

EST_MINUTES

Estimated number of allocation units moved per minute

EST_RATE

Estimated number of remaining allocation unitsEST_WORK

Number of allocation units moved so farSOFAR

Power allocated to this operationACTUAL

Power requested for this operationPOWER

State of operation: QUEUED or RUNNINGSTATE

Type of operation: REBALOPERATION

Disk groupGROUP_NUMBER

DescriptionColumn

Monitoring Long-Running Operations Using V$ASM_OPERATION

The ALTER DISKGROUP DROP, RESIZE, and REBALANCE commands return before the operation is complete. To monitor progress of these long-running operations, you can query the V$ASM_OPERATION fixed view. This view is described in the table in this slide.

Page 47: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-31

Copyright © 2004, Oracle. All rights reserved.15-31

ASM Administration

• ASM instance

• Disk groups and disks

• Files 00100010

Page 48: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-32

Copyright © 2004, Oracle. All rights reserved.15-32

ASM Files

Database file

ASM file automatically spread inside dgroupA

CREATE TABLESPACE sample DATAFILE ’+dgroupA’;

1234

1 2 3 4

Automatic ASM filecreation

RMAN

ASM FilesASM files are Oracle database files stored in ASM disk groups. When a file is created, certain file attributes are permanently set. Among these are its protection policy and its striping policy.

ASM files are Oracle-managed files. Any file that is created by ASM is automatically deleted when it is no longer needed. However, ASM files that are created by specifying a user alias are not considered Oracle-managed files. These files are not automatically deleted.

All circumstances where a database must create a new file allow for the specification of a disk group for automatically generating a unique file name.

With ASM, file operations are specified in terms of database objects. Administration of databases never requires knowing the name of a file, though the name of the file is exposed through some data dictionary views or the ALTER DATABASE BACKUP CONTROLFILETO TRACE command.

Because each file in a disk group is physically spread across all disks in the disk group, a backup of a single disk is not useful. Database backups of ASM files must be made with RMAN.

Note: ASM does not manage binaries, alert logs, trace files, or password files.

Page 49: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-33

Copyright © 2004, Oracle. All rights reserved.15-33

ASM File Names

ASM file name

Fully qualified

Incompletewith

templateNumeric Alias Alias with

template Incomplete

Reference Single-filecreation

Multiple-filecreation

ASM File NamesASM file names can take several forms:

• Fully qualified• Numeric• Alias• Alias with template• Incomplete• Incomplete with template

The correct form to use for a particular situation depends on the context of how the file name is used. There are three such contexts:

• When an existing file is being referenced• When a single file is about to be created• When multiple files are about to be created

As shown in the graphic, each context has possible choices for file name form.

Note: ASM files that are created by specifying a user alias are not considered Oracle Managed Files. The files are not automatically deleted.

Page 50: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-34

Copyright © 2004, Oracle. All rights reserved.15-34

ASM File Name Syntax

+<group>/<dbname>/<file_type>/<tag>.<file#>.<incarnation#>

+<group>.<file#>.<incarnation#>

+<group>/<directory1>/…/<directoryn>/<file_name>

+<group>

+<group>(<temp>)

+<group>/<directory1>/…/<directoryn>/<file_name>(<temp>)

ASM File Name SyntaxThese examples give you syntax that you can use to refer to ASM files:

1. Fully qualified ASM file names are used for referencing existing ASM files. They specify a disk group name, a database name, a file type, a type-specific tag, a file number, and an incarnation number. The fully qualified name is automatically generated for every ASM file when it is created. Even if a file is created via an alias, a fully qualified name is also created. Since ASM assigns the name as part of file creation, fully qualified names cannot be used for file creation. The names can be found in the same hierarchical directory structure as alias names. All of the information in the name is automatically derived by ASM. Fully qualified ASM file names are also called system aliases, implying that these aliases are created and maintained by ASM. The end users cannot modify them.A fully qualified name has the following form: +<group>/<dbname>/<file type>/<tag>.<file>.<incarnation>Where:

- <group> is the disk group name- <dbname> is the database name to which the file belongs- <file type> is the Oracle file type (CONTROLFILE, DATAFILE, and so on)- <tag> is type-specific information about the file (like the tablespace name for a

data file)- <file>.<incarnation> is the file/incarnation number pair, used for

uniqueness

Page 51: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-35

ASM file name Syntax (continued)An example of a fully qualified ASM file name is the following:+dgroupA/db1/controlfile/CF.257.8675309

2. Numeric ASM file names are used for referencing existing ASM files. They specify a disk group name, a file number, and an incarnation number. Because ASM assigns the file and incarnation numbers as part of creation, numeric ASM file names cannot be used for file creation. These names do not appear in the ASM directory hierarchy. They are derived from the fully qualified name. These names are never reported to you by ASM, but they can be used in any interface that needs the name of an existing file.An example of a numeric ASM file name is the following:+dgroupA.257.8675309

3. Alias ASM file names are used both for referencing existing ASM files and for creating new ASM files. Alias names specify a disk group name, but instead of a file and incarnation number, they include a user-friendly name string. Alias ASM file names are distinguished from fully qualified or numeric names because they do not end in a dotted pair of numbers. It is an error to attempt to create an alias that ends with a dotted pair of numbers. Alias file names are provided to allow administrators to reference ASM files with human-understandable names. Alias file names are implemented using a hierarchical directory structure, with the slash (/) separating name components. Name components are in UTF-8 format and may be up to 48 bytes in length, but must not contain a slash. This implies a 48 character limit in a single-byte language but a lower limit in a multibyte language depending upon how many multibyte characters are present in the string. The total length of the alias file name, including all components and all separators, is limited to 256 bytes. The components of alias file names can have space between sets of characters, but the space should not be the first or last character of a component. Alias ASM file names are case-insensitive. Here is a possible example of ASM alias file name:+dgroupA/myfiles/control_file1 +dgroupA/A rather LoNg and WeiRd name/for a fileEvery ASM file will be given a fully qualified name during file creation based upon its attributes. An administrator may create an additional alias for each file during file creation, or an alias can be created for an existing file using the ALTER DISKGROUPADD ALIAS command. An alias ASM file name is normally used in the CONTROL_FILES initialization parameter. An administrator may create directorystructures as needed to support whatever naming convention is desired, subject to the 256-byte limit.

4. Alias ASM file names with templates are used only for ASM file creation operations. They specify a disk group name, an alias name, and a file creation template name (see next slide in this lesson). If an alias ASM file name with template is specified, and the alias portion refers to an existing file, then the template specification is ignored. An example of an alias ASM file name with template is the following: +dgroupA/config1(spfile)

5. Incomplete ASM file names are used only for file creation operations. They consist of a disk group name only. ASM uses a default template for incomplete ASM file names as defined by their file type. An example of an incomplete ASM file name is the following:+dgroupA

6. Incomplete ASM file names with templates are used only for file creation operations. They consist of a disk group name followed by a template name. The template name determines the file creation attributes applied to the file. An example of an incomplete ASM file name with template is the following: +dgroupA(datafile)

Page 52: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-36

Copyright © 2004, Oracle. All rights reserved.15-36

ASM File Name MappingOracle File Type <File Type> <Tag> Def Template

Control files controlfile CF/BCF CONTROLFILE

Data files datafile <ts_name>_<file#> DATAFILE

Online logs online_log log_<thread#> ONLINELOG

Archive logs archive_log parameter ARCHIVELOG

Temp files temp <ts_name>_<file#> TEMPFILE

Data file backup pieces backupset Client Specified BACKUPSET

Data file incrementalbackup pieces

backupset Client Specified BACKUPSET

Arch log backup piece backupset Client Specified BACKUPSET

Data file copy datafile <ts_name>_<file#> DATAFILE

Initialization parameters init spfile PARAMETERFILE

Broker configurations drc drc DATAGUARDCONFIG

Flashback logs rlog <thread#>_<log#> FLASHBACK

Change tracking bitmaps CTB BITMAP CHANGETRACKING

Auto backup AutoBackup Client Specified AUTOBACKUP

Data Pump dump set Dumpset dump DUMPSET

Cross-platform converted data files

XTRANSPORT

ASM File Name MappingASM supports most file types required by the database. However, certain classes of file types, such as operating system executables, are not supported by ASM. Each file type is associated with a default template name.

This table specifies ASM-supported file types with their corresponding naming conventions.

When ASM creates a data file for a permanent tablespace (or a temp file for a temporary tablespace), the data file is set to auto-extensible with an unlimited maximum size and 100 MB default size. An AUTOEXTEND clause may override this default.

ASM applies attributes to the files that it creates as specified by the corresponding system default template.

Page 53: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-37

Copyright © 2004, Oracle. All rights reserved.15-37

ASM File Templates

System Template StripedExternal Normal High CONTROLFILE fineunprotected 2-way mirror 3-way mirror

DATAFILE coarseunprotected 2-way mirror 3-way mirror

ONLINELOG fineunprotected 2-way mirror 3-way mirror

ARCHIVELOG coarseunprotected 2-way mirror 3-way mirror

TEMPFILE coarseunprotected 2-way mirror 3-way mirror

BACKUPSET coarseunprotected 2-way mirror 3-way mirror

XTRANSPORT coarseunprotected 2-way mirror 3-way mirror

PARAMETERFILE coarseunprotected 2-way mirror 3-way mirror

DATAGUARDCONFIG coarseunprotected 2-way mirror 3-way mirror

FLASHBACK fineunprotected 2-way mirror 3-way mirror

CHANGETRACKING coarseunprotected 2-way mirror 3-way mirror

AUTOBACKUP coarseunprotected 2-way mirror 3-way mirror

DUMPSET coarseunprotected 2-way mirror 3-way mirror

Unprotected

2-way

Mirror

3-way

Mirror

ASM File TemplatesASM file templates are named collections of attributes applied to files during file creation. Templates simplify file creation by mapping complex file-attribute specifications onto a single name. Templates, while applied to files, are associated with a disk group.When a disk group is created, ASM establishes a set of initial system default templates associated with that disk group. These templates contain the default attributes for the various Oracle database file types. Attributes of the default templates may be changed by the administrator. Additionally, administrators may add their own unique templates as required. This enables you to specify the appropriate file creation attributes as a template for less sophisticated administrators to use. System default templates cannot be deleted.If you need to change an ASM file attribute after the file has been created, the file must be copied via RMAN into a new file with the new attributes. This is the only method of changing file attributes.Depending on the defined disk group redundancy characteristics, the system templates are created with the attributes shown.When defining or altering a template, you can specify if the files should be mirrored or not. You can also specify if the files created under that template are COARSE or FINE striped.Note: The redundancy and striping attributes used for ASM metadata files are predetermined by ASM and are not changeable by the template mechanism.

Page 54: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-38

Copyright © 2004, Oracle. All rights reserved.15-38

ALTER DISKGROUP dgroupA ADD TEMPLATE reliable ATTRIBUTES (MIRROR);

ALTER DISKGROUP dgroupA DROP TEMPLATE reliable;

ALTER DISKGROUP dgroupA DROP FILE ’+dgroupA.268.8675309’;

ALTER DISKGROUP dgroupA ADD DIRECTORY ’+dgroupA/mydir’;

ALTER DISKGROUP dgroupA ADD ALIAS ’+dgroupA/mydir/datafile.dbf’FOR ’+dgroupA.274.38745’;

ALTER DISKGROUP dgroupADROP ALIAS ’+dgroupA/mydir/datafile.dbf’;

Template and Alias Examples

Template and Alias ExamplesThe first statement shows how to add a new template to a disk group. In this example, the RELIABLE template is created in disk group DGROUPA that is two-way mirrored. The second statement shows how you can remove the previously defined template.

The third statement shows you how a file might be removed from a disk group.The fourth statement creates a user directory called MYDIR. The parent directory must exist before attempting to create a subdirectory or alias in that directory. Then, the example creates an alias for file +dgroupA.274.38745. The same code example shows you how to delete the alias. You also have the possibility to drop a directory by using the ALTERDISKGROUP DROP DIRECTORY command. Using the same kind of commands, you can also rename an alias or a directory using the ALTER DISKGROUP RENAME commands.

Page 55: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-39

Copyright © 2004, Oracle. All rights reserved.15-39

Retrieving Aliases

SELECT reference_index INTO :alias_idFROM V$ASM_ALIAS WHERE name = ’+dgroupA’;

SELECT reference_index INTO :alias_id FROM V$ASM_ALIASWHERE parent_index = :alias_id AND name = ’mydir’;

SELECT name FROM V$ASM_ALIAS WHERE parent_index = :alias_id;

Retrieving AliasesSuppose that you want to retrieve all aliases that are defined inside the previously defined directory +dgroupA/mydir. You can traverse the directory tree, as shown in the example.The REFERENCE_INDEX number is usable only for entries that are directory entries in the alias directory. For nondirectory entries, the reference index is set to zero. The example retrieves REFERENCE_INDEX numbers for each subdirectory and uses the last REFERENCE_INDEX as the PARENT_INDEX of needed aliases.

Page 56: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-40

Copyright © 2004, Oracle. All rights reserved.15-40

SQL Commands and File Naming

CREATE CONTROLFILE DATABASE sample

RESETLOGS ARCHIVELOG

MAXLOGFILES 5 MAXLOGHISTORY 100

MAXDATAFILES 10 MAXINSTANCES 2

LOGFILE GROUP 1 (’+dgroupA’,’+dgroupB’) SIZE 100M,

GROUP 2 (’+dgroupA’,’+dgroupB’) SIZE 100M

DATAFILE ’+dgroupA.261.12345678’ SIZE 100M,

’+dgroupA.262.12345678’ SIZE 100M;

SQL Commands and File NamingASM file names are accepted in SQL commands wherever file names are legal. For most commands, there is an alternate method for identifying the file (a file number, for example) so that the name need not be typed. Since one of the principal design objectives of ASM is to eliminate the need for specifying file names, you are discouraged from using ASM file names as much as possible. However, certain commands must have file names as parameters. For example, data files and log files stored in an ASM disk group should be given to the CREATE CONTROLFILE command using the file reference context form. However, the use of the RESETLOGS option requires the use of file creation context form for the specification of the log files.

Page 57: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-41

Copyright © 2004, Oracle. All rights reserved.15-41

DBCA and Storage Options

DBCA and Storage OptionsIn order to support ASM as a storage option, a new screen is added to the DBCA. This allows you to choose the storage options: file system, ASM, or raw devices.

Page 58: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-42

Copyright © 2004, Oracle. All rights reserved.15-42

Database Instance Parameter Changes

INSTANCE_TYPE = RDBMS

LOG_ARCHIVE_FORMAT

DB_BLOCK_SIZE

DB_CREATE_ONLINE_LOG_DEST_n

DB_CREATE_FILE_DEST

DB_RECOVERY_FILE_DEST

CONTROL_FILES

LOG_ARCHIVE_DEST_n

LOG_ARCHIVE_DEST

STANDBY_ARCHIVE_DEST

LARGE_POOL_SIZE = 8MB

Database Instance Parameter ChangesINSTANCE_TYPE defaults to RDBMS and specifies that this instance is an RDBMS instance.LOG_ARCHIVE_FORMAT is ignored if LOG_ARCHIVE_DEST is set to an incomplete ASM file name: +dGroupA, for example. If LOG_ARCHIVE_DEST is set to an ASM directory (for example, +dGroupA/myarchlogdir/), then LOG_ARCHIVE_FORMAT is used and the files are non-OMF. Unique file names for archived logs are automatically created by the Oracle database.DB_BLOCK_SIZE must be set to one of the standard block sizes (2 KB, 4 KB, 8 KB, 16 KB, or 32 KB). Databases using nonstandard block sizes, such as 6 KB, are not supported.The following parameters accept the multifile creation context form of ASM file names as a destination:• DB_CREATE_ONLINE_LOG_DEST_n• DB_CREATE_FILE_DEST• DB_RECOVERY_FILE_DEST• CONTROL_FILES• LOG_ARCHIVE_DEST_n• LOG_ARCHIVE_DEST• STANDBY_ARCHIVE_DEST

Note: Because extent maps for ASM files are allocated from the LARGE_POOL, you must set the LARGE_POOL_SIZE initialization parameter to a value greater than 8 MB.

Page 59: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-43

Copyright © 2004, Oracle. All rights reserved.15-43

Migrate Your Database to ASM

1. Shut down your database cleanly2. Modify your server parameter file to use OMF3. Edit and execute the following RMAN script:STARTUP NOMOUNT;

RESTORE CONTROLFILE FROM ’/u1/c1.ctl’;

ALTER DATABASE MOUNT;

BACKUP AS COPY DATABASE FORMAT ’+dgroup1’;

SWITCH DATABASE TO COPY;

# Repeat command for all online redo log members ...

SQL "ALTER DATABASE RENAME ’/u1/log1’ TO ’+dgroup1’ ";

ALTER DATABASE OPEN RESETLOGS;

# Repeat command for all temporary tablespaces

SQL "ALTER TABLESPACE temp ADD TEMPFILE";

SQL "ALTER DATABASE TEMPFILE ’/u1/temp1’ DROP";

Migrate Your Database to ASMBecause ASM files cannot be accessed through normal operating system interfaces, RMAN is the only means for copying ASM files.

RMAN commands enable non-ASM files to be relocated to an ASM disk group.

The following gives you an overview of the procedure you can use to relocate your entire database to an ASM disk group. It is assumed that you are using a server parameter file:

• Obtain the file names of the current control files and online redo logs using V$CONTROLFILE and V$LOGFILE.

• Shut down the database consistently.• Modify the server parameter file of your database as follows:

- Set the necessary OMF destination parameters to the desired ASM disk group.- Remove the CONTROL_FILES parameter. It will be recreated automatically.

• Edit and then run the RMAN command file (see slide), which backs up the database, switches the current data files to the backups, renames the online redo logs, and recreate the tempfiles. You also have the ability to move only tablespaces or data files using the BACKUP AS COPY command.

• Delete the old database files.

Note: For more information refer to the Backup and Recovery Advanced User’s Guide.

Page 60: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-44

Copyright © 2004, Oracle. All rights reserved.15-44

Summary

In this lesson, you should have learned how to: • Use DBCA to create an ASM instance• Start up and shut down ASM instances• Create and maintain ASM disk groups• Create database files using ASM• Use RMAN to migrate your database to ASM

Page 61: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 15-45

Copyright © 2004, Oracle. All rights reserved.15-45

Practice 15 Overview

This practice covers the following topics:• Use DBCA to create an ASM instance.• Create new ASM disk groups using Database

Control.• Add new tablespace to your database using ASM

disk groups.• Migrate tablespaces to ASM disk groups.

Page 62: Oracle 10g New Features for Administrators Vol II
Page 63: Oracle 10g New Features for Administrators Vol II

Copyright © 2004, Oracle. All rights reserved.

Maintaining Software

Page 64: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-2

16-2 Copyright © 2004, Oracle. All rights reserved.

Objectives

After completing this lesson, you should be able to do the following:• Understand the supported upgrade paths to

Oracle Database 10g• Use new utility to perform pre-upgrade validation

checks • Use simplified upgrade process that automatically

determines the components to be upgraded • Start up the database using a new mode when

upgrading

Page 65: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-3

16-3 Copyright © 2004, Oracle. All rights reserved.

Oracle Database 10g Upgrade Paths

• Direct upgrade supported from:– 9.2.0, 9.0.1, 8.1.7, 8.0.6

• Direct upgrade not supported from:– 8.1.6, 8.1.5, 8.0.5, 8.0.4, 8.0.3, 7.3.4– Must first upgrade to an intermediate release

Oracle Database 10g Upgrade Paths

The path that you must take to upgrade to Oracle Database 10g depends on the release number of your current database. If a direct upgrade is not supported from the release number of your database, then you must first upgrade your database to an intermediate Oracle release. The database can then be upgraded from this intermediate release to the new Oracle Database 10g release.

Note: For the latest information on supportable upgrade paths, please refer to the Database Upgrade Guide, or get information online at OracleMetaLink.

Page 66: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-4

16-4 Copyright © 2004, Oracle. All rights reserved.

Choose an Upgrade Method

Select from one of the available upgrade methods:• Database Upgrade Assistant (DBUA)

– DBUA is a graphical user interface tool that provides a simplified upgrade of a database toOracle Database 10g.

• Manual upgrade– A manual upgrade consists of running SQL scripts

and utilities from the command line.

• Export and Import utilities

Choose an Upgrade MethodYou can ease the process of upgrading a database to Oracle Database 10g through careful planning and use of the Oracle Database 10g tools. Oracle Database 10g supports the following methods for upgrading a database:

• Use the Database Upgrade Assistant (DBUA): This tool can be launched by the Oracle Universal Installer (OUI), depending upon the type of installation you select, and provides a GUI that guides you through the upgrade of a database. During the installation, you can choose not to use DBUA, instead choosing to launch it as a stand-alone tool at any time in the future to upgrade a database.

• Perform a manual upgrade: A manual upgrade provides a command-line upgrade of a database using SQL scripts and utilities.

• Perform a full or partial export from your database: Perform a full or partial export from your database, followed by a full or partial import into a new Oracle Database 10g database. Export and Import can copy a subset of the data in a database. Export and Import leaves the database unchanged and makes a copy of the data.

Note: DBUA is the preferred method of upgrading a database. Oracle Corporation highly recommends using DBUA to upgrade to Oracle Database 10g.

Page 67: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-5

16-5 Copyright © 2004, Oracle. All rights reserved.

DBUA Advantages

• Automatically performs pre-upgrade steps• Optionally backs up any necessary files• Checks for adequate resources• Creates newly required objects• Shows upgrade progress through the upgrade• Writes detailed trace and logging files• Updates all databases and configuration files in a

Real Application Clusters (RAC) environment• Supports silent mode for single-command

upgrade

DBUA Advantages

Your upgrade process is automated by DBUA, which performs all of the tasks you would normally perform manually. Before the upgrade can begin, the following pre-upgrade steps are performed by DBUA:

• Check for any invalid user accounts or roles • Check for any invalid data types• Check for any desupported character sets• Check for adequate resources, including rollback segments, tablespaces, and free disk

space• Optionally backs up all necessary files• Disable archiving during upgrade phase

DBUA automatically modifies or creates newly required tablespaces, invokes the appropriate upgrade scripts, archives the redo logs, and disables archiving during the upgrade phase. While the upgrade is running, DBUA shows the upgrade progress for each component, writes detailed trace and log files, and produces a complete HTML report for later reference. To enhance security, DBUA automatically locks new user accounts in the upgraded database,then proceeds to create new configuration files (parameter and listener files) in the new Oracle home. In a RAC environment, DBUA upgrades all the database and configuration files on all nodes in the cluster. DBUA supports a silent mode of operation where no user interface is presented to the user.

Page 68: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-6

16-6 Copyright © 2004, Oracle. All rights reserved.

Manual Upgrade: Advantages and Disadvantages

Advantages:• The DBA controls every step of the upgrade

process.Disadvantages:• More work:

– Must perform a manual space check for SYSTEMtablespace

– Must manually adjust all obsolete or deprecated initialization parameters

– Must perform a user-driven backup of the database

• Subject to errors

Manual Upgrade: Advantages and DisadvantagesA manual upgrade consists of running SQL scripts and utilities from a command line to upgrade a database to Oracle Database 10g. Depending on the release of the database being upgraded, you may need to perform additional pre-upgrade steps. If you must upgrade to an intermediate release, please check the release documentation for the release that you are upgrading to.

While a manual upgrade gives you finer control over the upgrade process, it is susceptible to error if any of the upgrade or pre-upgrade steps are either not followed or performed out of order. In contrast, DBUA performs all necessary pre-upgrade and upgrade steps.

Page 69: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-7

16-7 Copyright © 2004, Oracle. All rights reserved.

New Pre-Upgrade Information Utility

This new utility performs pre-upgrade validation tasks:• Checks for certain known database settings that

may cause the upgrade to fail; generates warnings• Runs in the context of the database that you are

upgrading (as SYSDBA)• DBUA automatically performs any required actions.• Called by utlu101i.sql script

SQL> spool 10gUP.logSQL> @?/rdbms/admin/utlu101i.sqlAnalyzing database. Please wait. This may take a minute or so...Oracle Database 10.1 Upgrade Information Tool 11-30-2003 19:09:31**********************************************************

New Pre-Upgrade Information UtilityThe Upgrade Information Tool is a SQL script that ships with Oracle Database 10g and must be run in the environment of the database to be upgraded. The tool analyzes the database to be upgraded, alerting you to changes that need to be made to the database to ensure a successful upgrade. DBUA automatically runs the tool as part of its pre-upgrade check. The Upgrade Information Tool checks for the following conditions:

• Database version and compatibility• Redo logs smaller than 4 MB• Updated parameters (for example, shared_pool_size)• Deprecated (renamed) and obsolete parameters• Cluster check• Names of components in database (for example, JVM and Spatial)• Tablespaces

- Increase in size recommendations- New SYSAUX tablespace

• Character set• Installed options• Upgrade time estimate

Page 70: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-8

16-8 Copyright © 2004, Oracle. All rights reserved.

Oracle Database 10g: Simplified Upgrade

• An automatic determination of components to be upgraded – Performs all necessary upgrades in correct

dependency order

• Checks for components in DBA_SERVER_REGISTRY table

• Prior to Oracle Database 10g, much of the script invocation was manual.

Oracle Database 10g: Simplified UpgradeOracle Database 10g simplifies the upgrade procedure by performing all necessary upgrades of database components. It validates the existence of the components from the DBA_SERVER_REGISTRY table.

Page 71: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-9

16-9 Copyright © 2004, Oracle. All rights reserved.

New Post-Upgrade Status Utility

This new utility performs post-upgrade validation tasks:• Queries DBA_SERVER_REGISTRY to determine

upgrade status• Provides information about invalid or incorrect

component upgrades• Provides names of scripts to rerun if necessary• DBUA calls this script to display status and then

takes corrective action.• Called by utlu101s.sql script

SQL> @?/rdbms/admin/utlu101s.sql TEXTPL/SQL procedure successfully completed.

New Post-Upgrade Status Utility The DBA_SERVER_REGISTRY table is used to record and manage information about all the component upgrade. You can query the DBA_SERVER_REGISTRY table to verify the status of installed components.

SQL> select comp_id, comp_name, version, status2 from dba_server_registry;

COMP_ID COMP_NAME VERSION STATUS------- --------------------------- --------- -------CATALOG Oracle Database Catalog Views 10.1.0.2.0 VALIDCATPROC Oracle Database Packages and T 10.1.0.2.0 VALID. . . Output truncatedODM Oracle Data Mining 10.1.0.2.0 VALIDCONTEXT Oracle Text 10.1.0.2.0 VALIDXDB Oracle XML Database 10.1.0.2.0 VALIDAPS OLAP Analytic Workspace 10.1.0.2.0 VALIDXOQ Oracle OLAP API 10.1.0.2.0 VALIDAMD OLAP Catalog 10.1.0.2.0 VALIDSDO Spatial 10.1.0.2.0 VALID15 rows selected.

Note: The preceding output has been formatted.

Page 72: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-10

16-10 Copyright © 2004, Oracle. All rights reserved.

Properly Prepared Upgrade

• Enforced use of UPGRADE mode for database open when performing upgrade:

• Automatically handles the setting of certain system parameters that can otherwise cause problems during upgrade:– Sets job_queue_processes = 0

SQL> startup upgrade;

Properly Prepared UpgradeThe UPGRADE clause instructs Oracle to modify certain system parameters dynamically as required for upgrade. STARTUP DOWNGRADE is also supported.

The UPGRADE mode suppresses certain spurious and unnecessary upgrade (or downgrade) errors: for example, it handles ORA-00942 on DROP TABLE commands. With this new functionality there should be no ORA or PLS errors in the upgrade log file, so it is easier to see if there were any real problems during the upgrade.

You must use the UPGRADE option when upgrading your database, else you receive a "database must be opened with UPGRADE option" error message.

Page 73: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-11

16-11 Copyright © 2004, Oracle. All rights reserved.

Creating SYSAUX Tablespace

Creating SYSAUX Tablespace

A SYSAUX tablespace is automatically added to all new Oracle Database 10g databases that you create. Because it is the default tablespace for many Oracle features and products that previously required their own tablespaces, the SYSAUX tablespace reduces the number of tablespaces that you must maintain. The SYSAUX creation step is automated by DBUA. The DBUA wizard screen prompts you for the SYSAUX tablespace attributes, and DBUA creates SYSAUX using these attributes and executes the appropriate upgrade script to create the users, tables, and other schema objects in SYSAUX. Default values are provided for the tablespace attributes. If the SYSAUX tablespace already exists, you are directed to drop or rename the existing tablespace to make room for the creation of the SYSAUX tablespace. If you specify an existing file name, you must check the Reuse Existing File Name field.

Page 74: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-12

16-12 Copyright © 2004, Oracle. All rights reserved.

Recompiling Invalid Objects

Recompiling Invalid ObjectsWhen you upgrade a database to Oracle Database 10g, many of the PL/SQL modules in your database become invalid. As a result, you need to recompile all existing packages, procedures, and types in the INVALID state. You can choose to recompile these PL/SQL modules at the end of the upgrade time, thereby eliminating the run-time recompilation.

By selecting this option, DBUA recompiles any INVALID PL/SQL modules immediately after the upgrade has completed. This ensures that you do not experience any performance issues later as you begin using your newly upgraded database. Selecting this option is the same as running the utlrp.sql script, which is used to recompile stored PL/SQL and Java code.

DBUA can take advantage of multiple CPUs to speed up this recompilation time. If you have multiple CPUs, an additional section is shown on this page to allow you to change the degree of parallelism. DBUA sets the default degree of parallelism to one less than the number of CPUs that you have on your system.

Page 75: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-13

16-13 Copyright © 2004, Oracle. All rights reserved.

Backing Up the Database Before Upgrade

Backing Up the Database Before UpgradeYou can use DBUA to create a cold backup of your database before the upgrade procedure begins. DBUA does not compress your database files, and the backup directory must be a valid location. You cannot specify a raw device for the backup files. In addition, DBUAcreates a batch file in the directory that you specify, which can be used to restore the database files. On Windows systems, the file is <dbname>BACK.DAT. On UNIX systems, the file is <dbname>back.sh.

Page 76: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-14

16-14 Copyright © 2004, Oracle. All rights reserved.

Selecting Database Control

Selecting Database ControlIf the Oracle Management Agent is installed, then you can choose the Grid Control option and select a Management Service from the drop-down list. After installation, the database is automatically available as a managed target in Oracle Enterprise Manager Grid Control.

You select Database Control to allow Enterprise Manager to manage your database. You can optionally select Enable Email Notifications if you want the SYSMAN user to receive e-mail notifications whenever a specific metric reaches a critical or warning threshold.

You can also enable daily backups to back up your database with a minimum of configuration, based on the scheduled start time that you enter on this page. You can later use Enterprise Manager to further customize your backup strategy.

Page 77: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-15

16-15 Copyright © 2004, Oracle. All rights reserved.

Specifying a Flash Recovery Area

Specifying a Flash Recovery AreaYou use the Flash Recovery Area field to specify the location and size of your flash recovery area. You can use variables to identify some standard locations, such as the Oracle home. When you specify the flash recovery area, you must also set the size of the flash recovery area in the Flash Recovery Area Size field.

Page 78: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-16

16-16 Copyright © 2004, Oracle. All rights reserved.

Selecting Passwords

Selecting PasswordsYou can set a single password that is applied to each of these Enterprise Manager user accounts, or you can provide unique passwords for each.

Page 79: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-17

16-17 Copyright © 2004, Oracle. All rights reserved.

Upgrade Summary

Upgrade SummaryYou can review your upgrade selections from this page before committing to upgrade the database. You should use this page to verify the following upgrade details:

• Database name• Source Oracle home• Source database version• Target Oracle home• Target database version• Upgrade time

DBUA additionally lists the database components to be upgraded and the initialization parameters that are changed during the upgrade.

Scroll down to see the upgrade time. The upgrade time is an estimate of how long the upgrade of the database will take. It does not include the recompilation time of the invalid PL/SQL modules.

Note: After you click Finish and start the upgrade, you cannot go back to previous screens. You can, however, click Stop to stop the upgrade operation. If you click Stop, Oracle Corporation recommends that you remove the database that you are upgrading and restore the backup database.

Page 80: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-18

16-18 Copyright © 2004, Oracle. All rights reserved.

Upgrade Results

Upgrade ResultsYou can use this screen to:

• Examine the results of the upgrade• Manage the passwords in the upgraded database• Restore the original database settings (if necessary)

If you are not satisfied with the upgrade results, you can click Restore. Depending on the method you used to back up your database, the Restore option performs one of two tasks:

• If you used DBUA to back up your database, then clicking Restore restores the original database and the original database settings from the backup.

• If you used your own backup procedure to back up the database, clicking Restore only restores the original database settings. You must perform a database restore manually with your own backup utilities.

Page 81: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-19

16-19 Copyright © 2004, Oracle. All rights reserved.

Performing the Manual Upgrade

1. Install the Oracle 10g software.2. Run the pre-upgrade utility:

3. Make adjustments (per pre-upgrade utility recommendations).

4. Shut down the database to be upgraded:

SQL> spool 10gUP.logSQL> @?/rdbms/admin/utlu101i.sql

SQL> shutdown immediate;

Performing the Manual UpgradePrior to performing a manual upgrade, you should have completed a backup of your database. Follow the instructions in your Oracle operating system–specific documentation to complete the installation of the Oracle Database 10g software using Oracle Universal Installer.

You must copy the Upgrade Information Tool from the new softwareORACLE_HOME/rdbms/admin directory to another directory location, and then run the tool while connected to the database version that you are upgrading. After you have run the utility and made any required recommendations, shut down your database.

Page 82: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-20

16-20 Copyright © 2004, Oracle. All rights reserved.

Performing the Manual Upgrade

5. Switch to new Oracle Database 10g home and start up the 10g database:

6. Create the SYSAUX tablespace.

7. Run the upgrade script:

SQL> startup upgrade;

SQL> spool 92_upgrade.log

SQL> @u0902000.sql

SQL> spool off

Performing the Manual Upgrade (continued)Switch to the new Oracle Database 10g home and start the Oracle Database 10g instance with the STARTUP UPGRADE option. If you see error messages listing obsolete initialization parameters during startup, you can remove these at the next shut down of the database. In Oracle Database 10g, the SYSAUX tablespace is used to consolidate data from a number of tablespaces that were separate in previous releases. The SYSAUX tablespace must be created with the following mandatory attributes: online, permanent, read/write, extent management local, and segment space management auto.

The Upgrade Information Tool provides you with an estimate for the size of the SYSAUXtablespace. You can use the following syntax to create the SYSAUX tablespace:

SQL> CREATE TABLESPACE sysaux DATAFILE ’sysaux01.dbf’2 SIZE 111M REUSE3 EXTENT MANAGEMENT LOCAL4 SEGMENT SPACE MANAGEMENT AUTO5 ONLINE;

You should also check the spool file generated to verify that the packages and procedures compiled successfully.

Page 83: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-21

16-21 Copyright © 2004, Oracle. All rights reserved.

Performing the Manual Upgrade

8. Run the post-upgrade status utility:

9. Recompile any remaining stored PL/SQL and Java code:

SQL> shutdown immediate;SQL> startupSQL> @utlrp.sql

SQL> spool status.logSQL> @?/rdbms/admin/utlu101s.sql TEXTPL/SQL procedure successfully completed.SQL> spool off

Performing the Manual Upgrade (continued)You should review the spool file from the post-upgrade Status Tool. The post-upgrade Status Tool displays the status of the components in the upgraded database, displaying output similar to the following when it is run:

Oracle Database 10.1 Upgrade Status Tool 11-DEC-2003 04:21:42--> Oracle Database Catalog Views Normal successful completion--> Oracle Database Packages and Types Normal successful completion--> JServer JAVA Virtual Machine Normal successful completion--> Oracle XDK Normal successful completion--> Oracle Database Java Packages Normal successful completion--> Oracle XML Database Normal successful completion--> Oracle Workspace Manager Normal successful completion

You now shut down and restart the instance to reinitialize the system parameters for normal operation. The restart also performs Oracle Database 10g initialization for JServer Java Virtual Machine and other components. Executing this clean shutdown flushes all caches, clears buffers, and performs other housekeeping activities. These measures are an important final step to ensure the integrity and consistency of the newly upgraded Oracle Database 10gdatabase. The utlrp.sql script recompiles any remaining stored PL/SQL and Java code. Your database is now upgraded to the new Oracle Database 10g release.

Page 84: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 16-22

16-22 Copyright © 2004, Oracle. All rights reserved.

Summary

In this lesson, you should have learned how to:• Identify which database versions are supported

for direct upgrade• Use new scripts to perform pre- and post-upgrade

validation checks• Use DBCA to simplify the upgrade process• Use STARTUP UPGRADE mode when upgrading

Page 85: Oracle 10g New Features for Administrators Vol II

Copyright © 2004, Oracle. All rights reserved.

Security

Page 86: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-2

Copyright © 2004, Oracle. All rights reserved.17-2

Objectives

After completing this lesson, you should be able to do the following:• Apply a column-level Virtual Private Database

policy• Apply static and nonstatic policies• Share VPD policy functions• Use the unified audit trails• Use fine-grained auditing for DML statements

Page 87: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-3

Copyright © 2004, Oracle. All rights reserved.17-3

Virtual Private Database: Overview

• Virtual Private Database consists of:– Fine-grained access control– Secure application context

• Uses policies to rewrite SQL statements to protect sensitive data

• Application attributes defined inside an application context are used by fine-grained access policies.

Virtual Private Database: OverviewVirtual Private Database (VPD) is the aggregation of server-enforced fine-grained access control and secure application context in the Oracle database. VPD enables you to build applications that enforce your security policies at the row level. When a user directly or indirectly accesses a table, a view, or a synonym associated with a VPD security policy, the server dynamically modifies the user’s SQL statement. The modification is based on a WHERE clause returned by a function which implements the security policy. The database modifies the statement dynamically (transparently to the user) using any condition that can be expressed in, or returned by, a function.

Application context is a feature that allows application developers to define, set, and access application attributes, and then use these attributes to supply the predicate values for fine-grained access control policies.

Note: Although application context is an integral part of VPD, it can be implemented alone, without fine-grained access control.

Page 88: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-4

Copyright © 2004, Oracle. All rights reserved.17-4

Virtual Private Database: Enhancements

• Column-level VPD enforces row-level access control based on accessed security columns.

• Customization allows you to define static and nonstatic policies.

• Shared policies allow you to associate one policy with multiple objects.

• Policy type can be INDEX.

• Policy predicate text string can be 32 KB long.

Virtual Private Database: Enhancements• Column-level privacy enforces row-level access control only when a command

accesses or references security-relevant columns. If you do not specify any relevant columns then the database applies VPD rewrites to all commands that access or reference the object. This behavior is consistent with previous releases.

• Customization provides the flexibility for all types of policy implementations to base VPD on the individual requirements of customers’ deployments. You can customize VPD to always enforce the same predicate with a static policy, or you can have VPD predicates that change dynamically with a nonstatic policy.

• Shared policies allow you to apply a single VPD policy to multiple objects. This feature reduces administration costs.

• You can now enforce security policies on index maintenance operations performed with the DDL statements CREATE INDEX and ALTER INDEX. This is important because users need full table access to create table indexes. Consequently, a user who has privileges to maintain an index can see all the row data although the user does not have full table access under a regular query.

• The DBMS_RLS.ADD_POLICY has the new argument LONG_PREDICATE. Its default value is FALSE so that the policy function may return up to 4000 bytes of predicate length. Setting this value to TRUE allows the function to return up to 32 KB of predicate text string.

Page 89: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-5

Copyright © 2004, Oracle. All rights reserved.17-5

Column-Level VPD: Example

• Statements are not always rewritten.• Consider a policy protecting the SALARY and the

COMMISSION_PCT columns of the EMPLOYEEStable. The fine-grained access control is:– Not enforced for this query

– Enforced for these queries

SQL> SELECT last_name, salary2 FROM employees;

SQL> SELECT last_name FROM employees;

SQL> SELECT * FROM employees;

Column-Level VPD: ExampleIn this example, the business policy, and therefore the imposed VPD policy, is that a manager can access EMPLOYEES sensitive information only for his employees.

The Oracle database does not enforce the VPD policy when you select only the LAST_NAME column from the EMPLOYEES table. So all employees can accessnonsensitive information in the EMPLOYEES table.

However, when you issue queries that access columns considered as security-relevant, then VPD applies the fine-grained access control defined by the policy function.

One of the benefits of using column-level VPD is that the statements are only rewritten when they access security-relevant columns. This means that the combination of row-level access control and security-relevant columns implies that you can control access down to theelement referenced.

Note: Some commands explicitly reference the columns and others reference them implicitly. Depending on how you defined the policy function, it can be applied for DML statements as well.

Page 90: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-6

Copyright © 2004, Oracle. All rights reserved.17-6

Creating a Column-Level Policy

BEGINdbms_rls.add_policy(object_schema => ’hr’,object_name => ’employees’,policy_name => ’hr_policy’,function_schema =>’hr’,policy_function => ’hrsec’,statement_types =>’select,insert’,sec_relevant_cols=>’salary,commission_pct’);

END;/

Creating a Column-Level PolicyYou must follow these steps to apply a column-level VPD policy:

• Grant the appropriate privilege to the user who applies the policy.GRANT EXECUTE ON dbms_rls to admin1;

• Create the function that implements the VPD policy. The policy can optionally access an application context or it can be simpler, such as dependent on the time of the day. This step is exactly the same as with previous releases.

• Apply the policy to the table, view, or synonym by using the DBMS_RLS package. In the example, you apply the policy implemented by the HRSEC function to the EMPLOYEES table. You also set the policy to only apply the VPD predicate for SELECT and INSERT statements. The two security-relevant columns in the EMPLOYEES table are SALARY and COMMISSION_PCT.

Page 91: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-7

Copyright © 2004, Oracle. All rights reserved.17-7

Policy Types: Overview

• Five different policy types:– DBMS_RLS.STATIC

– DBMS_RLS.SHARED_STATIC

– DBMS_RLS.CONTEXT_SENSITIVE

– DBMS_RLS.SHARED_CONTEXT_SENSITIVE

– DBMS_RLS.DYNAMIC

• Specify how often a policy function should be reevaluated

• Used to avoid:– Unnecessary policy function execution– Policy function redundancy

Policy Types: OverviewThe execution of policy functions can consume a significant amount of system resources. If you can minimize the number of times that policy functions must execute, then you can optimize your database performance.

In previous releases, policies were dynamic by default. This means that the Oracle database executed the policy function for each DML statement. In addition to dynamic policies, Oracle Database 10g provides static and context-sensitive policies. These policy types provide a way to improve server performance because they do not always reexecute policy functions for each DML statement, and they can be shared across multiple database objects.

The five different policy types are listed in the slide. The DBMS_RLS.DYNAMIC type is the default and corresponds to what was available in previous releases. This means that the Oracle database assumes that the predicate may be affected by any system or session attribute. The Oracle database makes no assumption about when the change takes place, and therefore always reexecutes the policy function on each statement parsing or execution.

Page 92: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-8

Copyright © 2004, Oracle. All rights reserved.17-8

Static Policies

• The policy function is evaluated once.• The resulting policy predicate is cached in SGA.• Every statement accessing protected objects uses

the same policy predicate.• Shared policies allow you to share the same policy

function with different objects.

exec dbms_rls.add_policy(object_schema =>’hr’, object_name => ’employees’, -policy_name => ’hr_policy’ , -function_schema =>’hr’,policy_function=>’hrsec’ , -statement_types => ’select,insert’ , -policy_type => dbms_rls.static , -sec_relevant_cols =>’salary,commission_pct’);

Static PoliciesWhen you use static policies, VPD always enforces the same predicate for access control. Regardless of which user accesses the objects, everyone gets the same predicate.The Oracle database only needs to execute the policy function once. The returned predicate is cached in SGA for all static policies with the same policy function. This makes static policies very fast since the database does not reexecute the policy function for each query.You use a static policy when every query needs the same policy predicate.For the static category, shared static policies allow you to share the same policy function with multiple objects. The caching behavior in this case is exactly the same except that the Oracle database first looks for cached predicates generated by the same policy function of the same policy type.You enable static or shared static policies by setting the POLICY_TYPE parameter of the DBMS_RLS.ADD_POLICY procedure to DBM_RLS.STATIC or DBMS_RLS.SHARED_STATIC, respectively.In this example, the business policy is that a manager can access EMPLOYEES sensitive information only for his employees.Note: Although the policy predicate is the same for every rewritten statements, each execution of the same rewritten statement could produce a different row set because the predicate may filter the data differently based on context attributes or functions like SYSDATE.

Page 93: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-9

Copyright © 2004, Oracle. All rights reserved.17-9

Context-Sensitive Policies

• The policy function is evaluated for each session when:– The statement is first parsed– There is a related local application context change

• The resulting policy predicate is cached in the user’s session memory.

exec dbms_rls.add_policy(object_schema =>’hr’, object_name =>’employees2’, -policy_name => ’hr_policy2’ , -function_schema =>’hr’,policy_function=>’hrsec2’, -statement_types => ’select,insert’ , -policy_type => dbms_rls.context_sensitive , -sec_relevant_cols =>’salary,commission_pct’);

Context-Sensitive PoliciesThere are cases where policy predicates should be static for a particular user session, though different users may be subjected to different predicates. There are also cases where the policy predicate can change when certain context attributes are changed within a user session. So a context-sensitive policy assumes that the policy predicate may be changed after statement parsing for a particular database session, and that such change can occur only if there are some session context changes. Therefore the server reevaluates the policy function at statement execution time if it detects context changes since the last use of the cursor. The policy predicate is cached in the session memory.When a context-sensitive policy shares its policy function, the caching behavior is similar except that the server first looks for cached policy predicate generated by the same policy function for the same policy type within the same database session.You use a context-sensitive policy when a predicate need not change for a user’s session, but the policy must enforce two or more different predicates for different users. You enable context-sensitive or shared context-sensitive policies by setting the POLICY_TYPEparameter of the DBMS_RLS.ADD_POLICY procedure to DBM_RLS.CONTEXT_SENSITIVE or DBMS_RLS.SHARED_CONTEXT_SENSITIVE, respectively.In this example, the business policy is that a manager can access EMPLOYEES2 sensitive information only for his employees, and employees who are not managers can access only their own sensitive information.

Page 94: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-10

Copyright © 2004, Oracle. All rights reserved.17-10

Sharing Policy Functions

departments

countries

emp_v

employees

Same policyfunction

Sharing Policy FunctionsWith Oracle Database 10g, you can apply both the static and nonstatic VPD policies to multiple objects. These policies are called shared policies.

With shared policies, you can enforce a company’s business policy (such as “Users should only see data relevant to their business line”) on several objects using a single policy function. This is very helpful to ease the administration of policy functions. This is a better model than repeatedly creating one policy function per object.

In order to share policy functions, you should use the same policy function in each policy that you define with the DBMS_RLS.ADD_POLICY procedure. Each policy has its own name, but the corresponding functions are the same. The policy type must be DBMS_RLS.SHARED_STATIC or DBMS_RLS.SHARED_CONTEXT_SENSITIVE.

Page 95: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-11

Copyright © 2004, Oracle. All rights reserved.17-11

Auditing Mechanisms: Overview

• Mandatory auditing: Some changes are always audited by the database (for example, startup and shutdown).

• Standard auditing: You enable auditing and then set the objects and privileges to audit.

• Fine-grained auditing: You audit at row level using audit policies.

• Auditing of the SYS user: Writes all DBA activities to the operating system

Auditing Mechanisms: Overview• Mandatory auditing: All Oracle databases audit certain actions regardless of other

audit options or parameters. The reason for mandatory audit logs is that the database needs to record some database activities, such as system startup and shutdown.

• Standard auditing, or simply “auditing,” has been available in the Oracle database for many releases. Auditing is set at the system level using the AUDIT_TRAILinitialization parameter. You enable auditing by setting the AUDIT_TRAIL parameter to True, On, DB, or OS. Once you have enabled auditing, you can select which objects and privileges you want to audit. That is, as long as auditing is enabled, you can add and drop auditing from any table, view, privilege, and so on.

• Fine-grained auditing (FGA) enables you to audit based on the data content. FGA uses policies that you add to an object. An audit policy can have sophisticated means to decide whether the database should create an audit record based on the exact query, condition, and data that the statement accesses. You also have the option of auditing only those statements that reference a particular column. Oracle Database 10genhances this capability.

• Auditing the sys user: Oracle9i Database Release 2 added the auditing of the sys user. This is also known as DBA auditing. This feature allows you to separate the auditing duties between the DBA and an auditor (or security administrator) who monitors the DBA activities in an operating system audit trail.

Page 96: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-12

Copyright © 2004, Oracle. All rights reserved.17-12

Uniform Audit Trails

DBA_AUDIT_TRAIL DBA_FGA_AUDIT_TRAIL

DBA_COMMON_AUDIT_TRAIL

EXTENDED_TIMESTAMP,PROXY_SESSIONID, GLOBAL_UID,INSTANCE_NUMBER, OS_PROCESS, TRANSACTIONID, SCN, SQL_BIND, SQL_TEXT

STATEMENTID,ENTRYID

AUDIT_TRAIL=DB_EXTENDED

Uniform Audit TrailsOracle Database 10g tracks the same fields for standard and fine-grained auditing. This allows you to easily analyze database activities. To accomplish this, both the standard audit trail and the fine-grained audit trail have new and changed attributes to complement each other.Extra information collected by standard auditing include:

• The system change number (SCN) records every change to the system.• The exact SQL text executed by the user and the bind variables used with the SQL

text. These columns appear only if you have specified AUDIT_TRAIL=DB_EXTENDED in your initialization parameter file.

Extra information collected by fine-grained auditing include:• A serial number for each audit record• A statement number that links multiple audit entries that originate from a single

statementAdded and changed attributes common to the standard and fine-grained audit trails:

• A global time stamp in Universal Time Coordinates (UTC). This field is useful for monitoring across servers in separate geographic locations and time zones.

• An instance number that is unique for each RAC instance• A transaction identifier that helps you group audit records of a single transaction

There is a new audit trail view that combines standard and fine-grained audit log records. This view is DBA_COMMON_AUDIT_TRAIL.

Page 97: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-13

Copyright © 2004, Oracle. All rights reserved.17-13

Enhanced Enterprise User Auditing

Standard audit

USERNAMEGLOBAL_UID

Fine-grained audit

DB_USERGLOBAL_UID

Standard audit

USERNAME

Fine-grained audit

DB_USER

Exclusive schema Shared schema

Enhanced Enterprise User AuditingOracle Database 10g automatically captures the identity of enterprise users in its audit trails. Enterprise users are users managed by an LDAP-compliant directory, such as Oracle Internet Directory (OID). These additional attributes make it easier for the administrator to monitor the activities of both authorized and unauthorized users.

Enterprise users can map to an exclusive schema in the database; then the database user name represents the enterprise user. Exclusive schemas have a one-to-one mapping between directory user and database user or schema. With enterprise users accessing exclusive schemas:

• Standard auditing: The USERNAME column shows the user identity in the database, and the GLOBAL_UID column shows the same user’s global identity.

• Fine-grained auditing: The DB_USER column shows the user identity in the database, and the GLOBAL_UID column shows the same user’s global identity.

Often enterprise users map to a shared schema in the database, in which case the audit trails capture both the username of the shared schema user and the identity of the actual user managed in the directory. With enterprise users accessing shared schemas:

• Standard auditing: The USERNAME column shows the shared schema, and the GLOBAL_UID column shows the identity of the enterprise user.

• Fine-grained auditing: The DB_USER column shows the shared schema, and the GLOBAL_UID column shows the identity of the enterprise user.

Page 98: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-14

Copyright © 2004, Oracle. All rights reserved.17-14

Fine-Grained Auditing Enhancements

• Support for DML statements:– INSERT

– UPDATE

– DELETE

– MERGE

• More than one relevant column:– DBMS_FGA.ALL_COLUMNS

– DBMS_FGA.ANY_COLUMNS

• Support for NULL FGA policy predicate

• Support for fine-grained auditing without SQL information overhead

Fine-Grained Auditing EnhancementsThe Oracle9i Database introduced the concept of FGA and provided support for SELECTstatements only. Oracle Database 10g extends FGA in the following ways:

• Provides support for UPDATE, INSERT, DELETE, and MERGE statements as well• More than one relevant column is supported for an FGA policy. In earlier releases,

only one relevant column could be specified. By default, if any one of these columns is present in the SQL statement, it is audited. An option is provided to audit based on whether any or all of the relevant columns are used in the statement.

• NULL FGA policy predicates: In previous releases, the FGA policy required a statement to meet a Boolean audit condition for auditing to fire. You could overcome this restriction by using an audit condition such as 1=1. However, this forced the predicate’s evaluation. Oracle Database 10g does not require such a condition. This greatly improves the performance for FGA-SELECTs in particular.

• By default, audit trail always writes the SQL text and SQL bind information to LOBs. You have the ability to perform FGA without the LOB information overhead if this represents a huge performance impact.

Page 99: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-15

Copyright © 2004, Oracle. All rights reserved.17-15

Fine-Grained Auditing Policy: Example

BEGINdbms_fga.add_policy(object_schema => ’HR’,object_name => ’EMPLOYEES’,policy_name => ’my_policy’,audit_condition => NULL,audit_column => ’SALARY,COMMISSION_PCT’,audit_column_opts => DBMS_FGA.ALL_COLUMNS,audit_trail => DBMS_FGA.DB,statement_types => ’INSERT,UPDATE’);

END;

Fine-Grained Auditing Policy: ExampleThe example shown applies the MY_POLICY fine-grained auditing policy to the EMPLOYEES table in the HR schema. There is no condition for FGA to evaluate, so the database creates an audit record for all INSERT and UPDATE statements that reference both the SALARY and COMMISSION_PCT columns.

This statement also implies that FGA does not write the SQL text and SQL bind information to the audit trail.

Page 100: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-16

Copyright © 2004, Oracle. All rights reserved.17-16

Audited DML Statement Considerations

• Records are audited if FGA predicate is satisfied and relevant columns are referenced

• DELETE statements are always audited.• MERGE statements are audited with underlying

INSERT or UPDATE generated statements.

UPDATE hr.employeesSET salary = 10WHERE commission_pct = 90;

UPDATE hr.employeesSET salary = 10WHERE employee_id = 111;

Audited DML Statement ConsiderationsWith an FGA policy defined for DML statements, a DML statement is audited if data rows (both new and old) being manipulated meet the policy predicate criteria.

However, if relevant columns are also specified in the policy definition, then the statement is audited when the data meets the FGA policy predicate and it also references the relevant columns defined.

For delete statements, specifying relevant columns during policy definition is not useful because all columns in a table are touched by a delete statement. Hence a delete statement is always audited regardless of the relevant columns.

Merge statements are supported by FGA by auditing the underlying INSERT or UPDATEstatements performed by the MERGE statements if they meet any defined INSERT or UPDATE FGA policies.

Using the previously defined FGA policy, the first statement is audited while the second one is not.

Page 101: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-17

Copyright © 2004, Oracle. All rights reserved.17-17

Summary

In this lesson, you should have learned how to:• Apply a column-level VPD policy• Apply static and nonstatic policies• Share VPD policy functions• Use the unified audit trails• Use fine-grained auditing for DML statements

Page 102: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 17-18

Copyright © 2004, Oracle. All rights reserved.17-18

Practice 17: Overview

This practice covers the following topics:• Implement a VPD policy• Use the new characteristics of VPD policies

Page 103: Oracle 10g New Features for Administrators Vol II

Copyright © 2004, Oracle. All rights reserved.

Miscellaneous New Features

Page 104: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-2

Copyright © 2004, Oracle. All rights reserved.18-2

Objectives

After completing this lesson, you should be able to do the following:• Aggregate more meaningful statistics across a

multitier environment• Use SQL to flush the buffer cache • Provide greater flexibility by enabling resumable

timeout at the instance level• Use regular expression support in SQL and

PL/SQL for string searching, matching, and replacing

• Use additional linguistic comparison and sorting methods in SQL

Page 105: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-3

Copyright © 2004, Oracle. All rights reserved.18-3

Transaction Monitoring

• Support for Real-time monitoring:– Transaction rollback– Transaction recovery

• Provides better estimate of rollback duration• Provides better determination of recovery times• Ensures optimization of system resources

Monitor

Rollback

Historical

Transaction MonitoringIn previous releases, you could monitor parallel transaction recovery with two views: V$FAST_START_SERVERS and V$FAST_START_TRANSACTIONS. However, you could not monitor normal transaction rollback or transactions recovered by SMON.

Through enhancements to transaction rollback monitoring, you can now monitor (in real-time) normal transaction rollback and transaction recovery by SMON. In addition, you can view historical information about transaction recovery and transaction rollback. Given historical information about transaction recovery, you can calculate average rollback duration. When you have the current state of the recovery, you can determine how much work has been done and how much work remains. Using these two pieces of information, you can better estimate transaction recovery time and set the FAST_START_PARALLEL_ROLLBACK initialization parameter more appropriately to optimize system performance.

Page 106: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-4

Copyright © 2004, Oracle. All rights reserved.18-4

Dynamic Performance View Changes

V$FAST_START_TRANSACTIONS

V$FAST_START_SERVERS

XID

RCVSERVERSPXID

Dynamic Performance View Changes

V$FAST_START_TRANSACTIONS contains the information about the progress of the transactions that the Oracle server is recovering. It also contains information about transactions that the Oracle server has recovered. For transactions that the Oracle server is recovering, the STATE is RECOVERING. For transactions that the Oracle server has recovered, the STATE is RECOVERED. Only limited historical information is kept in this view, and small (in terms of undo blocks) transactions are not tracked.

New columns added are:• XID: Transaction ID of this transaction• PXID: Transaction ID of the parent transaction• RCVSERVERS: Number of servers working on this transaction (including the

coordinator server). It can be 1 if only SMON is doing the recovery.

V$FAST_START_SERVERS provides information about all the recovery servers that are performing or that have performed parallel transaction recovery. One additional column is added to this view: XID gives you the transaction ID of the transaction that a particular server is working on.

Note: For more information about detailed column definitions, see the Oracle Database Reference guide.

Page 107: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-5

Copyright © 2004, Oracle. All rights reserved.18-5

V$FAST_START_TRANSACTIONS view

SELECT state,undoblocksdone,undoblockstotal,cputime FROM v$fast_start_transactions;

STATE UNDOBLOCKSDONE UNDOBLOCKSTOTAL CPUTIME---------- -------------- --------------- ---------RECOVERING 574 1945 16…SQL> /STATE UNDOBLOCKSDONE UNDOBLOCKSTOTAL CPUTIME---------- -------------- --------------- ---------RECOVERING 1300 1945 34…SQL> /STATE UNDOBLOCKSDONE UNDOBLOCKSTOTAL CPUTIME---------- -------------- --------------- ---------RECOVERED 1945 1945 65

V$FAST_START_TRANSACTIONS view

This statement can be used to track transaction recovery after instance startup. As you can see, once the transaction is recovered, its statistics remain inside the V$FAST_START_TRANSACTIONS view, but its STATE is set to RECOVERED. Historical information is kept in V$FAST_START_TRANSACTIONS until the next instance shutdown.

More operations are added into V$SESSION_LONGOPS. This allows you to monitor ROLLBACK and ROLLBACK TO operations longer than six seconds.

SQL> SELECT message FROM v$session_longops; MESSAGE ---------------------------------------------Transaction Rollback: xid:0x0001.00a.00000812 : 4600 out of 4600 Blocks done Transaction Rollback: xid:0x0001.007.00000812 : 4601 out of 4601 Blocks done 2 rows selected. SQL>

Page 108: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-6

Copyright © 2004, Oracle. All rights reserved.18-6

Session-Based Tracing

$ trcsess output=<user.trc>clientid = <user_name> *.trc

Possible trace files

Dispatcher

Shared Servers

Session-Based TracingIn a shared server environment there are many trace files that may be associated with a given session, which makes tracing the life of a session very difficult.

You can consolidate the information from these many trace files into a single output using the trcsess command line tool.

This output is then directed to a file or to your window. You supply the name of the trace files to be consolidated, and these file names can contain wildcard characters.

The output is raw consolidated information from the trace files. To evaluate the information, you need to format it with the tkprof utility.

Page 109: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-7

Copyright © 2004, Oracle. All rights reserved.18-7

End-to-End Tracing

• Debug performance problems in a multitier environment with the CLIENT_IDENTIFIER attribute

• Visible in V$SESSION and SYS_CONTEXT(’USERENV’,’CLIENT_IDENTIFIER’)

Client Application server Database server

Client identifier

Client identifier

End-to-End TracingEnd-to-End Tracing facilitates the following tasks:

• Debugging of performance problems in multitier environments: In multitier environments, a request from an end-client is routed to different database sessions by the middle tier. Previously, there was no easy way to keep track of a client across these different database sessions. End-to-End Tracing makes this possible by introducing a new attribute, CLIENT_IDENTIFIER, which uniquely identifies a given end-client and is carried through all tiers to the database server. Enabling tracing based on the CLIENT_IDENTIFIER solves the problem of debugging performance problems in multitier environments. The client identifier is visible in the CLIENT_IDENTIFIERcolumn of V$SESSION and also visible through the system context, as shown in the following query:

SQL> SELECT SYS_CONTEXT (’USERENV’, ’CLIENT_IDENTIFIER’)2 FROM dual;

• Efficient management and accounting of workload: For applications using services that have been instrumented with MODULE and ACTION name annotation, End-to-End Tracing provides a means to set apart important transactions in an application.

Page 110: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-8

Copyright © 2004, Oracle. All rights reserved.18-8

New Statistic Aggregation Dimensions

Meaningful statistics accumulation for multitier architectures using connection pooling or shared server configuration

Service name, module name, and action

name

Client identifier Service name

New Statistic Aggregation DimensionsPreviously, statistics aggregation was provided at the instance, session, and SQL levels. In Oracle Database 10g, you can use the following additional dimensions to aggregate statistics:

• Client identifier• Service name• Hierarchical combination of service name, module name, and action name

These additional dimensions make statistics accumulation for multitier architectures using connection pooling or shared server configuration more meaningful. You enable statistics aggregation to monitor performance problems based on a client identifier or for a given hierarchical set of service, module, and action names. This initiates aggregation of key metrics and statistics that are useful for problem diagnosis and analysis. These statistics are used for the following purposes:

• Performance monitoring of individual clients and services• Workload management• Setting threshold-based alerts such as elapsed time and CPU services

Note: In Oracle Database 10g, you can configure attributes through the JDBC / OCI calls (specifically OCIAttrSet call), thereby avoiding additional calls to the server. This is the preferred mechanism for setting these session attributes.

Page 111: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-9

Copyright © 2004, Oracle. All rights reserved.18-9

Using Enterprise Manager to Enable Statistics Aggregation

Using Enterprise Manager to Enable Statistics AggregationYou can use EM Database Control or the DBMS_MONITOR PL/SQL package to enable statistics aggregation. After the application is executed, you can then use EM to retrieve statistical information or query views.

You can enable and disable statistics aggregation on the Top Modules, Top Actions, and Top Client pages. You navigate to these pages from the Database Control home page by clicking the Performance tab.You then select Top Consumers from the Additional Monitoring link, and choose Top Modules, Top Actions, or Top Clients.

The following views have been added to support client-based and service-based statistic aggregation:• DBA_ENABLED_AGGREGATIONS: Displays information about enabled on-demand

statistics aggregation• V$CLIENT_STATS: Displays measures for all sessions that are active for the client

identifier per instance. The statistics displayed are a subset of system statistics for a given client.

• V$SERVICE_STATS: Displays a minimal set of performance statistics• V$SERV_MOD_ACT_STATS: Displays the same set of performance statistics as

V$SERVICE_STATS for a specific combination of service/module/action names• V$SVCMETRIC: Displays continuous metrics for elapsed time and CPU use

Page 112: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-10

Copyright © 2004, Oracle. All rights reserved.18-10

Using DBMS_MONITOR to Enable Statistics Aggregation

• Enabling based on client identifier:

• Enabling based on service name, module name, and action name:

EXECUTE DBMS_MONITOR.CLIENT_ID_STAT_ENABLE(<client id>);

EXECUTE DBMS_MONITOR.SERV_MOD_ACT_STAT_ENABLE(<service name>, <module name>, <action name>);

Using DBMS_MONITOR to Enable Statistics Aggregation

You can use the DBMS_MONITOR PL/SQL package to control additional tracing and statistics gathering. The DBMS_MONITOR package contains the following procedures used to enable and disable additional statistics aggregation:• CLIENT_ID_STAT_ENABLE: Enables statistics accumulation for a given client

identifier• CLIENT_ID_STAT_DISABLE: Disables statistics accumulation for a given client

identifier• SERV_MOD_ACT_STAT_ENABLE: Enables statistics accumulation for a given

hierarchy of service name, module name, and action name• SERV_MOD_ACT_STAT_DISABLE: Disables statistics accumulation for a given

hierarchy of service name, module name, and action name

Note: Service-level statistics are automatically accumulated.

Page 113: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-11

Copyright © 2004, Oracle. All rights reserved.18-11

Generalized Trace Enabling

Client identifier

begindbms_monitor. client_id_trace_enable (client_id => <user_name>);end;

Service name, module name,

and action name

$ trcsess output=<user.trc>clientid = <user_name> *.trc

Generalized Trace EnablingNew trace-enabling procedures have been implemented as part of the DBMS_MONITORpackage. These procedures enable tracing globally for a database. Tracing can also be enabled at a session level. Tracing is enabled on:

• A specified client identifier• A hierarchical combination of service name, module name, and action name

The procedures create a set of trace files that have to be combined using the trcsessutility. You use the trcsess utility to scan through all of the trace files and combine the sections from the specified client into a single trace file. After combining the set of trace files, you can use standard trace-file analysis methods, such the tkprof utility, for diagnostic purposes.The example in the slide shows how to enable tracing for all calls for a given client using the DBMS_MONITOR package. You then have an example of enabling tracing for a specific client identifier and using the trcsess utility to combine the files. Note: The tracing state for a client identifier or service/module/action is persistent across database shutdown and applies to all instances.

Page 114: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-12

Copyright © 2004, Oracle. All rights reserved.18-12

Using Enterprise Manager to Enable and View SQL Tracing

SELECT * FROM dba_enabled_traces;

Using Enterprise Manager to View Enabled TracesYou can enable, disable, and view SQL tracing on the Top Modules, Top Actions, and Top Client pages. You navigate to these pages from the Database Control home page and then click the Performance tab. You select Top Consumers from the Additional Monitoringlink, and choose Top Services, Top Modules, Top Actions, Top Clients, and Top Sessions.

You can query the DBA_ENABLED_TRACES view to determine the traces enabled. The DBA_ENABLED_TRACES view contains the following columns:• TRACE_TYPE: Trace type: CLIENT_ID, SESSION, SERVICE,

SERVICE_MODULE, SERVICE_MODULE_ACTION• PRIMARY_ID: Primary qualifier (specific client identifier or service name)• QUALIFIER_ID1: Secondary qualifier (specific module name)• QUALIFIER_ID2: Additional qualifier (specific action name)• WAITS: TRUE if waits are traced• BINDS: TRUE if binds are traced• INSTANCE_NAME: Instance name for tracing restricted to named instances

Page 115: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-13

Copyright © 2004, Oracle. All rights reserved.18-13

Enabling and Disabling Tracing

Use the DBMS_MONITOR procedures to enable and disable tracing:

CLIENT_ID_TRACE_[ENABLE|DISABLE](<client_id>|, waits |, binds)

SERV_MOD_ACT_TRACE_[ENABLE|DISABLE](

<service_name>, <module_name>,<action_name> |, waits |, binds |, <instance_name>)

SESSION_TRACE_[ENABLE|DISABLE](<session_id> |, <serial_num> |, waits |, binds)

Enabling and Disabling TracingYou can use the CLIENT_ID_TRACE_ENABLE procedure to enable the trace for a given client identifier globally for the database. The CLIENT_ID_TRACE_DISABLE procedure is used to disable the tracing. You must supply the client identifier as input to the CLIENT_ID_TRACE_DISABLE procedure.

You can use the SERV_MOD_ACT_TRACE_ENABLE procedure to enable SQL tracing for a given combination of service name, module name, and action name globally, unless an instance name is also specified. The SERV_MOD_ACT_TRACE_DISABLE procedure is used to disable the tracing at all enabled instances. You must supply the service name as input to the SERV_MOD_ACT_TRACE_DISABLE procedure but can optionally specify the module name and action name.

You use the SESSION_TRACE_ENABLE procedure to enable SQL tracing for a given database session identifier on the local instance. If SERIAL_NUM is NULL but SESSION_ID is specified, a session with a given SESSION_ID is traced irrespective of its serial number. If both SESSION_ID and SERIAL_NUM are NULL, the current user session is traced.

The default values for waits and binds are TRUE and FALSE, respectively, and represent the existence of wait event and bind information in the trace file.

Page 116: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-14

Copyright © 2004, Oracle. All rights reserved.18-14

Configurationless Client Connect

• New connect identifier for SQL Clients– Offers minimal syntax– Full connectivity

• No restrictions on host and database naming• No lookup services required• No preconfiguration required• No ongoing maintenance• Supports transparent middle-tier

Configurationless Client ConnectOracle Database 10g introduces a new connect identifier for SQL Clients with minimal syntax and full connectivity to a wide variety of database services. This new connect identifier has no restrictions on host and database naming, does not rely on configuration files, does not require name lookup services, and (most importantly) does not require any preconfiguration or ongoing configuration maintenance. It also makes the middle tier much more transparent and accessible.

Page 117: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-15

Copyright © 2004, Oracle. All rights reserved.18-15

Configurationless Client Connect

• Connectivity without post-installation configuration– Eliminates heavy administration

• Syntax:

• Cannot be used for:– Platforms where TCP/IP is not native or common– Server features that require full address constructs

CONNECT username/pwd@[//]host[:port][/[service_name]]

Configurationless Client Connect (continued)The host name is mandatory. The host name adapter qualifies the host with a domain if possible and attempts to look up the host by the normal means on that machine. If the host lookup fails, the adapter returns an error.The default port is 1521. The default for the service_name is whatever the host is set to. In case the host is qualified by a domain, the service_name uses the fully qualified host name, which may not necessarily be identical to the value specified in the connect identifier. The new connect identifier syntax assumes that a host, port, and service_name are all that a client needs to establish a connection to a database service. This syntax merely abbreviates the standard connection identifiers. An example of the new connect identifier is the following:

CONNECT hr/hr@//atlas:1521/recipes

Note: Platforms where TCP/IP is not native or not common are not able to use the abbreviated connect identifier. This applies to clients directly as well as to servers that are not available via TCP/IP.

Page 118: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-16

Copyright © 2004, Oracle. All rights reserved.18-16

Simplified Shared Server Configuration

Oracle Database 10g is shared-server aware:• One TCP protocol dispatcher on startup• Modify SHARED_SERVERS parameter as required

• Much simplified configuration

SQL> ALTER SYSTEM SET SHARED_SERVERS=3;

Simplified Shared Server ConfigurationThe diagram shows an abstract view of the shared server architecture. In prior versions, you had to set up at least one dispatcher for the shared server configuration to be enabled at instance start up. It is very possible for a different shared server to handle each of the requests submitted by a single session.

In an Oracle Database 10g instance, one TCP protocol dispatcher starts automatically, making the instance shared server aware regardless of your parameter settings. However, no shared server processes are started. If you decide that you need to use shared servers while the system is running, you simply set the dynamic SHARED_SERVERS initialization parameter to a value greater than zero with an ALTER SYSTEM command. As with other parameters, you can change just the current instance with this command and, if you are using an SPFILE, you can change the parameter for future instances as well. For example, to activate three shared servers in the current instance and the SPFILE, enter this command:

SQL> ALTER SYSTEM SET SHARED_SERVERS=3;

There are several other parameters that can be set in the shared server environment, but none of the others are required. Once you set SHARED_SERVERS, your system is running in shared server mode.

Page 119: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-17

Simplified Shared Server Configuration (continued)Note: When you change the the DISPATCHERS parameter dynamically, the results of the change depend on which attributes you modify. Since several of the attributes affect the network session layer when a dispatcher is started, these cannot be changed for dispatchers that are already started. These attributes are PROTOCOL, ADDRESS, DESCRIPTION, PRESENTATION, CONNECTIONS, SESSIONS, TICKS, and MULTIPLEX.

You can dynamically modify the other attributes (LISTENER and SERVICE) and affect existing as well as new dispatchers of the same configuration.

Page 120: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-18

Copyright © 2004, Oracle. All rights reserved.18-18

Viewing the Dispatcher Configuration

SQL> SELECT name, dispatchers, service, idle, busy

2 FROM v$dispatcher JOIN

3 v$dispatcher_config USING (conf_indx);

NAME DISPATCHERS SERVICE IDLE BUSY

---- ----------- ---------------------- ---------- ----------

D000 1 U401XDB.us.oracle.com 3239364 0

Viewing the Dispatcher ConfigurationYou can query the V$DISPATCHER_CONFIG view for information about existing dispatchers. This view displays information about the dispatcher configurations, including attributes that were not specified and were given a default value.

You can join the CONF_INDX column in V$DISPATCHER_CONFIG to the CONF_INDXcolumn in V$DISPATCHER to see all of the detailed information about a given dispatcher. You use this information to make more informed decisions on what attributes to modify and to determine if you need to add or remove dispatchers.

Page 121: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-19

Copyright © 2004, Oracle. All rights reserved.18-19

Resumable Space Allocation Enhancements

• Enable with initialization parameter:

• Can now be enabled at the instance level:

• Automatic alert notification sent when an operation is suspended

RESUMABLE_TIMEOUT=7200

SQL> ALTER SYSTEM 2 SET RESUMABLE_TIMEOUT=<non zero value>;

Resumable Space Allocation EnhancementsYou previously enabled resumable statements at the session level by issuing the ALTERSESSION ENABLE RESUMABLE [ TIMEOUT integer] [NAME string] command. This same behavior is maintained in Oracle Database 10g. However, a new initialization parameter called RESUMABLE_TIMEOUT is introduced, allowing you to enable or disable resumable statements and specify resumable timeout at the system level. This parameter is changed dynamically at the system level with the ALTER SYSTEM command, or at the session level with the ALTER SESSION command. For Real Application Clusters (RAC), multiple instances can have different values. If RESUMABLE_TIMEOUT initialization parameter is set to 0, then resumable space allocation is disabled initially for all sessions. This is the default behavior. The RESUMABLE_TIMEOUT parameter does not change the definition of a resumable operation, and the default value of the resumable timeout for the ALTER SESSION ENABLE RESUMABLE command is still two hours.

Note: With previous releases of the Oracle database, you were not allowed to start a distributed transaction in a resumable enabled session. This restriction is removed with Oracle Database 10g. However, in a distributed transaction, if you enable or disable resumable statements, or change the resumable timeout setting, only the local instance is affected. In a distributed transaction, sessions on remote instances can be suspended only if resumable statements are enabled on those remote instances.

Page 122: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-20

Copyright © 2004, Oracle. All rights reserved.18-20

Flushing the Buffer Cache

ALTER SYSTEM FLUSH BUFFER_CACHE;

Flushing the Buffer CacheThe intent of flushing the database buffer cache is to provide for an identical starting point for comparison of rewritten SQL statements. Once you execute this command, the buffer is emptied and the next statement has a 100 percent cache miss. You should execute this command only on a test system; you should also execute it only when everyone using the system is aware of the ramifications.

The benefit of this feature is that it allows you to establish a consistent testing environment. You can flush the buffer cache manually between runs of test queries, thereby making it possible to determine the effects of changes in queries or applications.

Page 123: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-21

Copyright © 2004, Oracle. All rights reserved.18-21

MAXTRANS and Maximum Concurrency

PCTFREE integer

PCTUSED

INITRANS

integer

integer

Storage_clause

physical_attributes_clause::=

MAXTRANS and Maximum Concurrency

Previously MAXTRANS represented the physical attribute of a table, index, or cluster that specifies the maximum number of concurrent update transactions for any given data block belonging to the segment. In Oracle Database10g, objects are now preconfigured for maximum concurrency.

To ensure backward compatibility, if you specify MAXTRANS while creating a table, you do not get an error message. This parameter is simply ignored.

Page 124: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-22

Copyright © 2004, Oracle. All rights reserved.18-22

Large Object (LOB) Data Type Changes

• Support for terabyte-sized LOBs– BLOB, CLOB, NCLOB

• New DBMS_LOB.GET_STORAGE_LIMIT function– Returns actual LOB size limit

Large Object (LOB) Data Type ChangesIn earlier releases, the maximum size of the LOB data types (BLOB, CLOB, and NCLOB) was 4 GB. Oracle Database 10g increases the size of LOBs substantially. The new maximum size of LOBs is [(4 GB –1) ×(value of CHUNK ]. CHUNK is a parameter of LOB storage whose value is controlled by the block size of thetablespace in which the LOB is stored. CHUNK is a multiple of the database block size if the tablespace has the same block size as the database. If the tablespace uses a nonstandard block size, then CHUNK is a multiple of the tablespace block size. The default CHUNK size is one tablespace block, and the maximum value is 32KB, so the LOB size limit ranges from 8 TB to 128 TB.

You can use terabyte-sized LOBs with all procedures in the DBMS_LOB PL/SQL package. The DBMS_LOB.GET_STORAGE_LIMIT function returns the storage limit for your database configuration.

The Oracle Call Interface API is also enhanced to support LOBs that are larger than 4 GB.

Page 125: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-23

Copyright © 2004, Oracle. All rights reserved.18-23

Implicit Conversion Between CLOB and NCLOB

Transparent implicit conversion is supported in:• SQL IN and OUT bind variables for query and DML

• PL/SQL functions and procedure parameter passing

• PL/SQL variable assignment

Implicit Conversion Between CLOB and NCLOB

Converting data between Unicode and the database national language character set is becoming a more frequent requirement. Explicit conversion between CLOB and NCLOB is already available in SQL and in PL/SQL with the TO_CLOB and TO_NCLOB functions. Oracle Database 10g introduces implicit conversion for SQL IN and OUT bind variables in queries and DML operations, as well as for PL/SQL function and procedure parameter passing and PL/SQL variable assignment. For example, conversion is completely transparent in the following scenario:

CREATE TABLE my_table (nclob_col NCLOB);DECLARE

clob_var CLOB;nclob_var NCLOB;

BEGINclob_var := ’clob data’; -- initialize the CLOB INSERT INTO my_table VALUES (clob_var); -- Bind a CLOB into an NCLOB columnSELECT nclob_col INTO clob_var FROM my_table;

-- Define an NCLOB column as a CLOB var END;

Page 126: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-24

Copyright © 2004, Oracle. All rights reserved.18-24

Regular Expression Support

• A powerful method of describing both simple and complex patterns for searching and manipulating

• A multilingual regular expression support for SQL and PL/SQL string types

• Several new functions, all prefixed with REGEXP_– REGEXP_LIKE

– REGEXP_REPLACE

– REGEXP_INSTR

– REGEXP_SUBSTR

Regular Expression SupportString manipulation and searching contribute to a large percentage of the logic within a Web-based application. Regular expressions are a method of describing both simple and complex patterns for searching and manipulating. Usage ranges from the simple (“Find the word SAN in the text”) to the more complex (“Extract all URLs from the text”) to the archaic (“Find all words in which every second character is a vowel”).

In Oracle Database 10g, you can use both SQL and PL/SQL to implement regular expression support. The National Language Support Run Time Library (NLSRTL) provides all of the linguistic elements used to implement regular expression support. The following functions have been introduced:• REGEXP_LIKE: Similar to the LIKE operator, but performs regular expression

matching instead of simple pattern matching• REGEXP_REPLACE: Searches for a regular expression pattern and replaces it with a

replacement string• REGEXP_INSTR: Searches for a given string for a regular expression pattern and

returns the position were the match is found• REGEXP_SUBSTR: Searches for a regular expression pattern within a given string and

returns the matched substring

Page 127: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-25

Copyright © 2004, Oracle. All rights reserved.18-25

Matching Mechanism

Regular Expression: ’a(b|c)d’String to Match: ’aabcd’

No matchLook for ’a’ and fail, reset, and advance^

No matchLook for ’a’ and fail, reset, and advance^

No matchLook for ’a’ and fail, reset, and advance^

No matchLook for ’c’ as last remembered alternative and fail, reset, and advance

^

No matchLook for ’d’ and fail^

MatchLook for ’b’ and succeed, remember ’c’ as alternative

^

MatchLook for ’a’ and succeed^

No matchLook for ’c’ and fail, reset, and advance^

No matchLook for ’b’ and fail^

MatchLook for ’a’ and succeed^

dcbaa

Matching MechanismA match is attempted at the beginning of the string at the first character. If the character does not match, the process starts again at the next character in the string. If the character matches, the next character to be matched is examined and any alternatives that would also have resulted in a match are remembered. This process continues until a character fails. The latest remembered alternative is then attempted at the position for which it was valid.

If the regular expression has no more alternatives to the match, it fails to produce a positive result.

Note: Oracle Database 10g follows the exact syntax and matching semantics for these operators as defined in the POSIX standard for matching ASCII data.

Page 128: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-26

Copyright © 2004, Oracle. All rights reserved.18-26

• srcstr: Search value• pattern: Regular expression• match_option: Option to change default

matching. Can include one or more of the following values:– ‘c’ – Case-sensitive matching (default) – ‘i’ – Case-insensitive matching – ‘n’ – Allows match-any-character operator – ‘m’ – Treats source string as multiple line

REGEXP_LIKE(srcstr, pattern [,match_option])

Syntax: Example

Syntax: ExampleIn the syntax, the REGEXP_LIKE condition evaluates to TRUE if the search value (srcstr) matches the regular expression (pattern), optionally using the matching option (match_option).

The search value is a character expression and can be any of the following data types: CHAR, VARCHAR2, NCHAR, NVARCHAR2, CLOB, or NCLOB. The regular expression is usually a text literal and can be a CHAR, VARCHAR2, NCHAR, or NVARCHAR2 data type. If the data type of the regular expression is different from the data type of the search value, the regular expression is implicitly converted to the data type of the search value. The matching option modifies the default matching behavior. You can, for example, choose case-insensitive matching or treat a search value as a multiple line string. If either the search value or the regular expression is NULL, the result is unknown.

Page 129: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-27

Copyright © 2004, Oracle. All rights reserved.18-27

Using REGEXP_LIKE in SQL

SELECT first_name, last_name, salary, TO_CHAR(hire_date, ’yyyy’)

FROM employeesWHERE REGEXP_LIKE(

TO_CHAR(hire_date, ’yyyy’), ’^199[6-9]$’);

FIRST_NAME LAST_NAME SALARY TO_C--------------- --------------- ---------- ----David Austin 4800 1997Valli Pataballa 4800 1998Diana Lorentz 4200 1999John Chen 8200 1997Ismael Sciarra 7700 1997Jose Manuel Urman 7800 1998Luis Popp 6900 1999...79 rows selected.

Using REGEXP_LIKE in SQL

This example illustrates the use of the REGEXP_LIKE functions to display employee names and salaries for employees hired between 1996 and 1999. The example uses the ‘^’ to indicate that the beginning of the line has to be 199, and [ - ] with ‘$’ to specify a range of valid characters as the very last character.

Page 130: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-28

Copyright © 2004, Oracle. All rights reserved.18-28

Case- and Accent-Insensitive Query and Sort

Two new sorting options are available in Oracle Database 10g:• Case-insensitive sort• Accent-insensitive sort

Case- and Accent-Insensitive Query and SortCase-insensitive comparison and sorting are frequently used features in the database. In previous releases, you could call functions to make SQL statements case-insensitive. This however, has three disadvantages:

• It is often hard to migrate from other database vendors. Many customers want to have the same SQL behaviors without changing existing code.

• There is a performance degradation when you use the LOWER/UPPER function. These functions convert the whole string to lower or upper case and then do the comparison.

• There is less flexibility and reusability for the same SQL query statements with different comparison-level requirements.

With previous releases, the Unicode standard for multilingual linguistic sorts is used for the level of comparison utilizing three levels of sorting. The primary level is for base-letter difference. The secondary level is for accent differences. The third level is for case differences.

Oracle Database 10g introduces two new sorting options: case-insensitive sort and accent-insensitive sort.

Page 131: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-29

Copyright © 2004, Oracle. All rights reserved.18-29

Changes in Configuration Parameters

• Use the NLS_SORT parameter to specify the linguistic name:

• Examples:

• Use the NLS_COMP parameter to specify the sort action for WHERE clauses and PL/SQL blocks:

NLS_SORT = <NLS_sort_name>[_AI | _CI]

NLS_SORT = FRENCH_M_AI

NLS_SORT = XGERMAN_CI

NLS_COMP = BINARY | ANSI

Changes in Configuration ParametersYou use the session parameter NLS_SORT to specify the linguistic sort name. The default value is derived from the initialization parameter NLS_LANGUAGE. The _AI and _CIvalues are suffixed to the sort name to indicate an accent-insensitive sort or a case-insensitive sort. From the example in the slide, the following determination is made:

1. Accent-insensitive and case-insensitive ‘French_M’ sort2. Accent-sensitive and case-insensitive ‘Xgerman’ sort

Normally, comparisons in the WHERE clause and in PL/SQL blocks are binary unless you use the NLSSORT function. By setting NLS_COMP to ANSI, you indicate that comparisons in the WHERE clause and in PL/SQL blocks should use the linguistic sort specified in the NLS_SORT parameter. You must also define an index on the column for which you want linguistic sorts.Note: The new format of the NLS_SORT parameter applies for both monolingual and multilingual linguistic sorts. In the monolingual sort, only major and minor levels are included. If the NLS_COMP parameter is set to ANSI, the options apply to any SQL or PL/SQL operators that already support collation-based compares in previous database releases. The _AI or _CI options are not affected in the SQL functions INSTR, TRIM, and LIKE because these functions only compare strings in binary order.

Page 132: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-30

Copyright © 2004, Oracle. All rights reserved.18-30

Support in SQL and Functions

• SQL clauses supporting NLS_SORT and NLS_COMPsettings:– WHERE

– ORDER BY

– START WITH

– HAVING

– IN/NOT IN

– BETWEEN

– CASE-WHEN

• The NLSSORT() function is extended to support case-insensitive and accent-insensitive functionality.

Support in SQL and FunctionsThe SQL clauses listed in the slide are affected when the _AI or _CI options are appended to the NLS_SORT parameter.

SELECT cust_last_nameFROM customersWHERE NLSSORT(cust_last_name, ’NLS_SORT = generic_m_ai’)

= NLSSORT(’De Niro’, ’NLS_SORT=generic_m_ai’);

CUST_LAST_NAME--------------------de NiroDe Nirodë Nirõ

You typically use the NLSSORT function in an ORDER BY or WHERE clause when the linguistic setting of the session parameter NLS_SORT is different from the linguistic setting in the SQL statement. The example in the illustration searches for all occurrences of “De Niro” regardless of the case and accent. You can achieve the same outcome as shown in the illustration by setting the NLS_COMP parameter:

ALTER SESSION SET NLS_SORT=generic_m_ai;ALTER SESSION SET NLS_COMP=ansi;

Page 133: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-31

Copyright © 2004, Oracle. All rights reserved.18-31

Quote Operator q

• Eliminates the need to use escape characters for single quotation marks in text literals

• Supports CHAR and NCHAR literals

• Valid values are:– Any single or multibyte character– Paired [ ], { }, ( ), and < >

SELECT cust_address FROM customersWHERE cust_last_name = q’X ’John’s Bait Shop’ X’;

. . .v_string1 := q’[’So,’ she said, ’It’s finished.’]’;v_string2 := q’!name LIKE ’%DBMS_%’!’;

SQL

PL/SQL

Quote Operator q

You can eliminate previous additional quotation strings in character string literals by choosing your own quotation mark delimiter. It supports both CHAR and NCHAR literals. You choose any convenient delimiter, single or multibyte, or any of the [ ], { }, ( ), or < > character pairs. The delimiter can even be a single quotation mark. However, if the delimiter appears in the text literal itself, ensure that it is not immediately followed by a single quotation mark. In the first example, X is used as the quotation mark delimiter. You do not need to prefix the single quotation mark inside ‘John’s Bait Shop’ with another single quotation mark. The second example shows PL/SQL using the paired brackets [ ] as the delimiter. Hence you do not need to use two single quotation marks inside the character string used to initialize the v_string1 variable. This makes your SQL text much more readable. The new quote operator can also be used with the new SQL_TUNE function, which takes a SQL statement as its argument. For example:

EXECUTE SQL_TUNE –('select * from emp where name LIKE ''%DBMS_%''',

...)

With the new quote operator, you can rewrite this statement as:EXECUTE SQL_TUNE –

(q'!select * from emp where name LIKE '%DBMS_%'!')

Page 134: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-32

Copyright © 2004, Oracle. All rights reserved.18-32

UTL_MAIL Package

A user-friendly interface by which to send e-mail:• Hides the underlying SMTP API protocol• Performs a send e-mail operation in one PL/SQL

call• Uses parameters for common e-mail elements

– Attachments– Sender/recipients– Cc/Bcc– Subject– Message body

UTL_MAIL Package

The supplied UTL_MAIL PL/SQL package is a user-friendly utility for managing e-mail. It allows you to use well-defined and commonly used e-mail features such as attachments, Cc, and Bcc. Using UTL_MAIL, you can send e-mail in a single PL/SQL call and use parameters to pass commonly used e-mail elements such as the sender, receivers, Cc, Bcc, subject, and message body.

As an example, if you have a bug system and you want an easy interface to send e-mail with a small attachment to a recipient, UTL_MAIL provides a good interface for this task.

For sending large attachments (larger than 32 KB) to hundreds of recipients, use the UTL_SMTP package. The UTL_MAIL package will be enhanced in the future to include greater functionality.

Note: To install the UTL_MAIL package, you need to run the utlmail.sql and prvtmail.plb scripts located in the $ORACLE_HOME/rdbms/admin directory.

For more information on the UTL_MAIL package, please see the PL/SQL Packages and Types Reference.

Page 135: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-33

Copyright © 2004, Oracle. All rights reserved.18-33

execute utl_mail.SEND -(sender => ’[email protected]’ -,recipients=> ’some valid email address’ -,subject => ’10gNF, UTL_MAIL Demo’ -,message => ’Note: 1st message, no attachment’);

execute utl_mail.SEND_ATTACH_VARCHAR2 -( ... -, message => ’2nd message, attachment in line’ -, attachment=> ’The 2nd demo attachment text’ -, att_inline=> TRUE );

execute utl_mail.SEND_ATTACH_VARCHAR2 -( ... -, att_inline => FALSE -, att_filename =>’message.doc’ );

UTL_MAIL Examples

UTL_MAIL Examples

The first example shows how you can use the SEND procedure to send an e-mail message without attachments. The second example shows you how to use theSEND_ATTACH_VARCHAR2 procedure to send an e-mail with an in-line attachment. The ATT_INLINE argument is set to TRUE.The third example shows how you can send e-mail messages with out-of-line attachments. Note: The ATT_FILENAME argument is the suggested file name if recipients are to save the attachment as a file. To send a file as an out-of-line attachment, you need to copy it into a BLOB and then send it as an attachment.

Page 136: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-34

Copyright © 2004, Oracle. All rights reserved.18-34

UTL_COMPRESS Package

• Provides a set of data compression functions:– LZ_COMPRESS

– LZ_UNCOMPRESS

• Reduces the size of a piece of data (data can later be expanded to its original form)

• Useful for:– Data warehousing developers– Web-based file servers– XML– iFS

UTL_COMPRESS Package

You use the UTL_COMPRESS package to compress data then restore the data to its original uncompressed format. Compressed data is less expensive to store in terms of disk or database space. The compression process reduces the size of a piece of data in such a way that it can later be expanded to its original form. A file is scanned for repeated patterns of bytes that can be expressed in terms of bytes and numbers in the compressed file. Some file types, such as those that tend to contain repeated word patterns, benefit more from compression. Compression efficiency and speed are tunable parameters. The greater the speed of compression, the less the overall efficiency (and vice versa). The optional quality argument allows you to choose between speed and compression quality, meaning the percentage of reduction in size. A faster speed results in less compression of the data, and a slower speed results in more compression of the data. Valid values are 1–9, with 1=fastest and 9=slowest. For this release of the UTL_COMPRESS utility, compression must perform at the rate of at least 10 KB per minute.

Note: The output of the UTL_COMPRESS compressed data is compatible with gzip (with -n option) or gunzip on a single file.

Page 137: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-35

Copyright © 2004, Oracle. All rights reserved.18-35

LogMiner Enhancements

• Automatically add log for mining:

• Generate reconstructed statements without a row ID:

• Remove redo logs from analysis:

EXECUTE DBMS_LOGMNR.START_LOGMNR( -OPTIONS => DBMS_LOGMNR.CONTINUOUS_MINE, -STARTTIME => (’25-Sep-2003 12:00:00’));

EXECUTE DBMS_LOGMNR.START_LOGMNR( -OPTIONS => DBMS_LOGMNR.NO_ROWID_IN_STMT);

EXECUTE DBMS_LOGMNR.REMOVE_LOGFILE( -LOGFILENAME => ’/oradata/arch012.rdo’);

LogMiner EnhancementsIf you are using LogMiner against the same database that generated the redo log files, LogMiner scans the control file and determines the redo log files that are needed to satisfy your requested time or system change number (SCN) range. LogMiner adds the redo logs from the mining database by default. You no longer need to map your time frame to an explicit set of redo log files. You must use the CONTINUOUS_MINE option and specify a STARTSCN or STARTTIME. If you are not sure of the SCN or time, you can query V$ARCHIVED_LOG to obtain that information. You can also use this view to determine what redo log files are available for automatic detection by LogMiner. You can use the NO_ROWID_IN_STMT option to disable the generation of physical row identifiers in the reconstructed SQL statements. With supplemental logging, the redo stream contains logically unique identifiers for the modified rows, so the physical row identifiers are not needed.

In previous releases, you used the REMOVEFILE option with ADD_LOGFILE to remove redo log files. That option has been deprecated; now you can remove redo log files with the REMOVE_LOGFILE procedure.

Page 138: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-36

Copyright © 2004, Oracle. All rights reserved.18-36

Summary

In this lesson, you should have learned how to:• Enable and disable statistics aggregation and

tracing information in Enterprise Manager for more meaningful data capture

• Flush the buffer cache to establish a common basis for SQL command comparisons

• Enable or disable resumable statements at the instance level for greater flexibility

• Use regular expressions to provide searching and manipulation methods for simple and complex patterns

• Use NLS_SORT and NLS_COMP initialization parameters to provide linguistic sorting and comparison methods

Page 139: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators 18-37

Copyright © 2004, Oracle. All rights reserved.18-37

Practice 18 Overview

This practice covers the following topics:• Demonstrates the use of Regular Expressions for

searching capabilities.• Demonstrates using case-insensitive sorting to

affect query output .• Using the DBMS_MONITOR package to capture trace

information.

Page 140: Oracle 10g New Features for Administrators Vol II
Page 141: Oracle 10g New Features for Administrators Vol II

______________

A Practices

______________

Page 142: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-2

Practice 2-1: Navigating Using Database Control For most of these practice exercises you will be using Enterprise Manager Database Control. In this exercise you will take a full offline backup of your database, and start your database using Database Control. You will then perform some navigational exercises to familiarize yourself with Enterprise Manager Database Control. 1. Perform a full offline backup of your database from $ORACLE_BASE/oradata/orcl to

the $HOME/DONTTOUCH directory. Include a copy of the SPFILE from $ORACLE_HOME/dbs/spfile<sid>.ora. Before doing the backup, make sure that your instance is shutdown cleanly. These files can be used for restoration purposes at any stage in the following practice exercises.

2. Determine your host IP address from your PC from the /etc/hosts file. Open your

browser and enter the URL: http://<IP address>:5500/em to initiate Enterprise Manager Database Control. At the status page, click startup.

3. Enter the host credentials (oracle/oracle) and database credentials (sys/oracle) and click OK.

Click Yes to confirm startup database in open mode. Enter username as SYS with a password of oracle and connect as SYSDBA.

4. Determine the size and location of the Flash Recovery Area.

Note: There are numerous ways to get the solutions for the following questions. 5. What basic parameters are set for the instance? 6. What tablespaces exist in your database? 7. What features are currently configured?

Page 143: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-3

Practice 3-1: Using Data Pump For this practice, you should log in as system, with a password of oracle, either through Database Control or SQL*Plus. 1. Using Database Control, create a new user called DP identified by DP. The user DP should have

EXAMPLE as its default tablespace, and TEMP as its temporary tablespace. Make sure that you grant the CONNECT, RESOURCE, and DBA roles to user DP.

2. You decide that you need to export the SALES, PRODUCTS, and COSTS tables from the SH

schema. However, you want to know which other tables the above three are depending on. Determine the complete list of tables that need to be exported.

3. Connected as user DP, use the Data Pump Export wizard to export the following SH tables:

SALES, PRODUCTS, COSTS, CHANNELS, PROMOTIONS, TIMES, CUSTOMERS, and COUNTRIES. Ensure the following: • Set 1 as the maximum number of threads in the export job. • The Oracle directory DPDIR1 is used to store both the log file and the dump file set.

DPDIR1 should point directly to your $HOME OS directory. Make sure you specify the complete path without using environment variables.

• Do not include the row that corresponds to CHANNEL_ID 5 in the CHANNELS table. • Do not submit the export job. • Write down the Data Pump job name.

4. Submit the Export job previously created. Note: Due to the very short time duration of the job execution, please be aware of the

solution required for the following Step 5 so you can successfully monitor the job operation. If you do not see the expected behavior, you can remove the log and dump files and restart from Step 3 above.

5. You want to see and change some of the Data Pump job characteristics. How can you do this? 6. Now that the Data Pump job execution is suspended, connect as user DP through SQL*Plus.

What table has been created? 7. Connect as user oracle from your terminal emulator window and determine the list of

processes associated with your instance. What is your conclusion? Hint: Look at all the new processes spawned in Oracle Database 10g. 8. How can you see the amount of work performed so far by your Data Pump job? 9. Connect as the oracle user from your terminal emulator window and attach to the existing

export Data Pump job. Connect as the oracle user from a second terminal emulator window and determine the list of processes associated with your instance. What is your conclusion?

Page 144: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-4

10. Back in the first terminal emulator window, change the degree of parallelism of your Data Pump job from 1 to 4. Issue the STATUS command. When done, start your Data Pump job again, and continue the client session. Return quickly to your second emulator window and determine the list of processes that are executing on your instance. What is your conclusion?

11. Remove the Database Control job run from the repository. 12. Now that you successfully exported your tables from the SH user, import only the SALES and

PRODUCTS tables back into the DP schema using the Data Pump Import Wizard. 13. To clean up your environment, you should delete your Database Control job run, and drop the

user DP from your database.

Page 145: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-5

Practice 4-1: Proactively Managing Your Database Using ADDM Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Use Database Control to create a new tablespace called TBSADDM. This tablespace should have

only one 50 MB file and must be locally managed. Also, make sure that TBSADDM does not use automatic segment space management.

2. Using Database Control, create a new user called ADDM identified by ADDM. Make sure that the

ADDM user has TBSADDM as its default tablespace, and TEMP as its temporary tablespace. When done, grant the following roles to the ADDM user: CONNECT, RESOURCE, DBA.

3. Connected as ADDM in SQL*Plus, execute the lab_04_01_03.sql script 4. Connect as user oracle from your terminal emulator and execute the lab_04_01_04.sh

script from your labs directory. 5. From the Database Control home page go to the Performance page. If this is the first time you

go to the Performance page, you need to click Accept in the Adobe license agreement pop-up screen. On the Performance page, make sure that the View Data field is set to Real Time: 15 Seconds Refresh. After a while, you should see a spike on the Sessions: Waiting and Working graph. After the spike is finished, execute the lab_04_01_05.sql script. This script forces the creation of a new snapshot. Looking at the graph, you can already determine that this instance is suffering concurrency problems.

6. Return to the Database Control home page. Because the ADDM data is not refreshed too

frequently on the console, you may not see the latest ADDM result in the Diagnostic Summary region. Retrieve the latest ADDM findings, and determine the cause of the problem.

7. To fix the problem, create a new tablespace called TBSADDM2, and execute the

lab_04_01_07.sql script from your labs directory. This script drops the ADDM table, and re-creates it in the new tablespace. This script also gathers statistics on the table and takes a new snapshot.

8. Connect as user oracle in your terminal emulator and execute again the lab_04_01_04.sh

script from your labs directory. 9. From the Database Control home page, go to the Performance page. On the Performance

page, make sure that the View Data field is set to Real Time: 15 Seconds Refresh. After a while, you should see a spike on the Sessions: Waiting and Working graph. When the spike is finished, execute the lab_04_01_05.sql script. This script forces the creation of a new snapshot. Looking at the graph, you can already determine that this instance is no longer suffering from concurrency problems.

10. Verify that you have fixed the problem. 11. To clean up your environment, execute the lab_04_01_11.sql script.

Page 146: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-6

Practice 4-2: Using Automatic Shared Memory Tuning Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Use Database Control to shut down your instance, and start it up again using the

init_sgalab.ora initialization parameter file located in your labs directory. Before doing this, make sure that the init_sgalab.ora parameter file can be used to start up your instance.

2. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_02.sql script. This

script creates a new tablespace and a new table, and populates the table. 3. Use Database Control to check the size of the various SGA buffers of your instance. 4. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_04.sql script. This

script executes a parallel query on the previously created table. What happens and why? 5. Using Database Control only, how can you fix this problem? Implement your solution. 6. Connect as SYSDBA through SQL*Plus and determine the effects of the previous step on the

memory buffers. What are your conclusions? 7. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_04.sql script again.

This script executes a parallel query on the previously created table. Using Database Control, and while the script is running, verify that your solution is working. What happens and why?

8. If you use SQL*Plus instead of Database Control, what commands do you execute to enable the

Automatic Shared Memory Management feature after you started your instance using the init_sgalab.ora file? Explain your decision. It is assumed that you want to have a maximum of 256MB of SGA memory allocated.

9. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_09.sql script to clean

up your environment.

Page 147: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-7

Practice 5-1: Using Server-Generated Alerts Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Connect as SYSDBA through SQL*Plus and execute the lab_05_01_01.sql script. This

script adds the new subscriber ALERT_USR1 to the internal ALERT_QUE queue. It then grants user SYSTEM the right to dequeue from the ALERT_QUE. Then, the script creates a special procedure that is used by user SYSTEM to dequeue alert information from the ALERT_QUE.

2. Connect as SYSDBA through SQL*Plus, check that you do not have any outstanding alerts

for the User Commits Per Sec metric, and look at your alert history. Then, set the User Commits Per Sec metric with a warning threshold set to 3, and a critical threshold set to 6. Make sure that the observation period is set to one minute, and that the number of consecutive occurrences is set to 2. When done, check that the metrics thresholds have been set correctly. Again, look at your outstanding alerts and alert history. What are your conclusions?

3. Execute the lab_05_01_03.sql script. This script creates a new table and inserts one row in

it. 4. Connect as SYSDBA through Database Control and look at the corresponding metrics graphic

rate. Then, execute the lab_05_01_04.sql script. This script generates a commit rate between three and six commits per second for one minute on your system. While the script is executing, observe the metrics graph using Database Control. After a minute or two, through SQL*Plus, look at your outstanding alerts and alert history. What are your conclusions?

5. While connected as SYSDBA through Database Control, look at the corresponding metrics

graphic rate, and execute the lab_05_01_05.sql script. This script generates a commit rate of five commits per second for three minutes on your system. While the script is executing, observe the metrics graph using Database Control. After the script finishes its execution, examine your outstanding alerts and alert history using both SQL*Plus and another Database Control session. What are your conclusions?

6. Wait three more minutes, and view your outstanding alerts and the alert history again. What are

your conclusions? 7. While connected as SYSDBA through Database Control, look at the corresponding metrics

graphic rate, and execute the lab_05_01_07.sql script. This script generates a commit rate of eight commits per second for three minutes on your system. While the script is executing, observe the metrics graph using Database Control. After the script finishes its execution, look at your outstanding alerts and alert history using both SQL*Plus and Database Control. What are your conclusions?

8. Wait three more minutes, and look at your outstanding alerts and the alert history again. What are

your conclusions? 9. Connect as user SYSTEM through SQL*Plus and execute the SYS.SA_DEQUEUE procedure

multiple times. This procedure was created during the first step. Before executing the procedure, execute the SET SERVEROUTPUT ON command. What are your conclusions?

Page 148: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-8

10. Using Database Control, disable the thresholds check for the User Commits (per second)

metric. 11. Execute the lab_05_01_11.sql script to clean up your environment.

Page 149: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-9

Practice 6-1: Proactively Tuning High Load SQL Statements Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Connect as SYSDBA through Database Control and navigate to the Performance tab of the

Database Control home page. On the Performance page, make sure that the View Data field is set to Real Time: 15 second Refresh. When done, open a terminal emulator window connected as user oracle. When done change your current directory to your labs directory: cd $HOME/labs. Then, enter the following command from the OS prompt:

. ./setup_perflab.sh 2. When the setup_perflab.sh script completes, in approximately five minutes, observe the

Performance page for six minutes. What are your conclusions? 3. How can you quickly fix the problem? 4. Fix the problem. 5. After you fix the problem, how can you quickly verify that the problem was solved? 6. To stop the workload, execute the following command: . ./stop_workload2.sh from

your terminal emulator window. 7. Assume that someone else has executed the previous steps some time ago when you were out for

vacation. Back in the office, you want to see what happened while you were away. How can you do this? Returning to the previous example, retrieve the history of what happened to your system.

8. Return to the Performance page. During the period of time where the workload was running,

determine the most important wait category from the Sessions: Waiting and Working graph, and find the history of what was done to fix the problem.

9. To clean up your environment, execute the following command from your command-line

window: . ./cleanup_perflab.sh.

Page 150: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-10

Practice 6-2: Using the SQL Access Advisor Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Connected as SYSDBA through SQL*Plus, flush the shared pool and execute the following four

scripts, in this order: a. lab_06_02_01a.sql b. lab_06_02_01b.sql: (Star query) c. lab_06_02_01c.sql: (Star query) d. lab_06_02_01d.sql: (Order by)

2. Connected as SYSDBA through SQL*Plus, execute the lab_06_02_02.sql script. This script

creates a new SQL tuning set called MY_STS_WORKLOAD, which captures the SQL statements that you ran in step one.

3. Connected as SYSDBA through Database Control, use the SQL Access Advisor to generate recommendations for the MY_STS_WORKLOAD SQL tuning set.

4. Looking at the Recommendations page for your SQL Access Advisor task, what are your

conclusions? 5. Implement the SQL Access Advisor recommendation that has the most benefit on your workload.

Then, redo Steps 3 and 4. What are your conclusions? 6. Use Database Control to clean up your environment by removing:

• The SQL Access Advisor analysis • The MY_STS_WORKLOAD SQL tuning set. • The implementation job Use SQL*Plus to remove the objects created by the implementation job. When done, execute lab_06_02_06.sql in order to clean up your schemas.

Page 151: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-11

Practice 7-1: Using Partitioned Outer Joins In this practice you will create two small tables, based on the SH schema. Using these two tables, you investigate the difference between a partitioned outer join and a regular outer join. Unless specified otherwise, you should be logging in as SH either through SQL*Plus or iSQL*Plus. 1. Connect to the SH schema, and alter the session so that the NLS_DATE_FORMAT is set to 'DD-

MON-YYYY'. Confirm the two tables T1 and S1 you create in the next step do not presently exist. You can use the script lab_07_01_01.sql.

2. Create a table S1 with the following SQL statement:

create table s1 as select DISTINCT time_id, prod_id, quantity_sold from sales where time_id between '02-JAN-2001'

and '05-JAN-2001' and prod_id < 15;

You can use the lab_07_01_02.sql script.

3. Execute the lab_07_01_03.sql script to create the table T1. Query the contents of T1. 4. Define a break on PROD_ID (to enhance output readability), and execute the right outer join

query in the lab_07_01_04.sql script. What do you notice about the returned rows? 5. Now, execute the partitioned outer join query in the lab_07_01_05.sql script. 6. Compare the results of the two queries executed in steps 4 and 5. What is the difference? 7. You will need the S1 table in the next practice; you can drop the T1 table now.

Page 152: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-12

Practice 7-2: Using the MODEL Clause You can use the S1 table you created in the previous practice to experiment with the new MODEL clause to perform inter-row calculations. 1. Connect as the SH schema and query all rows of the S1 table to see the table contents.

TIP: Remember to clear the format break set in the previous practice. 2. Execute the lab_07_02_02.sql script to see the MODEL clause at work. 3. Change the above query to suppress the original rows from the S1 table by adding the RETURN

UPDATED ROWS clause after the RULES keyword. You can execute the lab_07_02_03.sql script.

4. You can drop the S1 table now.

Page 153: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-13

Practice 7-3: Using Some Materialized View Enhancements 1. Connect to the SH schema, and run the lab_07_03_01.sql script to ensure the MY_MV

materialized view does not exist. 2. Execute the lab_07_03_02.sql script to create a materialized view called MY_MV, and

execute the dbms_stats.gather_table_stats(USER, 'MY_MV') procedure to gather statistics against MY_MV.

3. Execute the lab_07_03_03.sql script. There is an intentional typographical error in the

script to help identify the QUERY_OR_REWRITE hint at work. 4. Fix the error: Change QUANTITY_SOLD into AMOUNT_SOLD on line 3, and repeat the test. 5. Run the lab_07_03_05.sql script to execute EXPLAIN PLAN against the query in the

previous step and query the PLAN_TABLE table, to see the improved execution plan readability. 6. Before you can use the DBMS_MVIEW.EXPLAIN_REWRITE procedure, you must create the

REWRITE_TABLE table with the utlxrw.sql script available in the $ORACLE_HOME/rdbms/admin directory. Run the $ORACLE_HOME/rdbms/admin/utlxrw.sql script now.

7. Using the lab_07_03_07.sql script, execute the DBMS_MVIEW.EXPLAIN_REWRITE

procedure against the query and the MY_MV materialized view, and query the REWRITE_TABLE table to see the results.

8. Execute the lab_07_03_08.sql script to clean up your database environment by dropping

the MY_MV materialized view and the REWRITE_TABLE table.

Page 154: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-14

Practice 9-1: Monitoring the Scheduler In this practice, you use the Database Control application to define and monitor the Scheduler and automate tasks. Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Log in to EM Database Control as the SYSTEM user and grant the following roles to the HR user:

• CONNECT role • RESOURCE role • DBA role Because you are going to use user HR to administer jobs through Database Control, you need to make sure that HR is registered as a possible Administrator.

2. Log in to Database Control as the HR user. From the Administration tab, click the Jobs link in

the Scheduler region, at the bottom right corner of the page. Are there any existing jobs?

3. Are there any existing programs? (Hint: Use the browser Back button). 4. Are there any existing schedules? 5. Are there any existing windows? What resource plan is associated with each window? 6. Are there any existing job classes? If so, what resource consumer group is associated with each

job class?

Page 155: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-15

Practice 9-2: Creating Scheduler Components In this practice, you will use Database Control to create Scheduler objects and automate tasks. Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. While logged in to the database as the HR user in Database Control, click the Administration

tab. Under the heading Scheduler, click Jobs. Click the Create button to open the Create Job window. Create a simple job that runs a SQL script:

• General: Name: CREATE_LOG_TABLE_JOB Owner: HR Description: Create the SESSION_HISTORY table for the next part of this practice Logging level: RUNS Command type: In-line Program: Executable Executable: /home/oracle/labs/lab_09_02_01.sh

• Schedule: Repeating: Do not Repeat Start: Immediately

• Options: No special options.

2. Click the OK button to create the job. 3. If the job does not appear on the Scheduler Jobs page, click the Refresh button. Then click the

Run History tab and verify that the job ran successfully. 4. Create a program called LOG_SESS_COUNT_PRGM that logs the current number of database

sessions into a table. Use the following code, or use the lab_09_02_04.sql script: DECLARE sess_count NUMBER; BEGIN SELECT COUNT(*) INTO sess_count FROM V$SESSION; INSERT INTO session_history VALUES (systimestamp, sess_count); COMMIT; END;

5. Create a schedule named SESS_UPDATE_SCHED owned by HR that executes every three

seconds. Because the Database Control interface supports scheduled intervals of only one minute or greater, you will use SQL*Plus and the DBMS_SCHEDULER.CREATE_SCHEDULE procedure to create the program.

6. Return to the Database Control, and verify that the schedule was created.

Hint: You may have to refresh the page for the Schedule to appear. 7. Using Database Control, create a job named LOG_SESSIONS_JOB that uses the

LOG_SESS_COUNT_PRGM program and the SESS_UPDATE_SCHED schedule. Make sure the job uses FULL logging.

Page 156: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-16

8. Check the HR.SESSION_HISTORY table for rows. If there are rows in the table, are the timestamps three seconds apart?

9. Use Database Control to alter the SESS_UPDATE_SCHED schedule from every three seconds

to every three minutes. 10. Connect as HR schema, and query the SESSION_HISTORY table to verify that the rows are

being added every three minutes now, instead of every three seconds. 11. Alter the HR.SESSION_HISTORY table to contain a new column, BACKGROUND_COUNT of

type NUMBER. 12. Alter the LOG_SESS_COUNT_PRGM program to log new information into the logging table.

Modify the code to look like the following text, or use the lab_09_02_12.sql script: DECLARE sess_count NUMBER; back_count NUMBER; BEGIN SELECT COUNT(*) INTO sess_count FROM V$SESSION; SELECT COUNT(*) INTO back_count FROM V$SESSION WHERE type = ''BACKGROUND''; INSERT INTO session_history VALUES (systimestamp, sess_count,

back_count); COMMIT; END;

13. Run the LOG_SESSIONS_JOB job immediately, and verify that the new information was added

to the HR.SESSION_HISTORY table. 14. Drop the LOG_SESSIONS_JOB job, the LOG_SESS_COUNT_PRGM program, and the schedule

SESS_UPDATE_SCHED. Note: Make sure you do not delete the wrong schedule.

Page 157: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-17

Practice 10-1: Proactively Managing Tablespace Space Usage Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Using the DBMS_SERVER_ALERT.SET_THRESHOLD procedure, reset the database-wide

threshold values for the Tablespace Space Usage metric. You can use the script lab_10_01_01.sql.

2. Check the database-wide threshold values for the Tablespace Space Usage metric by using the

following command: SELECT warning_value,critical_value FROM dba_thresholds WHERE metrics_name='Tablespace Space Usage' AND object_name IS NULL;

3. Create a new tablespace called TBSALERT with one 5 MB file called alert1.dbf. Make sure

this tablespace is locally managed and uses Automatic Segment Space Management. Also, do not make it autoextensible, and do not specify any thresholds for this tablespace. Use Database Control to create it. If this tablespace already exists in your database, drop it first, including its files.

4. Using Database Control, change the Tablespace Space Usage thresholds of the TBSALERT

tablespace. Set its warning level to 50 percent, and its critical level to 60 percent. 5. Using SQL*Plus, check the new threshold values for TBSALERT. 6. Select the reason and resolution columns from DBA_ALERT_HISTORY for the

TBSALERT tablespace. How do you explain the result? 7. Execute the lab_10_01_07.sql script that populates new tables in TBSALERT. 8. Check the fullness level of the TBSALERT tablespace using either Database Control or

SQL*Plus. The current level should be around 53%. Wait for approximately 10 minutes, and check that the warning level is reached for the TBSALERT tablespace.

9. Execute the lab_10_01_09.sql script to add data to TBSALERT. Wait for 10 minutes and

view the critical level in both the database and in Database Control. Verify that TBSALERT fullness is around 63%.

10. Execute the lab_10_01_10.sql script. This script deletes rows from tables in TBSALERT. 11. Now run the Segment Advisor for the TBSALERT tablespace by using Database Control. Make

sure that you run the Advisor in Comprehensive mode without time limitation. Accept and implement its recommendations. After the recommendations have been implemented, check that the fullness level of TBSALERT is below 50%.

12. Wait for approximately 10 more minutes, and check that there are no longer any outstanding

alerts for the TBSALERT tablespace.

Page 158: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-18

13. Using Database Control, retrieve the history of the Tablespace Space Usage metric for TBSALERT for the last 24 hours.

14. Reset the database wide default thresholds from the Tablespace Space Usage metric for

tablespace TBSALERT.

Page 159: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-19

Practice 10-2: Sizing Your Undo Tablespace with the Undo Advisor Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. For this lab, it is assumed that: • undo_management is set to AUTO • undo_retention is set to 900 • undo_tablespace is set to UNDOTBS1 1. Create a database session connected as SYSDBA through SQL*Plus. This session is referred to as

the First session. Using either Database Control or SQL*Plus, create a new undo tablespace called UT2 with only one 1MB file.

2. Change your current undo tablespace to UT2. 3. Using a second SQL*Plus session, connect as SYSDBA. This session is referred to as the

Second session. Execute the lab_10_02_03.sql script. If you get an error when executing the script, switch your undo tablespace back to UNDOTBS1, and start again.

4. In the second session, prepare to execute the lab_10_02_04a.sql script, and in the first

session prepare to execute the lab_10_02_04b.sql script. When done, execute the script in the second session, and then immediately after, execute the one from the first session. What happens and why?

5. From the first session look at the alert history. What do you see? Use Database Control to locate

the warning, and click the corresponding alert link. 6. Use the Undo Advisor to get recommendations to correctly size UT2. Use the recommendation to

correctly size the UT2 tablespace. 7. Redo step 4. What happens and why? 8. Switch your undo tablespace back to UNDOTBS1, and drop UT2 including its data files, as well

as TBSALERT.

Page 160: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-20

Practice 11-1: Interpreting ROWIDs of Rows Stored in Bigfile Tablespaces. Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Using Database Control, create a new bigfile tablespace called TBSBF containing one 5 MB file. 2. Using Database Control, try to add a new file to TBSBF. What happens and why? 3. Using Database Control, how can you resize TBSBF to 10 MB? What simplification can you

observe? 4. Using Database Control, create table EMP as a copy of HR.EMPLOYEES. Make sure that EMP

resides in the TBSBF tablespace. 5. Explain why the following statement is incorrect. Then fix it, and determine the correct output:

SELECT distinct DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID) FROM sys.emp;

6. Explain why the following statement is incorrect. Then fix it, and determine the correct output:

SELECT distinct DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'BIGFILE') FROM hr.employees;

7. Explain why the following statement is correct. What is your conclusion?

SELECT DBMS_ROWID.ROWID_TO_RESTRICTED(rowid,1) FROM sys.emp WHERE rownum<2;

8. Execute the following statement with the previously found restricted ROWID. Explain why it is

incorrect, and then fix it: SELECT first_name FROM sys.emp WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('&rid',NULL,NULL,0) FROM dual);

9. Execute the lab_11_01_09.sql script to clean up your environment.

Page 161: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-21

Practice 12-1: Setting Up a Flash Recovery Area Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. In this lab you will be following Oracle’s best practices for managing database files and recovery

related files by establishing a database area and flash recovery area for your database. Use Database Control to configure OMF to /u01/app/oracle/oradata/orcl. Ensure that parameter changes are written to the current SPFILE. Turn on ARCHIVELOG mode for your database. This requires a restart of your instance.

2. Using Database Control, check that you are now using automatically a flash recovery area. Then

make sure that the size of your flash recovery area is set to 3GB. What happens to the Archive Log Destination 10?

3. Gather information regarding the flash recovery area by querying the

v$recovery_file_dest view. You can use the lab_12_01_03.sql lab script. Note: Returned values may vary from the provided solution.

Page 162: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-22

Practice 12-2: Enabling Block Change Tracking Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Using Database Control, enable fast incremental backups for your database. What is the default

location for the change tracking file? Ensure that your retention policy allows for recovery within the last 31 days.

2. Query the v$block_change_tracking view to show the status, file name, and size of the

file. You can use the lab_12_02_02.sql script.

Page 163: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-23

Practice 12-3: Using Oracle Suggested Strategy for Backups Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Using Database Control, back up the Oracle database using the Oracle Suggested Strategy. View

the backup logs as they are generated through the backup progress. The log generation is dynamic, so refresh your browser to view more output.

Page 164: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-24

Practice 12-4: Using Optimized Incremental Backups Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Run the lab_12_04_01.sql script to create a new user called HR1, using the EXAMPLE

tablespace to store the created tables. Using Database Control, confirm the existence of the following tables:

• BR_JOB_HISTORY • BR_EMPLOYEES • BR_JOBS • BR_DEPARTMENTS • BR_LOCATIONS • BR_COUNTRIES • BR_REGIONS

2. Run the Oracle Suggested Strategy again by creating a new backup job. Follow the same steps as

in Practice 12-3. 3. View the RMAN job output.

From the following region of log, it took only 26 seconds to complete the backup. Backup times will vary from host to host.

4. After the backup job has completed, run the lab_12_04_04.sql script to view the formatted

output of the number of blocks actually backed up.

Page 165: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-25

Practice 12-5: Using Incrementally Updated Backups Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Run the lab_12_05_01.sql script to update the HR1s BR_REGIONS table. 2. Run the Oracle Suggested Strategy again by creating a new backup job. Follow the same steps as

in Practice 12-3. 3. View the log of the RMAN backup job. You can see that RMAN merges the previous

incremental backup into the image copies.

Page 166: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-26

Practice 12-6: Managing Space in the Flash Recovery Area Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Determine the current flash recovery area size. 2. Using Database Control, reduce the size of the flash recovery area so that a warning is issued on

the next backup. 3. Run the Oracle Suggested Strategy again by creating a new backup job. Follow the same steps as

in Practice 12-3. 4. When there is no more space available in the flash recovery area, the following actions occur:

• The RMAN backup job errors because there is no more space for the backup file. View the EM job output (if possible)

• An error is written to the alert.log. • A row is inserted into the DBA_OUTSTANDING_ALERTS view. Using Database Control, look at the latest entries in the alert.log.

5. Reset the flash recovery area size to 3 GB.

Page 167: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-27

Practice 12-7: RMAN Channel Failover Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. In this exercise you will simulate a channel failover when using multiple channels and backing

up to tape. From a terminal window, use mkdir to create a temporary directory location for the tape device to act as the pseudo-SBT device type at /home/oracle/tape. Set the RMAN channel configuration by running the lab_12_07_01.sql script.

2. Using Database Control, back up your whole database to tape. 3. Use Database Control to clean up your environment by:

• Removing the HR1 user • Turning off Archivelog mode • Restarting the Database Console • Remove the /home/oracle/tape directory.

Page 168: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-28

Practice 13-1: Flashback Dropped Tables Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Create a new locally managed tablespace called TBSFD containing only one 500 KB file. Also,

TBSFD should use Automatic Segment Space Management. Use either Database Control or command line to create it. If this tablespace already exists in your database, drop it first, including its files.

2. Create a new user called FD, identified by FD, having TBSFD as its default tablespace and TEMP

as its temporary tablespace. Make sure that user FD has the following roles granted: CONNECT, RESOURCE, and DBA. If this user already exists on your system, drop it first.

3. Connect as user FD and execute the lab_13_01_03.sql script through SQL*Plus. This script

creates: • Table EMP as a copy of HR.EMPLOYEES • Table DEPT as a copy of HR.DEPARTMENTS • The NOTHING trigger on EMP • The EMP primary key • The DEPT primary key • The EMPFK constraint on EMP that references the DEPT primary key • The EMPFKINDX index on EMPFK • The EMPSALCONS check constraint on EMP • The EMPIDMGRFK self-referencing constraint on EMP • A materialized view log on EMP

4. Use Database Control to determine the available free space remaining on the TBSFD tablespace.

Connected as FD in SQL*Plus, list the segments and constraints created by user FD. In the report, also include the size of each segment.

5. Using Database Control, drop the EMP table, and look at the FD users recycle bin. What do you

observe? 6. Connect as user FD through SQL*Plus and determine the size of each free extent in the TBSFD

tablespace. What is your conclusion? 7. Although the EMP table has been dropped, it is still possible to query its content as long as it is

visible from the recycle bin. Query the content of the dropped EMP table using Database Control. 8. Connect as user FD through SQL*Plus, and list all the objects and constraints that belong to user

FD. What are your conclusions? 9. Using Database Control, flashback the dropped table. 10. Connect as user FD through SQL*Plus, query the EMP table, and list the available free space in

tablespace TBSFD. What are your conclusions?

Page 169: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-29

11. Connect as user FD through SQL*Plus and create a new table DEPT2 as a copy of HR.DEPARTMENTS. Make sure that DEPT2 resides in TBSFD. When done, drop the table EMP again, and create a new table EMP2 as a copy of HR.EMPLOYEES. Make sure that EMP2 is stored in TBSFD. When done, try to flash back the dropped EMP table. What happens and why?

12. Using Database Control, drop the DEPT2 table and purge the corresponding entry in the FD

recycle bin. 13. Connected as SYSDBA through SQL*Plus, execute the lab_13_01_13.sql script to clean up

the environment.

Page 170: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-30

Practice 13-2: Flashback Database Unless specified otherwise, you should be logging in as SYSDBA through either SQL*Plus or Database Control. 1. Connected as SYSDBA through SQL*Plus, execute the lab_13_02_01.sql script. This script

creates a new user called JFV identified by JFV, and also creates a new tablespace called JFVTBS.

2. Using SQ*Plus, determine the list of processes associated to your instance. Then check that your

database is in NOARCHIVELOG mode, and that it does not use flashback logging. List the content of your flash recovery area.

3. Using Database Control, enable both ARCHIVELOG mode and flashback logging. 4. Using SQL*Plus, determine the list of processes associated to your instance. Then check that

your database is in ARCHIVELOG mode, and that it uses flashback logging. List the content of your flash recovery area. What are your conclusions?

5. Connected as user JFV under SQL*Plus, execute the lab_13_02_05.sql script. This script

creates a new table called EMP. It also selects the sum of all the salaries of the EMP table. Then the script returns the current SCN of your database, and it looks at the contents of V$UNDOSTAT, V$FLASHBACK_DATABASE_LOG, and V$FLASHBACK_DATABASE_STAT. Write down the information provided by lab_13_02_05.sql.

6. Connected as user JFV under SQL*Plus, repeat the execution of the lab_13_02_06.sql

script three times. What are your conclusions? 7. Connected as user JFV under SQL*Plus, create a new tablespace called JFVTBS2. This

tablespace should have only one 500 KB data file. When done, disable flashback logging on JFVTBS2. Then check that flashback logging is not enabled on JFVTBS2.

8. Connected as user JFV under SQL*Plus, execute the lab_13_02_08.sql script. This script

creates a new table called EMP2 inside tablespace JFVTBS2. The script also returns the flashback statistics and then executes a long running update of the EMP2 table. In the end, the script shows you again the flashback statistics. What are your conclusions?

9. Connected as user JFV under SQL*Plus, execute the lab_13_02_09.sql script. Write down

the information returned by this script. 10. Connected as SYSDBA under SQL*Plus try to recover your database to the SCN calculated

during step 9. What happens and why? 11. Using SQL*Plus, fix the problem, and redo step 10. When done, open your database in READ

ONLY mode, and check the result of your flashback database operation. Then, shutdown and startup mount your instance.

12. Connected as SYSDBA under SQL*Plus, flashback your database to the SCN returned in step 5.

Then open your database in READ WRITE mode, and check your database. What is your conclusion?

Page 171: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-31

13. Still connected as SYSDBA under SQL*Plus, clean up your environment by doing the following:

• Drop the JFVTBS tablespace including its data file. • Drop user JFV. • Disable flashback logging • Return to NOARCHIVELOG mode.

Page 172: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-32

Practice 14-1: Using The Redo Log File Size Advisor Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Execute the lab_14_01_01.sql script to create a new table that will be used to generate a

workload on your instance. 2. Use Database Control to shut down your instance, and start it up again using the

init_lfszadv.ora initialization parameter file located in your labs directory. Before doing this, make sure that the init_lfszadv.ora parameter file can be used to start up your instance.

3. Execute the lab_14_01_03.sql script. This script updates the previously defined

T_LFSZADV table. This is done to generate a workload on your instance. 4. When done, determine the size advice for your redo log groups using Database Control. 5. Implement the recommendation by adding two new redo log groups of 50 MB, and by dropping

the existing redo log groups. 6. Redo steps 1 and 2. 7. Redo steps 3 and 4. What are your conclusions? 8. To clean up the environment, log out from any session that you created so far and connect as

SYSDBA through SQL*Plus. Then execute the lab_14_01_08.sql script.

Page 173: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-33

Practice 15-1: Setting Up an ASM Instance Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Use DBCA to create the ASM instance on your machine. During the ASM instance creation,

DBCA asks you whether you want to change the default values for the ASM initialization parameter. Make sure that the disk discovery string is set to /u02/asmdisks/*. Then DBCA asks you to create new disk groups. Create one disk group called DGROUP1 that is using the following four ASM disks: • /u02/asmdisks/disk0 • /u02/asmdisks/disk1 • /u02/asmdisks/disk2 • /u02/asmdisks/disk3 Make sure to specify that DGROUP1 is using external redundancy. After the ASM instance and the disk group are created, you can exit DBCA. Do not create a database.

Page 174: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-34

Practice 15-2: Understanding ASM Automatic Rebalancing 1. Connected as user oracle in your terminal emulator window, start your ASM instance and list

the processes associated to it. Then determine the characteristics of: • The mounted disk groups • The associated ASM disks • The associated ASM files

2. Connected as SYSDBA under SQL*Plus in another terminal emulator window, determine the list

of disk groups that are visible from your database instance. Then list the processes associated to your database instance. When done, create a new tablespace called TBSASM that is stored inside the ASM disk group DGROUP1, and that has only one 200 MB data file. When done, determine the list of processes associated to your database instance again, and list the data files associated to your database. What do you observe?

3. Back on your ASM instance, list all the ASM files that were created so far. Then, look at the

ASM disk activity and free space. Execute the lab_15_02_03.sql script to simulate the addition of a new disk to your system. Again, look at the ASM disk activity and free space. When done, add the new disk /u02/asmdisks/disk4 to DGROUP1. Look at the ongoing ASM operations until there is no outstanding one. Then look again at the ASM disk activity and free space. What are your conclusions?

4. On your database instance, execute the lab_15_02_04.sql script. This script creates and

populates a new table called T, which is stored in TBSASM. When executed, set timing statistics in your SQL*Plus session and execute the following query: SELECT count(distinct -

DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE')) FROM t;

5. From your ASM instance, drop the ASM disk DGROUP1_0004 from DGROUP1. 6. In your database instance, execute again the following query:

SELECT count(distinct -DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE'))

FROM t; What are your conclusions?

7. Back in your ASM instance, check the impact on the ASM disk activity and free space. What are your conclusions?

Page 175: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-35

Practice 15-3: Migrating Tablespaces to ASM 1. Connected as SYSDBA under SQL*Plus in your database instance, create a new tablespace called

TBSASMMIG. This tablespace should contain only one 10 MB file stored in your file system (not using ASM). Create a table called T2 stored in TBSASMMIG. Insert one row inside T2.

2. From your database instance, migrate TBSASMMIG to ASM storage. When done, check that the

migration was successful. 3. From your ASM instance, check the number of files created in your ASM disks. 4. From your database instance, cleanup your environment by dropping tablespace TBSASMMIG

including its contents and data file. Do the same with tablespace TBSASM. Also, remove the file system file that was originally created to store TBSASMMIG.

Page 176: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-36

Practice 17-1: Implement VPD Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Execute the lab_17_01_01.sql script. This script does the following:

• It creates three new users VPD, JF, and MH all identified by their name. • User VPD is granted the CONNECT, RESOURCE, and DBA roles. The script also creates a new

table called VPD.EMPLOYEES with the same structure as HR.EMPLOYEES. This table contains three rows: One corresponding to user JF, one to user MH, and another one corresponding to the hypothetical user CL.

• Users JF, and MH are granted the CONNECT and RESOURCE roles, and also SELECT on VPD.EMPLOYEES.

2. Connect as user VPD through SQL*Plus and create a new package called

APP_SECURITY_CONTEXT. This package should contain only one procedure called SET_EMPNO. The goal of the SET_EMPNO procedure is to assign to the EMPNO attribute of the VPD_CONTEXT context the employee’s identifier corresponding to the connected user. Use the procedure DBMS_SESSION.SET_CONTEXT to set the EMPNO attribute, and the SYS_CONTEXT('USERENV','SESSION_USER') function to determine the name of the connected user.

3. When done, create the VPD_CONTEXT context using the APP_SECURITY_CONTEXT

package. 4. Create an AFTER LOGON trigger that calls the

VPD.APP_SECURITY_CONTEXT.SET_EMPNO procedure only if the current schema is JF or MH.

5. Connect as user VPD through SQL*Plus and execute the lab_17_01_05.sql script. This

script creates a new package called VPD_SECURITY. This package contains one function called EMPNO_SEC. The goal of this function is to return the VPD predicate used by your policy. In this case the returned predicate is: employee_id = SYS_CONTEXT('vpd_context', 'empno').

6. Connect as VPD through SQL*Plus and create a new policy called VPD_POLICY. This policy

should have the following characteristics: • Is attached to the VPD.EMPLOYEES table • Uses the VPD.VPD_SECURITY.EMPNO_SEC function • Is applied only for SELECT statements • Is a dynamic policy • Specifies the SALARY and COMMISSION_PCT columns as the list of relevant columns You can use the lab_17_01_06.sql script.

7. Connect as user JF through SQL*Plus and execute the following statements:

SELECT first_name FROM vpd.employees; SELECT first_name FROM vpd.employees; SELECT last_name FROM vpd.employees; SELECT salary FROM vpd.employees; What do you observe, and what are your conclusions?

Page 177: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-37

8. Connect as user MH through SQL*Plus and execute the following statements:

select first_name from vpd.employees; select last_name from vpd.employees; select last_name as ln from vpd.employees; select salary from vpd.employees; What do you observe, and what are your conclusions?

9. Connect as user VPD and drop the VPD_POLICY policy, and re-create it with the exact same characteristics except that it should now be a static policy instead of being dynamic. When done, flush the shared pool of your instance. You can use the lab_17_01_09.sql script.

10. Connect as user JF through SQL*Plus and execute the following statements:

select first_name from vpd.employees; select first_name from vpd.employees; select last_name from vpd.employees; select salary from vpd.employees; select commission_pct from vpd.employees; What do you observe, and what are your conclusions?

11. Connect as SYSDBA and determine which statements are using the defined policy on your instance. What are your conclusions?

12. To clean up your environment, execute the lab_17_01_12.sql script.

Page 178: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-38

Practice 18-1: Using Regular Expressions 1. Connect as SYSDBA and write a query with a single WHERE clause condition (using the

REGEXP_LIKE function) that asks for a search-string and then displays the view definitions of all views with the name [DBA|USER|ALL]_search-string. Make sure your query is case insensitive. You can use lab_18_01_01.sql.

2. Execute the following query:

select banner from v$version where rownum = 1;

a. Use the REGEXP_INSTR function to alter this query to return the position of the fifth

word in this banner text. You can use lab_18_01_02a.sql. b. Use the REGEXP_INSTR function to return the position of the second word starting with

a lowercase or uppercase “e” with a length of at least seven characters. You can use lab_18_01_02b.sql.

Page 179: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-39

Practice 18-2: Using Case-Insensitive Sorting 1. Connect to the HR schema, and create a table called NAMES, with first names using the following

statements: create table names as select first_name from employees where rownum <= 30; update names set first_name = lower(first_name) where rownum <= 15; You can use the script lab_18_02_01.sql

2. Execute the following query and look at the default ordering:

select * from names order by first_name;

3. By default, uppercase characters sort before lowercase characters. Using the ALTER SESSION

command, change NLS_SORT for your session to use case-insensitive binary sorting and repeat the query from the previous step.

4. Drop the NAMES table, and reset your session to use default binary sorting.

Page 180: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators A-40

Practice 18-3: Using the DBMS_MONITOR Package 1. Start two sessions, one connected as SYSDBA and one connected as SH. 2. From the SYSDBA session, determine the session ID (sid) and serial number (serial#) from

v$session for the SH user, and then describe the DBMS_MONITOR package. Then, from the SYSDBA session, enable tracing using the sid and serial# values for the other session, including the waits and bind information, with the following command: execute dbms_monitor.session_trace_enable ( - session_id => <sid> , -

serial_num => <serial#> , - waits => true , - binds => true ) ;

3. From the SH session, execute the lab_18_03_03.sql script, and then exit your session. 4. From the remaining SYSDBA session, determine your user_dump_dest location, locate the

trace file, and view the contents.

Page 181: Oracle 10g New Features for Administrators Vol II

______________

B Solutions

______________

Page 182: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-2

Practice 2-1 Solution: Navigating Using Database Control For most of these practice exercises you will be using Enterprise Manager Database Control. In this exercise you will take a full offline backup of your database, and start your database using Database Control. You will then perform some navigational exercises to familiarize yourself with Enterprise Manager Database Control. 1. Perform a full offline backup of your database from $ORACLE_BASE/oradata/orcl to

the $HOME/DONTTOUCH directory. Include a copy of the SPFILE from $ORACLE_HOME/dbs/spfile<sid>.ora. Before doing the backup, make sure that your instance is shutdown cleanly. These files can be used for restoration purposes at any stage in the following practice exercises.

sqlplus / as sysdba << END set echo on connect / as sysdba shutdown immediate; exit; END cp $ORACLE_BASE/oradata/orcl/* $HOME/DONTTOUCH cp $ORACLE_HOME/dbs/spfile*.ora $HOME/DONTTOUCH

2. Determine your host IP address from your PC from the /etc/hosts file. Open your

browser and enter the URL: http://<IP address>:5500/em to initiate Enterprise Manager Database Control. At the status page, click startup.

more /etc/hosts # Do not remove the following line, or various programs # that require network functionality will fail. 127.0.0.1 localhost.localdomain localhost 139.185.35.115 edrsr15p1.us.oracle.com edrsr15p1

3. Enter the host credentials (oracle/oracle) and database credentials (sys/oracle) and click OK.

Click Yes to confirm startup database in open mode. Enter username as SYS with a password of oracle and connect as SYSDBA.

a. At the Startup/Shutdown: Specify Host and Target Database Credentials, enter oracle / oracle

for the target database machine credentials, and sys / oracle for the target database credentials. b. Click OK when done. c. In the Startup/Shutdown window, click Yes to confirm startup database in open mode. d. Enter the username as SYS with a password of oracle, connect as SYSDBA, and click Login.

Page 183: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-3

e. On the Oracle Database Licensing Information 10g page click the I Agree button.

4. Determine the size and location of the Flash Recovery Area.

Note: There are numerous ways to get the solutions for the following questions.

a. From the Database Control home page: Maintenance > Configure Recovery Settings b. Scroll down to the Flash Recovery Area region.

5. What basic parameters are set for the instance?

a. From the Database Control home page: Administration > All Initialization Parameters b. Use the scroll bar or the Filter field to search on a name or partial name.

6. What tablespaces exist in your database?

a. From the Database Control home page: Administration > Tablespaces

7. What features are currently configured?

a. From the Database Control home page: Administration > Configuration Management > Database Usage Statistics

b. Use the Previous and Next links to scroll through the features.

Page 184: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-4

Practice 3-1 Solution: Using Data Pump For this practice, you should log in as system, with a password of oracle, either through Database Control or SQL*Plus. 1. Using Database Control, create a new user called DP identified by DP. The user DP should have

EXAMPLE as its default tablespace, and TEMP as its temporary tablespace. Make sure that you grant the CONNECT, RESOURCE, and DBA roles to user DP.

a. From the Database Control home page: Administration > Users b. On the Users page click the Create button. c. On the Create User page, specify the following fields: Name, Enter Password, Confirm Password,

Default Tablespace, and Temporary Tablespace. d. When done, click the Roles tab. e. Click the Modify button. f. On the Modify Roles page, select RESOURCE and DBA from the Available Roles list. When done, click

the Move link. Then click the OK button. g. After you are returned to the Create User page, click the OK button.

2. You decide that you need to export the SALES, PRODUCTS, and COSTS tables from the SH

schema. However, you want to know which other tables the above three are depending on. Determine the complete list of tables that need to be exported.

a. From the Database Control home page, click the Administration tab. b. On the Administration page, click the Tables link in the Schema region. c. On the Tables page, specify SH in the Schema field in the Search region. Then click the Go button. d. Select the SALES table from the Results region, and select Show Dependencies from the Actions drop-

down list. Then click the Go button in the Results region. e. On the Show Dependencies page for the SALES table, the Dependencies tab lists the tables on which

SALES depends. From that list you can determine that SALES depends on CHANNELS, CUSTOMERS, PRODUCTS, PROMOTIONS, and TIMES.

f. Similarly, you can determine that PRODUCTS does not depend on any other table, and that COSTS depends on CHANNELS, PRODUCTS, PROMOTIONS, TIMES and COUNTRIES.

g. Now, by using the same procedure, you can determine that CHANNELS, PROMOTIONS, and TIMES are not depending on other tables. However CUSTOMERS depends on COUNTRIES.

h. So, the complete list of tables that need to be exported is: SALES, PRODUCTS, COSTS, CHANNELS, PROMOTIONS, TIMES, CUSTOMERS, and COUNTRIES.

Page 185: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-5

3. Connected as user DP, use the Data Pump Export wizard to export the following SH tables: SALES, PRODUCTS, COSTS, CHANNELS, PROMOTIONS, TIMES, CUSTOMERS, and COUNTRIES. Ensure the following: • Set 1 as the maximum number of threads in the export job. • The Oracle directory DPDIR1 is used to store both the log file and the dump file set.

DPDIR1 should point directly to your $HOME OS directory. Make sure you specify the complete path without using environment variables.

• Do not include the row that corresponds to CHANNEL_ID 5 in the CHANNELS table. • Do not submit the export job. • Write down the Data Pump job name.

a. From the Database Control home page, click the Maintenance tab. b. On the Maintenance page, click the Export to Files link in the Utilities region. c. On the Export: Export Type page, select the Tables option button, and specify the username and

password for your host credentials. You should use the ones corresponding to your Oracle account. Make sure that the Save as Preferred Credential checkbox is selected. When done, click the Continue button.

d. On the Export: Tables page click the Add button. e. On the Export: Add Tables page, enter SH in the Schema field, and make sure that the Tables option

button is selected. Then click the Go button. f. In the Search Results region, select the following tables: SALES, PRODUCTS, COSTS, CHANNELS,

PROMOTIONS, TIMES, CUSTOMERS, and COUNTRIES. (You may have to click the Next link in the Search Results region to see all of the above tables.)

g. When done, click the Select button. h. Back to the Export:Tables page, click the Next button. i. On the Export: Options page, set the Maximum Number of Threads in Export Job field to 1. j. In the Optional File region, make sure that the Generate Log File option is selected. Also, click the

Create Directory Object button to create the DPDIR1 directory. k. On the Export: Create Directory page, specify the corresponding Name and Operating System

Directory fields. Then click the OK button. l. Back on the Export: Options page, select DPDIR1 from the Directory Object drop-down list. m. When done, click the Show Advanced Options link. n. In the Query region of the Export: Options page, click the Add button. o. On the Export Options: Add Query page, enter SH.CHANNELS in the Table Name field. p. In the Predicate Clause field, enter WHERE channel_id<>5. q. When done, click the OK button. r. After you a returned to the Export: Options page, click the Next button. s. On the Export: Files page, make sure that you select DPDIR1 in the directory Object drop-down list.

Then click the Next button. t. On the Export: Schedule page, make sure the Immediately option button is selected. Then click the

Next button. u. On the Export: Review page, retrieve the Data Pump job name.

Page 186: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-6

4. Submit the Export job previously created. Note: Due to the very short time duration of the job execution, please be aware of the

solution required for the following Step 5 so you can successfully monitor the job operation. If you do not see the expected behavior, you can remove the log and dump files and restart from Step 3 above.

a. On the Export: Review page, click the Submit Job button. b. This brings you to the Processing page, which displays a running clock to indicate that the job is in

progress.

5. You want to see and change some of the Data Pump job characteristics. How can you do this?

a. You must suspend the Data Pump job execution. When you are on the Status page, click the View Job button.

b. This brings you to the Execution page from where you must click the Monitor Data Pump Job button. c. On the Monitor Data Pump Job page, you can see the objects currently being exported, and you can add

new files to your dump set. You can also change the Data Pump job parallelism degree. d. On the Monitor Data Pump Job page, click the Change Job State button. e. This brings you to the Change Data Pump Job State page. On this page, select the Suspend option

button, and click the OK button. f. You should now see the Change Job Status Success message. Click the OK button to return to the

Execution page.

6. Now that the Data Pump job execution is suspended, connect as user DP through SQL*Plus.

What table has been created?

Answer: There is one table that was created by the Data Pump job. This is the Master Table associated with the job.

connect dp/dp select table_name from user_tables; TABLE_NAME ------------------------------ EXPORT000005 SQL>

Page 187: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-7

7. Connect as user oracle from your terminal emulator window and determine the list of processes associated with your instance. What is your conclusion?

Hint: Look at all the new processes spawned in Oracle Database 10g.

Answer: There are currently no Data Pump background processes running. This is because the current export Data Pump job has been suspended.

$ ps –ef | grep orcl oracle 5122 1 0 Dec04 ? 00:00:00 ora_pmon_orcl oracle 5124 1 0 Dec04 ? 00:00:00 ora_mman_orcl oracle 5126 1 0 Dec04 ? 00:00:21 ora_dbw0_orcl oracle 5128 1 0 Dec04 ? 00:00:36 ora_lgwr_orcl oracle 5130 1 0 Dec04 ? 00:00:01 ora_ckpt_orcl oracle 5132 1 0 Dec04 ? 00:01:00 ora_smon_orcl oracle 5134 1 0 Dec04 ? 00:00:00 ora_reco_orcl oracle 5136 1 0 Dec04 ? 00:00:01 ora_cjq0_orcl oracle 5138 1 0 Dec04 ? 00:00:00 ora_d000_orcl oracle 5140 1 0 Dec04 ? 00:00:00 ora_s000_orcl oracle 5146 1 0 Dec04 ? 00:00:00 ora_qmnc_orcl oracle 5148 1 0 Dec04 ? 00:01:38 ora_mmon_orcl oracle 5150 1 0 Dec04 ? 00:00:00 ora_mmnl_orcl oracle 5397 1 0 Dec04 ? 00:00:12 oracleorcl (LOCAL=NO) oracle 5402 1 0 Dec04 ? 00:18:20 oracleorcl (LOCAL=NO) oracle 5406 1 0 Dec04 ? 00:29:32 oracleorcl (LOCAL=NO) oracle 5408 1 0 Dec04 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 5414 1 0 Dec04 ? 00:00:21 oracleorcl (LOCAL=NO) oracle 5420 1 0 Dec04 ? 00:10:22 oracleorcl (LOCAL=NO) oracle 5428 1 0 Dec04 ? 00:00:03 oracleorcl (LOCAL=NO) oracle 5434 1 0 Dec04 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 5775 1 0 Dec04 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 5778 1 0 Dec04 ? 00:00:10 oracleorcl (LOCAL=NO) oracle 5806 1 0 Dec04 ? 00:04:24 oracleorcl (LOCAL=NO) oracle 5831 1 0 Dec04 ? 00:05:37 oracleorcl (LOCAL=NO) oracle 5835 1 0 Dec04 ? 00:09:36 ora_j000_orcl oracle 5837 1 0 Dec04 ? 00:00:18 ora_j001_orcl oracle 7957 1 0 Dec04 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 21772 1 0 02:28 ? 00:00:12 oracleorcl (LOCAL=NO) oracle 22168 1 0 02:41 ? 00:00:00 ora_q005_orcl oracle 22455 1 0 02:51 ? 00:00:00 ora_q002_orcl oracle 22504 1 2 02:52 ? 00:00:02 oracleorcl (DESCRIPTION=(LOCAL=Y oracle 22514 1 0 02:53 ? 00:00:00 ora_q003_orcl oracle 22517 1 0 02:53 ? 00:00:00 ora_q000_orcl oracle 22521 22306 0 02:54 pts/3 00:00:00 grep orcl

8. How can you see the amount of work performed so far by your Data Pump job?

a. Back on the Execution page of your job, click the Export link in the Logs region. b. This brings you to the Step: Export page where you can see the log output. It should look similar to the

following:

Job EXPORT000005 has been reopened at Friday, 28 November, 2003 7:55

Page 188: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-8

Restarting "DP"."EXPORT000005": Estimate in progress using BLOCKS method... Processing object type TABLE_EXPORT/TABLE/TBL_TABLE_DATA/TABLE/TABLE_DATA . estimated "SH"."CUSTOMERS" 12 MB . estimated "SH"."SALES":"SALES_Q4_2001" 2 MB . estimated "SH"."SALES":"SALES_Q1_1999" 1024 KB . estimated "SH"."SALES":"SALES_Q3_2001" 1024 KB . estimated "SH"."SALES":"SALES_Q1_2000" 960 KB . estimated "SH"."SALES":"SALES_Q1_2001" 960 KB . .output truncated…. . . estimated "SH"."COSTS":"COSTS_Q4_1998" 64 KB . estimated "SH"."COSTS":"COSTS_Q4_1999" 64 KB . estimated "SH"."COSTS":"COSTS_Q4_2000" 64 KB . estimated "SH"."COSTS":"COSTS_Q4_2001" 64 KB . estimated "SH"."COSTS":"COSTS_Q4_2002" 64 KB . estimated "SH"."COSTS":"COSTS_Q4_2003" 64 KB . estimated "SH"."COUNTRIES" 64 KB . estimated "SH"."PRODUCTS" 64 KB . estimated "SH"."SALES":"SALES_1995" 64 KB Job "DP"."EXPORT000063" stopped by user request at 07:55

c. Click the Execution: orcl link to return to the Execution page.

9. Connect as the oracle user from your terminal emulator window and attach to the existing

export Data Pump job. Connect as the oracle user from a second terminal emulator window and determine the list of processes associated with your instance. What is your conclusion?

Answer: You have a new DM00 process started. This process corresponds to the Master process of your Data Pump job.

$ expdp dp/dp ATTACH = EXPORT000005 Export: Release 10.1.0.2.0 - Production on Monday, 08 December, 2003 2:52 Copyright (c) 2003, Oracle. All rights reserved. Connected to: Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Produn With the Partitioning, OLAP and Data Mining options Job: EXPORT000005 Owner: DP Operation: EXPORT Creator Privs: FALSE GUID: CDF5ACAB8ADA03C2E030007F0100562C Start Time: Monday, 08 December, 2003 2:52 Mode: TABLE Instance: orcl Max Parallelism: 1 EXPORT Job Parameters: Parameter Name Parameter Value: DATA_ACCESS_METHOD AUTOMATIC ESTIMATE BLOCKS INCLUDE_METADATA 1 LOG_FILE_DIRECTORY DPDIR1

Page 189: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-9

LOG_FILE_NAME EXPDAT.LOG TABLE_CONSISTENCY 0 State: IDLING Bytes Processed: 0 Current Parallelism: 1 Job Error Count: 0 Dump File: /home/oracle/EXPDAT%u.DMP Dump File: /home/oracle/EXPDAT01.DMP bytes written: 4,096 Worker 1 Status: State: UNDEFINED Object Schema: SH Object Name: COSTS Object Type: TABLE_EXPORT/TABLE/TBL_TABLE_DATA/TABLE/TABLE_DATA Completed Objects: 62 Total Objects: 62 Export> $ ps -ef | grep orcl oracle 5122 1 0 Dec04 ? 00:00:00 ora_pmon_orcl oracle 5124 1 0 Dec04 ? 00:00:00 ora_mman_orcl oracle 5126 1 0 Dec04 ? 00:00:21 ora_dbw0_orcl oracle 5128 1 0 Dec04 ? 00:00:36 ora_lgwr_orcl oracle 5130 1 0 Dec04 ? 00:00:01 ora_ckpt_orcl oracle 5132 1 0 Dec04 ? 00:01:00 ora_smon_orcl oracle 5134 1 0 Dec04 ? 00:00:00 ora_reco_orcl oracle 5136 1 0 Dec04 ? 00:00:01 ora_cjq0_orcl oracle 5138 1 0 Dec04 ? 00:00:00 ora_d000_orcl oracle 5140 1 0 Dec04 ? 00:00:00 ora_s000_orcl oracle 5146 1 0 Dec04 ? 00:00:00 ora_qmnc_orcl oracle 5148 1 0 Dec04 ? 00:01:38 ora_mmon_orcl oracle 5150 1 0 Dec04 ? 00:00:00 ora_mmnl_orcl . output truncated . oracle 5835 1 0 Dec04 ? 00:09:36 ora_j000_orcl oracle 5837 1 0 Dec04 ? 00:00:18 ora_j001_orcl oracle 7957 1 0 Dec04 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 21772 1 0 02:28 ? 00:00:12 oracleorcl (LOCAL=NO) oracle 22168 1 0 02:41 ? 00:00:00 ora_q005_orcl oracle 22455 1 0 02:51 ? 00:00:00 ora_q002_orcl oracle 22504 1 2 02:52 ? 00:00:02 oracleorcl (DESCRIPTION=(LOCAL=Y oracle 22506 1 0 02:52 ? 00:00:00 ora_dm00_orcl oracle 22514 1 0 02:53 ? 00:00:00 ora_q003_orcl oracle 22517 1 0 02:53 ? 00:00:00 ora_q000_orcl oracle 22521 22306 0 02:54 pts/3 00:00:00 grep orcl $

Page 190: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-10

10. Back in the first terminal emulator window, change the degree of parallelism of your Data Pump job from 1 to 4. Issue the STATUS command. When done, start your Data Pump job again, and continue the client session. Return quickly to your second emulator window and determine the list of processes that are executing on your instance. What is your conclusion?

Answer: Because the Data Pump job is not finished yet, you can still see the Master Table process DM00, and also the four worker processes called DW0n.

Export> parallel = 4 Export> Export> status Job: EXPORT000062 Operation: EXPORT Mode: TABLE State: IDLING Bytes Processed: 0 Current Parallelism: 4 Job Error Count: 0 Dump File: /home/oracle/EXPDAT%u.DMP Dump File: /home/oracle/EXPDAT01.DMP bytes written: 4,096 Worker 1 Status: State: UNDEFINED Object Schema: SH Object Name: COSTS Object Type: TABLE_EXPORT/TABLE/TBL_TABLE_DATA/TABLE/TABLE_DATA Completed Objects: 62 Export> start_job Export> continue_client Job EXPORT000062 has been reopened at Monday, 08 December, 2003 4:22 Restarting "DP"."EXPORT000062": Estimate in progress using BLOCKS method... Processing object type TABLE_EXPORT/TABLE/TBL_TABLE_DATA/TABLE/TABLE_DATA . estimated "SH"."CUSTOMERS" 12 MB . estimated "SH"."SALES":"SALES_Q4_2001" 2 MB . estimated "SH"."SALES":"SALES_Q1_1999" 1024 KB . estimated "SH"."SALES":"SALES_Q3_2001" 1024 KB . estimated "SH"."SALES":"SALES_Q1_2000" 960 KB . .output truncated . . estimated "SH"."COSTS":"COSTS_Q3_1999" 0 KB . estimated "SH"."COSTS":"COSTS_Q3_2000" 0 KB . estimated "SH"."COSTS":"COSTS_Q3_2001" 0 KB . estimated "SH"."COSTS":"COSTS_Q3_2002" 0 KB . estimated "SH"."COSTS":"COSTS_Q3_2003" 0 KB . estimated "SH"."COSTS":"COSTS_Q4_1998" 0 KB . estimated "SH"."SALES":"SALES_Q4_2002" 0 KB . estimated "SH"."SALES":"SALES_Q4_2003" 0 KB . . exported "SH"."CUSTOMERS" 9.850 MB 55500 rows

Page 191: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-11

Total estimation using BLOCKS method: 28.31 MB . . exported "SH"."SALES":"SALES_Q4_2001" 2.257 MB 69749 rows . .output truncated . . . exported "SH"."SALES":"SALES_Q3_2003" 0 KB 0 rows . . exported "SH"."SALES":"SALES_Q4_2002" 0 KB 0 rows . . exported "SH"."SALES":"SALES_Q4_2003" 0 KB 0 rows Processing object type TABLE_EXPORT/TABLE/TABLE . . exported "SH"."CHANNELS" 6.640 KB 4 rows Processing object type TABLE_EXPORT/TABLE/GRANT/TBL_OWNER_OBJGRANT/OBJECT_GRANT Processing object type TABLE_EXPORT/TABLE/INDEX/INDEX Processing object type TABLE_EXPORT/TABLE/CONSTRAINT/CONSTRAINT Processing object type TABLE_EXPORT/TABLE/INDEX/STATISTICS/INDEX_STATISTICS Processing object type TABLE_EXPORT/TABLE/STATISTICS/TABLE_STATISTICS Processing object type TABLE_EXPORT/TABLE/COMMENT Processing object type TABLE_EXPORT/TABLE/CONSTRAINT/REF_CONSTRAINT Processing object type TABLE_EXPORT/TABLE/INDEX/TBL_FBM_INDEX_INDEX/INDEX Processing object type TABLE_EXPORT/TABLE/INDEX/STATISTICS/TBL_FBM_IND_STATS/INS Master table "DP"."EXPORT000062" successfully loaded/unloaded ****************************************************************************** Dump file set for DP.EXPORT000062 is: /home/oracle/EXPDAT01.DMP /home/oracle/EXPDAT02.DMP /home/oracle/EXPDAT03.DMP Job "DP"."EXPORT000062" successfully completed at 04:23 $ $ ps -ef | grep orcl oracle 5122 1 0 Dec04 ? 00:00:00 ora_pmon_orcl oracle 5124 1 0 Dec04 ? 00:00:00 ora_mman_orcl oracle 5126 1 0 Dec04 ? 00:00:21 ora_dbw0_orcl oracle 5128 1 0 Dec04 ? 00:00:36 ora_lgwr_orcl oracle 5130 1 0 Dec04 ? 00:00:01 ora_ckpt_orcl oracle 5132 1 0 Dec04 ? 00:01:02 ora_smon_orcl oracle 5134 1 0 Dec04 ? 00:00:00 ora_reco_orcl oracle 5136 1 0 Dec04 ? 00:00:01 ora_cjq0_orcl oracle 5138 1 0 Dec04 ? 00:00:00 ora_d000_orcl oracle 5140 1 0 Dec04 ? 00:00:00 ora_s000_orcl oracle 5146 1 0 Dec04 ? 00:00:00 ora_qmnc_orcl oracle 5148 1 0 Dec04 ? 00:01:39 ora_mmon_orcl oracle 5150 1 0 Dec04 ? 00:00:00 ora_mmnl_orcl . .output truncated . oracle 22504 1 0 02:52 ? 00:00:04 oracleorcl (DESCRIPTION=(LOCAL=Y oracle 22506 1 1 02:52 ? 00:00:17 ora_dm00_orcl oracle 22752 1 0 03:02 ? 00:00:00 ora_q005_orcl oracle 22907 1 0 03:07 ? 00:00:00 ora_q001_orcl

Page 192: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-12

oracle 22918 1 0 03:08 ? 00:00:00 ora_q004_orcl oracle 22922 1 0 03:09 ? 00:00:00 ora_q000_orcl oracle 22926 1 0 03:09 ? 00:00:00 ora_q002_orcl oracle 22928 1 15 03:09 ? 00:00:03 ora_dw01_orcl oracle 22930 1 7 03:09 ? 00:00:01 ora_dw02_orcl oracle 22932 1 8 03:09 ? 00:00:01 ora_dw03_orcl oracle 22934 1 6 03:09 ? 00:00:01 ora_dw04_orcl oracle 22936 1 0 03:09 ? 00:00:00 ora_q003_orcl oracle 22940 22306 0 03:10 pts/3 00:00:00 grep orcl $

11. Remove the Database Control job run from the repository.

a. Back on the Execution page of your job, click the Delete Run button. b. On the Confirmation page, click the Yes button.

12. Now that you successfully exported your tables from the SH user, import only the SALES and

PRODUCTS tables back into the DP schema using the Data Pump Import Wizard.

a. From the Database Control home page, click the Maintenance link. b. On the Maintenance page, click the Import from Files link. c. On the Import: Files page, make sure that the Database Version of Files to Import field is set to 10g or

later, and click the Go button. d. In the Files region, select the DPDIR1 directory from where the Data Pump Import job can retrieve the

previously generated Dump File Set. Also, make sure that the File Name field is set correctly. e. In the Import Type region, select the Tables option button. Make sure that the host credentials are

correct. f. When done, click the Continue button. g. Data Pump starts reading the Dump File set to extract the metadata information. h. At this stage, you can look at the objects owned by the DP user under your SQL*Plus session. You should

see that the Master Table has been resurrected from the Dump File Set. If you want to do so, execute again step 6 of this lab.

i. After the metadata is successfully extracted from the Dump File Set, you should see the Import Read Succeed message on the Import: Tables page.

j. Now, click the Add button on this page. k. In the Import: Add Tables page, enter SH in the Schema field in the Search region. Then click the Go

button. l. You should now see the list of tables that you exported previously. m. Select the SALES and PRODUCTS tables from the Search Results list. n. When done, click the Select button. o. Back to the Import: Tables page, click the Next button. p. On the Import: Re-Mapping page, click the Add Another Row button in the Re-Map Schemas region. q. When done, make sure that the Source Schema is set to SH and that the Destination Schema is set to

DP. r. Then click the Next button. s. On the Import: Options page, make sure that the Directory Object field is set to DPDIR1, and then click

the Next button. t. On the Import: Schedule page, make sure the Immediately option button is selected, and then click the

Next button.

u. On the Import: Review page, click the Submit Job button.

Page 193: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-13

v. On the Status page, click the View Job button. w. On the Execution: orcl page, refresh your browser page until the Status field reads Succeeded. x. Click the Import link to look at the job’s log file.

13. To clean up your environment, you should delete your Database Control job run, and drop the

user DP from your database.

a. From the Execution: orcl page, click the Delete Run button. b. On the Confirmation page, click the Yes button. c. Log out from Database Control, and log in again as SYSDBA. d. On the Database Control home page, click the Administration tab. e. On the Administration tab, click the Users link. f. On the Users page, select user DP in the Results table, and then click the Delete button. g. On the Confirmation page, make sure that you no longer have any DP connections, and then click the

Yes button.

Page 194: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-14

Practice 4-1 Solution: Proactively Managing Your Database Using ADDM Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Use Database Control to create a new tablespace called TBSADDM. This tablespace should have

only one 50 MB file and must be locally managed. Also, make sure that TBSADDM does not use automatic segment space management.

a. From Database Control home page: Administration > Tablespaces. b. On the Tablespaces page, click the Create button. c. On the Create Tablespace page, specify the Name field, and then click the Add button. d. On the Create Tablespace: Add Datafile page, specify the File Name field and change the File Size to

50MB. You can call this file addm1.dbf. When done, click the Continue button. e. After you are returned to the Create Tablespace page, click the Storage tab. f. Make sure that Manual is selected for the Segment Space Management region. Click the OK button.

2. Using Database Control, create a new user called ADDM identified by ADDM. Make sure that the

ADDM user has TBSADDM as its default tablespace, and TEMP as its temporary tablespace. When done, grant the following roles to the ADDM user: CONNECT, RESOURCE, DBA.

a. From the Database Control home page: Administration > Users b. On the Users page click the Create button. c. On the Create User page, specify the following fields: Name, Enter Password, Confirm Password,

Default Tablespace, and Temporary Tablespace. d. When done, click the Roles tab. e. Click the Modify button. f. On the Modify Roles page, select RESOURCE, and DBA from the Available Roles list. When done, click

the Move link. Then click the OK button. g. Back to the Create User page, click the OK button.

3. Connected as ADDM in SQL*Plus, execute the lab_04_01_03.sql script connect addm/addm drop table addm purge; create table addm(id number, name varchar2(2000)); exec DBMS_STATS.GATHER_TABLE_STATS(- ownname=>'ADDM', tabname=>'ADDM',- estimate_percent=>DBMS_STATS.AUTO_SAMPLE_SIZE); exec DBMS_WORKLOAD_REPOSITORY.CREATE_SNAPSHOT();

Page 195: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-15

4. Connect as user oracle from your terminal emulator and execute the lab_04_01_04.sh script from your labs directory.

$ . ./lab_04_01_04.sh [1] 14195 [2] 14197 [3] 14201 [4] 14203 [5] 14205 [6] 14210 [7] 14212 [8] 14214 $

5. From the Database Control home page go to the Performance page. If this is the first time you

go to the Performance page, you need to click Accept in the Adobe license agreement pop-up screen. On the Performance page, make sure that the View Data field is set to Real Time: 15 Seconds Refresh. After a while, you should see a spike on the Sessions: Waiting and Working graph. After the spike is finished, execute the lab_04_01_05.sql script. This script forces the creation of a new snapshot. Looking at the graph, you can already determine that this instance is suffering concurrency problems.

Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

Connect addm/addm exec DBMS_WORKLOAD_REPOSITORY.CREATE_SNAPSHOT(); exec DBMS_STATS.GATHER_TABLE_STATS(- ownname=>'ADDM', tabname=>'ADDM',- estimate_percent=>DBMS_STATS.AUTO_SAMPLE_SIZE);

Page 196: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-16

6. Return to the Database Control home page. Because the ADDM data is not refreshed too

frequently on the console, you may not see the latest ADDM result in the Diagnostic Summary region. Retrieve the latest ADDM findings, and determine the cause of the problem.

a. From Database Control home page click the Advisor Central link under the Related Links section. b. On the Advisor Central page, select ADDM in the Advisory Type drop-down list, and select Last 24

Hours in the Advisor Runs drop-down list. When done, click the Go button. c. Select the latest ADDM task completed by the ADDM user. When done, click the View Result button. d. This brings you to the Automatic Database Diagnostic Monitor (ADDM) page where you can see the

results of the Performance Analysis. Note: Depending on when you run the workload, you may see differences between your findings and the ones provided in this solution.

e. Looking at the Performance Analysis region, you can see that the first finding has a 100% impact on the

system. So your first reflex is to look at the corresponding recommendation. Click the SQL statements consuming significant database time were found link to investigate further. This brings you to the Performance Finding Details page where ADDM identifies the high-load SQL statement.

f. Click the Run Advisor Now button to tune this statement. When the analysis is done, you are directed to

the Recommendations for SQL ID: dadywybcgph5f page. Unfortunately, there is no possible recommendation for this INSERT statement.

g. Therefore, the problem is further below in the stack. Return to the Automatic Database Diagnostic Monitor (ADDM) page to investigate further.

h. The second recommendation indicates a lack of CPU on the system. Because you cannot change this right now, look at the third recommendation by clicking the Read and write contention on database blocks was consuming significant database time link. This recommendation is related to the schema category.

Page 197: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-17

i. Here you are advised to use the Automatic Segment Space Management feature for your ADDM table.

7. To fix the problem, create a new tablespace called TBSADDM2, and execute the

lab_04_01_07.sql script from your labs directory. This script drops the ADDM table, and re-creates it in the new tablespace. This script also gathers statistics on the table and takes a new snapshot.

a. Therefore, to implement the recommendation, you must re-create the objects. First, you need to create a new tablespace that uses the Automatic Space Management feature. Return to the Database Control home page, and click the Administration tab.

b. Click the Tablespaces link, and click the Create button. Specify the name of the new tablespace in the Name field. You can call this new tablespace TBSADDM2. Click the Add button to add a file to this tablespace. You can call this file addm2_1.dbf.

c. On the Create Tablespace: Add Datafile page, specify the name of the new file, and make sure that its size is set to 50MB. When done, click the Continue button.

d. Back to the Create Tablespace page, click the Storage tab, and make sure that Automatic is set in the Segment Space Management region. Then click the OK button to create the new tablespace.

e. Now, you need to recreate table ADDM in the new tablespace:

@lab_04_01_07.sql

8. Connect as user oracle in your terminal emulator and execute again the lab_04_01_04.sh

script from your labs directory. $ . ./lab_04_01_04.sh [1] 14195 [2] 14197 [3] 14201 [4] 14203 [5] 14205 [6] 14210 [7] 14212 [8] 14214 $

Page 198: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-18

9. From the Database Control home page, go to the Performance page. On the Performance page, make sure that the View Data field is set to Real Time: 15 Seconds Refresh. After a while, you should see a spike on the Sessions: Waiting and Working graph. When the spike is finished, execute the lab_04_01_05.sql script. This script forces the creation of a new snapshot. Looking at the graph, you can already determine that this instance is no longer suffering from concurrency problems.

Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

Connect addm/addm exec DBMS_WORKLOAD_REPOSITORY.CREATE_SNAPSHOT(); exec DBMS_STATS.GATHER_TABLE_STATS(- ownname=>'ADDM', tabname=>'ADDM',- estimate_percent=>DBMS_STATS.AUTO_SAMPLE_SIZE);

10. Verify that you have fixed the problem.

a. Return to the Database Control home page. Because the ADDM data is not refreshed very frequently on the console, you may not see the latest ADDM result in the Diagnostic Summary region. Retrieve the latest ADDM findings, and verify that the previously analyzed problem was fixed.

b. From Database Control home page click the Advisor Central link under the Related Links section. c. On the Advisor Central page, select ADDM in the Advisory Type drop-down list, and select Last 24

Hours in the Advisor Runs drop-down list. When done, click the Go button. d. Then select the latest ADDM task COMPLETED by the ADDM user. When done, click the View Result

button. e. This brings you to the Automatic Database Diagnostic Monitor (ADDM) page from where you can see

the results of the Performance Analysis. Note: Depending on when you run the workload, you may see differences between your findings and the ones provided in this solution.

Page 199: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-19

f. Looking at the Performance Analysis region, you can see that there is no longer any schema-related recommendation. By moving the ADDM table to TBSADDM2, you obviously fixed the root cause found in the previous steps.

11. To clean up your environment, execute the lab_04_01_11.sql script. connect / as sysdba drop user addm cascade; drop tablespace tbsaddm including contents and datafiles; drop tablespace tbsaddm2 including contents and datafiles;

Page 200: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-20

Practice 4-2 Solution: Using Automatic Shared Memory Tuning Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Use Database Control to shut down your instance, and start it up again using the

init_sgalab.ora initialization parameter file located in your labs directory. Before doing this, make sure that the init_sgalab.ora parameter file can be used to start up your instance.

a. From the Database Control home page, click the Shutdown button. b. On the Startup/Shutdown: Specify Host and Target Database Credentials page, specify the needed

credentials and make sure that you save them to disk. c. Click the OK button. d. On the Startup/Shutdown: Confirmation page click the Yes button. e. After a while, click the Refresh button on the Startup/Shutdown: Activity Information page. f. On the Database: orcl page, click the Startup button. g. If necessary, specify all the needed credentials on the Startup/Shutdown: Specify Host and Target

Database Credentials page, and then click the OK button. h. On the Startup/Shutdown: Confirmation page, click the Advanced Options button. i. On the Startup/Shutdown: Advanced Startup Options page, make sure that you select the Specify

parameter file (pfile) on the database server machine option button, and specify the location and name of the parameter file you want to use. Then click the OK button.

j. After you are returned to the Startup/Shutdown: Confirmation page, click the Yes button. k. On the Login to Database: orcl page, specify your SYSDBA credentials, and click the Login button.

2. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_02.sql script. This

script creates a new tablespace and a new table, and populates the table. connect / as sysdba drop tablespace tbssga including contents and datafiles; create tablespace tbssga datafile 'tbssga1.dbf' size 20m; create table sgalab(a number, b number) tablespace tbssga; begin for i in 1..100000 loop insert into sgalab values (i, i); end loop; end; / commit; alter table sgalab parallel 48;

3. Use Database Control to check the size of the various SGA buffers of your instance.

Page 201: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-21

a. From the Database Control home page, click the Administration tab. b. Click the Memory Parameters link in the Instance region. c. On the Memory Parameters page, you should see that Automatic Shared Memory Management is

currently disabled, and you should also see the following figures: • Shared Pool 100 MB • Buffer Cache 100 MB • Large Pool 4 MB • Java Pool 48 MB • Other (MB) 1 • Total SGA (MB) 253 • Maximum SGA Size (MB) 300

4. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_04.sql script. This

script executes a parallel query on the previously created table. What happens and why?

Answer: Because your large pool buffer is too small, and because Automatic Shared Memory Tuning is not enabled, you get an ORA-04031 error.

SQL> select /*+ PARALLEL */ count(*) 2 from (select /*+ parallel(s 12) */ * from sgalab s group by a); from (select /*+ parallel(s 12) */ * from sgalab s group by a) * ERROR at line 2: ORA-12853: insufficient memory for PX buffers: current 3776K, max needed 208896K ORA-04031: unable to allocate 131084 bytes of shared memory ("large pool","unknown object","large pool","PX msg pool")

5. Using Database Control only, how can you fix this problem? Implement your solution.

a. On the Memory Parameters page, click the Enable button. b. On the Enable Automatic Shared Memory Management page, make sure that the Total SGA Size for

Automatic Shared Memory Management field is set to the same value as the Current Total SGA Size (MB) field. This should be 253 MB.

c. When done, click the OK button.

6. Connect as SYSDBA through SQL*Plus and determine the effects of the previous step on the

memory buffers. What are your conclusions?

Answer: On the server side, the SGA_TARGET initialization parameter was dynamically changed to a non-zero value to enable the Automatic Shared Memory Management feature. The sizes of the automatically tuned buffers are still the same, but their corresponding values in the V$PARAMETER view are modified to their minimum value. This is done automatically by Database Control to allow those buffers to shrink. You can verify this by looking at the ALTER SYSTEM commands that were logged in the alert.log file.

Page 202: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-22

show parameter sga_ col component format a30 select component,current_size,min_size,granule_size from v$sga_dynamic_components where component in ('shared pool','large pool', 'java pool','DEFAULT buffer cache'); col name format a30 col value format a30 SELECT name, value, isdefault FROM v$parameter WHERE name in ('shared_pool_size','large_pool_size','java_pool_size', 'db_cache_size');

7. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_04.sql script again.

This script executes a parallel query on the previously created table. Using Database Control, and while the script is running, verify that your solution is working. What happens and why?

Answer: While the script is running, you can click the Refresh button of the Memory Parameters page. You should see that the large pool buffer has dynamically allocated more memory to satisfy the parallel query execution. You should not get any error, and the script should complete. When the query runs, you should observe that no more memory is allocated to the large pool buffer. After a while, most of the memory that was allocated to the large pool should return automatically to the buffer cache memory pool.

connect / as sysdba select /*+ PARALLEL */ count(*) from (select /*+ parallel(s 12) */ * from sgalab s group by a);

8. If you use SQL*Plus instead of Database Control, what commands do you execute to enable the

Automatic Shared Memory Management feature after you started your instance using the init_sgalab.ora file? Explain your decision. It is assumed that you want to have a maximum of 256MB of SGA memory allocated.

Answer: Following is the list of commands that would be required:

alter system set sga_target=256m; alter system set db_cache_size=0; alter system set shared_pool_size=0; alter system set java_pool_size=0; alter system set large_pool_size=0;

Because the total SGA size immediately after instance startup using init_sgalab.ora is already 256 MB, if you issue the first statement above, the memory manager cannot take memory from the buffer cache because its minimum value is already specified in the init_sgalab.ora file. In this context, to allow the buffer cache to shrink, you should explicitly set it to a smaller value. By setting it to zero, you are setting it to its minimum possible value. You should do the same for the other components.

Page 203: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-23

9. Connect as SYSDBA through SQL*Plus and execute the lab_04_02_09.sql script to clean

up your environment. connect / as sysdba drop tablespace tbssga including contents and datafiles; shutdown immediate; startup;

Page 204: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-24

Practice 5-1 Solution: Using Server-Generated Alerts Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Connect as SYSDBA through SQL*Plus and execute the lab_05_01_01.sql script. This

script adds the new subscriber ALERT_USR1 to the internal ALERT_QUE queue. It then grants user SYSTEM the right to dequeue from the ALERT_QUE. Then, the script creates a special procedure that is used by user SYSTEM to dequeue alert information from the ALERT_QUE.

connect / as sysdba exec DBMS_AQADM.ADD_SUBSCRIBER('SYS.ALERT_QUE',- AQ$_AGENT('ALERT_USR1','',0)); -- exec DBMS_AQADM.CREATE_AQ_AGENT(agent_name=>'ALERT_USR1'); exec DBMS_AQADM.ENABLE_DB_ACCESS(agent_name=>'ALERT_USR1',- db_username=>'SYSTEM'); exec DBMS_AQADM.GRANT_QUEUE_PRIVILEGE(privilege=>'DEQUEUE',- queue_name=>'ALERT_QUE',- grantee=>'SYSTEM',grant_option=>FALSE); -- DECLARE -- reginfo aq$_reg_info; -- reginfolist aq$_reg_info_list; -- BEGIN -- reginfo := AQ$_REG_INFO('ALERT_QUE:ALERT_USR1', -- DBMS_AQ.NAMESPACE_AQ, 'mailto://[email protected]',NULL); -- -- Create the registration info list -- reginfolist := AQ$_REG_INFO_LIST(reginfo); -- -- Register the registration info list -- DBMS_AQ.REGISTER(reginfolist, 1); -- END; -- / -- BEGIN -- DBMS_AQELM.SET_MAILHOST('yourmailhost.com'); -- DBMS_AQELM.SET_MAILPORT(25); -- DBMS_AQELM.SET_SENDFROM('[email protected]'); -- COMMIT; -- END; -- / create or replace procedure sa_dequeue is dequeue_options dbms_aq.dequeue_options_t; message_properties dbms_aq.message_properties_t; message ALERT_TYPE; message_handle RAW(16); begin dequeue_options.consumer_name := 'ALERT_USR1'; /* Never wait */ dequeue_options.wait := DBMS_AQ.NO_WAIT; /* Always reset the position to the begining of the AQ */ dequeue_options.navigation := DBMS_AQ.FIRST_MESSAGE; /* remove the message when done */ dequeue_options.dequeue_mode := DBMS_AQ.REMOVE;

Page 205: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-25

DBMS_AQ.DEQUEUE( queue_name => 'SYS.ALERT_QUE', dequeue_options => dequeue_options, message_properties => message_properties, payload => message, msgid => message_handle); DBMS_OUTPUT.PUT_LINE('Alert message dequeued:'); DBMS_OUTPUT.PUT_LINE(' Timestamp: ' || message.timestamp_originating); . output truncated . DBMS_OUTPUT.PUT_LINE(' Suggested action: ' || dbms_server_alert.expand_message(userenv('LANGUAGE'), message.suggested_action_msg_id, message.action_argument_1, message.action_argument_2, message.action_argument_3, message.action_argument_4, message.action_argument_5)); DBMS_OUTPUT.PUT_LINE(' Error instance id: ' || message.error_instance_id); DBMS_OUTPUT.PUT_LINE(' Advisor Name: ' || message.advisor_name); DBMS_OUTPUT.PUT_LINE(' Scope: ' || message.scope); end; / grant execute on sa_dequeue to system;

2. Connect as SYSDBA through SQL*Plus, check that you do not have any outstanding alerts

for the User Commits Per Sec metric, and look at your alert history. Then, set the User Commits Per Sec metric with a warning threshold set to 3, and a critical threshold set to 6. Make sure that the observation period is set to one minute, and that the number of consecutive occurrences is set to 2. When done, check that the metrics thresholds have been set correctly. Again, look at your outstanding alerts and alert history. What are your conclusions?

Answer: After you set the metric thresholds, you should see a new row in the alert history that indicates that thresholds were updated on the User Commits Per Sec metric.

connect / as sysdba select reason from dba_outstanding_alerts; select reason from dba_alert_history where upper(reason) like '%COMMIT%' and to_date(substr(to_char(creation_time),1,18)|| substr(to_char(creation_time),26,3) , 'DD-MON-YY HH:MI:SS AM') > sysdate-30/1440 order by creation_time desc; exec DBMS_SERVER_ALERT.set_threshold( - dbms_server_alert.user_commits_sec, -

Page 206: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-26

dbms_server_alert.operator_ge, 3, - dbms_server_alert.operator_ge, 6, - 1, 2, 'orcl', - dbms_server_alert.object_type_system, null); col object_name format a20 col metrics_name format a25 col warning_value format a10 col critical_value format a10 select metrics_name,warning_value,critical_value, object_name from dba_thresholds; select reason from dba_outstanding_alerts; select reason from dba_alert_history where upper(reason) like '%COMMIT%' and to_date(substr(to_char(creation_time),1,18)|| substr(to_char(creation_time),26,3) , 'DD-MON-YY HH:MI:SS AM') > sysdate-30/1440 order by creation_time desc;

3. Execute the lab_05_01_03.sql script. This script creates a new table and inserts one row in

it. connect / as sysdba drop table t purge; create table t(c number) tablespace users; insert into t values(1); commit;

4. Connect as SYSDBA through Database Control and look at the corresponding metrics graphic

rate. Then, execute the lab_05_01_04.sql script. This script generates a commit rate between three and six commits per second for one minute on your system. While the script is executing, observe the metrics graph using Database Control. After a minute or two, through SQL*Plus, look at your outstanding alerts and alert history. What are your conclusions?

Answer: Although the commit rate is going above the warning level, you do not get any outstanding alert. This is because an alert is raised only after two consecutive occurrences of the observation period’s violation. So the rate should be above the warning level for more than one minute.

connect / as sysdba -- Should take around 1 minute begin for i in 1..60 loop for j in 1..6 loop update t set c=2;

Page 207: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-27

commit; end loop; dbms_lock.sleep(1); end loop; end; /

a. From the Database Control home page, click the All Metrics link. b. On the All Metrics page, expand the Throughput link. c. On the All Metrics page, under Throughput link, click the User Commits (per second) link. d. On the User Commits (per second) page, make sure that the View Data field is set to Real Time: 30

Seconds Refresh. Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

connect / as sysdba select reason from dba_outstanding_alerts; select reason from dba_alert_history where upper(reason) like '%COMMIT%' and to_date(substr(to_char(creation_time),1,18)|| substr(to_char(creation_time),26,3) , 'DD-MON-YY HH:MI:SS AM') > sysdate-30/1440 order by creation_time desc;

5. While connected as SYSDBA through Database Control, look at the corresponding metrics

graphic rate, and execute the lab_05_01_05.sql script. This script generates a commit rate of five commits per second for three minutes on your system. While the script is executing, observe the metrics graph using Database Control. After the script finishes its execution, examine your outstanding alerts and alert history using both SQL*Plus and another Database Control session. What are your conclusions?

Answer: Because this time the commit rate is maintained above the warning level, and less than the critical level for more than two minutes, you should get a warning alert.

Page 208: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-28

connect / as sysdba -- Should take around 3 minutes begin for i in 1..300 loop for j in 1..5 loop update t set c=2; commit; end loop; dbms_lock.sleep(1); end loop; end; /

a. From the Database Control home page, click the All Metrics link. Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

b. You can see the alert history by changing the View Data field on the User Commits (per second) page. Change its value to Last 24 hours, and you will see the alert history in the Alert History Last 24 Hours region of the page:

Note: Depending on when you run the workload, you may see differences between your output and the one provided in this solution. connect / as sysdba select reason from dba_outstanding_alerts; REASON ---------------------------------------------------------------------------- Metrics "User Commits Per Sec" is at 5 select reason from dba_alert_history where upper(reason) like '%COMMIT%' and

Page 209: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-29

to_date(substr(to_char(creation_time),1,18)|| substr(to_char(creation_time),26,3) , 'DD-MON-YY HH:MI:SS AM') > sysdate-30/1440 order by creation_time desc; REASON ---------------------------------------------------------------------------- Threshold is updated on metrics "User Commits Per Sec" for instance "orcl"

6. Wait three more minutes, and view your outstanding alerts and the alert history again. What are

your conclusions?

Answer: Because the commit rate is now close to zero for more than three minutes, the alert is automatically cleared.

Note: Depending on when you run the workload, you may see differences between your output and the one provided in this solution. connect / as sysdba select reason from dba_outstanding_alerts; no rows selected select reason from dba_alert_history where upper(reason) like '%COMMIT%' and to_date(substr(to_char(creation_time),1,18)|| substr(to_char(creation_time),26,3) , 'DD-MON-YY HH:MI:SS AM') > sysdate-30/1440 order by creation_time desc; REASON ---------------------------------------------------------------------------- Metrics "User Commits Per Sec" is at 0 Threshold is updated on metrics "User Commits Per Sec" for instance "orcl"

a. You should see that the alert is cleared from the User Commits (per second) page. If not, try to refresh the data:

7. While connected as SYSDBA through Database Control, look at the corresponding metrics

graphic rate, and execute the lab_05_01_07.sql script. This script generates a commit rate of eight commits per second for three minutes on your system. While the script is executing, observe the metrics graph using Database Control. After the script finishes its execution, look at your outstanding alerts and alert history using both SQL*Plus and Database Control. What are your conclusions?

Page 210: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-30

Answer: Because this time the commit rate is maintained above the critical level for more than two minutes, you should get a critical alert.

connect / as sysdba -- Should take around 3 minutes begin for i in 1..300 loop for j in 1..8 loop update t set c=2; commit; end loop; dbms_lock.sleep(1); end loop; end; /

a. On the User Commits (per second) page with View Data set to Real Time: 30 Second Refresh. Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

b. On the User Commits (per second) page with View Data set to Last 24 Hours:

Note: Depending on when you run the workload, you may see differences between your output and the one provided in this solution. connect / as sysdba select reason from dba_outstanding_alerts; REASON ----------------------------------------------------------------------------

Page 211: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-31

Metrics "User Commits Per Sec" is at 8 select reason from dba_alert_history where upper(reason) like '%COMMIT%' and to_date(substr(to_char(creation_time),1,18)|| substr(to_char(creation_time),26,3) , 'DD-MON-YY HH:MI:SS AM') > sysdate-30/1440 order by creation_time desc; REASON ---------------------------------------------------------------------------- Metrics "User Commits Per Sec" is at 0 Threshold is updated on metrics "User Commits Per Sec" for instance "orcl"

8. Wait three more minutes, and look at your outstanding alerts and the alert history again. What are

your conclusions?

Answer: Because the commit rate is now close to zero for more than three minutes, the alert is automatically cleared.

Note: Depending on when you run the workload, you may see differences between your output and the one provided in this solution. connect / as sysdba select reason from dba_outstanding_alerts; no rows selected select reason from dba_alert_history where upper(reason) like '%COMMIT%' and to_date(substr(to_char(creation_time),1,18)|| substr(to_char(creation_time),26,3) , 'DD-MON-YY HH:MI:SS AM') > sysdate-30/1440 order by creation_time desc; REASON ---------------------------------------------------------------------------- Metrics "User Commits Per Sec" is at 0 Metrics "User Commits Per Sec" is at 0 Threshold is updated on metrics "User Commits Per Sec" for instance "orcl"

a. You should see that the alert is cleared from the User Commits (per second) page. If not, try to refresh the data:

Page 212: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-32

9. Connect as user SYSTEM through SQL*Plus and execute the SYS.SA_DEQUEUE procedure

multiple times. This procedure was created during the first step. Before executing the procedure, execute the SET SERVEROUTPUT ON command. What are your conclusions?

Answer: Because the ALERT_QUE is a multiconsumer queue, alerts that were sent to the ALERT_QUE, and that were consumed by Database Control, are still available for other consumers such as user SYSTEM. So you must execute the SYS.SA_DEQUEUE procedure multiple times to retrieve the history of your metric. Do this until an error message is returned, at which point you no longer have messages to dequeue.

Note: Depending on when you run the workload, you may see differences between your output and the one provided in this solution. SQL> connect system/oracle Connected. SQL> set serveroutput on SQL> SQL> exec sys.sa_dequeue; Alert message dequeued: Timestamp: 03-DEC-03 05.45.43.868116 AM -08:00 Organization Id: oracle.com Component Id: SMG Hosting Client Id: Message Type: Notification Message Group: Configuration Message Level: 32 Host id: EDCDR5P1 Host Network Addr: 127.0.0.1 Module Id: SERVER MANAGEABILITY:kelr.c Process Id: "orcl"."orcl" Execution Context: Reason: Threshold is updated on metrics "User Commits Per Sec" forinstance "orcl" Sequence Id: 145 Reason Id: 126 Object Owner: Object Name: SYSTEM Subobject Name: Object Type: SYSTEM Instance Name: orcl Instance Number: 1 Suggested action: Check DBA_THRESHOLDS view to verify the result Error instance id: CD93B1044EAC-33B9-E030-007F0100282A-0 Advisor Name: Scope: Database PL/SQL procedure successfully completed. SQL> SQL> exec sys.sa_dequeue; Alert message dequeued: Timestamp: 03-DEC-03 06.20.57.144219 AM -08:00 Organization Id: oracle.com

Page 213: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-33

. output truncated . Instance Number: 1 Suggested action: Run ADDM to get more performance analysis about your system. Error instance id: CD952EFA576F-34C9-E030-007F01000E83-0 Advisor Name: ADDM Scope: Instance PL/SQL procedure successfully completed. SQL> SQL> exec sys.sa_dequeue; Alert message dequeued: Timestamp: 03-DEC-03 06.24.01.890329 AM -08:00 Organization Id: oracle.com Component Id: SMG Hosting Client Id: Message Type: Notification Message Group: Performance Message Level: 32 Host id: EDCDR5P1 Host Network Addr: 127.0.0.1 Module Id: SERVER MANAGEABILITY:kelr.c Process Id: "orcl"."orcl" Execution Context: Reason: Metrics "User Commits Per Sec" is at 0 Sequence Id: 146 Reason Id: 36 Object Owner: Object Name: SYSTEM Subobject Name: Object Type: SYSTEM Instance Name: orcl Instance Number: 1 Suggested action: Run ADDM to get more performance analysis about your system. Error instance id: CD952EFA576F-34C9-E030-007F01000E83-0 Advisor Name: ADDM Scope: Instance PL/SQL procedure successfully completed. SQL> SQL> exec sys.sa_dequeue; Alert message dequeued: Timestamp: 03-DEC-03 06.37.20.191643 AM -08:00 Organization Id: oracle.com Component Id: SMG Hosting Client Id: Message Type: Warning Message Group: Performance Message Level: 5 Host id: EDCDR5P1 Host Network Addr: 127.0.0.1 Module Id: SERVER MANAGEABILITY:kelr.c Process Id: "orcl"."orcl" Execution Context: Reason: Metrics "User Commits Per Sec" is at 8

Page 214: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-34

Sequence Id: 147 Reason Id: 36 Object Owner: Object Name: SYSTEM Subobject Name: Object Type: SYSTEM Instance Name: orcl Instance Number: 1 Suggested action: Run ADDM to get more performance analysis about your system. Error instance id: CD956992746C-D39B-E030-007F01000E83-0 Advisor Name: ADDM Scope: Instance PL/SQL procedure successfully completed. SQL> SQL> exec sys.sa_dequeue; Alert message dequeued: Timestamp: 03-DEC-03 06.39.23.060356 AM -08:00 Organization Id: oracle.com Component Id: SMG Hosting Client Id: Message Type: Warning Message Group: Performance Message Level: 1 Host id: EDCDR5P1 Host Network Addr: 127.0.0.1 Module Id: SERVER MANAGEABILITY:kelr.c Process Id: "orcl"."orcl" Execution Context: Reason: Metrics "User Commits Per Sec" is at 6 Sequence Id: 147 Reason Id: 36 Object Owner: Object Name: SYSTEM Subobject Name: Object Type: SYSTEM Instance Name: orcl Instance Number: 1 Suggested action: Run ADDM to get more performance analysis about your system. Error instance id: CD956992746C-D39B-E030-007F01000E83-0 Advisor Name: ADDM Scope: Instance PL/SQL procedure successfully completed. SQL> SQL> exec sys.sa_dequeue; Alert message dequeued: Timestamp: 03-DEC-03 06.41.25.860327 AM -08:00 Organization Id: oracle.com Component Id: SMG Hosting Client Id: Message Type: Notification Message Group: Performance Message Level: 32 Host id: EDCDR5P1 Host Network Addr: 127.0.0.1

Page 215: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-35

Module Id: SERVER MANAGEABILITY:kelr.c Process Id: "orcl"."orcl" . output truncated . Error instance id: CD956992746C-D39B-E030-007F01000E83-0 Advisor Name: ADDM Scope: Instance PL/SQL procedure successfully completed. SQL> SQL> exec sys.sa_dequeue; BEGIN sys.sa_dequeue; END; * ERROR at line 1: ORA-25228: timeout or end-of-fetch during message dequeue from SYS.ALERT_QUE ORA-06512: at "SYS.DBMS_AQ", line 333 ORA-06512: at "SYS.SA_DEQUEUE", line 15 ORA-06512: at line 1 SQL>

10. Using Database Control, disable the thresholds check for the User Commits (per second)

metric.

a. From the Database Control home page, click the Manage Metrics link. b. On the Manage Metrics page, click the Edit Thresholds button. c. On the Edit Thresholds page, scroll down to the User Commits (per second) entry in the table. d. Then, remove the values corresponding to the two thresholds, and click the OK button.

11. Execute the lab_05_01_11.sql script to clean up your environment. connect / as sysdba exec DBMS_SERVER_ALERT.set_threshold( - dbms_server_alert.user_commits_sec, - null,null, - null,null, - 1, 1, 'orcl', - dbms_server_alert.object_type_system, null); exec dbms_aqadm.disable_db_access('ALERT_USR1','SYSTEM'); exec DBMS_AQADM.REMOVE_SUBSCRIBER('SYS.ALERT_QUE',- AQ$_AGENT('ALERT_USR1','',0));

Page 216: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-36

Practice 6-1 Solution: Proactively Tuning High Load SQL Statements Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Connect as SYSDBA through Database Control and navigate to the Performance tab of the

Database Control home page. On the Performance page, make sure that the View Data field is set to Real Time: 15 second Refresh. When done, open a terminal emulator window connected as user oracle. When done change your current directory to your labs directory: cd $HOME/labs. Then, enter the following command from the OS prompt:

. ./setup_perflab.sh 2. When the setup_perflab.sh script completes, in approximately five minutes, observe the

Performance page for six minutes. What are your conclusions?

Answer: You should see the workload activity going up very quickly. Because the CPU used by the workload is very close to the maximum CPU available on your system, there must be an issue with this workload. Because the most important area corresponding to a wait class is the User I/O wait class, the issue must be associated to that class. Note that the snapshot interval is now around two minutes.

Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

Page 217: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-37

3. How can you quickly fix the problem?

Answer: First of all, you must determine the problem itself. The fastest way to determine it is by looking at an ADDM report analysis executed during the problematic period. Then, by following its analysis, ADDM should guide you through the process of fixing the problem.

a. From the Database Control home page, there are basically two different ways to identify the correct ADDM analysis task:

• If the time corresponding to the problematic time period corresponds with the latest ADDM run detected by Database Control, you should find the link corresponding to the correct performance analysis directly in the Diagnostic Summary region of the Database Control home page.

• If not, you should go to the Advisor Central page and search for the correct ADDM task. This is how you can retrieve the task from the Advisor Central page: • From the Database Control home page, click the Advisor Central link. • On the Advisor Central page, select ADDM in the Advisory Type drop-down list, and

select Last 24 Hours in the Advisor Runs drop-down list. • When done, click the Go button. • Then, select the ADDM task corresponding to the time of the problematic period. • When done, click the View Result button.

b. This brings you to the Automatic Database Diagnostic Monitor (ADDM) page where you can see the results of the Performance Analysis in question.

4. Fix the problem.

a. On the corresponding Automatic Database Diagnostic Monitor (ADDM) page, click the finding with the highest impact on the database time. It should correspond to a SQL Tuning recommendation.

Page 218: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-38

b. This brings you to the Performance Finding Details page. On this page, you should see the high-load SQL statement captured by the ADDM analysis. As you can see, the benefit on the database time will be very high if you tune this statement according to the SQL Tuning Advisor. Click the Run Advisor Now button for the highest high-load SQL statement detected.

c. This starts the execution of a SQL Tuning Advisor task.

d. After the task has executed, you are given the details of the corresponding recommendations:

Page 219: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-39

e. In this case the recommendation is to create a SQL profile in order to get a better execution plan. If you click the Original Explain Plan button, you can see the original plan.

f. If you click the spectacles icon associated to the proposed SQL profile, you can see the new execution

plan.

g. Because the potential benefit of using the proposed SQL profile is very high, you implement the SQL profile. To implement this tuning recommendation, click the Implement button after selecting the appropriate SQL profile from the Recommendations table.

Page 220: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-40

5. After you fix the problem, how can you quickly verify that the problem was solved?

a. From the Database Control home page, click the Performance tab. b. On the Performance page, you should see a dramatic drop for CPU Used, and all the wait class

categories on the Sessions: Waiting and Working graph. Similarly, you should see a dramatic drop in the number of physical reads per second in the Instance Throughput graph. Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

6. To stop the workload, execute the following command: . ./stop_workload2.sh from

your terminal emulator window.

Page 221: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-41

7. Assume that someone else has executed the previous steps some time ago when you were out for

vacation. Back in the office, you want to see what happened while you were away. How can you do this? Returning to the previous example, retrieve the history of what happened to your system.

Answer: You must return to the history of your database activity. You can do this by using the performance pages of Database Control.

a. From the Database Control home page, click the Performance tab. b. On the Performance page, if the period for which you want to observe your database activity is still

visible on the Sessions: Waiting and Working graph, then you can use the current graph. However, if the problematic period is no longer visible on the graph, you can select the Historical value from the View Data drop-down list. This allows you to select the desired period in the Historical Interval Selection region of the Performance page.

c. Returning to the current example, you should be able to see the problematic period without having to define the historical information.

Page 222: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-42

8. Return to the Performance page. During the period of time where the workload was running, determine the most important wait category from the Sessions: Waiting and Working graph, and find the history of what was done to fix the problem.

a. Looking at the Sessions: Waiting and Working graph for the critical period, the User I/O wait class is probably the most important one with the Concurrency category. Click the User I/O category in the graph’s legend. Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

b. This brings you to the Active Sessions Waiting: User I/O page. You should see that in the User I/O wait class, the read by other session waits is the most important. If necessary, move the time window to the exact time when the workload was at its maximum activity. When done, the Detail region should be refreshed to show you the corresponding Top Waiting SQL and Top Waiting Sessions graphs.

c. You should see that there is one SQL statement that is using almost all of the available resources on your system. Also, the Top Waiting Sessions graph shows you that the top five sessions are connected as SH and are consuming almost the same amount of resources. This seems to indicate that these top sessions are executing the same statement.

d. In the legend of the Top Waiting SQL graph, select the top SQL statement. Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

Page 223: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-43

e. This brings you to the SQL Details page of the corresponding SQL statement. f. Here, you can clearly see the problematic SQL statement:

g. By clicking the Execution History tab, you can see what happened to the statement during the observed period. Note: Depending on when you run the workload, you may see differences between your graph and the one provided in this solution.

Page 224: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-44

h. To get a better understanding of the graphs, you should select the Seconds Per Execution option button. i. The results shown above clearly show you that around 6:05 a.m. (in this case) the number of executions

per second for this statement is almost twice as much as it was at 6:00 a.m. At the same time, the elapsed time per execution drops dramatically. This indicates that the statement was tuned correctly by the SQL Tuning Advisor.

9. To clean up your environment, execute the following command from your command-line

window: . ./cleanup_perflab.sh.

Page 225: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-45

Practice 6-2 Solution: Using the SQL Access Advisor Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Connected as SYSDBA through SQL*Plus, flush the shared pool and execute the following four

scripts, in this order: a. lab_06_02_01a.sql b. lab_06_02_01b.sql: (Star query) c. lab_06_02_01c.sql: (Star query) d. lab_06_02_01d.sql: (Order by)

connect / as sysdba; alter system flush shared_pool; -- query 1: SELECT /* QueryJFV 1*/ t.calendar_month_desc,sum(s.amount_sold) AS dollars FROM sh.sales s , sh.times t WHERE s.time_id = t.time_id AND s.time_id between TO_DATE('01-JAN-2000', 'DD-MON-YYYY') AND TO_DATE('01-JUL-2000', 'DD-MON-YYYY') GROUP BY t.calendar_month_desc; -- query 2: star query SELECT /* QueryJFV 2 */ ch.channel_class, c.cust_city, t.calendar_quarter_desc, SUM(s.amount_sold) sales_amount FROM sh.sales s, sh.times t, sh.customers c, sh.channels ch WHERE s.time_id = t.time_id AND s.cust_id = c.cust_id AND s.channel_id = ch.channel_id AND c.cust_state_province = 'CA' AND ch.channel_desc in ('Internet','Catalog') AND t.calendar_quarter_desc IN ('1999-01','1999-02') GROUP BY ch.channel_class, c.cust_city, t.calendar_quarter_desc; -- query 3: star query SELECT /* QueryJFV 3 */ ch.channel_class, c.cust_city, t.calendar_quarter_desc, SUM(s.amount_sold) sales_amount FROM sh.sales s, sh.times t, sh.customers c, sh.channels ch WHERE s.time_id = t.time_id AND s.cust_id = c.cust_id AND s.channel_id = ch.channel_id AND c.cust_state_province = 'CA' AND ch.channel_desc in ('Internet','Catalog') AND t.calendar_quarter_desc IN ('1999-03','1999-04') GROUP BY ch.channel_class, c.cust_city, t.calendar_quarter_desc; -- new query 4: order by SELECT /* QueryJFV 4 */ c.country_id, c.cust_city, c.cust_last_name FROM sh.customers c WHERE c.country_id in (52790, 52798) ORDER BY c.country_id, c.cust_city, c.cust_last_name;

Page 226: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-46

2. Connected as SYSDBA through SQL*Plus, execute the lab_06_02_02.sql script. This script creates a new SQL tuning set called MY_STS_WORKLOAD, which captures the SQL statements that you ran in step one.

SQL> connect / as sysdba Connected. SQL> select sql_text from v$sql where sql_text like '%Query%'; SQL_TEXT -------------------------------------------------------------------------------- SELECT /* QueryJFV 4 */ c.country_id, c.cust_city, c.cust_last_name FROM sh.custome rs c WHERE c.country_id in (52790, 52798) ORDER BY c.country_id, c.cust_city, c. cust_last_name SELECT /* QueryJFV 3 */ ch.channel_class, c.cust_city, t.calendar_quarter_de sc, SUM(s.amount_sold) sales_amount FROM sh.sales s, sh.times t, sh.custo mers c, sh.channels ch WHERE s.time_id = t.time_id AND s.cust_id = c.cust_id A ND s.channel_id = ch.channel_id AND c.cust_state_province = 'CA' AND ch.ch annel_desc in ('Internet','Catalog') AND t.calendar_quarter_desc IN ('1999-03' ,'1999-04') GROUP BY ch.channel_class, c.cust_city, t.calendar_quarter_desc SQL_TEXT -------------------------------------------------------------------------------- select sql_text from v$sql where sql_text like '%Query%' SELECT /* QueryJFV 1*/ t.calendar_month_desc,sum(s.amount_sold) AS dollars FROM sh.sales s , sh.times t WHERE s.time_id = t.time_id AND s.time_id between TO_DATE('01-JAN-2000', 'DD-MON-YYYY') AND TO_DATE('01-JUL-2000', 'DD-MON-YYYY') GROUP BY t.calendar_month_desc SELECT /* QueryJFV 2 */ ch.channel_class, c.cust_city, t.calendar_quarter_de sc, SUM(s.amount_sold) sales_amount FROM sh.sales s, sh.times t, sh.custo mers c, sh.channels ch WHERE s.time_id = t.time_id AND s.cust_id = c.cust_id A ND s.channel_id = ch.channel_id AND c.cust_state_province = 'CA' AND ch.ch annel_desc in ('Internet','Catalog') AND t.calendar_quarter_desc IN ('1999-01' SQL_TEXT -------------------------------------------------------------------------------- ,'1999-02') GROUP BY ch.channel_class, c.cust_city, t.calendar_quarter_desc SQL> exec dbms_sqltune.drop_sqlset('MY_STS_WORKLOAD'); BEGIN dbms_sqltune.drop_sqlset('MY_STS_WORKLOAD'); END;

Page 227: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-47

* ERROR at line 1: ORA-13754: "SQL Tuning Set" "MY_STS_WORKLOAD" does not exist. ORA-06512: at "SYS.DBMS_SQLTUNE_INTERNAL", line 2948 ORA-06512: at "SYS.DBMS_SQLTUNE", line 478 ORA-06512: at line 1 SQL> DECLARE 2 sqlsetname VARCHAR2(30); 3 sqlsetcur dbms_sqltune.sqlset_cursor; 4 BEGIN 5 sqlsetname := 'MY_STS_WORKLOAD'; 6 7 dbms_sqltune.create_sqlset(sqlsetname, 'Access Advisor data'); 8 9 OPEN sqlsetcur FOR 10 SELECT VALUE(P) 11 FROM TABLE( 12 dbms_sqltune.select_cursor_cache( 13 'sql_text like ''SELECT /* Query %''', 14 NULL, 15 NULL, 16 NULL, 17 NULL, 18 NULL, 19 null) 20 ) P; 21 22 dbms_sqltune.load_sqlset(sqlsetname, sqlsetcur); 23 end; 24 / PL/SQL procedure successfully completed. SQL> 3. Connected as SYSDBA through Database Control, use the SQL Access Advisor to generate

recommendations for the MY_STS_WORKLOAD SQL tuning set.

a. From the Database Control home page, click the Advisor Central link. b. On the Advisor Central page, click the SQL Access Advisor link. c. On the SQL Access Advisor: Workload Source page, select the Import Workload from SQL

Repository option button, and set the SQL Tuning Set field to MY_STS_WORKLOAD. When done, click the Next button.

d. On the SQL Access Advisor: Recommendation Options page, click the Both Indexes and Materialized Views and Comprehensive Mode buttons. Then click the Show Advanced Options link, and make sure you use the EXAMPLE tablespace and the SH schema for indexes and materialized views in the Default Storage locations region. When done, click the Next button.

e. On the SQL Access Advisor: Schedule page, select Standard in the Schedule Type field. Make sure that the Immediately option button is selected, and click the Next button.

f. On the SQL Access Advisor: Review page, click the Submit button. g. Return to the Advisor Central page, wait for one minute, and click the Refresh button. Repeat this

operation until you see the COMPLETED status associated to your SQL Access Advisor task.

Page 228: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-48

h. Then, select your SQL Access Advisor task, and click the View Result button.

4. Looking at the Recommendations page for your SQL Access Advisor task, what are your

conclusions?

Answer: By implementing the two recommendations, three statements of your workload can benefit from them.

Select SQL Statements Improved by Recommendations in the View field of the Recommendations for Task page.

Page 229: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-49

Select Recommendations in the View field of the Recommendations for Task page, and click the Show SQL button.

Page 230: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-50

Page 231: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-51

5. Implement the SQL Access Advisor recommendation that has the most benefit on your workload. Then, redo Steps 3 and 4. What are your conclusions?

Answer: This shows you that by implementing the first recommendation, only the second one is produced after running the analysis again. This is indeed expected, and no additional recommendations are produced.

a. On the Recommendations page, make sure that you select only the Recommendation ID that has the most Workload Cost Benefit. Then click the Schedule Implementation button.

b. On the Schedule Implementation page, ensure the Immediately option button is selected, and click the Submit button.

c. On the Scheduler Jobs page, click the Refresh button until your job no longer appears as a Running job. d. Click the Run History tab, and make sure that your job’s status is now SUCCEEDED. e. When done, click the Database tab at the top of the Scheduler Jobs page. f. Return to the Database Control home page and click the Advisor Central link. g. On the Advisor Central page, click the SQL Access Advisor link. h. On the SQL Access Advisor: Workload Source page, select the Import Workload from SQL

Repository option button, and set the SQL Tuning Set field to MY_STS_WORKLOAD. When done, click the Next button.

i. On the SQL Access Advisor: Recommendation Options page, click the Both Indexes and Materialized Views and Comprehensive Mode buttons. Then click the Show Advanced Options link, and make sure you use the EXAMPLE tablespace and the SH schema for indexes and materialized views in the Default Storage locations region. When done, click the Next button.

j. On the SQL Access Advisor: Schedule page, ensure the Immediately option button is selected, and then click the Next button.

k. On the SQL Access Advisor: Review page, click the Submit button. l. Return to the Advisor Central page, wait for one minute, and click the Refresh button. Repeat this

operation until you see the COMPLETED status associated to your SQL Access Advisor task. m. Select your SQL Access Advisor task, and click the View Result button.

Page 232: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-52

6. Use Database Control to clean up your environment by removing:

• The SQL Access Advisor analysis • The MY_STS_WORKLOAD SQL tuning set. • The implementation job Use SQL*Plus to remove the objects created by the implementation job. When done, execute lab_06_02_06.sql in order to clean up your schemas.

a. On the Recommendations page for your SQL Access Advisor task, click the Advisor Central link. b. On the Advisor Central page, select your first SQL Access Advisor task, and click the View Result

button. c. On the Recommendations page, click the Show SQL button. d. On the Show SQL page, write down the names of the created objects, and click the OK button. e. Return to the Recommendations page, click the Advisor Central link again. f. On the Advisor Central page, select your SQL Access Advisor tasks, one at a time, and click the Delete

button. For each task, click the Yes button on the Confirmation page. g. On the Advisor Central page, click the Database: orcl link. h. On the Database Control home page, click the Administration tab. i. On the Administration page, click the SQL Tuning Sets link. j. On the SQL Tuning Sets page, select MY_STS_WORKLOAD, and click the Delete button. k. On the Confirmation page, click the Yes button. l. Return to the SQL Tuning Sets page, and click the Database: orcl link. m. Return to the Administration page, and click the Jobs link. n. On the Scheduler Jobs page, click the Run History tab. o. On the Run History page, select your SQL Access Advisor implementation job, and click the Purge Log

button. p. On the Confirmation page, click the Yes button.

Page 233: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-53

SQL> connect / as sysdba; Connected. SQL> SQL> exec dbms_sqltune.drop_sqlset('MY_STS_WORKLOAD'); BEGIN dbms_sqltune.drop_sqlset('MY_STS_WORKLOAD'); END; * ERROR at line 1: ORA-13754: "SQL Tuning Set" "MY_STS_WORKLOAD" does not exist. ORA-06512: at "SYS.DBMS_SQLTUNE_INTERNAL", line 2948 ORA-06512: at "SYS.DBMS_SQLTUNE", line 478 ORA-06512: at line 1 SQL> drop materialized view log on sh.customers; Materialized view log dropped. SQL> drop materialized view log on sh.channels; Materialized view log dropped. SQL> drop materialized view log on sh.times; Materialized view log dropped. SQL> drop materialized view log on sh.sales; Materialized view log dropped. SQL> select mview_name from dba_mviews; MVIEW_NAME ------------------------------ CAL_MONTH_SALES_MV FWEEK_PSCAT_SALES_MV MV$$_01620002 SQL> -- Use the last value returned by the previous query. Something like MV$$_2 SQL> SQL> drop materialized view &mvname; Enter value for mvname: MV$$_01620002 old 1: drop materialized view &mvname new 1: drop materialized view MV$$_01620002 Materialized view dropped.

Page 234: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-54

Practice 7-1 Solution: Using Partitioned Outer Joins In this practice you will create two small tables, based on the SH schema. Using these two tables, you investigate the difference between a partitioned outer join and a regular outer join. Unless specified otherwise, you should be logging in as SH either through SQL*Plus or iSQL*Plus. 1. Connect to the SH schema, and alter the session so that the NLS_DATE_FORMAT is set to 'DD-

MON-YYYY'. Confirm the two tables T1 and S1 you create in the next step do not presently exist. You can use the script lab_07_01_01.sql.

SQL> connect sh/sh Connected. SQL> alter session set nls_date_format='DD-MON-YYYY'; Session altered. SQL> drop table t1; Table dropped. SQL> drop table s1; Table dropped. 2. Create a table S1 with the following SQL statement:

create table s1 as select DISTINCT time_id, prod_id, quantity_sold from sales where time_id between '02-JAN-2001'

and '05-JAN-2001' and prod_id < 15;

You can use the lab_07_01_02.sql script.

SQL> create table s1 as 2 select DISTINCT 3 time_id, prod_id, quantity_sold 4 from sales 5 where time_id between '02-JAN-2001' 6 and '05-JAN-2001' 7 and prod_id < 15; Table created. SQL> select * from s1; TIME_ID PROD_ID QUANTITY_SOLD ----------- ---------- ------------- 02-JAN-2001 13 1 02-JAN-2001 14 1 03-JAN-2001 14 1 04-JAN-2001 13 1

Page 235: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-55

3. Execute the lab_07_01_03.sql script to create the table T1. Query the contents of T1. SQL> create table t1 (time_id date); Table created. SQL> begin 2 for i in 0..3 loop 3 insert into t1 values (to_date('02-JAN-2001') + i); 4 end loop; 5 end; 6 / PL/SQL procedure successfully completed. SQL> commit; Commit complete. SQL> select * from t1; TIME_ID ----------- 02-JAN-2001 03-JAN-2001 04-JAN-2001 05-JAN-2001

4. Define a break on PROD_ID (to enhance output readability), and execute the right outer join

query in the lab_07_01_04.sql script. What do you notice about the returned rows?

Answer: The regular outer join is adding rows for days without any sales at all: 05-JAN-2001. SQL> break on prod_id SQL> SELECT prod_id, time_id, quantity_sold 2 , sum(quantity_sold) over 3 ( partition by prod_id 4 order by time_id 5 ) as cumulative 6 FROM s1 7 RIGHT OUTER JOIN t1 8 using (time_id) 9 ORDER BY prod_id, time_id; PROD_ID TIME_ID QUANTITY_SOLD CUMULATIVE ---------- ----------- ------------- ---------- 13 02-JAN-2001 1 1 04-JAN-2001 1 2 14 02-JAN-2001 1 1 03-JAN-2001 1 2 05-JAN-2001 SQL>

5. Now, execute the partitioned outer join query in the lab_07_01_05.sql script.

Page 236: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-56

SQL> SELECT prod_id, time_id, quantity_sold 2 , sum(quantity_sold) over 3 ( partition by prod_id 4 order by time_id 5 ) as cumulative 6 FROM s1 7 PARTITION BY (prod_id) 8 RIGHT OUTER JOIN t1 9 using (time_id) 10 ORDER BY prod_id, time_id; PROD_ID TIME_ID QUANTITY_SOLD CUMULATIVE -------- ----------- ------------- ---------- 13 02-JAN-2001 1 1 03-JAN-2001 1 04-JAN-2001 1 2 05-JAN-2001 2 14 02-JAN-2001 1 1 03-JAN-2001 1 2 04-JAN-2001 2 05-JAN-2001 2 8 rows selected.

6. Compare the results of the two queries executed in steps 4 and 5. What is the difference?

Answer: The regular outer join from step 4 is only adding rows for days without any sales at all: 05-JAN-2001. The partitioned outer join from step 5 has added additional rows for each day one of the products was not sold. You have two products and four days, resulting in eight rows.

7. You will need the S1 table in the next practice; you can drop the T1 table now. SQL> drop table t1; Table dropped.

Page 237: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-57

Practice 7-2 Solution: Using the MODEL Clause You can use the S1 table you created in the previous practice to experiment with the new MODEL clause to perform inter-row calculations. 1. Connect as the SH schema and query all rows of the S1 table to see the table contents.

TIP: Remember to clear the format break set in the previous practice. SQL> connect sh/sh Connected. SQL> clear break breaks cleared SQL> SELECT time_id, prod_id, quantity_sold qs 2 FROM s1; TIME_ID PROD_ID QS --------- -------- -------- 02-JAN-01 13 1 04-JAN-01 13 1 02-JAN-01 14 1 03-JAN-01 14 1

2. Execute the lab_07_02_02.sql script to see the MODEL clause at work. SQL> SELECT time_id, prod_id, qs 2 FROM s1 3 MODEL 4 DIMENSION BY (prod_id, time_id) 5 MEASURES (quantity_sold qs) 6 RULES 7 ( qs[13,'09-JAN-2001'] = 8 sum(qs)[13,time_id between '02-JAN-2001' 9 and '08-JAN-2001'] 10 , qs[14,'09-JAN-2001'] = qs[13,'09-JAN-2001'] * 3 11 , qs[15,'09-JAN-2001'] = 42 12 ) 13 ORDER BY prod_id, time_id; TIME_ID PROD_ID QS --------- -------- -------- 02-JAN-01 13 1 04-JAN-01 13 1 09-JAN-01 13 2 02-JAN-01 14 1 03-JAN-01 14 1 09-JAN-01 14 6 09-JAN-01 15 42 7 rows selected.

Page 238: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-58

3. Change the above query to suppress the original rows from the S1 table by adding the RETURN UPDATED ROWS clause after the RULES keyword. You can execute the lab_07_02_03.sql script.

SQL> SELECT time_id, prod_id, qs 2 FROM s1 3 MODEL 4 DIMENSION BY (prod_id, time_id) 5 MEASURES (quantity_sold qs) 6 RULES 7 RETURN UPDATED ROWS 8 ( qs[13,'09-JAN-2001'] = 9 sum(qs)[13,time_id between '02-JAN-2001' 10 and '08-JAN-2001'] 11 , qs[14,'09-JAN-2001'] = qs[13,'09-JAN-2001'] * 3 12 , qs[15,'09-JAN-2001'] = 42 13 ) 14 ORDER BY prod_id, time_id; TIME_ID PROD_ID QS --------- -------- -------- 09-JAN-01 13 2 09-JAN-01 14 6 09-JAN-01 15 42 3 rows selected.

4. You can drop the S1 table now. SQL> drop table s1; Table dropped.

Page 239: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-59

Practice 7-3 Solution: Using Some Materialized View Enhancements 1. Connect to the SH schema, and run the lab_07_03_01.sql script to ensure the MY_MV

materialized view does not exist. SQL> connect sh/sh Connected. SQL> drop materialized view my_mv; Materialized view dropped.

2. Execute the lab_07_03_02.sql script to create a materialized view called MY_MV, and

execute the dbms_stats.gather_table_stats(USER, 'MY_MV') procedure to gather statistics against MY_MV.

SQL> create materialized view my_mv 2 build immediate 3 enable query rewrite 4 as select prod_id 5 , avg(amount_sold) as avg_amount 6 from sales 7 where channel_id = 9 8 group by prod_id; Materialized view created. SQL> execute dbms_stats.gather_table_stats(USER,'MY_MV'); PL/SQL procedure successfully completed. SQL> select * from my_mv; PROD_ID AVG_AMOUNT ---------- ---------- 16 11.99 21 899.99 26 149.99 27 44.99 30 9.99 35 49.99 40 44.99 46 22.99 48 11.99 116 11.99 128 27.99 PROD_ID AVG_AMOUNT ---------- ---------- 147 7.99 12 rows selected.

Page 240: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-60

3. Execute the lab_07_03_03.sql script. There is an intentional typographical error in the script to help identify the QUERY_OR_REWRITE hint at work.

Answer: Full text match query rewrite is not possible because the quantity_sold column does not appear in the underlying MY_MV materialized view definition.

SQL> select /*+ REWRITE_OR_ERROR */ 2 prod_id 3 , avg(quantity_sold) 4 from sales 5 where channel_id = 9 6 group by prod_id; from sales * ERROR at line 4: ORA-30393: a query block in the statement did not rewrite

4. Fix the error: Change QUANTITY_SOLD into AMOUNT_SOLD on line 3, and repeat the test. SQL> select /*+ REWRITE_OR_ERROR */ 2 prod_id 3 , avg(amount_sold) 4 from sales 5 where channel_id = 9 6 group by prod_id; PROD_ID AVG(AMOUNT_SOLD) -------- ---------------- 16 11.99 21 899.99 26 149.99 27 44.99 30 9.99 35 49.99 40 44.99 46 22.99 48 11.99 116 11.99 128 27.99 147 7.99 12 rows selected.

5. Run the lab_07_03_05.sql script to execute EXPLAIN PLAN against the query in the

previous step and query the PLAN_TABLE table, to see the improved execution plan readability. SQL> explain plan for 2 select prod_id 3 , avg(amount_sold) 4 from sales 5 where channel_id = 9 6 group by prod_id;

Page 241: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-61

Explained. SQL> select * from table(dbms_xplan.display); PLAN_TABLE_OUTPUT --------------------------------------------------------------------- Plan hash value: 3745461064 --------------------------------------------------------------------- | Id | Operation | Name |Rows |Bytes |Cost(%CPU)| --------------------------------------------------------------------- | 0 | SELECT STATEMENT | | 12 | 84 | 4 (25)| | 1 | MAT_VIEW REWRITE ACCESS FULL| MY_MV | 12 | 84 | 4 (25)| ---------------------------------------------------------------------

Note: The above output is formatted to fit the page size. 6. Before you can use the DBMS_MVIEW.EXPLAIN_REWRITE procedure, you must create the

REWRITE_TABLE table with the utlxrw.sql script available in the $ORACLE_HOME/rdbms/admin directory. Run the $ORACLE_HOME/rdbms/admin/utlxrw.sql script now.

SQL> @$ORACLE_HOME/rdbms/admin/utlxrw.sql Table created.

7. Using the lab_07_03_07.sql script, execute the DBMS_MVIEW.EXPLAIN_REWRITE

procedure against the query and the MY_MV materialized view, and query the REWRITE_TABLE table to see the results.

SQL> execute dbms_mview.explain_rewrite - 2 ( 'select prod_id - 3 , avg(amount_sold) - 4 from sales - 5 where channel_id = 9 - 6 group by prod_id' - 7 , 'SH.MY_MV' - 8 , 'Practice 07-3' - 9 ) ; PL/SQL procedure successfully completed. SQL> column message format a40 word SQL> select message 2 , original_cost, rewritten_cost 3 from rewrite_table; MESSAGE ORIGINAL_COST REWRITTEN_COST ---------------------------------------- ------------- -------------- QSM-01009: materialized view, MY_MV, 511 4 matched query text

8. Execute the lab_07_03_08.sql script to clean up your database environment by dropping

the MY_MV materialized view and the REWRITE_TABLE table.

Page 242: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-62

SQL> drop materialized view my_mv; Materialized view dropped. SQL> drop table rewrite_table; Table dropped.

Page 243: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-63

Practice 9-1 Solution: Monitoring the Scheduler In this practice, you use the Database Control application to define and monitor the Scheduler and automate tasks. Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Log in to EM Database Control as the SYSTEM user and grant the following roles to the HR user:

• CONNECT role • RESOURCE role • DBA role Because you are going to use user HR to administer jobs through Database Control, you need to make sure that HR is registered as a possible Administrator.

a. From the Database Control home page, click the Administration tab. b. On the Administration page, click the Users link in the Security region. c. On the Users page, click the HR username to edit the account. d. On the Edit User page, click the Roles tab. Then click the Modify button on the right side of the page. e. On the Modify Roles page, click the DBA role, and then press the Move button to grant this role to the HR

user. Repeat these steps for the RESOURCE role. Then click the OK button. f. On the Edit User page, click Apply. g. Click the Setup link. h. On the Administrators page, click the Create button. i. On the Create Administrators: Properties page, enter HR in the Name, Password, and Confirm

Password fields. j. Click the Finish button. k. On the Create Administrator: Review page, click the Finish button. l. Back to the Administrators page, click the Database tab.

2. Log in to Database Control as the HR user. From the Administration tab, click the Jobs link in

the Scheduler region, at the bottom right corner of the page. Are there any existing jobs? Answer: No.

a. In the upper right corner of the current page, click the Logout link. b. Click the Login button to log in again. c. For the username and password enter HR. Then click Login. d. On the Oracle Database Licensing Information 10g page click the I Agree button. e. Click the Administration tab. f. Click the Jobs link in the Scheduler region in the bottom right corner of the page.

3. Are there any existing programs? (Hint: Use the browser Back button).

a. Return to the Administration main page, and click the Programs link under the heading Scheduler. b. There are no existing programs.

Page 244: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-64

4. Are there any existing schedules?

a. Return to the Administration main page, and click the Schedules link under the heading Scheduler. b. There is one schedule, called DAILY_PURGE_SCHEDULE

5. Are there any existing windows? What resource plan is associated with each window?

a. Return to the Administration main page, and click the Windows link under the heading Scheduler. b. There are two windows, named WEEKNIGHT_WINDOW and WEEKEND_WINDOW. The windows do not

have any resource plan associated with them 6. Are there any existing job classes? If so, what resource consumer group is associated with each

job class?

a. Return to the Administration main page, and click the Job Classes link under the heading Scheduler. b. There are two job classes:

• DEFAULT_JOB_CLASS: no resource consumer group. • AUTO_TASKS_JOB_CLASS is associated to the AUTO_TASK_CONSUMER_GROUP resource

consumer group.

Page 245: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-65

Practice 9-2 Solution: Creating Scheduler Components In this practice, you will use Database Control to create Scheduler objects and automate tasks. Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. While logged in to the database as the HR user in Database Control, click the Administration

tab. Under the heading Scheduler, click Jobs. Click the Create button to open the Create Job window. Create a simple job that runs a SQL script:

• General: Name: CREATE_LOG_TABLE_JOB Owner: HR Description: Create the SESSION_HISTORY table for the next part of this practice Logging level: RUNS Command type: In-line Program: Executable Executable: /home/oracle/labs/lab_09_02_01.sh

• Schedule: Repeating: Do not Repeat Start: Immediately

• Options: No special options.

a. From the Database Console home page, click the Administration tab. b. In the Scheduler section, click the Jobs link. c. On the Scheduler Jobs page, click the Create button. d. On the Create Job page, enter CREATE_LOG_TABLE_JOB in the Name field. Make sure that HR is

specified in the Owner field. Enter Create the SESSION_HISTORY table for the next part of this practice in the Description field. Make sure that Logging Level is set to Log job runs only (RUNS). Make sure that the Job Class is set to DEFAULT_JOB_CLASS. Make sure that Auto Drop is set to FALSE. Make sure that Restartable is set to FALSE.

e. In the Command section, click the Change Command Type button. f. On the Select Command Option, select the In-line Program: Executable radio button, and click the

OK button. g. Back to the Create Job page, enter /home/oracle/labs/lab_09_02_01.sh in the Executable

Name field. h. Click the Schedule tab. i. On the Schedule page, make sure that the Immediately radio button is selected, and that the Repeat field

is set to Do Not Repeat. 2. Click the OK button to create the job. 3. If the job does not appear on the Scheduler Jobs page, click the Refresh button. Then click the

Run History tab and verify that the job ran successfully.

Page 246: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-66

4. Create a program called LOG_SESS_COUNT_PRGM that logs the current number of database sessions into a table. Use the following code, or use the lab_09_02_04.sql script:

DECLARE sess_count NUMBER; BEGIN SELECT COUNT(*) INTO sess_count FROM V$SESSION; INSERT INTO session_history VALUES (systimestamp, sess_count); COMMIT; END;

a. From the Administration page, click the Programs link under the heading Scheduler. b. Click Create. c. Enter LOG_SESS_COUNT_PRGM for the name of the Program. Set Enabled to Yes. d. Leave the type set to PL/SQL Block. e. Enter the above PL/SQL text into the Source field. f. Click OK.

5. Create a schedule named SESS_UPDATE_SCHED owned by HR that executes every three

seconds. Because the Database Control interface supports scheduled intervals of only one minute or greater, you will use SQL*Plus and the DBMS_SCHEDULER.CREATE_SCHEDULE procedure to create the program.

Connect hr/hr BEGIN DBMS_SCHEDULER.CREATE_SCHEDULE ( schedule_name => 'SESS_UPDATE_SCHED', start_date => SYSTIMESTAMP, repeat_interval => 'FREQ=SECONDLY;INTERVAL=3', comments => 'Every three seconds'); END; / 6. Return to the Database Control, and verify that the schedule was created.

Hint: You may have to refresh the page for the Schedule to appear.

a. Return to the Administration main page, and click the Schedules link under the heading Scheduler.

7. Using Database Control, create a job named LOG_SESSIONS_JOB that uses the

LOG_SESS_COUNT_PRGM program and the SESS_UPDATE_SCHED schedule. Make sure the job uses FULL logging.

a. Click the Jobs link under the heading Scheduler. b. Click the Create button to open the Create Job window. c. Enter LOG_SESSIONS_JOB for the name. d. Change the logging level to FULL. e. Click Change Command Type, and in the Select Command Option window, choose Program Name,

Page 247: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-67

and enter HR.LOG_SESS_COUNT_PRGM in the space next to it, or use the Lookup button to select the program. Click OK.

f. After you are returned to the Create Job window, click the Schedule tab. Change the Schedule Type to Use Pre-Defined Schedule. Select the HR.SESS_UPDATE_SCHED schedule by using look up.

g. Click OK to create the job. 8. Check the HR.SESSION_HISTORY table for rows. If there are rows in the table, are the

timestamps three seconds apart?

Answer: Yes there are rows, and yes the timestamps are three seconds apart. 9. Use Database Control to alter the SESS_UPDATE_SCHED schedule from every three seconds

to every three minutes.

a. From the Administration page, click Schedules. b. Click the SESS_UPDATE_SCHED link. c. Change the description to Every 3 minutes. d. Change Repeating from Do Not Repeat to By Minutes. e. Set the Interval to 3. f. Click Apply

10. Connect as HR schema, and query the SESSION_HISTORY table to verify that the rows are

being added every three minutes now, instead of every three seconds. Connect hr/hr SELECT * FROM SESSION_HISTORY ORDER BY snap_time; 11. Alter the HR.SESSION_HISTORY table to contain a new column, BACKGROUND_COUNT of

type NUMBER.

a. From the Administration page, click Tables under the heading Schema. b. Enter HR for the schema and SESSION_HISTORY for the table name, then click Go. c. Click the table name in the Results list. d. Click the Add 5 Table Columns button. e. In the first empty row (after NUM_SESSIONS) enter BACKGROUND_COUNT for the column name and

NUMBER for the data type. f. Click Apply to alter the table.

Page 248: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-68

12. Alter the LOG_SESS_COUNT_PRGM program to log new information into the logging table. Modify the code to look like the following text, or use the lab_09_02_12.sql script:

DECLARE sess_count NUMBER; back_count NUMBER; BEGIN SELECT COUNT(*) INTO sess_count FROM V$SESSION; SELECT COUNT(*) INTO back_count FROM V$SESSION WHERE type = ''BACKGROUND''; INSERT INTO session_history VALUES (systimestamp, sess_count,

back_count); COMMIT; END;

a. From the Administration page, click Programs under the heading Scheduler. b. Click the LOG_SESS_COUNT_PRGM link. c. Change the Source code to match the above text. d. Click Apply.

13. Run the LOG_SESSIONS_JOB job immediately, and verify that the new information was added

to the HR.SESSION_HISTORY table.

a. From the Administration page, click Jobs under the heading Scheduler. b. With the job LOG_SESSIONS_JOB selected, click the Run Now button. c. Click the Run History tab to verify that the job ran successfully. You might have to refresh the

Scheduler Jobs page in order to see the LOG_SESSIONS_JOB in the Scheduled tab. d. Query the HR.SESSION_HISTORY table to verify that the newest rows contain the background session

count. 14. Drop the LOG_SESSIONS_JOB job, the LOG_SESS_COUNT_PRGM program, and the schedule

SESS_UPDATE_SCHED. Note: Make sure you do not delete the wrong schedule.

a. From the Administration page, click Jobs under the heading Scheduler. b. With the LOG_SESSIONS_JOB job selected, click the Delete button. Select Drop the job and stop any

running instance, and then click Yes. c. Click the database breadcrumb at the left top corner of the page to return to the Administration page.

Then click Programs under the heading Scheduler. d. With the LOG_SESS_COUNT_PRGM program selected, click the Delete button. Click Yes to confirm. e. Click the Database breadcrumb at the left top corner of the page to return to the Administration page.

Click Schedules under the heading Scheduler. f. With the schedule SESS_UPDATE_SCHED selected, click the Delete button. Make sure you do not

delete the wrong schedule. g. Select If there are dependent objects, it will not be dropped, then click Yes to confirm.

Page 249: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-69

Practice 10-1 Solution: Proactively Managing Tablespace Space Usage Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Using the DBMS_SERVER_ALERT.SET_THRESHOLD procedure, reset the database-wide

threshold values for the Tablespace Space Usage metric. You can use the script lab_10_01_01.sql.

exec DBMS_SERVER_ALERT.SET_THRESHOLD(- dbms_server_alert.tablespace_pct_full,- NULL,NULL,NULL,NULL,1,1,NULL,- dbms_server_alert.object_type_tablespace,NULL); 2. Check the database-wide threshold values for the Tablespace Space Usage metric by using the

following command: SELECT warning_value,critical_value FROM dba_thresholds WHERE metrics_name='Tablespace Space Usage' AND object_name IS NULL;

select warning_value,critical_value from dba_thresholds where metrics_name='Tablespace Space Usage' and object_name is null; 3. Create a new tablespace called TBSALERT with one 5 MB file called alert1.dbf. Make sure

this tablespace is locally managed and uses Automatic Segment Space Management. Also, do not make it autoextensible, and do not specify any thresholds for this tablespace. Use Database Control to create it. If this tablespace already exists in your database, drop it first, including its files.

a. From the Database Control home page: Administration > Tablespaces b. Click the Create option button. c. Specify the tablespace name TBSALERT in the Name field, and click Add. d. Specify the File Name and File Size fields as alert1.dbf and 5MB. e. Click Continue. f. Click OK when done.

Page 250: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-70

4. Using Database Control, change the Tablespace Space Usage thresholds of the TBSALERT tablespace. Set its warning level to 50 percent, and its critical level to 60 percent.

a. From the Database Control home page: Administration > Tablespaces b. Select TBSALERT. c. Select Edit > Thresholds. d. Select Specify Thresholds, by percent used. e. Specify the Warning (%) and Critical (%) fields. f. Click Apply when done.

5. Using SQL*Plus, check the new threshold values for TBSALERT. select warning_value,critical_value from dba_thresholds where metrics_name='Tablespace Space Usage' and object_name='TBSALERT';

6. Select the reason and resolution columns from DBA_ALERT_HISTORY for the

TBSALERT tablespace. How do you explain the result?

Answer: If you used Database Control to create TBSALERT, you should see two identical rows. This is because Database Control explicitly sets the tablespace thresholds when creating it. If you used SQL*Plus, then you should see only one row, corresponding to the thresholds update.

select reason,resolution from dba_alert_history where object_name='TBSALERT'; 7. Execute the lab_10_01_07.sql script that populates new tables in TBSALERT. create table employees1 tablespace tbsalert as select * from hr.employees; create table employees2 tablespace tbsalert as select * from hr.employees; create table employees3 tablespace tbsalert as select * from hr.employees; create table employees4 tablespace tbsalert as select * from hr.employees; create table employees5 tablespace tbsalert as select * from hr.employees; alter table employees1 enable row movement; alter table employees2 enable row movement; alter table employees3 enable row movement; -- exec dbms_workload_repository.create_snapshot(); BEGIN FOR i in 1..5 LOOP insert into employees1 select * from employees1; insert into employees2 select * from employees2; insert into employees3 select * from employees3; insert into employees4 select * from employees4; insert into employees5 select * from employees5; commit;

Page 251: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-71

END LOOP; END; / -- exec dbms_workload_repository.create_snapshot(); -- 37.97% -- select (select sum(bytes) -- from dba_extents -- where tablespace_name='TBSALERT')*100/5177344 -- from dual; insert into employees1 select * from employees1; insert into employees2 select * from employees2; insert into employees3 select * from employees3; commit; -- exec dbms_workload_repository.create_snapshot();

8. Check the fullness level of the TBSALERT tablespace using either Database Control or

SQL*Plus. The current level should be around 53%. Wait for approximately 10 minutes, and check that the warning level is reached for the TBSALERT tablespace.

a. From Database Control home page: Administration > Tablespaces • Wait for approximately 10 minutes.

b. From the Database Control home page, you should see the new alert in the Space Usage region. -- 53.16% select (select sum(bytes) from dba_extents where tablespace_name='TBSALERT')*100/5177344 from dual; -- wait for 10 minutes and see warning select reason from dba_outstanding_alerts where object_name='TBSALERT'; 9. Execute the lab_10_01_09.sql script to add data to TBSALERT. Wait for 10 minutes and

view the critical level in both the database and in Database Control. Verify that TBSALERT fullness is around 63%.

Page 252: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-72

insert into employees4 select * from employees4; commit; -- 58.22% insert into employees5 select * from employees5; commit;

a. From the Database Control home page, you should see the new alert in the Space Usage region. b. You should see the red flag instead of the yellow one. c. To check the fullness level of the TBSALERT tablespace, from the Database Control home page:

Administration > Tablespaces -- 63.29% select (select sum(bytes) from dba_extents where tablespace_name='TBSALERT')*100/5177344 from dual; -- wait for 10 minutes and see critical. select reason, message_level from dba_outstanding_alerts where object_name='TBSALERT'; 10. Execute the lab_10_01_10.sql script. This script deletes rows from tables in TBSALERT. delete employees1 where department_id=50; commit; delete employees2 where department_id=50; commit; delete employees3 where department_id=50; commit;

Page 253: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-73

11. Now run the Segment Advisor for the TBSALERT tablespace by using Database Control. Make sure that you run the Advisor in Comprehensive mode without time limitation. Accept and implement its recommendations. After the recommendations have been implemented, check that the fullness level of TBSALERT is below 50%.

a. From the Database Control home page: Administration > Tablespaces b. Select TBSALERT. c. Select Run Segment Advisor from the Actions field. d. Click the Go button. This takes you to the Segment Advisor: Advisor Mode page. e. Make sure that Comprehensive mode is selected. f. Click the Continue button. g. On the Segment Advisor: Options page, make sure that Unlimited is selected. h. Click the Next button. i. On the Segment Advisor: Schedule page, select Standard in the Schedule Type field. Make sure that

the Immediately option button is selected. j. Click the Next button. k. Review the task on the Segment Advisor: Review page, and click the Submit button. This takes you

back to the Advisor Central page from where you can see the evolution of your task. l. Click the Refresh button until your shrink task is COMPLETED. m. When COMPLETED, select your shrink task and click the View Result button. This takes you to the

Segment Advisor Recommendations page. n. Accept all recommendations by clicking the Select All link. Then click the Schedule Implementation

button. o. On the Schedule page, make sure that Immediately is selected, and submit your job. p. When COMPLETED, verify that the TBSALERT tablespace fullness is now below 50%. You can do so

from the Tablespaces page. 12. Wait for approximately 10 more minutes, and check that there are no longer any outstanding

alerts for the TBSALERT tablespace.

a. From the Database Control home page, you should see the green flag for the Space Usage region. -- wait for 10 minutes. No rows from outstanding. select reason, message_level from dba_outstanding_alerts where object_name='TBSALERT';

Page 254: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-74

13. Using Database Control, retrieve the history of the Tablespace Space Usage metric for

TBSALERT for the last 24 hours.

a. From the Database Control home page, select All Metrics. b. Expand the Tablespaces Full category. c. Click the Tablespace Space Usage (%) link. d. On the Tablespace Space Used (%) page, click the TBSALERT link. e. This takes you to the Tablespace Space Used (%): Tablespace Name TBSALERT page from where

you can see the graphic that represents the history of this metric for the last 24 hours. 14. Reset the database wide default thresholds from the Tablespace Space Usage metric for

tablespace TBSALERT.

a. From the context of the Tablespace Space Used (%): Tablespace Name TBSALERT page, click the Edit Tablespace link.

b. This brings you to the Edit Tablespace: TBSALERT page. c. Click the Thresholds tab, and then select the Use Default Thresholds option button. d. Click the Apply button.

Page 255: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-75

Practice 10-2 Solution: Sizing Your Undo Tablespace with the Undo Advisor Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. For this lab, it is assumed that: • undo_management is set to AUTO • undo_retention is set to 900 • undo_tablespace is set to UNDOTBS1 1. Create a database session connected as SYSDBA through SQL*Plus. This session is referred to as

the First session. Using either Database Control or SQL*Plus, create a new undo tablespace called UT2 with only one 1MB file.

a. From the Database Control home page: Administration > Tablespaces b. On the Tablespaces page, click the Create button. c. On the Create Tablespace page, specify the Name field, and select Undo in the Type region. Then click

the Add button. d. On the Create Tablespace: Add Datafile page, specify the name field (for example ut2.dbf) and

change the File Size to 1 MB. Then click the Continue button. e. After you are returned to the Create Tablespace page, click the OK button.

2. Change your current undo tablespace to UT2.

a. From the Database Control home page: Administration > Undo Management b. On the Undo Management page, click the Change Tablespace button. c. On the Change Undo Tablespace page, select UT2 and click the OK button.

3. Using a second SQL*Plus session, connect as SYSDBA. This session is referred to as the

Second session. Execute the lab_10_02_03.sql script. If you get an error when executing the script, switch your undo tablespace back to UNDOTBS1, and start again.

-- Second session drop table b purge; create table b(b int, s varchar2(100)) tablespace tbsalert; begin for i in 1..100 loop insert into b values(i, rpad('s',100)); end loop; end; / commit;

Page 256: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-76

4. In the second session, prepare to execute the lab_10_02_04a.sql script, and in the first session prepare to execute the lab_10_02_04b.sql script. When done, execute the script in the second session, and then immediately after, execute the one from the first session. What happens and why?

Answer: The second session gets a Snapshot Too Old error. This is because the UT2 is too small to handle this workload.

-- Second session declare b number; cursor c1 is select b from b; begin open c1; loop fetch c1 into b; dbms_lock.sleep(1); exit when c1%notfound; end loop; close c1; end; / -- First session begin for i in 1..100 loop update b set b=+1, s=rpad('t',100); commit; end loop; end; / 5. From the first session look at the alert history. What do you see? Use Database Control to locate

the warning, and click the corresponding alert link.

Answer: You can see that the alert history contains the Snapshot Too Old error. It was automatically detected by the Oracle database.

-- First session select time_suggested, reason from dba_alert_history where object_name='UT2';

Page 257: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-77

a. Looking at the Database Control home page, after refreshing the page, you can also see the Snapshot

Too Old warning in the Alerts region of the page. b. Click the corresponding alert link. This brings you to the Snapshot Too Old due to Tablespace Limit:

Object Causing UT2 page, which provides advice about running the Undo Advisor. 6. Use the Undo Advisor to get recommendations to correctly size UT2. Use the recommendation to

correctly size the UT2 tablespace.

a. From the Database Control home page: Administration > Undo Management b. On the Undo Management page change the Analysis Time Period field to Last One Hour and click the

Update Analysis button. c. On the Undo Management page, you should see a recommendation to size UT2 to 10 MB. d. Click the Undo Advisor button to obtain more details about the recommendation. In particular, look at

the Required Tablespace Size by Undo Retention Length graph. You can, for example, change the New Undo Retention field to see the impact on your undo tablespace size.

e. Click the Cancel button. f. After you are returned to the Undo Management page, click the Edit Undo Tablespace button. g. This brings you to the Edit Tablespace: UT2 page from where you can add a new 10 MB file to UT2. h. Click the Add button. i. On the Edit Tablespace: UT2: Add Datafile page, specify the name of your additional file, and also

specify 10 MB for its size. j. Click the Continue button. k. After you are returned to the Edit Tablespace: UT2 page, click the Apply button.

7. Redo step 4. What happens and why?

Answer: This time both sessions succeed without any error. The Undo Advisor gave you a good recommendation.

-- Second session declare b number; cursor c1 is select b from b; begin open c1; loop fetch c1 into b; dbms_lock.sleep(1); exit when c1%notfound; end loop; close c1; end; /

Page 258: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-78

-- First session begin for i in 1..100 loop update b set b=+1, s=rpad('t',100); commit; end loop; end; / 8. Switch your undo tablespace back to UNDOTBS1, and drop UT2 including its data files, as well

as TBSALERT.

a. From Database Control: Administration > Undo Management b. On the Undo Management page, click the Change Tablespace button. c. On the Change Undo Tablespace page, make sure that UNDOTBS1 is selected, and click the OK button. d. Click the Database: orcl link, and then Tablespaces link. e. On the Tablespaces page, select UT2, and then click the Delete button. f. On the Warning page, make sure that the Delete associated data files from the OS field is selected.

Then click the Yes button. g. Do the same thing for the TBSALERT tablespace.

Page 259: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-79

Practice 11-1 Solution: Interpreting ROWIDs of Rows Stored in Bigfile Tablespaces. Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Using Database Control, create a new bigfile tablespace called TBSBF containing one 5 MB file.

a. From the Database Control home page: Administration > Tablespaces b. On the Tablespaces page, click the Create button. c. On the Create Tablespace page, specify the Name field, and make sure that the Use bigfile tablespace

checkbox is selected. d. Click the Add button. e. On the Create Tablespace: Add Datafile page, specify the File Name field (for example tbsbf.dbf)

and change the File Size to 5 MB. Then click the Continue button. f. After you are returned to the Create Tablespace page, click the OK button.

2. Using Database Control, try to add a new file to TBSBF. What happens and why?

Answer: Because a bigfile tablespace can contain only one data file, it is not possible to add a data file to TBSBF.

a. From the Database Control home page: Administration > Tablespaces b. On the Tablespaces page, make sure that Add Datafile is selected in the Actions drop-down list. c. Select tablespace TBSBF, and click the Go button. d. You should see the following error message in the Validation Error region: A bigfile

tablespace can contain a single datafile only. 3. Using Database Control, how can you resize TBSBF to 10 MB? What simplification can you

observe?

Answer: With bigfile tablespaces, you do not need to explicitly select one data file. The only possible one is already selected, and the resulting SQL statement is to apply the operation on the whole tablespace, and not on its corresponding file.

a. From the Database Control home page: Administration > Tablespaces b. On the Tablespaces page, select the TBSBF tablespace, and click the Edit button. c. On the Edit Tablespace: TBSBF page, click the Edit button. d. On the Edit Tablespace: TBSBF: Edit Datafile page, specify the File Size field to 10 MB, and click the

Continue button. e. After you are returned to the Edit Tablespace: TBSBF page, click the Show SQL button. f. You can see that the operation applies to the tablespace itself, and not specifically to its data file. g. Click the Return button. h. After you are returned to the Edit Tablespace: TBSBF page, click the Apply button.

Page 260: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-80

4. Using Database Control, create table EMP as a copy of HR.EMPLOYEES. Make sure that EMP resides in the TBSBF tablespace.

a. From the Database Control home page: Administration > Tables b. On the Tables page, click the Create button. c. On the Create Table: Table Organization page make sure that the Standard option button is selected. d. Click the Continue button. e. On the Create Table page specify the following:

• EMP in the Name field • SYS in the Schema field • TBSBF in the Tablespace field

f. When done, select SQL in the Define Using field. g. In the SQL region, enter SELECT * FROM HR.EMPLOYEES h. When done, click the OK button.

5. Explain why the following statement is incorrect. Then fix it, and determine the correct output:

SELECT distinct DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID) FROM sys.emp;

Answer: Because SYS.EMP is stored in a bigfile tablespace, you should use the BIGFILE value as the second argument of the ROWID_RELATIVE_FNO function. The default value of the second argument is SMALLFILE.

SQL> SELECT distinct DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID) 2 FROM sys.emp; DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID) ------------------------------------ 0 SQL> SQL> SELECT distinct DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID,'BIGFILE') 2 FROM sys.emp; DBMS_ROWID.ROWID_RELATIVE_FNO(ROWID,'BIGFILE') ---------------------------------------------- 1024 SQL> 6. Explain why the following statement is incorrect. Then fix it, and determine the correct output:

SELECT distinct DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'BIGFILE') FROM hr.employees;

Answer: Because HR.EMPLOYEES is stored in a smallfile tablespace, you should use the SMALLFILE value as the second argument of the ROWID_BLOCK_NUMBER function. The default value of the second argument is SMALLFILE.

SQL> SELECT distinct DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'BIGFILE') 2 FROM hr.employees;

Page 261: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-81

DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'BIGFILE') ---------------------------------------------- 4248682 4248683 SQL> SELECT distinct DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE') 2 FROM hr.employees; DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE') ------------------------------------------------ 54378 54379 SQL> 7. Explain why the following statement is correct. What is your conclusion?

SELECT DBMS_ROWID.ROWID_TO_RESTRICTED(rowid,1) FROM sys.emp WHERE rownum<2;

Answer: It is correct because there is no other possible argument for this call. However, it shows that you should no longer try to interpret restricted ROWIDs for rows from bigfile tablespaces.

SQL> SELECT DBMS_ROWID.ROWID_TO_RESTRICTED(rowid,1) 2 FROM sys.emp 3 WHERE rownum<2; DBMS_ROWID.ROWID_T ------------------ 00000014.0000.0000 SQL> 8. Execute the following statement with the previously found restricted ROWID. Explain why it is

incorrect, and then fix it: SELECT first_name FROM sys.emp WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('&rid',NULL,NULL,0) FROM dual);

Answer: It is incorrect because you are using a restricted ROWID without specifying the corresponding table. So, in the above context, the ROWID is interpreted as a row of a SMALLFILE tablespace. Thus, it cannot be interpreted. To fix the statement, you must explicitly specify the table corresponding to this ROWID.

SQL> SELECT first_name 2 FROM sys.emp 3 WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('&rid',NULL,NULL,0) 4 FROM dual); Enter value for rid: 14.0.0 old 3: WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('&rid',NULL,NULL,0) new 3: WHERE rowid = (SELECT

Page 262: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-82

DBMS_ROWID.ROWID_TO_EXTENDED('14.0.0',NULL,NULL,) WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('14.0.0',NULL,NULL,0) * ERROR at line 3: ORA-01410: invalid ROWID ORA-06512: at "SYS.DBMS_ROWID", line 155 ORA-06512: at line 1 SQL> SELECT first_name 2 FROM sys.emp 3 WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('&rid','SYS','EMP',0) 4 FROM dual); Enter value for rid: 14.0.0 old 3: WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('&rid','SYS','EMP',) new 3: WHERE rowid = (SELECT DBMS_ROWID.ROWID_TO_EXTENDED('14.0.0','SYS','EMP) FIRST_NAME -------------------- Steven SQL> 9. Execute the lab_11_01_09.sql script to clean up your environment. SQL> connect / as sysdba Connected. SQL> SQL> drop tablespace tbsbf including contents and datafiles; Tablespace dropped. SQL>

Practice 12-1 Solution: Setting Up a Flash Recovery Area Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. In this lab you will be following Oracle’s best practices for managing database files and recovery

related files by establishing a database area and flash recovery area for your database. Use Database Control to configure OMF to /u01/app/oracle/oradata/orcl. Ensure that parameter changes are written to the current SPFILE. Turn on ARCHIVELOG mode for your database. This requires a restart of your instance.

a. From the Database Control home page, select Administration > Instance > All Initialization

Parameters. b. Select SPFile tab, and check Apply changes in SPFile mode to the current running instance(s) box. c. In the Filter field, type in db_create and click Go. Set the path name to

Page 263: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-83

/u01/app/oracle/oradata/orcl for db_create_file_dest and db_create_online_log_dest_1.

d. Click the Apply button. e. From the Database Control home page, click the Disabled link of the Archiving field in the High

Availability section. f. On the Configure Recovery Settings page, check the ARCHIVELOG Mode box and click Apply. g. On the Confirmation page, click Yes. h. If needed, specify the necessary credentials on the Restart Database:Specify Host and Target

Database Credentials page, and click OK. i. On the Restart Database:Confirmation page, click Yes. j. On the Restart Database: Activity Information page, click the Refresh button after a while.

2. Using Database Control, check that you are now using automatically a flash recovery area. Then

make sure that the size of your flash recovery area is set to 3GB. What happens to the Archive Log Destination 10?

Answer: The Archive Log Destination 10 reflects the new extended syntax USE_DB_RECOVERY_FILE_DEST.

a. From the Database Control home page, select Maintenance > Configure Recovery Settings b. In the Flash Recovery Area Location field enter /u01/app/oracle/flash_recovery_area/. c. In the Flash Recovery Area Size field , enter 3 and click Apply. d. After the Flash Recovery Area has been set, Archive Log Destination # 10 reflects the new extended

syntax of USE_DB_RECOVERY_FILE_DEST.

3. Gather information regarding the flash recovery area by querying the

v$recovery_file_dest view. You can use the lab_12_01_03.sql lab script. Note: Returned values may vary from the provided solution. SQL> SELECT name, space_limit AS quota, 2 space_used AS used, 3 space_reclaimable AS reclaimable, 4 number_of_files AS files 5 FROM v$recovery_file_dest 6 /

Page 264: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-84

NAME -------------------------------------------------------------------------------- QUOTA USED RECLAIMABLE FILES ---------- ---------- ----------- ---------- /u01/app/oracle/flash_recovery_area 3221225472 10417152 0 1 SQL>

Page 265: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-85

Practice 12-2 Solution: Enabling Block Change Tracking Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Using Database Control, enable fast incremental backups for your database. What is the default

location for the change tracking file? Ensure that your retention policy allows for recovery within the last 31 days.

Answer: Because you enabled OMF in Practice 12-1, there is no need to specify a block-change tracking file name. An Oracle-managed file is created in the database area for the block-change tracking file.

a. From the Database Control home page: Maintenance > Configure Backup Settings b. Click the Policy tab. c. Select the Enable block change tracking for faster incremental backups checkbox. d. Select the “Retain backups that are necessary for a recovery to any time within the specified number

of days” item. e. Enter the host credentials as oracle/oracle. f. When done, click the OK button.

2. Query the v$block_change_tracking view to show the status, file name, and size of the

file. You can use the lab_12_02_02.sql script. SQL> SELECT filename, status, bytes 2 FROM v$block_change_tracking 3 / FILENAME -------------------------------------------------------------------------------- STATUS BYTES ---------- ---------- /u01/app/oracle/oradata/orcl/ORCL_EDRSR14P1/changetracking/o1_mf_0259vq9m_.chg ENABLED 11599872 SQL>

Page 266: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-86

Practice 12-3 Solution: Using Oracle Suggested Strategy for Backups Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Using Database Control, back up the Oracle database using the Oracle Suggested Strategy. View

the backup logs as they are generated through the backup progress. The log generation is dynamic, so refresh your browser to view more output.

a. From the Database Control home page: Maintenance > Schedule Backup b. Ensure that Oracle-suggested is selected in the Backup Strategy pull-down list. c. Select Disk as your backup destination, and enter your Host Credentials. d. Click Next. e. The flash recovery area is displayed in the Disk Settings region. f. Click Next. g. Determine your current time zone, choose values for Backup Time that cause the backup to begin the

soonest, then press Next. h. Review your Backup Settings, and press Submit Job. i. When your backup is running, you can click View Job to track the progress of the backup job. j. As your backup progresses, logs are generated. You can click the log name links to view the progress of

the backup job. Refresh your browser to view more output as it is generated.

Page 267: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-87

Practice 12-4 Solution: Using Optimized Incremental Backups Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Run the lab_12_04_01.sql script to create a new user called HR1, using the EXAMPLE

tablespace to store the created tables. Using Database Control, confirm the existence of the following tables:

• BR_JOB_HISTORY • BR_EMPLOYEES • BR_JOBS • BR_DEPARTMENTS • BR_LOCATIONS • BR_COUNTRIES • BR_REGIONS

a. From the Database Control home page: Administration > Schema > Tables b. Type in HR1 in the Schema field and click Go.

2. Run the Oracle Suggested Strategy again by creating a new backup job. Follow the same steps as

in Practice 12-3.

Page 268: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-88

3. View the RMAN job output. From the following region of log, it took only 26 seconds to complete the backup. Backup times will vary from host to host.

Click the Backup link on the Execution page once the operation completed.

4. After the backup job has completed, run the lab_12_04_04.sql script to view the formatted

output of the number of blocks actually backed up. SQL> @lab_12_04_04.sql Connected. FILE# BLOCKS_IN_FILE BLOCKS_READ BLOCKS_BACKED_UP PCT_READ_FOR_BACKUP --------- -------------- ----------- ---------------- ------------------- 1 56320 4480 462 7 2 3840 2688 2408 70 3 49920 16768 4457 33 4 640 64 1 10 5 19200 256 91 1 5 rows selected.

Page 269: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-89

Practice 12-5 Solution: Using Incrementally Updated Backups Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Run the lab_12_05_01.sql script to update the HR1s BR_REGIONS table. SQL> @lab_12_05_01.sql Session altered. Connected. ****** Populating REGIONS table .... 1 row created. 1 row created. 1 row created. 1 row created. Commit complete. SQL> 2. Run the Oracle Suggested Strategy again by creating a new backup job. Follow the same steps as

in Practice 12-3.

Page 270: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-90

3. View the log of the RMAN backup job. You can see that RMAN merges the previous incremental backup into the image copies.

Click the Backup link on the Execution page once the operation completed.

Page 271: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-91

Practice 12-6 Solution: Managing Space in the Flash Recovery Area Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. Determine the current flash recovery area size.

SQL> select * from v$recovery_file_dest; NAME -------------------------------------------------------------------------------- SPACE_LIMIT SPACE_USED SPACE_RECLAIMABLE NUMBER_OF_FILES ----------- ---------- ----------------- --------------- /u01/app/oracle/flash_recovery_area 3221225472 921220096 0 11 1 row selected. SQL>

2. Using Database Control, reduce the size of the flash recovery area so that a warning is issued on

the next backup.

a. From the Database Control home page, select Maintenance > Configure Recovery Settings b. In the Flash Recovery Area Size field, enter a value that is very close to what you see in Used Flash

Recovery Area Size (MB) and click Apply. This value should be close to 1MB. 3. Run the Oracle Suggested Strategy again by creating a new backup job. Follow the same steps as

in Practice 12-3. 4. When there is no more space available in the flash recovery area, the following actions occur:

• The RMAN backup job errors because there is no more space for the backup file. View the EM job output (if possible)

• An error is written to the alert.log. • A row is inserted into the DBA_OUTSTANDING_ALERTS view. Using Database Control, look at the latest entries in the alert.log.

a. From the Home page, in the Related Links section click the Alert Log Content link.

Page 272: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-92

5. Reset the flash recovery area size to 3 GB.

a. From the Database Control home page, select Maintenance > Configure Recovery Settings. b. In Flash Recovery Area Size field, enter 3GB and click Apply.

Page 273: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-93

Practice 12-7 Solution: RMAN Channel Failover Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. Your database must be running in ARCHIVELOG mode for these practices. 1. In this exercise you will simulate a channel failover when using multiple channels and backing

up to tape. From a terminal window, use mkdir to create a temporary directory location for the tape device to act as the pseudo-SBT device type at /home/oracle/tape. Set the RMAN channel configuration by running the lab_12_07_01.sql script. $ . ./sol_12_07_01.sh mkdir /home/oracle/tape Recovery Manager: Release 10.1.0.2.0 - Production Copyright (c) 1995, 2004, Oracle. All rights reserved. connected to target database: ORCL (DBID=1044443119) RMAN> RMAN> using target database controlfile instead of recovery catalog new RMAN configuration parameters: CONFIGURE DEVICE TYPE 'SBT_TAPE' PARALLELISM 2 BACKUP TYPE TO BACKUPSET; new RMAN configuration parameters are successfully stored RMAN> new RMAN configuration parameters: CONFIGURE CHANNEL 2 DEVICE TYPE 'SBT_TAPE' PARMS 'SBT_LIBRARY=oracle.disksbt, ; new RMAN configuration parameters are successfully stored RMAN> new RMAN configuration parameters: CONFIGURE CHANNEL 1 DEVICE TYPE 'SBT_TAPE' PARMS 'SBT_LIBRARY=oracle.disksbt, ; new RMAN configuration parameters are successfully stored RMAN> Recovery Manager complete. $

Page 274: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-94

2. Using Database Control, back up your whole database to tape.

a. From the Database Control home page, select Maintenance > Schedule Backup b. Select Customized from the Backup Strategy drop-down list. c. Select Whole Database. d. Enter your host credentials and click Next. e. On the Schedule Backup: Options, click Next. f. On the Schedule Backup: Settings page, select Tape, then click Next. g. On the Schedule Backup: Schedule page, click Next. h. On the Schedule Backup: Review page, click Submit Job. i. Click View Job to view the job’s progress. j. Click the Backup link on the Execution page once the operation completed.

3. Use Database Control to clean up your environment by:

• Removing the HR1 user • Turning off Archivelog mode • Restarting the Database Console • Remove the /home/oracle/tape directory.

a. From the Database Control home page, select Administration > Security > Users b. Select HR1 from the list of usernames, then press Delete. c. Click Yes at the Confirmation window to delete with the CASCADE option. d. From the Database Control home page, confirm that archiving is Enabled in the High Availability

region. Click the Enabled link. Clear the ARCHIVELOG Mode checkbox and click Apply. If the Archive log field is still disabled on the home page click the Disable link.

e. On the Confirmation page, click the Yes button. f. On the Restart Database: Specify Host and Target Database Credentials page, specify the host and

database credentials. Then click the OK button. g. On the Restart Database: Confirmation page, click the Yes button. h. After a while, click the Refresh button on the Restart Database: Activity Information page. i. From your operating system terminal emulator window, remove the /home/oracle/tape directory.

Page 275: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-95

Practice 13-1 Solution: Flashback Dropped Tables Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Create a new locally managed tablespace called TBSFD containing only one 500 KB file. Also,

TBSFD should use Automatic Segment Space Management. Use either Database Control or command line to create it. If this tablespace already exists in your database, drop it first, including its files.

a. From the Database Control home page: Administration > Tablespaces b. Click the Create option button and specify the Name field. c. Click Add. d. Specify the File Name and File Size fields. The file name can be fd1.dbf . e. Click Continue. f. Click OK.

2. Create a new user called FD, identified by FD, having TBSFD as its default tablespace and TEMP

as its temporary tablespace. Make sure that user FD has the following roles granted: CONNECT, RESOURCE, and DBA. If this user already exists on your system, drop it first.

a. From the Database Control home page:Administration > Users > Create b. On the Create User page, specify the following fields: Name, Enter Password, Confirm

Password, Default Tablespace, Temporary Tablespace. c. Click the Roles tab. d. By default, CONNECT is already associated to the user. e. Click the Modify button. f. On the Modify Roles page, select both RESOURCE and DBA from the Available Roles list. g. When done, click the Move link, and then the OK button. h. After you are returned to the Create User page, click the OK button to create the FD user.

3. Connect as user FD and execute the lab_13_01_03.sql script through SQL*Plus. This script

creates: • Table EMP as a copy of HR.EMPLOYEES • Table DEPT as a copy of HR.DEPARTMENTS • The NOTHING trigger on EMP • The EMP primary key • The DEPT primary key • The EMPFK constraint on EMP that references the DEPT primary key • The EMPFKINDX index on EMPFK • The EMPSALCONS check constraint on EMP • The EMPIDMGRFK self-referencing constraint on EMP • A materialized view log on EMP

Page 276: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-96

connect fd/fd create table emp tablespace tbsfd as select * from hr.employees; create table dept tablespace tbsfd as select * from hr.departments; create or replace trigger nothing before delete or insert or update on emp begin null; end; / alter table emp add constraint emppk primary key(employee_id); alter table dept add constraint deptpk primary key(department_id); alter table emp add constraint empfk foreign key(department_id) references dept(department_id); create index empfkindx on emp(department_id); alter table emp add CONSTRAINT empsalcons CHECK(salary > 0); alter table emp add CONSTRAINT empidmgrfk FOREIGN KEY(manager_id) references emp; CREATE MATERIALIZED VIEW LOG ON emp; 4. Use Database Control to determine the available free space remaining on the TBSFD tablespace.

Connected as FD in SQL*Plus, list the segments and constraints created by user FD. In the report, also include the size of each segment.

a. From the Database Control home page: Administration > Tablespaces b. You should see that TBSFD is 100% full.

Page 277: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-97

5. Using Database Control, drop the EMP table, and look at the FD users recycle bin. What do you observe?

Answer: In addition to EMP, you should now see two indexes and the NOTHING trigger inside the FD recycle bin. Note that the materialized view log is not in the recycle bin. This indicates that it is now definitely lost.

a. From Database Control: Administration > Tables b. On the Tables page, specify FD and EMP in the Schema and Object Name fields, respectively. c. Click the Go button. d. When done, click the Delete button. e. On the Confirmation page, click the Yes button. f. When you are returned to the Tables page, click the Recycle Bin button. g. On the Recycle Bin page, specify FD in the Schema Name field, and then click the Go button. h. You should now see the EMP table in the recycle bin. i. Expand the EMP object by clicking the plus (+) icon.

6. Connect as user FD through SQL*Plus and determine the size of each free extent in the TBSFD

tablespace. What is your conclusion?

Answer: You should observe that you have four extents of eight blocks each. These extents correspond to the EMP table, its associated two indexes, and the materialized view log.

SQL> select blocks from dba_free_space where tablespace_name='TBSFD'; BLOCKS ---------- 8 8 8 8 SQL> 7. Although the EMP table has been dropped, it is still possible to query its content as long as it is

visible from the recycle bin. Query the content of the dropped EMP table using Database Control.

a. From Database Control: Still in the Recycle Bin page, click the View Content button for the corresponding recycle bin row.

b. This brings you to the View Data for Table: FD.BIN$zImvyfFWP8ngNAgAINC/Yg==$0 page where you can see the corresponding rows.

c. On this page you can refine the query by clicking the Refine Query button. d. This allows you to select specific columns and define your WHERE clause. e. Click the OK button.

Page 278: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-98

8. Connect as user FD through SQL*Plus, and list all the objects and constraints that belong to user FD. What are your conclusions?

Answer: You can see that renamed objects still belong to user FD. Also, you definitely lost the two referential constraints defined on EMP, and all the other constraints that were defined on EMP have been renamed as well.

SQL> select object_name, object_type from user_objects; OBJECT_NAME OBJECT_TYPE -------------------------------------------------- ------------------- DEPT TABLE BIN$08bRi60c5DDgMLmLciNQmQ==$0 TABLE BIN$08bRi60b5DDgMLmLciNQmQ==$0 TRIGGER DEPTPK INDEX BIN$08bRi60a5DDgMLmLciNQmQ==$0 INDEX BIN$08bRi60Z5DDgMLmLciNQmQ==$0 INDEX 6 rows selected. SQL> select constraint_name, constraint_type, table_name from user_constraints; CONSTRAINT_NAME C TABLE_NAME ------------------------------ - ------------------------------ BIN$08bRi60Y5DDgMLmLciNQmQ==$0 C BIN$08bRi60c5DDgMLmLciNQmQ==$0 SYS_C007682 C DEPT BIN$08bRi60W5DDgMLmLciNQmQ==$0 C BIN$08bRi60c5DDgMLmLciNQmQ==$0 BIN$08bRi60V5DDgMLmLciNQmQ==$0 C BIN$08bRi60c5DDgMLmLciNQmQ==$0 BIN$08bRi60U5DDgMLmLciNQmQ==$0 C BIN$08bRi60c5DDgMLmLciNQmQ==$0 BIN$08bRi60T5DDgMLmLciNQmQ==$0 C BIN$08bRi60c5DDgMLmLciNQmQ==$0 DEPTPK P DEPT BIN$08bRi60X5DDgMLmLciNQmQ==$0 P BIN$08bRi60c5DDgMLmLciNQmQ==$0 8 rows selected. SQL> 9. Using Database Control, flashback the dropped table.

a. Still in the Recycle Bin page, select the EMP recycle bin object, and click the Flashback Drop button. b. This brings you to the Perform Recovery: Rename page where you can change the original name to

something different in case you created another EMP table after dropping the original one. c. Leave the original name, and click the Next button. d. On the Perform Recovery: Review page, click the Submit button. e. On the Confirmation page, click the OK button. f. This returns you to the Recycle Bin page, which is now empty.

10. Connect as user FD through SQL*Plus, query the EMP table, and list the available free space in

tablespace TBSFD. What are your conclusions?

Page 279: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-99

Answer: You can now see that the EMP table has been flashed back. There is only one free extent remaining in TBSFD. This extent corresponds to the materialized view log that was definitely dropped, and which could not be flashed back.

SQL> select * from emp; … WGIETZ 515.123.8181 07-JUN-94 AC_ACCOUNT 8300 205 110 EMPLOYEE_ID FIRST_NAME LAST_NAME ----------- -------------------- ------------------------- EMAIL PHONE_NUMBER HIRE_DATE JOB_ID SALARY ------------------------- -------------------- --------- ---------- ---------- COMMISSION_PCT MANAGER_ID DEPARTMENT_ID -------------- ---------- ------------- 107 rows selected. SQL> SQL> select blocks from dba_free_space where tablespace_name='TBSFD'; BLOCKS ---------- 8 SQL> 11. Connect as user FD through SQL*Plus and create a new table DEPT2 as a copy of

HR.DEPARTMENTS. Make sure that DEPT2 resides in TBSFD. When done, drop the table EMP again, and create a new table EMP2 as a copy of HR.EMPLOYEES. Make sure that EMP2 is stored in TBSFD. When done, try to flash back the dropped EMP table. What happens and why?

Answer: The flashback command returns an ORA-38305: object not in RECYCLE BIN error stating that EMP is not in the recycle bin. In fact, when you created DEPT2 you used the last available free extent. When EMP was dropped again, three new free extents were made available. Because one of these extents was used to create EMP2, the EMP table was purged from the recycle bin due to the space pressure.

SQL> create table dept2 tablespace tbsfd as select * from hr.departments; Table created. SQL> drop table emp; Table dropped.

Page 280: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-100

SQL> create table emp2 tablespace tbsfd as select * from hr.employees; Table created. SQL> flashback table FD.EMP to before drop; flashback table FD.EMP to before drop * ERROR at line 1: ORA-38305: object not in RECYCLE BIN SQL> 12. Using Database Control, drop the DEPT2 table and purge the corresponding entry in the FD

recycle bin.

a. From the Database Control home page: Administration > Tables b. On the Tables page, specify FD in the Schema field, and click the Go button. c. Select the DEPT2 entry from the Results table, and click the Delete button. d. On the Confirmation page, click the Yes button. e. After you are returned to the Tables page, click the Recycle Bin button. f. In the Recycle Bin page, specify FD in the Schema Name field, and then click the Go button. g. Select the DEPT2 object from the Results table. h. When done, click the Purge button. i. On the Purge page, click the Yes button.

13. Connected as SYSDBA through SQL*Plus, execute the lab_13_01_13.sql script to clean up

the environment. -- Cleanup connect / as sysdba drop user fd cascade; drop tablespace tbsfd including contents and datafiles;

Page 281: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-101

Practice 13-2 Solution: Flashback Database Unless specified otherwise, you should be logging in as SYSDBA through either SQL*Plus or Database Control. 1. Connected as SYSDBA through SQL*Plus, execute the lab_13_02_01.sql script. This script

creates a new user called JFV identified by JFV, and also creates a new tablespace called JFVTBS.

SQL> connect / as sysdba Connected. SQL> SQL> drop user jfv cascade; drop user jfv cascade * ERROR at line 1: ORA-01918: user 'JFV' does not exist SQL> drop tablespace jfvtbs including contents and datafiles; drop tablespace jfvtbs including contents and datafiles * ERROR at line 1: ORA-00959: tablespace 'JFVTBS' does not exist SQL> create smallfile tablespace jfvtbs 2 datafile 'jfvtbs1.dbf' size 500K 3 logging 4 extent management local 5 segment space management auto; Tablespace created. SQL> create user jfv identified by jfv 2 default tablespace jfvtbs 3 temporary tablespace temp; User created. SQL> grant connect, resource, dba to jfv; Grant succeeded. SQL>

Page 282: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-102

2. Using SQ*Plus, determine the list of processes associated to your instance. Then check that your database is in NOARCHIVELOG mode, and that it does not use flashback logging. List the content of your flash recovery area.

SQL> host ps -ef | grep orcl oracle 19563 1 0 05:31 ? 00:00:00 ora_pmon_orcl oracle 19565 1 0 05:31 ? 00:00:00 ora_mman_orcl oracle 19567 1 0 05:31 ? 00:00:00 ora_dbw0_orcl oracle 19569 1 0 05:31 ? 00:00:00 ora_lgwr_orcl oracle 19571 1 0 05:31 ? 00:00:00 ora_ckpt_orcl oracle 19573 1 0 05:31 ? 00:00:00 ora_smon_orcl oracle 19575 1 0 05:31 ? 00:00:00 ora_reco_orcl oracle 19579 1 0 05:31 ? 00:00:00 ora_cjq0_orcl oracle 19581 1 0 05:31 ? 00:00:00 ora_d000_orcl oracle 19583 1 0 05:31 ? 00:00:00 ora_s000_orcl oracle 19601 1 0 05:31 ? 00:00:00 ora_qmnc_orcl oracle 19608 1 0 05:31 ? 00:00:00 ora_mmon_orcl oracle 19610 1 0 05:31 ? 00:00:00 ora_mmnl_orcl oracle 19812 1 0 05:34 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 19817 1 2 05:34 ? 00:00:08 oracleorcl (LOCAL=NO) oracle 19819 1 1 05:34 ? 00:00:05 oracleorcl (LOCAL=NO) oracle 19821 1 0 05:34 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 19826 1 0 05:34 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 19830 1 0 05:34 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 19837 1 0 05:34 ? 00:00:01 oracleorcl (LOCAL=NO) oracle 19850 1 0 05:34 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 19852 1 0 05:34 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 20502 1 0 05:35 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 20504 1 2 05:35 ? 00:00:06 oracleorcl (LOCAL=NO) oracle 20514 1 1 05:35 ? 00:00:03 oracleorcl (LOCAL=NO) oracle 20545 1 0 05:35 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 20857 1 0 05:36 ? 00:00:00 oracleorcl (DESCRIPTION=(LOCAL=Y oracle 20859 1 0 05:37 ? 00:00:00 ora_q000_orcl oracle 20952 20852 0 05:40 pts/1 00:00:00 /bin/bash -c ps -ef | grep orcl oracle 20954 20952 0 05:40 pts/1 00:00:00 grep orcl SQL> SQL> archive log list Database log mode No Archive Mode Automatic archival Disabled Archive destination USE_DB_RECOVERY_FILE_DEST Oldest online log sequence 78 Current log sequence 80 SQL> SQL> select flashback_on from v$database; FLA --- NO SQL> SQL> host ls -lr $ORACLE_BASE/flash_recovery_area/* drwxr-x--- 2 oracle oinstall 4096 Feb 5 12:42 datafile drwxr-x--- 3 oracle oinstall 4096 Feb 5 12:42 backupset drwxr-x--- 3 oracle oinstall 4096 Feb 5 12:22 archivelog

Page 283: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-103

3. Using Database Control, enable both ARCHIVELOG mode and flashback logging.

a. From the Database Control home page, click the Maintenance tab. b. On the Maintenance page, click the Configure Recovery Settings link. c. On the Configure Recovery Settings page, select the ARCHIVELOG Mode checkbox and the Enable

flashback logging for fast database point-in-time recovery checkbox. d. When done, click the Apply button. e. On the Confirmation page, click the Yes button. f. On the Restart Database: Specify Host and Target Database Credentials page, specify the host and

database credentials. Then click the OK button. g. On the Restart Database: Confirmation page, click the Yes button. h. After a while, click the Refresh button on the Restart Database: Activity Information page.

4. Using SQL*Plus, determine the list of processes associated to your instance. Then check that

your database is in ARCHIVELOG mode, and that it uses flashback logging. List the content of your flash recovery area. What are your conclusions?

Answer: Because your database is now using flashback logging, you can see that the RVWR process is started. Also, one file has already been created by the RVWR process.

SQL> connect / as sysdba Connected. SQL> host ps -ef | grep orcl oracle 21389 1 0 05:54 ? 00:00:00 ora_pmon_orcl oracle 21391 1 0 05:54 ? 00:00:00 ora_mman_orcl oracle 21393 1 0 05:54 ? 00:00:00 ora_dbw0_orcl oracle 21404 1 0 05:54 ? 00:00:00 ora_lgwr_orcl oracle 21406 1 0 05:54 ? 00:00:00 ora_ckpt_orcl oracle 21408 1 0 05:54 ? 00:00:00 ora_smon_orcl oracle 21410 1 0 05:54 ? 00:00:00 ora_reco_orcl oracle 21412 1 0 05:54 ? 00:00:00 ora_cjq0_orcl oracle 21414 1 0 05:54 ? 00:00:00 ora_d000_orcl oracle 21416 1 0 05:54 ? 00:00:00 ora_s000_orcl oracle 21435 1 0 05:54 ? 00:00:00 ora_rvwr_orcl oracle 21437 1 0 05:54 ? 00:00:00 ora_arc0_orcl oracle 21439 1 0 05:54 ? 00:00:00 ora_arc1_orcl oracle 21443 1 0 05:54 ? 00:00:00 ora_qmnc_orcl oracle 21447 1 0 05:54 ? 00:00:01 ora_mmon_orcl oracle 21449 1 0 05:54 ? 00:00:00 ora_mmnl_orcl oracle 21739 1 0 05:57 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 21744 1 1 05:57 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 21746 1 0 05:57 ? 00:00:01 oracleorcl (LOCAL=NO) oracle 21748 1 0 05:57 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 21753 1 0 05:57 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 21760 1 0 05:57 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 21766 1 0 05:57 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 22464 1 0 05:58 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 22469 1 4 05:58 ? 00:00:04 oracleorcl (LOCAL=NO) oracle 22485 1 1 05:58 ? 00:00:01 oracleorcl (LOCAL=NO) oracle 22495 1 2 05:58 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 22799 1 0 05:59 ? 00:00:00 oracleorcl (DESCRIPTION=(LOCAL=Y oracle 22808 1 99 06:00 ? 00:00:01 ora_j000_orcl oracle 22810 1 2 06:00 ? 00:00:00 ora_j001_orcl

Page 284: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-104

oracle 22811 22795 0 06:00 pts/1 00:00:00 /bin/bash -c ps -ef | grep orcl oracle 22813 22811 0 06:00 pts/1 00:00:00 grep orcl SQL> archive log list Database log mode Archive Mode Automatic archival Enabled Archive destination USE_DB_RECOVERY_FILE_DEST Oldest online log sequence 79 Next log sequence to archive 81 Current log sequence 81 SQL> select flashback_on from v$database; FLA --- YES SQL> host ls -l $ORACLE_BASE/flash_recovery_area/ORCL*/flashback total 8020 -rw-r----- 1 oracle oinstall 8200192 Feb 6 02:16 o1_mf_026snyso_.flb SQL> 5. Connected as user JFV under SQL*Plus, execute the lab_13_02_05.sql script. This script

creates a new table called EMP. It also selects the sum of all the salaries of the EMP table. Then the script returns the current SCN of your database, and it looks at the contents of V$UNDOSTAT, V$FLASHBACK_DATABASE_LOG, and V$FLASHBACK_DATABASE_STAT. Write down the information provided by lab_13_02_05.sql.

SQL> connect jfv/jfv Connected. SQL> create table emp 2 tablespace jfvtbs 3 as select * from hr.employees; Table created. SQL> select sum(salary) from emp; SUM(SALARY) ----------- 691400 SQL> -- scn2 SQL> select current_scn from v$database; CURRENT_SCN ----------- 518159 SQL> select undoblks from v$undostat; UNDOBLKS ---------- 0

Page 285: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-105

108 187 SQL> select * from V$FLASHBACK_DATABASE_LOG; OLDEST_FLASHBACK_SCN OLDEST_FL RETENTION_TARGET FLASHBACK_SIZE -------------------- --------- ---------------- -------------- ESTIMATED_FLASHBACK_SIZE ------------------------ 1031015 15-DEC-03 1440 14147584 623149056 SQL> select * from V$FLASHBACK_DATABASE_STAT; BEGIN_TIM END_TIME FLASHBACK_DATA DB_DATA REDO_DATA --------- --------- -------------- ---------- ---------- ESTIMATED_FLASHBACK_SIZE ------------------------ 15-DEC-03 15-DEC-03 8806400 8871936 5928448 0 SQL> 6. Connected as user JFV under SQL*Plus, repeat the execution of the lab_13_02_06.sql

script three times. What are your conclusions?

Answer: Because the script modifies the same blocks, the overhead of flashback logging is less during the second and third executions.

SQL> connect jfv/jfv Connected. SQL> begin 2 for i in 1..10000 loop 3 update emp set salary=salary+1; 4 end loop; 5 commit; 6 end; 7 / PL/SQL procedure successfully completed. SQL> select undoblks from v$undostat; UNDOBLKS ---------- 6250 108 187 SQL> select * from V$FLASHBACK_DATABASE_LOG; OLDEST_FLASHBACK_SCN OLDEST_FL RETENTION_TARGET FLASHBACK_SIZE -------------------- --------- ---------------- -------------- ESTIMATED_FLASHBACK_SIZE

Page 286: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-106

------------------------ 1031015 15-DEC-03 1440 59858944 2979028992 SQL> select * from V$FLASHBACK_DATABASE_STAT; BEGIN_TIM END_TIME FLASHBACK_DATA DB_DATA REDO_DATA --------- --------- -------------- ---------- ---------- ESTIMATED_FLASHBACK_SIZE ------------------------ 15-DEC-03 15-DEC-03 53141504 58384384 112099840 0 SQL> host ls -l $ORACLE_BASE/flash_recovery_area/ORCL*/flashback total 58596 -rw-r----- 1 oracle oinstall 8200192 Dec 15 06:10 o1_mf_zxvh8yyt_.flb -rw-r----- 1 oracle oinstall 5963776 Dec 15 06:19 o1_mf_zxvj5yt9_.flb -rw-r----- 1 oracle oinstall 6389760 Dec 15 06:19 o1_mf_zxvjqnjk_.flb -rw-r----- 1 oracle oinstall 9240576 Dec 15 06:19 o1_mf_zxvjqtr3_.flb -rw-r----- 1 oracle oinstall 13328384 Dec 15 06:19 o1_mf_zxvjr1wp_.flb -rw-r----- 1 oracle oinstall 16785408 Dec 15 06:20 o1_mf_zxvjrd3r_.flb SQL> SQL> begin 2 for i in 1..10000 loop 3 update emp set salary=salary+1; 4 end loop; 5 commit; 6 end; 7 / PL/SQL procedure successfully completed. SQL> select undoblks from v$undostat; UNDOBLKS ---------- 12429 108 187 SQL> select * from V$FLASHBACK_DATABASE_LOG; OLDEST_FLASHBACK_SCN OLDEST_FL RETENTION_TARGET FLASHBACK_SIZE -------------------- --------- ---------------- -------------- ESTIMATED_FLASHBACK_SIZE ------------------------ 1031015 15-DEC-03 1440 59858944 2845999104 SQL> select * from V$FLASHBACK_DATABASE_STAT; BEGIN_TIM END_TIME FLASHBACK_DATA DB_DATA REDO_DATA --------- --------- -------------- ---------- ---------- ESTIMATED_FLASHBACK_SIZE ------------------------ 15-DEC-03 15-DEC-03 54910976 110493696 217976320

Page 287: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-107

0 SQL> host ls -l $ORACLE_BASE/flash_recovery_area/ORCL*/flashback total 58596 -rw-r----- 1 oracle oinstall 8200192 Dec 15 06:10 o1_mf_zxvh8yyt_.flb -rw-r----- 1 oracle oinstall 5963776 Dec 15 06:19 o1_mf_zxvj5yt9_.flb -rw-r----- 1 oracle oinstall 6389760 Dec 15 06:19 o1_mf_zxvjqnjk_.flb -rw-r----- 1 oracle oinstall 9240576 Dec 15 06:19 o1_mf_zxvjqtr3_.flb -rw-r----- 1 oracle oinstall 13328384 Dec 15 06:19 o1_mf_zxvjr1wp_.flb -rw-r----- 1 oracle oinstall 16785408 Dec 15 06:22 o1_mf_zxvjrd3r_.flb SQL> SQL> begin 2 for i in 1..10000 loop 3 update emp set salary=salary+1; 4 end loop; 5 commit; 6 end; 7 / PL/SQL procedure successfully completed. SQL> select undoblks from v$undostat; UNDOBLKS ---------- 18604 108 187 SQL> select * from V$FLASHBACK_DATABASE_LOG; OLDEST_FLASHBACK_SCN OLDEST_FL RETENTION_TARGET FLASHBACK_SIZE -------------------- --------- ---------------- -------------- ESTIMATED_FLASHBACK_SIZE ------------------------ 1031015 15-DEC-03 1440 59858944 2700460032 SQL> select * from V$FLASHBACK_DATABASE_STAT; BEGIN_TIM END_TIME FLASHBACK_DATA DB_DATA REDO_DATA --------- --------- -------------- ---------- ---------- ESTIMATED_FLASHBACK_SIZE ------------------------ 15-DEC-03 15-DEC-03 55353344 162258944 323805184 0 SQL> host ls -l $ORACLE_BASE/flash_recovery_area/ORCL*/flashback total 58596 -rw-r----- 1 oracle oinstall 8200192 Dec 15 06:10 o1_mf_zxvh8yyt_.flb -rw-r----- 1 oracle oinstall 5963776 Dec 15 06:19 o1_mf_zxvj5yt9_.flb -rw-r----- 1 oracle oinstall 6389760 Dec 15 06:19 o1_mf_zxvjqnjk_.flb -rw-r----- 1 oracle oinstall 9240576 Dec 15 06:19 o1_mf_zxvjqtr3_.flb -rw-r----- 1 oracle oinstall 13328384 Dec 15 06:19 o1_mf_zxvjr1wp_.flb -rw-r----- 1 oracle oinstall 16785408 Dec 15 06:23 o1_mf_zxvjrd3r_.flb

Page 288: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-108

SQL> 7. Connected as user JFV under SQL*Plus, create a new tablespace called JFVTBS2. This

tablespace should have only one 500 KB data file. When done, disable flashback logging on JFVTBS2. Then check that flashback logging is not enabled on JFVTBS2.

SQL> connect jfv/jfv Connected. SQL> create smallfile tablespace jfvtbs2 2 datafile 'jfvtbs2.dbf' size 500K 3 logging 4 extent management local 5 segment space management auto; Tablespace created. SQL> alter tablespace jfvtbs2 flashback off; Tablespace altered. SQL> select name,flashback_on from v$tablespace; NAME FLA ------------------------------ --- SYSTEM YES UNDOTBS1 YES SYSAUX YES USERS YES TEMP YES EXAMPLE YES JFVTBS YES JFVTBS2 NO 8 rows selected. SQL>

Page 289: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-109

8. Connected as user JFV under SQL*Plus, execute the lab_13_02_08.sql script. This script creates a new table called EMP2 inside tablespace JFVTBS2. The script also returns the flashback statistics and then executes a long running update of the EMP2 table. In the end, the script shows you again the flashback statistics. What are your conclusions?

Answer: Because the table blocks that are modified are located in a tablespace that does not log flashback data, you should not see a significant increase in the FLASHBACK_DATA statistic. However, if you notice an important increase similar to that shown in this solution, this is due to the corresponding rollback data that are still logged. If you do not see a significant increase, this is probably because the same rollback segment blocks were reused again.

SQL> connect jfv/jfv Connected. SQL> create table emp2 2 tablespace jfvtbs2 3 as select * from hr.employees; Table created. SQL> select * from V$FLASHBACK_DATABASE_STAT; BEGIN_TIM END_TIME FLASHBACK_DATA DB_DATA REDO_DATA --------- --------- -------------- ---------- ---------- ESTIMATED_FLASHBACK_SIZE ------------------------ 15-DEC-03 15-DEC-03 66068480 188989440 346866688 0 SQL> select undoblks from v$undostat; UNDOBLKS ---------- 5 1396 18636 108 187 SQL> begin 2 for i in 1..10000 loop 3 update emp2 set salary=salary+1; 4 end loop; 5 commit; 6 end; 7 / PL/SQL procedure successfully completed. SQL> select undoblks from v$undostat; UNDOBLKS ---------- 6172 1396 18636 108

Page 290: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-110

187 SQL> select * from V$FLASHBACK_DATABASE_STAT; BEGIN_TIM END_TIME FLASHBACK_DATA DB_DATA REDO_DATA --------- --------- -------------- ---------- ---------- ESTIMATED_FLASHBACK_SIZE ------------------------ 15-DEC-03 15-DEC-03 115720192 236994560 451949056 0 SQL> 9. Connected as user JFV under SQL*Plus, execute the lab_13_02_09.sql script. Write down

the information returned by this script. SQL> connect jfv/jfv Connected. SQL> select sum(salary) from emp; SUM(SALARY) ----------- 3901400 SQL> -- scn1 SQL> select current_scn from v$database; CURRENT_SCN ----------- 604083 SQL> insert into emp select * from emp; 107 rows created. SQL> commit; Commit complete. SQL> select sum(salary) from emp; SUM(SALARY) ----------- 7802800 SQL>

Page 291: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-111

10. Connected as SYSDBA under SQL*Plus try to recover your database to the SCN calculated during step 9. What happens and why?

Answer: It is not possible to flash back this database because one of its data files did not log its modifications.

SQL> set echo on SQL> @sol_13_02_10.sql SQL> SQL> connect / as sysdba Connected. SQL> SQL> shutdown immediate; Database closed. Database dismounted. ORACLE instance shut down. SQL> SQL> startup mount; ORACLE instance started. Total System Global Area 171966464 bytes Fixed Size 777956 bytes Variable Size 145760540 bytes Database Buffers 25165824 bytes Redo Buffers 262144 bytes Database mounted. SQL> SQL> -- scn1 SQL> flashback database to scn &scn; Enter value for scn: 604083 old 1: flashback database to scn &scn new 1: flashback database to scn 604083 flashback database to scn 604083 * ERROR at line 1: ORA-38753: Cannot flashback data file 7; no flashback log data. ORA-01110: data file 7: '/u01/app/oracle/product/10.1.0/db_1/dbs/jfvtbs2.dbf' SQL> 11. Using SQL*Plus, fix the problem, and redo step 10. When done, open your database in READ

ONLY mode, and check the result of your flashback database operation. Then, shutdown and startup mount your instance.

SQL> @sol_13_02_11.sql SQL> SQL> connect / as sysdba Connected. SQL> SQL> select name from v$datafile; NAME -----------------------------------------------------------------------------

Page 292: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-112

--- /u01/app/oracle/oradata/orcl/system01.dbf /u01/app/oracle/oradata/orcl/undotbs01.dbf /u01/app/oracle/oradata/orcl/sysaux01.dbf /u01/app/oracle/oradata/orcl/users01.dbf /u01/app/oracle/oradata/orcl/example01.dbf /u01/app/oracle/product/10.1.0/db_1/dbs/jfvtbs1.dbf /u01/app/oracle/product/10.1.0/db_1/dbs/jfvtbs2.dbf 7 rows selected. SQL> SQL> alter database 2 datafile '/u01/app/oracle/product/10.1.0/db_1/dbs/jfvtbs2.dbf' offline for; Database altered. SQL> SQL> -- scn1 SQL> flashback database to scn &scn; Enter value for scn: 604083 old 1: flashback database to scn &scn new 1: flashback database to scn 604083 Flashback complete. SQL> SQL> alter database open read only; Database altered. SQL> SQL> select count(*) from jfv.emp; COUNT(*) ---------- 107 SQL> SQL> select sum(salary) from jfv.emp; SUM(SALARY) ----------- 3901400 SQL> SQL> shutdown immediate; Database closed. Database dismounted. ORACLE instance shut down. SQL> startup mount; ORACLE instance started. Total System Global Area 171966464 bytes Fixed Size 777956 bytes Variable Size 145760540 bytes Database Buffers 25165824 bytes Redo Buffers 262144 bytes

Page 293: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-113

Database mounted. SQL> 12. Connected as SYSDBA under SQL*Plus, flashback your database to the SCN returned in step 5.

Then open your database in READ WRITE mode, and check your database. What is your conclusion?

Answer: The JFVTBS2 tablespace is now gone, including its data file.

SQL> set echo on SQL> SQL> connect / as sysdba Connected. SQL> SQL> -- scn 2 SQL> flashback database to scn &scn; Enter value for scn: 518159 old 1: flashback database to scn &scn new 1: flashback database to scn 518159 Flashback complete. SQL> alter database open resetlogs; Database altered. SQL> select tablespace_name from dba_tablespaces; TABLESPACE_NAME ------------------------------ SYSTEM UNDOTBS1 SYSAUX TEMP USERS EXAMPLE JFVTBS 7 rows selected. SQL> select count(*) from jfv.emp; COUNT(*) ---------- 107 SQL> select sum(salary) from jfv.emp; SUM(SALARY) ----------- 691400 SQL> 13. Still connected as SYSDBA under SQL*Plus, clean up your environment by doing the following:

• Drop the JFVTBS tablespace including its data file.

Page 294: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-114

• Drop user JFV. • Disable flashback logging • Return to NOARCHIVELOG mode.

SQL> connect / as sysdba Connected. SQL> drop tablespace jfvtbs including contents and datafiles; Tablespace dropped. SQL> drop user jfv cascade; User dropped. SQL> shutdown immediate; Database closed. Database dismounted. ORACLE instance shut down. SQL> startup mount ORACLE instance started. Total System Global Area 171966464 bytes Fixed Size 775608 bytes Variable Size 145762888 bytes Database Buffers 25165824 bytes Redo Buffers 262144 bytes Database mounted. SQL> alter database flashback off; Database altered. SQL> alter database noarchivelog; Database altered. SQL> alter database open; Database altered. SQL>

Page 295: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-115

Practice 14-1 Solution: Using The Redo Log File Size Advisor Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Execute the lab_14_01_01.sql script to create a new table that will be used to generate a

workload on your instance. connect / as sysdba exec DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS(10080,0); drop tablespace tbs_lfszadv including contents and datafiles; create tablespace tbs_lfszadv datafile 'lfszadvA.dbf' size 50m; drop table t_lfszadv purge; create table t_lfszadv (c1 number, c2 char(1), c3 char(1), c4 char(1), c5 char(1000)) tablespace tbs_lfszadv pctfree 0 storage (initial 4M next 2M pctincrease 0); begin for i in 1 .. 10000 loop insert into t_lfszadv values (i, 'a', 'a', 'a', NULL); end loop; commit; end; / 2. Use Database Control to shut down your instance, and start it up again using the

init_lfszadv.ora initialization parameter file located in your labs directory. Before doing this, make sure that the init_lfszadv.ora parameter file can be used to start up your instance.

a. From the Database Control home page, click the Shutdown button. b. On the Startup/Shutdown: Specify Host and Target Database Credentials page, specify the necessary

credentials and make sure that you save them to disk. c. Click the OK button. d. On the Startup/Shutdown: Confirmation page click the Yes button. e. After a while, click the Refresh button on the Startup/Shutdown: Activity Information page. f. On the Database: orcl page, click the Startup button. g. If necessary, specify all the required credentials on the Startup/Shutdown: Specify Host and Target

Database Credentials page, and then click the OK button. h. On the Startup/Shutdown: Confirmation page, click the Advanced Options button. i. On the Startup/Shutdown: Advanced Startup Options page, make sure that you select the Specify

parameter file (pfile) on the database server machine option button, and specify the location and name of the parameter file you want to use. Then click the OK button.

Page 296: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-116

j. After you are returned to the Startup/Shutdown: Confirmation page, click the Yes button. k. On the Login to Database:orcl page, specify your SYSDBA credentials, and then click the Login button.

3. Execute the lab_14_01_03.sql script. This script updates the previously defined

T_LFSZADV table. This is done to generate a workload on your instance. begin update t_lfszadv set c5='1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111' where mod(c1,1)=0; commit; end; / 4. When done, determine the size advice for your redo log groups using Database Control.

a. From the Database Control home page: Click the Administration tab. b. On the Administration tab, click the Redo Log Groups link. c. On the Redo Log Groups page, you can see that the size of each group is 10 MB. d. Still on the Redo Log Groups page, select Sizing Advice in the Actions drop-down list. e. Click the Go button. f. In the Update Message region of the Redo Log Groups page, you should now see the recommended

optimal redo log file size of approximiately 50 MB. Note that, depending on the background activity, the size may be more but it should be between 49 MB and 60 MB.

5. Implement the recommendation by adding two new redo log groups of 50 MB, and by dropping

the existing redo log groups.

a. On the Redo Log Groups page, click the Create button. b. On the Create Redo Log Group page, specify the new recommended size of 50 MB for the new group. c. Click the OK button. d. After you are returned to the Redo Log Groups page, perform the same steps again to add another group

of the recommended size of 50 MB. e. Remember the name and location of the original group members, and drop them. f. Before dropping a group, make sure that it is inactive. You can see the group’s status from the Redo Log

Groups page. g. Select an Inactive group, and click the Delete button. h. On the Confirmation page, click the Yes button. i. Repeat this until you have dropped all the original groups. j. If one group is shown as Current, or Active, you can make it inactive by forcing a log switch or a log

checkpoint. You can do so by selecting either Force checkpoint or Switch logfile from the Actions drop-down list, and then click the Go button.

6. Redo steps 1 and 2.

Page 297: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-117

connect / as sysdba exec DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS(10080,0); drop tablespace tbs_lfszadv including contents and datafiles; create tablespace tbs_lfszadv datafile 'lfszadvA.dbf' size 50m; drop table t_lfszadv purge; create table t_lfszadv (c1 number, c2 char(1), c3 char(1), c4 char(1), c5 char(1000)) tablespace tbs_lfszadv pctfree 0 storage (initial 4M next 2M pctincrease 0); begin for i in 1 .. 10000 loop insert into t_lfszadv values (i, 'a', 'a', 'a', NULL); end loop; commit; end; /

a. From the Database Control home page, click the Shutdown button. b. On the Startup/Shutdown: Specify Host and Target Database Credentials page, specify the necessary

credentials and make sure that you save them to disk. c. Click the OK button. d. On the Startup/Shutdown: Confirmation page click the Yes button. e. After a while, click the Refresh button on the Startup/Shutdown: Activity Information page. f. On the Database: orcl page, click the Startup button. g. If necessary, specify all the required credentials on the Startup/Shutdown: Specify Host and Target

Database Credentials page, and then click the OK button. h. On the Startup/Shutdown: Confirmation page, click the Advanced Options button. i. On the Startup/Shutdown: Advanced Startup Options page, make sure that you select the Specify

parameter file (pfile) on the database server machine option button and specify the location and name of the parameter file you want to use. Then click the OK button.

j. After you are returned to the Startup/Shutdown: Confirmation page, click the Yes button. k. On the Login to Database: orcl page, specify your SYSDBA credentials, and then click the Login button.

Page 298: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-118

7. Redo steps 3 and 4. What are your conclusions?

Answer: After you ran the workload again, you should see that the size advice is identical to the one provided in step 4. However, because there may be some background activity, it is possible that the recommendation is different. However, there should not be a big difference, and it should be between 49 MB and 60 MB.

begin update t_lfszadv set c5='1111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111111' where mod(c1,1)=0; commit; end; /

a. From the Database Control home page: Click the Administration tab. b. On the Administration tab, click the Redo Log Groups link. c. On the Redo Log Groups page, you can see that the size of each group is 50 MB. d. Still on the Redo Log Groups page, select Sizing Advice in the Actions drop-down list. e. Click the Go button. f. In the Update Message region of the Redo Log Groups page, you should now see the recommended

optimal redo log file size of approximately 50 MB. Note that, depending on the background activity, the size may be more but it should be between 49 MB and 60 MB.

8. To clean up the environment, log out from any session that you created so far and connect as

SYSDBA through SQL*Plus. Then execute the lab_14_01_08.sql script. connect / as sysdba exec DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS(10080,30); drop tablespace tbs_lfszadv including contents and datafiles; alter database add logfile group 1 '/u01/app/oracle/oradata/orcl/redo01.log' size 10m reuse; alter database add logfile group 2 '/u01/app/oracle/oradata/orcl/redo02.log' size 10m reuse; alter database add logfile group 3 '/u01/app/oracle/oradata/orcl/redo03.log' size 10m reuse; alter system switch logfile; alter system checkpoint; alter database drop logfile group 4; alter system switch logfile;

Page 299: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-119

alter system checkpoint; alter database drop logfile group 5; host rm /u01/app/oracle/oradata/orcl/redo4.log host rm /u01/app/oracle/oradata/orcl/redo5.log shutdown immediate; startup;

Page 300: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-120

Practice 15-1 Solution: Setting Up an ASM Instance Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Use DBCA to create the ASM instance on your machine. During the ASM instance creation,

DBCA asks you whether you want to change the default values for the ASM initialization parameter. Make sure that the disk discovery string is set to /u02/asmdisks/*. Then DBCA asks you to create new disk groups. Create one disk group called DGROUP1 that is using the following four ASM disks: • /u02/asmdisks/disk0 • /u02/asmdisks/disk1 • /u02/asmdisks/disk2 • /u02/asmdisks/disk3 Make sure to specify that DGROUP1 is using external redundancy. After the ASM instance and the disk group are created, you can exit DBCA. Do not create a database.

a. $ dbca

b. On the Welcome page, click the Next button.

Page 301: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-121

c. On the Operations page, select the Create Database option button. d. Click the Next button.

Page 302: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-122

e. On the Database Templates page, select the General Purpose option button. f. Click the Next button.

Page 303: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-123

g. On the Database Identification page, specify a Global Database Name. For example:

jfv1.us.oracle.com. h. Click the Next button.

Page 304: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-124

i. On the Management Options page, make sure the Configure the Database with Enterprise Manager checkbox is selected.

j. Click the Next button.

Page 305: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-125

k. On the Database Credentials page, make sure that the Use the Same Password for All Accounts option button is selected. Then specify a Password.

l. Click the Next button.

Page 306: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-126

m. On the Storage Options page, make sure that the Automatic Storage Management (ASM) option button is selected.

n. Click the Next button.

Page 307: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-127

o. Because there is currently no ASM instance on your system, DBCA will create one automatically. p. On the Create ASM Instance page, specify the SYS password for your ASM instance. q. Click the ASM Parameters button.

Page 308: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-128

r. In the ASM Parameters dialog box, make sure that the asm_diskstring field is set to /u02/asmdisks/* After setting asm_diskstring click in the Override Default field to get the tick sign.

s. Click the Close button and then Next.

Page 309: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-129

t. In the Database Configuration Assistant dialog box, click the OK button.

Page 310: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-130

u. On the ASM Disk Groups page, click the Create New button.

Page 311: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-131

v. In the Create Disk Group dialog box, specify DGROUP1 in the Disk Group Name field. Then make sure that the External option button is selected.

w. When done, select all CANDIDATE disks from the Select Member Disks array. x. Click the OK button.

Page 312: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-132

y. The disk group creation may take a while to complete.

Page 313: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-133

z. After the disk group is created, aa. Select DGROUP1. bb. Click the Next button.

Page 314: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-134

cc. On the Database File Locations page, click the Cancel button. dd. Exit DBCA.

Page 315: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-135

Practice 15-2 Solution: Understanding ASM Automatic Rebalancing 1. Connected as user oracle in your terminal emulator window, start your ASM instance and list

the processes associated to it. Then determine the characteristics of: • The mounted disk groups • The associated ASM disks • The associated ASM files

$ ORACLE_SID=+ASM $ export ORACLE_SID $ echo $ORACLE_SID +ASM $ sqlplus / as sysdba SQL*Plus: Release 10.1.0.2.0 - Production on Fri Dec 19 02:04:11 2003 Copyright (c) 1982, 2003, Oracle. All rights reserved. Connected to an idle instance. SQL> @sol_15_02_01.sql SQL> SQL> startup ASM instance started Total System Global Area 100663296 bytes Fixed Size 783672 bytes Variable Size 99879624 bytes Database Buffers 0 bytes Redo Buffers 0 bytes ASM diskgroups mounted SQL> host ps -ef | grep ASM oracle 2701 1 0 02:04:19 ? 0:00 asm_mman_+ASM oracle 2699 1 0 02:04:19 ? 0:00 asm_pmon_+ASM oracle 2711 1 0 02:04:20 ? 0:00 asm_rbal_+ASM oracle 2747 2696 0 02:20:53 pts/4 0:00 grep ASM oracle 2705 1 0 02:04:19 ? 0:00 asm_lgwr_+ASM oracle 2724 1 0 02:05:50 ? 0:00 oracle+ASM (DESCRIPTION=(LOCAL=Y) oracle 2707 1 0 02:04:19 ? 0:00 asm_ckpt_+ASM oracle 2703 1 0 02:04:19 ? 0:01 asm_dbw0_+ASM oracle 2713 2696 0 02:04:25 ? 0:00 oracle+ASM (DESCRIPTION=(LOCAL=Y) oracle 2709 1 0 02:04:19 ? 0:00 asm_smon_+ASM SQL> select * from v$asm_diskgroup; GROUP_NUMBER NAME SECTOR_SIZE BLOCK_SIZE ------------ ------------------------------ ----------- ---------- ALLOCATION_UNIT_SIZE STATE TYPE TOTAL_MB FREE_MB -------------------- ----------- ------ ---------- ---------- 1 DGROUP1 512 4096 1048576 MOUNTED EXTERN 800 744 SQL> col name format a20 SQL> col failgroup format a20 SQL>

Page 316: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-136

SQL> select name,free_mb,failgroup,bytes_read,bytes_written 2 from v$asm_disk; NAME FREE_MB FAILGROUP BYTES_READ BYTES_WRITTEN -------------- ---------- -------------------- ---------- ------------- DGROUP1_0000 182 DGROUP1_0000 61440 57344 DGROUP1_0001 189 DGROUP1_0001 24576 0 DGROUP1_0002 185 DGROUP1_0002 36864 8192 DGROUP1_0003 188 DGROUP1_0003 32768 12288 SQL> select group_number,file_number,bytes,type,striped 2 from v$asm_file; no rows selected SQL> 2. Connected as SYSDBA under SQL*Plus in another terminal emulator window, determine the list

of disk groups that are visible from your database instance. Then list the processes associated to your database instance. When done, create a new tablespace called TBSASM that is stored inside the ASM disk group DGROUP1, and that has only one 200 MB data file. When done, determine the list of processes associated to your database instance again, and list the data files associated to your database. What do you observe?

Answer: As soon as the new tablespace is created, the ASM processes are started on the database instance. They are used to communicate with the ASM instance.

SQL> connect / as sysdba Connected. SQL> SQL> select * from v$asm_diskgroup; GROUP_NUMBER NAME SECTOR_SIZE BLOCK_SIZE ------------ ------------------------------ ----------- ---------- ALLOCATION_UNIT_SIZE STATE TYPE TOTAL_MB FREE_MB -------------------- ----------- ------ ---------- ---------- 1 DGROUP1 512 4096 1048576 MOUNTED EXTERN SQL> SQL> host ps -ef | grep orcl oracle 3240 1 0 Feb05 ? 00:00:01 /u01/app/oracle/product/10.1.0/p oracle 18036 1 0 05:05 ? 00:00:00 ora_pmon_orcl oracle 18038 1 0 05:05 ? 00:00:00 ora_mman_orcl oracle 18040 1 0 05:05 ? 00:00:00 ora_dbw0_orcl oracle 18042 1 0 05:05 ? 00:00:00 ora_lgwr_orcl oracle 18044 1 0 05:05 ? 00:00:00 ora_ckpt_orcl oracle 18046 1 0 05:05 ? 00:00:01 ora_smon_orcl oracle 18048 1 0 05:05 ? 00:00:00 ora_reco_orcl oracle 18050 1 0 05:05 ? 00:00:00 ora_cjq0_orcl oracle 18052 1 0 05:05 ? 00:00:00 ora_d000_orcl

Page 317: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-137

oracle 18054 1 0 05:05 ? 00:00:00 ora_s000_orcl oracle 18071 1 0 05:05 ? 00:00:00 ora_ctwr_orcl oracle 18074 1 0 05:05 ? 00:00:00 ora_qmnc_orcl oracle 18078 1 0 05:05 ? 00:00:01 ora_mmon_orcl oracle 18080 1 0 05:05 ? 00:00:00 ora_mmnl_orcl oracle 18082 1 0 05:05 ? 00:00:03 ora_j000_orcl oracle 18098 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18101 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18159 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18165 1 0 05:06 ? 00:00:04 oracleorcl (LOCAL=NO) oracle 18167 1 0 05:06 ? 00:00:04 oracleorcl (LOCAL=NO) oracle 18169 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18177 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18184 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18186 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18189 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18195 1 0 05:07 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18721 1 0 05:21 ? 00:00:00 ora_q000_orcl oracle 18846 1 5 05:26 ? 00:00:00 oracleorcl (DESCRIPTION=(LOCAL=) oracle 18849 18812 0 05:26 pts/1 00:00:00 /bin/bash -c ps -ef | grep orcl oracle 18851 18849 0 05:26 pts/1 00:00:00 /bin/bash -c ps -ef | grep orcl SQL> create tablespace tbsasm 2 datafile '+DGROUP1' size 200M; Tablespace created. SQL> host ps -ef | grep orcl oracle 3240 1 0 Feb05 ? 00:00:01 /u01/app/oracle/product/10.1.0/p oracle 18036 1 0 05:05 ? 00:00:00 ora_pmon_orcl oracle 18038 1 0 05:05 ? 00:00:00 ora_mman_orcl oracle 18040 1 0 05:05 ? 00:00:00 ora_dbw0_orcl oracle 18042 1 0 05:05 ? 00:00:00 ora_lgwr_orcl oracle 18044 1 0 05:05 ? 00:00:00 ora_ckpt_orcl oracle 18046 1 0 05:05 ? 00:00:01 ora_smon_orcl oracle 18048 1 0 05:05 ? 00:00:00 ora_reco_orcl oracle 18050 1 0 05:05 ? 00:00:00 ora_cjq0_orcl oracle 18052 1 0 05:05 ? 00:00:00 ora_d000_orcl oracle 18054 1 0 05:05 ? 00:00:00 ora_s000_orcl oracle 18071 1 0 05:05 ? 00:00:00 ora_ctwr_orcl oracle 18074 1 0 05:05 ? 00:00:00 ora_qmnc_orcl oracle 18078 1 0 05:05 ? 00:00:01 ora_mmon_orcl oracle 18080 1 0 05:05 ? 00:00:00 ora_mmnl_orcl oracle 18082 1 0 05:05 ? 00:00:03 ora_j000_orcl oracle 18098 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18101 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18159 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18165 1 0 05:06 ? 00:00:04 oracleorcl (LOCAL=NO) oracle 18167 1 0 05:06 ? 00:00:05 oracleorcl (LOCAL=NO) oracle 18169 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18177 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18184 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18186 1 0 05:06 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18189 1 0 05:06 ? 00:00:02 oracleorcl (LOCAL=NO) oracle 18195 1 0 05:07 ? 00:00:00 oracleorcl (LOCAL=NO) oracle 18846 1 1 05:26 ? 00:00:01 oracleorcl

Page 318: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-138

(DESCRIPTION=(LOCAL=) oracle 18857 1 0 05:26 ? 00:00:00 ora_q000_orcl oracle 18875 1 0 05:27 ? 00:00:00 ora_asmb_orcl oracle 18879 1 0 05:27 ? 00:00:00 ora_rbal_orcl oracle 18881 1 0 05:27 ? 00:00:00 ora_o000_orcl oracle 18896 18812 0 05:28 pts/1 00:00:00 /bin/bash -c ps -ef | grep orcl SQL> SQL> col file_name format a46 SQL> SQL> select file_name,tablespace_name 2 from dba_data_files; FILE_NAME TABLESPACE_NAME ---------------------------------------------- ------------------------------/u01/app/oracle/oradata/orcl/users01.dbf USERS /u01/app/oracle/oradata/orcl/sysaux01.dbf SYSAUX /u01/app/oracle/oradata/orcl/undotbs01.dbf UNDOTBS1 /u01/app/oracle/oradata/orcl/system01.dbf SYSTEM /u01/app/oracle/oradata/orcl/example01.dbf EXAMPLE +DGROUP1/orcl/datafile/tbsasm.256.1 TBSASM 6 rows selected. SQL>

Page 319: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-139

3. Back on your ASM instance, list all the ASM files that were created so far. Then, look at the ASM disk activity and free space. Execute the lab_15_02_03.sql script to simulate the addition of a new disk to your system. Again, look at the ASM disk activity and free space. When done, add the new disk /u02/asmdisks/disk4 to DGROUP1. Look at the ongoing ASM operations until there is no outstanding one. Then look again at the ASM disk activity and free space. What are your conclusions?

Answer: You can see that the disk activity is almost equally distributed across all ASM disks during the tablespace creation. After the tablespace has been created, the free space is almost the same on each ASM disk. This is because ASM tries to stripe ASM extents across all ASM disks. Then when you add a new ASM disk to the disk group, ASM automatically starts a rebalance operation to redistribute some of the ASM extents to the new disk. In the end, each disk has the same amount of free space. During the rebalance operation, disk4 had a lot of writes, and few reads, whereas the other disks had the same amount of read, and few writes.

SQL> select group_number,file_number,bytes,type,striped 2 from v$asm_file; GROUP_NUMBER FILE_NUMBER BYTES ------------ ----------- ---------- TYPE STRIPE ---------------------------------------------------------------- ------ 1 256 209723392 DATAFILE COARSE SQL> select name,free_mb,failgroup,bytes_read,bytes_written 2 from v$asm_disk; NAME FREE_MB FAILGROUP BYTES_READ BYTES_WRITTEN ---------------- ---------- -------------------- ---------- ------------- DGROUP1_0000 132 DGROUP1_0000 1105920 54898688 DGROUP1_0001 139 DGROUP1_0001 57344 52449280 DGROUP1_0002 135 DGROUP1_0002 61440 52465664 DGROUP1_0003 137 DGROUP1_0003 73728 52650496 SQL> host dd if=/dev/zero of=/u02/asmdisks/disk4 bs=1024k count=200 200+0 records in 200+0 records out SQL> select name,free_mb,failgroup,bytes_read,bytes_written 2 from v$asm_disk; NAME FREE_MB FAILGROUP BYTES_READ BYTES_WRITTEN ---------------- ---------- -------------------- ---------- ------------- 0 DGROUP1_0000 132 DGROUP1_0000 1110016 54980608 DGROUP1_0001 139 DGROUP1_0001 61440 52449280 DGROUP1_0002 135 DGROUP1_0002 65536 52465664 DGROUP1_0003 137 DGROUP1_0003 77824 52650496 SQL> ALTER DISKGROUP dgroup1 2 ADD DISK '/u02/asmdisks/disk4'; Diskgroup altered.

Page 320: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-140

SQL> select operation,power,actual,est_minutes from V$ASM_OPERATION; OPERA POWER ACTUAL EST_MINUTES ----- ---------- ---------- ----------- REBAL 1 1 0 SQL> / OPERA POWER ACTUAL EST_MINUTES ----- ---------- ---------- ----------- REBAL 1 1 0 SQL> / no rows selected SQL> select name,free_mb,failgroup,bytes_read,bytes_written 2 from v$asm_disk; NAME FREE_MB FAILGROUP BYTES_READ BYTES_WRITTEN ---------------- ---------- -------------------- ---------- ------------- DGROUP1_0000 146 DGROUP1_0000 15867904 55361536 DGROUP1_0001 147 DGROUP1_0001 11624448 55652352 DGROUP1_0002 146 DGROUP1_0002 12677120 53661696 DGROUP1_0003 150 DGROUP1_0003 14835712 53957120 DGROUP1_0004 152 DGROUP1_0004 36864 50372608 SQL> 4. On your database instance, execute the lab_15_02_04.sql script. This script creates and

populates a new table called T, which is stored in TBSASM. When executed, set timing statistics in your SQL*Plus session and execute the following query: SELECT count(distinct -

DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE')) FROM t;

SQL> create table t(c number) tablespace tbsasm; Table created. SQL> insert into t values(42); 1 row created. SQL> commit; Commit complete. SQL> insert into t select * from t; 1 row created. SQL> / 2 rows created.

Page 321: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-141

SQL> / 4 rows created. SQL> / 8 rows created. . output truncated . 262144 rows created. SQL> commit; Commit complete. SQL> insert into t select * from t; 524288 rows created. SQL> commit; Commit complete. SQL> set timing on SQL> SELECT count(distinct DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE')) 2 FROM t; COUNT(DISTINCTDBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE')) --------------------------------------------------------------- 1589 Elapsed: 00:01:39.78 SQL> 5. From your ASM instance, drop the ASM disk DGROUP1_0004 from DGROUP1. SQL> ALTER DISKGROUP dgroup1 DROP DISK DGROUP1_0004; Diskgroup altered. SQL>

Page 322: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-142

6. In your database instance, execute again the following query: SELECT count(distinct -

DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE')) FROM t;

What are your conclusions? Answer: When you drop an ASM disk, ASM automatically rebalances the extents of that disk to the remaining ones. While this process is going on in the background, you can continue to execute queries against that disk group without experiencing any interruption. Therefore, the time to execute the query the second time is a little bit more than for the first execution, but this does not represent a noticeable impact.

SQL> SELECT count(distinct DBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE')) 2 FROM t; COUNT(DISTINCTDBMS_ROWID.ROWID_BLOCK_NUMBER(ROWID,'SMALLFILE')) --------------------------------------------------------------- 1589 Elapsed: 00:01:41.56 SQL> set timing off; SQL> 7. Back in your ASM instance, check the impact on the ASM disk activity and free space. What are

your conclusions?

Answer: The same amount of free space is available on each ASM disk, and the major activity on the ASM disk represents the same amount of writes on each of them. The amount of read is not significant in this case.

SQL> select name,free_mb,failgroup,bytes_read,bytes_written 2 from v$asm_disk; NAME FREE_MB FAILGROUP BYTES_READ BYTES_WRITTEN ---------------- ---------- -------------------- ---------- ------------- 0 DGROUP1_0000 136 DGROUP1_0000 17317888 68694016 DGROUP1_0001 136 DGROUP1_0001 13144064 68784128 DGROUP1_0002 135 DGROUP1_0002 13631488 66359296 DGROUP1_0003 136 DGROUP1_0003 15917056 70951424 SQL>

Page 323: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-143

Practice 15-3 Solution: Migrating Tablespaces to ASM 1. Connected as SYSDBA under SQL*Plus in your database instance, create a new tablespace called

TBSASMMIG. This tablespace should contain only one 10 MB file stored in your file system (not using ASM). Create a table called T2 stored in TBSASMMIG. Insert one row inside T2.

SQL> create tablespace tbsasmmig 2 datafile 'asmmig1.dbf' size 10M; Tablespace created. SQL> col file_name format a52 SQL> col tablespace_name format a10 SQL> SQL> select file_name,tablespace_name 2 from dba_data_files; FILE_NAME TABLESPACE ---------------------------------------------------- ---------- /u01/app/oracle/oradata/orcl/users01.dbf USERS /u01/app/oracle/oradata/orcl/sysaux01.dbf SYSAUX /u01/app/oracle/oradata/orcl/undotbs01.dbf UNDOTBS1 /u01/app/oracle/oradata/orcl/system01.dbf SYSTEM /u01/app/oracle/oradata/orcl/example01.dbf EXAMPLE +DGROUP1/orcl/datafile/tbsasm.256.1 TBSASM /u01/app/oracle/product/10.1.0/db_1/dbs/asmmig1.dbf TBSASMMIG 7 rows selected. SQL> SQL> create table t2(c number) tablespace tbsasmmig; Table created. SQL> insert into t2 values(1); 1 row created. SQL> commit; Commit complete. SQL> 2. From your database instance, migrate TBSASMMIG to ASM storage. When done, check that the

migration was successful. SQL> set echo on SQL> SQL> connect / as sysdba Connected. SQL> host rman target / nocatalog Recovery Manager: Release 10.1.0.2.0 - Production

Page 324: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-144

Copyright (c) 1995, 2004, Oracle. All rights reserved. connected to target database: ORCL (DBID=1045673060) using target database controlfile instead of recovery catalog RMAN> SQL "alter tablespace tbsasmmig offline"; sql statement: alter tablespace tbsasmmig offline RMAN> backup as copy tablespace tbsasmmig format '+DGROUP1'; Starting backup at 12-FEB-04 allocated channel: ORA_DISK_1 channel ORA_DISK_1: sid=272 devtype=DISK channel ORA_DISK_1: starting datafile copy input datafile fno=00007 name=/u01/app/oracle/product/10.1.0/db_1/dbs/asmmig1.df output filename=+DGROUP1/orcl/datafile/tbsasmmig.257.1 tag=TAG20040212T051812 r4 channel ORA_DISK_1: datafile copy complete, elapsed time: 00:00:03 Finished backup at 12-FEB-04 RMAN> switch tablespace tbsasmmig to copy; datafile 7 switched to datafile copy "+DGROUP1/orcl/datafile/tbsasmmig.257.1" RMAN> SQL "alter tablespace tbsasmmig online"; sql statement: alter tablespace tbsasmmig online RMAN> exit Recovery Manager complete. SQL> select file_name,tablespace_name 2 from dba_data_files; FILE_NAME TABLESPACE ---------------------------------------------------- ---------- /u01/app/oracle/oradata/orcl/users01.dbf USERS /u01/app/oracle/oradata/orcl/sysaux01.dbf SYSAUX /u01/app/oracle/oradata/orcl/undotbs01.dbf UNDOTBS1 /u01/app/oracle/oradata/orcl/system01.dbf SYSTEM /u01/app/oracle/oradata/orcl/example01.dbf EXAMPLE +DGROUP1/orcl/datafile/tbsasm.256.1 TBSASM +DGROUP1/orcl/datafile/tbsasmmig.257.1 TBSASMMIG 7 rows selected. SQL> select * from t2; C ---------- 1 SQL> SQL>

Page 325: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-145

3. From your ASM instance, check the number of files created in your ASM disks. SQL> select group_number,file_number,bytes,type,striped 2 from v$asm_file; GROUP_NUMBER FILE_NUMBER BYTES ------------ ----------- ---------- TYPE STRIPE ---------------------------------------------------------------- ------ 1 256 209723392 DATAFILE COARSE 1 257 10493952 DATAFILE COARSE SQL> 4. From your database instance, cleanup your environment by dropping tablespace TBSASMMIG

including its contents and data file. Do the same with tablespace TBSASM. Also, remove the file system file that was originally created to store TBSASMMIG.

SQL> connect / as sysdba Connected. SQL> drop tablespace tbsasmmig including contents and datafiles; Tablespace dropped. SQL> drop tablespace tbsasm including contents and datafiles; Tablespace dropped. SQL> host rm $ORACLE_HOME/dbs/asmmig1.dbf SQL>

Page 326: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-146

Practice 17-1 Solution: Implement VPD Unless specified otherwise, you should be logging in as SYSDBA either through Database Control or SQL*Plus. 1. Execute the lab_17_01_01.sql script. This script does the following:

• It creates three new users VPD, JF, and MH all identified by their name. • User VPD is granted the CONNECT, RESOURCE, and DBA roles. The script also creates a new

table called VPD.EMPLOYEES with the same structure as HR.EMPLOYEES. This table contains three rows: One corresponding to user JF, one to user MH, and another one corresponding to the hypothetical user CL.

• Users JF, and MH are granted the CONNECT and RESOURCE roles, and also SELECT on VPD.EMPLOYEES.

connect / as sysdba drop user jf cascade; create user jf identified by jf default tablespace example temporary tablespace temp; grant connect, resource to jf; drop user mh cascade; create user mh identified by mh default tablespace example temporary tablespace temp; grant connect, resource to mh; drop user vpd cascade; create user vpd identified by vpd default tablespace example temporary tablespace temp; grant connect, resource, dba to vpd; connect vpd/vpd drop table employees purge; create table employees as select * from hr.employees where 1=2; insert into employees values (300,'JF','JF','[email protected]','6500000',sysdate,58,1000,0.5,500,10); insert into employees values (400,'MH','MH','[email protected]','6500001',sysdate,59,2000,0.6,500,10); insert into employees values (500,'CL','CL','[email protected]','6500002',sysdate,60,3000,0.7,600,10); commit;

Page 327: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-147

grant select on employees to jf; grant select on employees to mh;

2. Connect as user VPD through SQL*Plus and create a new package called

APP_SECURITY_CONTEXT. This package should contain only one procedure called SET_EMPNO. The goal of the SET_EMPNO procedure is to assign to the EMPNO attribute of the VPD_CONTEXT context the employee’s identifier corresponding to the connected user. Use the procedure DBMS_SESSION.SET_CONTEXT to set the EMPNO attribute, and the SYS_CONTEXT('USERENV','SESSION_USER') function to determine the name of the connected user.

connect vpd/vpd CREATE OR REPLACE PACKAGE app_security_context IS PROCEDURE set_empno; END; / CREATE OR REPLACE PACKAGE BODY app_security_context IS PROCEDURE set_empno IS empid NUMBER; BEGIN SELECT employee_id INTO empid FROM vpd.employees WHERE first_name = SYS_CONTEXT('USERENV','SESSION_USER'); DBMS_SESSION.SET_CONTEXT('vpd_context', 'empno', empid); END; END; / 3. When done, create the VPD_CONTEXT context using the APP_SECURITY_CONTEXT

package. connect vpd/vpd CREATE CONTEXT vpd_context USING vpd.app_security_context;

Page 328: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-148

4. Create an AFTER LOGON trigger that calls the VPD.APP_SECURITY_CONTEXT.SET_EMPNO procedure only if the current schema is JF or MH.

connect vpd/vpd CREATE OR REPLACE TRIGGER on_logon AFTER LOGON ON DATABASE BEGIN IF user in ('JF','MH') THEN vpd.app_security_context.set_empno(); END IF; END; / 5. Connect as user VPD through SQL*Plus and execute the lab_17_01_05.sql script. This

script creates a new package called VPD_SECURITY. This package contains one function called EMPNO_SEC. The goal of this function is to return the VPD predicate used by your policy. In this case the returned predicate is: employee_id = SYS_CONTEXT('vpd_context', 'empno').

connect vpd/vpd CREATE OR REPLACE PACKAGE vpd_security AS FUNCTION empno_sec (D1 VARCHAR2, D2 VARCHAR2) RETURN VARCHAR2; END; / CREATE OR REPLACE PACKAGE BODY vpd_security AS FUNCTION empno_sec (D1 VARCHAR2, D2 VARCHAR2) RETURN VARCHAR2 IS predicate VARCHAR2 (2000); j number; BEGIN j:=0; for i in 1..100000 loop j:=atan(i); end loop; predicate := 'employee_id = SYS_CONTEXT(''vpd_context'', ''empno'')'; RETURN predicate; END; END; /

Page 329: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-149

6. Connect as VPD through SQL*Plus and create a new policy called VPD_POLICY. This policy should have the following characteristics: • Is attached to the VPD.EMPLOYEES table • Uses the VPD.VPD_SECURITY.EMPNO_SEC function • Is applied only for SELECT statements • Is a dynamic policy • Specifies the SALARY and COMMISSION_PCT columns as the list of relevant columns You can use the lab_17_01_06.sql script.

connect vpd/vpd exec DBMS_RLS.ADD_POLICY( - OBJECT_SCHEMA => 'vpd' ,- OBJECT_NAME => 'employees' ,- POLICY_NAME => 'vpd_policy' ,- FUNCTION_SCHEMA => 'vpd' ,- POLICY_FUNCTION => 'vpd_security.empno_sec',- STATEMENT_TYPES => 'select' ,- UPDATE_CHECK => false ,- ENABLE => true ,- STATIC_POLICY => false ,- POLICY_TYPE => DBMS_RLS.DYNAMIC ,- LONG_PREDICATE => false ,- SEC_RELEVANT_COLS => 'SALARY,COMMISSION_PCT'); 7. Connect as user JF through SQL*Plus and execute the following statements:

SELECT first_name FROM vpd.employees; SELECT first_name FROM vpd.employees; SELECT last_name FROM vpd.employees; SELECT salary FROM vpd.employees; What do you observe, and what are your conclusions? Answer: Each time you execute a statement that is not parsed already, the policy function is evaluated. This is because the policy is set to be dynamic. The fact that the policy function evaluation is long in this case is simply because the EMPNO_SEC function is looping for a while before returning the predicate. Also, the last statement returns only one row corresponding to the connected user. So it is clear that the policy function is applied only in the last case.

connect jf/jf select first_name from vpd.employees; select first_name from vpd.employees; select last_name from vpd.employees; select salary from vpd.employees;

Page 330: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-150

8. Connect as user MH through SQL*Plus and execute the following statements: select first_name from vpd.employees; select last_name from vpd.employees; select last_name as ln from vpd.employees; select salary from vpd.employees; What do you observe, and what are your conclusions? Answer: The first two statements are already parsed in memory because of the previous step. So, the policy function is not evaluated in this case because it has already been done. However, for the third statement, the function is evaluated because the statement has never been executed. The last statement returns the salary of the corresponding user. Again the policy function is applied only on the last statement because it references the SALARY column.

connect mh/mh select first_name from vpd.employees; select last_name from vpd.employees; select last_name as ln from vpd.employees; select salary from vpd.employees; 9. Connect as user VPD and drop the VPD_POLICY policy, and re-create it with the exact same

characteristics except that it should now be a static policy instead of being dynamic. When done, flush the shared pool of your instance. You can use the lab_17_01_09.sql script.

connect vpd/vpd exec DBMS_RLS.DROP_POLICY( - OBJECT_SCHEMA => 'vpd', - OBJECT_NAME => 'employees', - POLICY_NAME => 'vpd_policy'); exec DBMS_RLS.ADD_POLICY( - OBJECT_SCHEMA => 'vpd' ,- OBJECT_NAME => 'employees' ,- POLICY_NAME => 'vpd_policy' ,- FUNCTION_SCHEMA => 'vpd' ,- POLICY_FUNCTION => 'vpd_security.empno_sec',- STATEMENT_TYPES => 'select' ,- UPDATE_CHECK => false ,- ENABLE => true ,- STATIC_POLICY => true ,- POLICY_TYPE => NULL ,- LONG_PREDICATE => false ,- SEC_RELEVANT_COLS => 'SALARY,COMMISSION_PCT'); alter system flush shared_pool; 10. Connect as user JF through SQL*Plus and execute the following statements:

Page 331: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-151

select first_name from vpd.employees; select first_name from vpd.employees; select last_name from vpd.employees; select salary from vpd.employees; select commission_pct from vpd.employees; What do you observe, and what are your conclusions? Answer: In this case, because the policy is declared to be static, the function is evaluated only once.

connect jf/jf select first_name from vpd.employees; select first_name from vpd.employees; select last_name from vpd.employees; select salary from vpd.employees; select commission_pct from vpd.employees; 11. Connect as SYSDBA and determine which statements are using the defined policy on your

instance. What are your conclusions?

Answer: This step confirms that only two statements were using the policy function. They are the ones that reference the SALARY and COMMISSION_PCT columns. This can be verified by using the V$VPD_POLICY view.

connect / as sysdba SELECT count(*) FROM v$vpd_policy; select sql_text from v$sql where sql_id in (select sql_id from v$vpd_policy); 12. To clean up your environment, execute the lab_17_01_12.sql script. connect / as sysdba drop user mh cascade; drop user jf cascade; drop user vpd cascade; drop context vpd_context;

Page 332: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-152

Practice 18-1 Solution: Using Regular Expressions 1. Connect as SYSDBA and write a query with a single WHERE clause condition (using the

REGEXP_LIKE function) that asks for a search-string and then displays the view definitions of all views with the name [DBA|USER|ALL]_search-string. Make sure your query is case insensitive. You can use lab_18_01_01.sql.

SQL> select view_name, text 2 from dba_views 3 where regexp_like(view_name,'^(dba|all|user)_&search.$','i');

When you have the solution, you can try these search-string alternatives: catalog,

constraints, clusters, data_files, db_links, extents, tablespaces, … 2. Execute the following query:

select banner from v$version where rownum = 1;

SQL> select banner 2 from v$version 3 where rownum = 1; BANNER ---------------------------------------------------------------- Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 – Prod

a. Use the REGEXP_INSTR function to alter this query to return the position of the fifth

word in this banner text. You can use lab_18_01_02a.sql. SQL> select banner 2 , regexp_instr(banner,'[^ ]+', 1, 5) word_5 3 from v$version 4 where rownum = 1; BANNER WORD_5 ---------------------------------------------------------------- ------ Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Prod 32

Page 333: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-153

b. Use the REGEXP_INSTR function to return the position of the second word starting with a lowercase or uppercase “e” with a length of at least seven characters. You can use lab_18_01_02b.sql.

SQL> select banner 2 , regexp_instr(banner,'e[a-z]{6,}', 1, 2, 0, 'i') hit_2 3 from v$version 4 where rownum = 1; BANNER HIT_2 ---------------------------------------------------------------- ----- Oracle Database 10g Enterprise Edition Release 10.1.0.2.0 - Prod 32

Page 334: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-154

Practice 18-2 Solution: Using Case-Insensitive Sorting 1. Connect to the HR schema, and create a table called NAMES, with first names using the following

statements: create table names as select first_name from employees where rownum <= 30; update names set first_name = lower(first_name) where rownum <= 15; You can use the script lab_18_02_01.sql

SQL> connect hr/hr Connected. SQL> create table names as 2 select first_name 3 from employees 4 where rownum <= 30; Table created. SQL> update names 2 set first_name = lower(first_name) 3 where rownum <= 15; 15 rows updated.

2. Execute the following query and look at the default ordering:

select * from names order by first_name;

SQL> select * from names order by first_name; FIRST_NAME ---------- Alberto Britney Bruce Curtis Daniel Jennifer John Julia Karen Kelly Kevin Lex Louise Nanette Pat alexis amit

Page 335: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-155

anthony david david elizabeth ellen gerald harrison hermann laura mozhe sarah shelli sundar

3. By default, uppercase characters sort before lowercase characters. Using the ALTER SESSION

command, change NLS_SORT for your session to use case-insensitive binary sorting and repeat the query from the previous step.

SQL> alter session 2 set nls_sort = binary_ci; Session altered. SQL> select * from names order by first_name; FIRST_NAME ---------- Alberto alexis amit anthony Britney Bruce Curtis Daniel david david elizabeth ellen gerald harrison hermann Jennifer John Julia Karen Kelly Kevin laura Lex Louise mozhe Nanette Pat sarah shelli sundar

Page 336: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-156

4. Drop the NAMES table, and reset your session to use default binary sorting. SQL> drop table names; Table dropped. SQL> alter session 2 set nls_sort = binary; Session altered.

Page 337: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-157

Practice 18-3 Solution: Using the DBMS_MONITOR Package 1. Start two sessions, one connected as SYSDBA and one connected as SH. SQL> connect / as sysdba Connected. SQL>

SQL> connect sh/sh Connected. SQL>

2. From the SYSDBA session, determine the session ID (sid) and serial number (serial#) from

v$session for the SH user, and then describe the DBMS_MONITOR package. Then, from the SYSDBA session, enable tracing using the sid and serial# values for the other session, including the waits and bind information, with the following command: execute dbms_monitor.session_trace_enable ( - session_id => <sid> , -

serial_num => <serial#> , - waits => true , - binds => true ) ;

SQL> select sid, serial# 2 from v$session 3 where username = 'SH'; SID SERIAL# ---------- ---------- 131 26696 SQL> SQL> describe dbms_monitor PROCEDURE CLIENT_ID_STAT_DISABLE Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- CLIENT_ID VARCHAR2 IN ... PROCEDURE SESSION_TRACE_ENABLE Argument Name Type In/Out Default? ------------------------------ ----------------------- ------ -------- SESSION_ID BINARY_INTEGER IN DEFAULT SERIAL_NUM BINARY_INTEGER IN DEFAULT WAITS BOOLEAN IN DEFAULT BINDS BOOLEAN IN DEFAULT SQL>

Page 338: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-158

SQL> exec dbms_monitor.session_trace_enable ( - > session_id => &sid , - > serial_num => &serial , - > waits => true , - > binds => true ) ; Enter value for sid: 131 Enter value for serial: 26696 PL/SQL procedure successfully completed. SQL>

3. From the SH session, execute the lab_18_03_03.sql script, and then exit your session. SH SQL> select c.cust_last_name 2 , t.calendar_year 3 , sum(s.amount_sold) 4 from sales s join 5 customers c using (cust_id) join 6 times t using (time_id) 7 group by c.cust_last_name, t.calendar_year 8 order by c.cust_last_name, t.calendar_year; CUST_LAST_NAME CALENDAR_YEAR SUM(S.AMOUNT_SOLD) ------------------ ------------- ------------------ ... ... ... Ziluca 1998 37771.8 Ziluca 1999 32056.42 Ziluca 2000 46480.56 Ziluca 2001 30791.05 Zimmer 1998 23478.49 Zimmer 1999 18655.24 Zimmer 2000 11108.92 Zimmer 2001 48991.66 Zimmerman 1998 37338.23 Zimmerman 1999 32201.97 Zimmerman 2000 58806.81 Zimmerman 2001 71710.31 Zoldos 1998 46096.77 Zoldos 1999 71375.51 Zoldos 2000 12383.68 Zoldos 2001 84018.39 Zwolinsky 1998 11475.14 Zwolinsky 2000 3817.61 3026 rows selected. SQL> exit

4. From the remaining SYSDBA session, determine your user_dump_dest location, locate the

trace file, and view the contents.

Page 339: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-159

SQL> show parameter user_dump name TYPE value ---------------- --------- ---------------------------------- user_dump_dest string /u01/app/oracle/admin/orcl/udump SQL> host $ cd /u01/app/oracle/admin/orcl/udump $ view orcl_ora_26997.trc ... *** 2003-12-22 07:43:27.760 *** ACTION NAME:() 2003-12-22 07:43:27.759 *** MODULE NAME:(SQL*Plus) 2003-12-22 07:43:27.759 *** SERVICE NAME:(SYS$USERS) 2003-12-22 07:43:27.759 *** SESSION ID:(139.18972) 2003-12-22 07:43:27.759 PARSING IN CURSOR #1 len=259 dep=0 uid=61 oct=3 lid=61 m=1046980281015229 hv=215424196 ad='57cd5ae8' select c.cust_last_name , t.calendar_year , sum(s.amount_sold) from sales s join customers c using (cust_id) join times t using (time_id) group by c.cust_last_name, t.calendar_year order by c.cust_last_name, t.calendar_year END OF STMT PARSE 1:c=20000,e=20382,p=0,cr=0,cu=0,mis=1,r=0,dep=0,og=1,tim=1046980281015200 BINDS #1: EXEC #1:c=0,e=198,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=1,tim=1046980281016198 WAIT #1: nam='SQL*Net message to client' ela= 11 p1=1650815232 p2=1 p3=0 WAIT #1: nam='db file sequential read' ela= 74 p1=5 p2=3715 p3=1 WAIT #1: nam='db file scattered read' ela= 10676 p1=5 p2=3716 p3=5 WAIT #1: nam='db file scattered read' ela= 15295 p1=5 p2=3769 p3=8 WAIT #1: nam='db file scattered read' ela= 2130 p1=5 p2=3778 p3=7 WAIT #1: nam='db file scattered read' ela= 328 p1=5 p2=3785 p3=8 ... WAIT #1: nam='direct path write temp' ela= 2 p1=201 p2=4687 p3=7 WAIT #1: nam='direct path write temp' ela= 2 p1=201 p2=4736 p3=7 WAIT #1: nam='direct path read temp' ela= 38 p1=201 p2=4745 p3=7 WAIT #1: nam='direct path read temp' ela= 23 p1=201 p2=4701 p3=7 ... FETCH #1:c=20330000,e=23361287,p=5085,cr=3232,cu=0,mis=0,r=1,dep=0,og=1, tim=1046980304385232 WAIT #1: nam='SQL*Net message from client' ela= 870 p1=1650815232 p2=1 3=0 WAIT #1: nam='SQL*Net message to client' ela= 5 p1=1650815232 p2=1 p3=0 FETCH 1:c=0,e=158,p=0,cr=0,cu=0,mis=0,r=15,dep=0,og=1,tim=1046980304386861 ... *** 2003-12-22 07:44:05.697 WAIT #1: nam='SQL*Net message from client' ela= 11328652 p1=1650815232 2=1 p3=0 XCTEND rlbk=0, rd_only=1 STAT #1 id=1 cnt=3026 pid=0 pos=1 obj=0 op='SORT GROUP BY (cr=3232 pr=5085 pw=1932 time=23370900 us)'

Page 340: Oracle 10g New Features for Administrators Vol II

Oracle Database 10g: New Features for Administrators B-160

STAT #1 id=2 cnt=918843 pid=1 pos=1 obj=0 op='HASH JOIN (cr=3232 pr=5085 pw=1932 time=19569204 us)' STAT #1 id=3 cnt=1826 pid=2 pos=1 obj=49567 op='TABLE ACCESS FULL OBJ#(49567) (cr=56 pr=54 pw=0 time=61542 us)' STAT #1 id=4 cnt=918843 pid=2 pos=2 obj=0 op='HASH JOIN (cr=3176 pr=5031 pw=1932 time=13972181 us)' STAT #1 id=5 cnt=55500 pid=4 pos=1 obj=49577 op='TABLE ACCESS FULL OBJ#(49577) (cr=1459 pr=1455 pw=0 time=682525 s)' STAT #1 id=6 cnt=918843 pid=4 pos=2 obj=0 op='PARTITION RANGE ALL PARTITION: 1 28 (cr=1717 pr=1644 pw=0 time=5789341 us)' STAT #1 id=7 cnt=918843 pid=6 pos=1 obj=49509 op='TABLE ACCESS FULL OBJ#(49509) PARTITION: 1 28 (cr=1717 pr=1644 pw=0 time=3297530 us)'