Oracle 9i DBA Fund - II

390
Oracle9i Database: Fundamentals II ANDREW C. SIMKOVSKY INSTRUCTOR’S EDITION

Transcript of Oracle 9i DBA Fund - II

Page 1: Oracle 9i DBA Fund - II

Oracle9iDatabase:Fundamentals II

A N D R E W C . S I M K O V S K Y

I N S T R U C T O R ’ S E D I T I O N

Page 2: Oracle 9i DBA Fund - II

Oracle9i Database: Fundamentals II

Andrew C.SimkovskyAndrew Simkovsky is an OracleCertified Professional DatabaseAdministrator and publishedauthor. His previous works includeOracle training manuals forElement K Press, and Oracle8i:OCP Virtual Test Center (Sybex).Currently, he is a Senior DatabaseAdministrator for World FuelServices Corporation in Miami,Florida. Andrew is also a SYSOPfor the world-renowned QuestSoftware/RevealNet Labs DBAPipeline (www.quest-pipelines.com). Prior to working at WorldFuel Services, Andrew held severalOracle-related positions, includingIT manager, DBA, consultant, andOCP instructor. He has managedOracle databases ranging in sizefrom 5 gigabytes to over 20terabytes, and his Oracleexperience includes Internetstartups, telecommunications,retail, and teaching.

Page 3: Oracle 9i DBA Fund - II

ORACLE9I DATABASE: FUNDAMENTALS II

Course Number: 079176Course Edition: 1.0For software version: version 9.2.0.1.0

ACKNOWLEDGEMENTS

Project Team

Curriculum Developer and Technical Writer: Andrew C. Simkovsky • Sr. Copy Editors: Angie J. French andChristy D. Johnson • Material Editor: Lance Anderson • Graphic/Print Designer: Isolina Salgado Toner •Project Technical Support: Michael Toscano

Project Support

Content Manager: Susan B. SanFilippo • Project Coordinator: Nicole Heinsler • Development Assistance:Warren Capps

NOTICESDISCLAIMER: While Element K Content LLC takes care to ensure the accuracy and quality of these materials, we cannot guarantee their accuracy, and all materials areprovided without any warranty whatsoever, including, but not limited to, the implied warranties of merchantability or fitness for a particular purpose. The name used in the datafiles for this course is that of a fictitious company. Any resemblance to current or future companies is purely coincidental. We do not believe we have used anyone’s name increating this course, but if we have, please notify us and we will change the name in the next revision of the course. Element K is an independent provider of integratedtraining solutions for individuals, businesses, educational institutions, and government agencies. Use of screenshots, photographs of another entity’s products, or anotherentity’s product name or service in this book is for editorial purposes only. No such use should be construed to imply sponsorship or endorsement of the book by, nor anyaffiliation of such entity with Element K. This courseware may contain links to sites on the Internet that are owned and operated by third parties (the “External Sites”). ElementK is not responsible for the availability of, or the content located on or through, any External Site. Please contact Element K if you have any concerns regarding such links orExternal Sites.

TRADEMARK NOTICES: Element K and the Element K logo are trademarks of Element K LLC and its affiliates. Oracle9i is a registered trademark of Oracle Corporation inthe U.S. and other countries; the Oracle products and services discussed or described may be trademarks of Oracle Corporation. All other product names and services usedthroughout this book may be common law or registered trademarks of their respective proprietors.

Copyright © 2003 Element K Content LLC. All rights reserved. Screenshots used for illustrative purposes are the property of the software proprietor. This publication, or anypart thereof, may not be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, storage in an informationretrieval system, or otherwise, without express written permission of Element K, 500 Canal View Boulevard, Rochester, NY 14623, (585) 240-7500, (800) 434-3466. Element KCourseware LLC’s World Wide Web site is located at www.elementkcourseware.com.

This book conveys no rights in the software or other products about which it was written; all use or licensing of such software or other products is the responsibility of theuser according to terms and conditions of the owner. Do not make illegal copies of books or software. If you believe that this book, related materials, or any other Element Kmaterials are being reproduced or transmitted without permission, please call 1-800-478-7788.

ii Oracle9i Database: Fundamentals II

Page 4: Oracle 9i DBA Fund - II

ORACLE9I DATABASE: FUNDAMENTALS II

About This Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ix

Lesson 1: Oracle Networking. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1

Lesson 2: Backup and Recovery Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

Lesson 3: User-managed Backup and Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . 141

Lesson 4: Recovery Manager Backups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 205

Lesson 5: Recovery Manager Recoveries . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 285

Lesson 6: Loading and Moving Data . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 317

Additional Instructor Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 365

Glossary. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 367

Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 371

CONTENTOVERVIEW

Contents iii

Page 5: Oracle 9i DBA Fund - II

ORACLE9I DATABASE: FUNDAMENTALS II

CONTENTSAbout This Course . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ixCourse Setup Information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . ixHow To Use This Book. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xiii

LESSON 1: ORACLE NETWORKING

Topic 1A Oracle9i Networking Overview . . . . . . . . . . . . . . . . . . . . . . . . 3Task 1A-1 Describe Oracle Net Architecture . . . . . . . . . . . . . . . . . . . . 6

The User Connection Process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7Task 1A-2 Identify the Steps in the User Connection Process . . . . . . . . 12

Oracle Net Layered Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12Task 1A-3 Describe Oracle Net Layered Architecture . . . . . . . . . . . . . . . 17

Additional Networking Options . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18Task 1A-4 Identify Additional Networking Options . . . . . . . . . . . . . . . . 24

Topic 1B Basic Oracle Net Server-side Configuration . . . . . . . . . . . . . . 25Task 1B-1 Configuring the Listener Process . . . . . . . . . . . . . . . . . . . . 28

The Listener Control (lsnrctl) Utility. . . . . . . . . . . . . . . . . . . . . . . . . . . 35Task 1B-2 Using the Listener Control (lsnrctl) Utility . . . . . . . . . . . . . . 37

Configure the Listener Manually . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42Task 1B-3 Configuring the Listener Manually . . . . . . . . . . . . . . . . . . . 42

Topic 1C Basic Oracle Net Client-side Configuration . . . . . . . . . . . . . . 46Task 1C-1 Identify Names Resolution Methods . . . . . . . . . . . . . . . . . . 48

Configure Host Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49Task 1C-2 Configuring Host Naming . . . . . . . . . . . . . . . . . . . . . . . . . 51

Configure Local Naming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 55Task 1C-3 Configuring Local Naming . . . . . . . . . . . . . . . . . . . . . . . . . 57

Troubleshooting Connection Issues . . . . . . . . . . . . . . . . . . . . . . . . . . . 64Task 1C-4 Configuring Client and Server Tracing . . . . . . . . . . . . . . . . . 68

Topic 1D Oracle Shared Server. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74Task 1D-1 Describing Oracle Shared Server Architecture . . . . . . . . . . . . 77

Configuring Oracle Shared Server . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80Task 1D-2 Configure Oracle Shared Server. . . . . . . . . . . . . . . . . . . . . . 83

Monitoring and Tuning Oracle Shared Server . . . . . . . . . . . . . . . . . . . . 83Task 1D-3 Describe Methods to Monitor and Tune Oracle Shared Server. . 86

CONTENTS

iv Oracle9i Database: Fundamentals II

Page 6: Oracle 9i DBA Fund - II

Configuring the Listener for Web Clients . . . . . . . . . . . . . . . . . . . . . . . 87Task 1D-4 Configure the Listener for Web Clients. . . . . . . . . . . . . . . . . 90

Lesson Review 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

LESSON 2: BACKUP AND RECOVERY OVERVIEW

Topic 2A Introduction to Backup and Recovery . . . . . . . . . . . . . . . . . . 96Task 2A-1 Identify Types of Failures . . . . . . . . . . . . . . . . . . . . . . . . . 99

Backup and Recovery Basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 100Task 2A-2 Describe Backup and Recovery Basics . . . . . . . . . . . . . . . . . 104

Instance and Media Recovery Structures . . . . . . . . . . . . . . . . . . . . . . . 105Task 2A-3 Identify Instance and Media Recovery Structures . . . . . . . . . 113

Topic 2B Cold Backup and Recovery Concepts. . . . . . . . . . . . . . . . . . . .114Task 2B-1 Performing a Cold Database Backup . . . . . . . . . . . . . . . . . . 115

Cold Recovery Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120Task 2B-2 Perform a Cold Database Recovery . . . . . . . . . . . . . . . . . . . 123

Topic 2C Hot Backup and Recovery Concepts . . . . . . . . . . . . . . . . . . . .127Task 2C-1 Configuring Archivelog Mode . . . . . . . . . . . . . . . . . . . . . . . 132

Hot Recovery Concepts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 135Task 2C-2 Describe Hot Database Recovery. . . . . . . . . . . . . . . . . . . . . 138

Lesson Review 2 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139

LESSON 3: USER-MANAGED BACKUP AND RECOVERY

Topic 3A User-managed Backups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .142Task 3A-1 Hot Backup Tablespaces . . . . . . . . . . . . . . . . . . . . . . . . . . 144

Backing Up the Control File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148Task 3A-2 Backing Up the Control File. . . . . . . . . . . . . . . . . . . . . . . . 150

Read-only Tablespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 153Task 3A-3 Identify Backup Considerations for Read-only Tablespaces . . . 154

Resolving a Failed Hot Backup . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 154Task 3A-4 Resolve a Failed Hot Backup . . . . . . . . . . . . . . . . . . . . . . . 155

Topic 3B User-managed Complete Recovery . . . . . . . . . . . . . . . . . . . . .159Task 3B-1 Recover a Tablespace After a Failure . . . . . . . . . . . . . . . . . . 162

Trial Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 168Task 3B-2 Perform a Trial Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . 169

Restoring Datafiles to New Locations. . . . . . . . . . . . . . . . . . . . . . . . . . 171Task 3B-3 Restore Datafiles to New Locations. . . . . . . . . . . . . . . . . . . 173

Topic 3C User-managed Incomplete Recovery. . . . . . . . . . . . . . . . . . . .176Task 3C-1 Describe Incomplete Recovery Concepts . . . . . . . . . . . . . . . 180

Loss of Control File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 180

CONTENTS

Contents v

Page 7: Oracle 9i DBA Fund - II

Task 3C-2 Recovering After Loss of Control File . . . . . . . . . . . . . . . . . 182Loss of the Current Online Log Group. . . . . . . . . . . . . . . . . . . . . . . . . . 189

Task 3C-3 Recover From the Loss of the Current Online Log Group. . . . . 190Read-only Tablespaces . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 196

Task 3C-4 Identify Recovery Considerations for Read-only Tablespaces . . 198Tablespace Point-in-Time Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . 200

Task 3C-5 Describe Tablespace Point-in-Time Recovery . . . . . . . . . . . . . 201Lesson Review 3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 202

LESSON 4: RECOVERY MANAGER BACKUPS

Topic 4A RMAN Architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .207Task 4A-1 List and Describe RMAN Features . . . . . . . . . . . . . . . . . . . . 208

The RMAN Repository . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209Task 4A-2 Describe the RMAN Repository and its Contents . . . . . . . . . . 213

RMAN Process Flow . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213Task 4A-3 Describe the RMAN Process Flow . . . . . . . . . . . . . . . . . . . . 216

Image Copies and Backup Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217Task 4A-4 Describe How RMAN Creates Image Copies and Backup Sets . . 219

Topic 4B Configuring the RMAN Environment . . . . . . . . . . . . . . . . . . . .219Task 4B-1 Using the Control File as the RMAN Repository. . . . . . . . . . . 221

Create the Recovery Catalog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 222Task 4B-2 Creating the Recovery Catalog . . . . . . . . . . . . . . . . . . . . . . 224

Register a Target Database . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 227Task 4B-3 Registering a Target Database . . . . . . . . . . . . . . . . . . . . . . 227

RMAN Configuration Parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 229Task 4B-4 Set the RMAN Configuration Parameters . . . . . . . . . . . . . . . 233

Topic 4C RMAN Backups. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .236Task 4C-1 Performing Cold Database Backups Using RMAN . . . . . . . . . . 239

RMAN Hot Backups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243Task 4C-2 Perform a Hot Backup of the Database Using RMAN . . . . . . . 244

RMAN Incremental Hot Backups . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245Task 4C-3 Perform Incremental Hot Backups using RMAN . . . . . . . . . . . 248

Backing Up the Archive Logs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252Task 4C-4 Backing Up the Archive Logs . . . . . . . . . . . . . . . . . . . . . . . 253

Topic 4D RMAN Catalog Maintenance and Management . . . . . . . . . . . .254Task 4D-1 Creating, Using, and Managing RMAN Scripts . . . . . . . . . . . . 256

RMAN Reports and Lists . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 259Task 4D-2 Generate RMAN Reports and Lists . . . . . . . . . . . . . . . . . . . . 262

Crosscheck and Delete Backup Sets . . . . . . . . . . . . . . . . . . . . . . . . . . . 266Task 4D-3 Crosschecking and Deleting Backup Sets . . . . . . . . . . . . . . . 269

Catalog OS-level Database Backups . . . . . . . . . . . . . . . . . . . . . . . . . . . 272Task 4D-4 Cataloging OS-level Database Backups. . . . . . . . . . . . . . . . . 273

CONTENTS

vi Oracle9i Database: Fundamentals II

Page 8: Oracle 9i DBA Fund - II

Backup and Restore Validation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 275Task 4D-5 Validate Backup and Restore Operations . . . . . . . . . . . . . . . 275

Backing Up the Recovery Catalog . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 277Task 4D-6 List and Describe Methods to Back Up the Recovery Catalog . 279

Lesson Review 4 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 280

LESSON 5: RECOVERY MANAGER RECOVERIES

Topic 5A RMAN Complete Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . .286Task 5A-1 Restoring Files with RMAN . . . . . . . . . . . . . . . . . . . . . . . . 288

Performing Complete Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 292Task 5A-2 Perform a Complete Recovery. . . . . . . . . . . . . . . . . . . . . . . 293

Block Media Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 295Task 5A-3 Describe Block Media Recovery. . . . . . . . . . . . . . . . . . . . . . 296

Topic 5B RMAN Incomplete Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . .297Task 5B-1 Describe Recovery with RMAN After Loss of Control File. . . . . 300

Loss of the Current Redo Log Group . . . . . . . . . . . . . . . . . . . . . . . . . . . 301Task 5B-2 Using RMAN to Recover After Loss of the Current Redo Log . . 302

Tablespace Point-in-Time Recovery . . . . . . . . . . . . . . . . . . . . . . . . . . . 308Task 5B-3 Describe Tablespace Point-in-Time Recovery Using RMAN . . . . 313

Lesson Review 5 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 314

LESSON 6: LOADING AND MOVING DATA

Topic 6A Load Data into the Database . . . . . . . . . . . . . . . . . . . . . . . . . .318Task 6A-1 Using SQL*Loader . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 324

Direct Load Inserts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 329Task 6A-2 Loading Data Using Direct Load Inserts. . . . . . . . . . . . . . . . 330

External Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 333Task 6A-3 Creating and Accessing External Tables . . . . . . . . . . . . . . . . 336

Topic 6B The Export and Import Utilities . . . . . . . . . . . . . . . . . . . . . . .341Task 6B-1 Exporting the Database. . . . . . . . . . . . . . . . . . . . . . . . . . . 344

The Import Utility . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 348Task 6B-2 Importing Data into the Database . . . . . . . . . . . . . . . . . . . 350

Transportable Tablespaces. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353Task 6B-3 Transporting a Tablespace . . . . . . . . . . . . . . . . . . . . . . . . . 355

Apply Your Knowledge 6-1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 361Lesson Review 6 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 362

Additional Instructor Notes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .365

Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .367

Index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .371

CONTENTS

Contents vii

Page 9: Oracle 9i DBA Fund - II

viii Oracle9i Database: Fundamentals II

Page 10: Oracle 9i DBA Fund - II

ABOUT THIS COURSEThis course introduces the concepts of Oracle9i® network configuration and data-base backup and recovery. You will learn how to configure the Oracle9i networkenvironment to support connections to and from the database. You will also learnhow to perform backups of the Oracle database using various techniques and howto recover the database in various failure scenarios. Finally, you will learn how toload, move, and reorganize large volumes of data very quickly using Oracle-provided utilities. This course helps prepare students for Oracle’s exam, Oracle9iDatabase: Fundamentals II (1Z0-032).

Course PrerequisitesTo ensure your success, we recommend you first take the following Element Kcourses or have equivalent knowledge:

• Oracle9i: SQL, PL/SQL, and SQL*Plus

• Oracle9i Database: Fundamentals I

Course ObjectivesWhen you’re done working your way through this course, you’ll be able to:

• Describe and configure the Oracle Network Environment.

• Describe the basic concepts of database backup and recovery in Oracle9i.

• Perform user-managed backups and recoveries of the database.

• Perform backups of the database using RMAN.

• Perform complete and incomplete recoveries of the database using RMAN.

• Move data around quickly and easily using Oracle-provided utilities.

COURSE SETUP INFORMATIONHardware and Software RequirementsTo run this course, you will need:

ABOUT THISCOURSE

About This Course ix

Page 11: Oracle 9i DBA Fund - II

• Each machine (instructor and student) to meet the following minimum hard-ware requirements:

— Pentium II 600 processor or faster.

— At least 256 MB of RAM.

— A minimum of 10 GB of available hard disk space for the System andOracle partitions.

— 256 k cache.

— 4x CD-ROM drive.

— SVGA monitor.

— Mouse or compatible pointing device.

• Each machine (instructor and student) to have the following softwareinstalled or available:

— Microsoft Windows 2000 Professional with Service Pack 2 or higher.

— Oracle9i Enterprise Edition 9.2.0.1.0 (this installation will include bothServer and Client).

— Microsoft Notepad v.4.0 or better.

— One of the following Web browsers:

• Netscape Navigator 4.76 or higher.

• Microsoft Internet Explorer 5.0 or higher.

Class RequirementsIn order for the class to run properly, perform the procedures described below.

1. As you prepare for the installation of the Oracle software, it is expected thatyou will have your computer configured with the previously outlinedrequirements. Please be sure that your hard drives are partitioned into atleast two partitions. One partition should be designated as the C drive for theoperating system software. The system drive should be at least 2 GB in sizeand formatted as either FAT or NTFS. The second partition should be desig-nated as the D drive and reserved for the Oracle installation. This driveneeds to be at least 8 GB and formatted as either FAT or NTFS.

2. Once the computer’s operating system is fully installed and configured, startWindows 2000 Professional and log on as Administrator.

Note: If you are installing Oracle by using the downloaded installation filesfrom Oracle Corporation’s Web site, rather than the installation CD-ROMs,follow the instructions that came with the downloaded media. Additionally, theinstallation files require considerable space on disk. Therefore, once theOracle9i software is installed, you should immediately delete the downloadedinstallation files from the system.

Insert the Oracle9i (9.2.0.1.0) Enterprise Edition CD in the CD-ROM drive.The CD will automatically run, and you will see the initial Oracle9i Wel-come screen displayed on the screen. Click Install/Deinstall Products, andthe Oracle Universal Installer will begin loading.

3. Once the installer loads, you will see the Welcome screen. Click Next.

This course will normallyrefer to the D:\oracle drive. Inreality, you may be using theD drive, the E drive, or some

other drive letter. If yourOracle partition is declared

as a letter other than D, youwill need to replace the

references in this manualwith your respective drive

letter.

x Oracle9i Database: Fundamentals II

Page 12: Oracle 9i DBA Fund - II

4. The File Locations screen prompts you to enter the paths for the source anddestination. The Source should show E:\stage\products.jar. If Destinationalready doesn’t show it, set the Destination Name to OraHome92 and thePath to D:\oracle\ora92. Click Next.

Note: If you are installing Oracle from the downloaded installation files, theSource path may be different than the one given here.

You will see a progress meter in the upper-right corner of the installer win-dow as the products list is loaded. This progress meter will appear severaltimes throughout the installation process.

5. The Available Products screen asks you to select a product to install. SelectOracle9i Database 9.2.0.1.0, and then click Next.

Note: The software version you may actually be installing might have aslightly different version number, such as 9.2.0.2.0. This course is designed towork with Oracle9i version 9.2.0.1.0 or higher.

6. The Installation Types screen asks you to select an installation type. SelectEnterprise Edition, and then click Next.

7. The Database Configuration screen asks you to select a database suited toyour needs. Select General Purpose, and then click Next.

8. The Oracle Services for Microsoft Transaction Server screen asks you toenter the port number on which the Oracle MTS Recovery Service will lis-ten for requests. Leave the value at its default setting, and then click Next.

9. The Database Identification screen asks you to enter the Global DatabaseName for the new database that will be created. For the Global DatabaseName, type ora92. The same value for SID will automatically be entered foryou. Click Next.

10. The Database File Location screen allows you to select a directory to storedatabase files. If Directory For Database Files doesn’t show it, set the pathto D:\oracle\oradata. Click Next.

11. The Database Character Set screen asks you which character set should beused in your database. The default character set should already be selected.Click Next.

12. The Summary screen provides you with a summary of the installation set-tings you have selected. Review the settings, and then click Install.

The Install screen shows a progress meter as Oracle is installed. Long pausesin the progress of the meter are normal.

Note: The entire installation process could take 30 to 45 minutes or more,depending on your system. You may occasionally see a number of windowsappearing and disappearing quickly throughout the installation process. This isnormal.

About This Course xi

Page 13: Oracle 9i DBA Fund - II

13. Once the software is installed, the Configuration Tools screen will appear.This screen displays information about the configuration tools that will auto-matically be launched for you in sequence to guide you through someadditional configuration steps.

You will see the Database Configuration Assistant dialog box appear. Thedialog box will show the steps being taken to create and start the database,along with a progress meter.

Once the database has been created and started, a new dialog box willappear asking you to change the passwords for the SYS and SYSTEM users.Set the password to ora92 for both the SYS and SYSTEM users, and thenclick OK.

You will be returned to the Configuration Tools screen of the Oracle Univer-sal Installer. You will see the installer execute additional configuration tools.

Once these tools have completed executing, the installer will move on to theEnd Of Installation screen. This screen provides information about the HTTPserver that was installed with the database. Click Exit. A question box willappear asking if you really want to exit. Click Yes.

14. After a few moments, the Oracle Enterprise Manager (OEM) Console willappear. In the left pane of the Network tree, click the plus sign next to Data-bases to expand the tree.

You will see an icon for ORA92 database. Double-click the ORA92 databaseicon. The Database Connect Information dialog box will appear.

In the Username text box, type sys, and in the Password text box, typeora92. Click the drop-down list for the Connect As entry, and selectSYSDBA. Click OK. After a moment, the Database Connect Informationdialog box will disappear, and the tree below the ORA92 database willexpand.

15. In the ORA92 tree, click the plus sign next to the Security icon to expandthe tree further.

Click the Users icon. The right pane will change to show a list of useraccounts that exist in the database.

16. In the right pane, find the user name RMAN in the list of users. Right-clickthe RMAN user name to bring up a command menu. Click Remove.

A dialog box will appear stating that RMAN still owns objects in the data-base, and asking if you are sure that you want drop the user and the objectsusing the CASCADE option. Click Yes.

After a few moments, the RMAN user name will disappear from the list ofusers.

17. Choose File→Exit to close the OEM Console.

18. Remember to delete the installation files as specified in the note at step 2.

To install the student files for this class, perform the following procedures:

1. Insert the CD-ROM that accompanies this course into the CD-ROM drive.

xii Oracle9i Database: Fundamentals II

Page 14: Oracle 9i DBA Fund - II

2. Choose Start→Run, enter E:\079176\Data\079176dd.exe into the Open textbox, and click OK.

3. Once the self-extracting WinZip file opens, confirm or change that it willwrite your files to the C drive in a folder named 079176.

List of Additional FilesPrinted with each lesson is a list of files students open to complete the tasks inthat lesson. Many tasks also require additional files that students do not open, butare needed to support the file(s) students are working with. These supporting filesare included with the student data files on the course CD-ROM or data disk. Donot delete these files.

HOW TO USE THIS BOOKYou can use this book as a learning guide, a review tool, and a reference.

As a Learning GuideEach lesson covers one broad topic or set of related topics. Lessons are arrangedin order of increasing proficiency with Oracle9i; skills you acquire in one lessonare used and developed in subsequent lessons. For this reason, you should workthrough the lessons in sequence.

We organized each lesson into explanatory topics and step-by-step activities. Top-ics provide the theory you need to master Oracle9i, and activities allow you toapply this theory to practical hands-on examples.

You get to try out each new skill on a specially prepared sample file. This savesyou typing time and allows you to concentrate on the technique at hand. Throughthe use of sample files, hands-on activities, illustrations that give you feedback atcrucial steps, and supporting background information, this book provides youwith the foundation and structure to learn Oracle9i quickly and easily.

As a Review ToolAny method of instruction is only as effective as the time and effort you are will-ing to invest in it. For this reason, we encourage you to spend some timereviewing the book’s more challenging topics and activities.

As a ReferenceYou can use the Concepts sections in this book as a first source for definitions ofterms, background information on given topics, and summaries of procedures.

About This Course xiii

Page 15: Oracle 9i DBA Fund - II

xiv Oracle9i Database: Fundamentals II

Page 16: Oracle 9i DBA Fund - II

Oracle Networking

OverviewOracle’s networking environment, called Oracle Net, enables connectivitybetween clients and database servers, and also between multiple databaseservers, thereby enabling distributed enterprise level database applications.In this lesson, you will learn about the features provided by Oracle Net andhow to configure your environment to provide optimal connectivity to yourdatabase servers. You will learn how to configure the database server toaccept connections and also how to configure the client to initiateconnections. Additionally, you will learn how to optimize your Oracle Netconfiguration to scale your environment to allow dozens, even hundreds, ofconnections to the database if necessary.

ObjectivesTo describe and configure the Oracle Network Environment, you will:

1A Describe the features of the Oracle9i network environment.

Oracle Net provides network connectivity to Oracle databases. You willlearn about the features of Oracle Net, its overall architecture, and thesteps involved in connecting a client to the database server. You will alsolearn the additional networking options that can be configured to enhancenetwork security.

1B Configure the database server to accept incoming networkconnections.

Configuring the database server to accept incoming network connectionsconsists primarily of configuring the listener process. The responsibilityof the listener is to receive incoming connection requests from a varietyof sources and process them accordingly. In this topic, you will learn howto configure the listener process and how to manage the listener throughthe Listener Control (lsnrctl) utility.

1C Configure a client to connect to an Oracle9i database through thenetwork.

When a client connects to a remote database, a username and passwordmust be passed to the database. Additionally, the client must be able tolocate the target database on the network. In this topic, you will learnhow to configure the Oracle client to locate and connect to remotedatabases.

1D Describe and configure Oracle Shared Server.

In a standard dedicated server configuration, each user that sends a con-nection request to the listener will connect to the database through a

Data Filesnone

Lesson Time4 hours, 25 minutes

LESSON

1

Lesson 1: Oracle Networking 1

Page 17: Oracle 9i DBA Fund - II

dedicated server process. If you have a high number of concurrent usersonline, this can be very costly in resources and impact performance.Oracle Shared Server is a configuration that allows each server process tohandle multiple connections to user processes. This will allow a highernumber of user processes to connect to the database, while saving onresources. You will learn the basic architecture of Oracle Shared Server(OSS), and how to configure and tune an Oracle Shared Serverconfiguration.

2 Oracle9i Database: Fundamentals II

Page 18: Oracle 9i DBA Fund - II

Topic 1AOracle9i Networking OverviewIn the early days of the information industry, the very first database systems werebuilt on stand-alone mainframes. This means that a user must be physically sit-ting at the machine where the data was stored to log in and retrieve data. It’seasy to see why this type of configuration would not support multiple users andcould not fulfill many of the requirements for a corporate data system. With theadvent of the microcomputer, better known as the personal computer or PC, anew type of configuration evolved, marrying the microcomputer and the main-frame and providing the best of both worlds. A user could sit at his or her owndesk and use the PC to log in to the mainframe. This is known as client-serverarchitecture or two-tier architecture. The PC acts as the client, while the main-frame acts as a server. Most often, there would be a single server with multipleclients connecting to it from various locations, allowing a much larger user baseto access the system simultaneously. Figure 1-1 shows an example of client-server architecture.

Figure 1-1: Client-server architecture.

The disadvantage to client-server architecture is that each client requires specialsoftware to connect to the server. Companies can have dozens, or even hundreds,of clients, each requiring manual configuration. Also, if any configurations neededto be changed or adjusted, each client would have to be changed individually,

Client-server Architecture

client-serverarchitecture:A configuration wheremultiple clients connect to asingle server.

Lesson 1: Oracle Networking 3

Page 19: Oracle 9i DBA Fund - II

requiring many hours of additional work. Also, older mainframe-style serverscould support only a limited number of users before performance started todegrade significantly, and the rapid-fire development and release of newer ver-sions of client software made it almost impossible to manage a large number ofclients.

As companies continued to grow, so did the requirements and expectations oftheir information systems. True scalability became the focus of many softwareand hardware manufacturers throughout the industry. Companies now began tolook for systems that could be purchased on a small scale, but that could grow asthe company grows, eliminating the need to replace critical systems as they reachtheir maximum use. The solution began as a fairly simple one, but revolutionizedthe way systems are designed and built, separating each component of the systeminto its own tier. This became known as a multi-tier or N-tier configuration. TheN represents a number, meaning an N-tier architecture can be made up of three,four, or more tiers as requirements dictate. In a 3-tier architecture, the databaseserver itself would be on one tier, a centralized application on the middle tier, andthe client on the third tier. Figure 1-2 shows a database system configured withan N-tier architecture.

Figure 1-2: N-tier architecture.

In Figure 1-2, the clients use their own computers to connect to a centralizedapplication that runs on a server. The client is configured with only the minimalsoftware required to connect to the application, which can be as simple as anInternet connection and a browser. The application server at the middle tier con-tains all the program code required to run the application. Users on the clientmachines issue simple commands to the application, which connects to the data-base on the clients’ behalf and returns the data to the clients. More advancedapplication servers can combine database requests from multiple clients and sendthem to the database server in a single group, thereby reducing network trafficand increasing performance. As the system grows, additional application servers

N-tier Architecture

N-tier configuration:A multi-level configuration

where each component of asystem, such as client,

application, and database,resides at its own tier.

4 Oracle9i Database: Fundamentals II

Page 20: Oracle 9i DBA Fund - II

can be added to the middle tier to keep up with user demands. Any changes orupgrades to the application only need to be done to the middle tier, simplifyingsoftware management. This powerful configuration provides full scalability, easeof maintenance, and superb performance regardless of the volume of data or thenumber of users.

To facilitate connections to the Oracle database, either in a client-server or N-tierarchitecture, Oracle makes use of its own network communication system calledOracle Net. Oracle Net is a term that collectively refers to Oracle’s networkinginfrastructure that enables clients to connect to servers and for servers to connectto other servers. Database applications accomplish their tasks in a distributedenvironment, meaning that a client may initiate a request to a single server, butthe request may be fulfilled by one, two, or more integrated application and data-base servers. Oracle Net provides the connectivity between a client and thedatabase server, or between an application and database server, and provides ahost of features to support the connectivity, stability, and security requirements oftoday’s networked database application systems.

Oracle Net ComponentsOracle Net has evolved over the years from being just a standard protocol tobeing a suite of products and features designed specifically to handle the chal-lenge of operating database applications on the enterprise level by addressingscalability, load balancing, failover, distributed transactions, security, and highavailability. Since Oracle Net uses a common network interface between applica-tions and the database, it can be used with both older and newer applications toprovide access to the database, and basic connection requirements only need avery simple configuration to get a client machine up and running. The followinglist of general Oracle Net features can be used individually or in combinations toallow Oracle to operate in the most demanding and diverse networkenvironments.

• Oracle Listener—Brokers connection requests from clients to the databaseserver. Multiple listeners allow for load balancing, connect-time failover, andtransparent application failover.

• Centralized Names Resolution—A central repository that stores the locationof all available database services. This allows clients to only require a singleaddress to access any service they need.

• Oracle Connection Manager—Allows for client and server with different pro-tocols to communicate. Also provides connection concentration andcontrolled access to database services based upon IP address.

• Oracle Advanced Security—Allows for single sign-on for authentication andauthorization to multiple database services as well as data encryption anddata checksumming.

• Heterogeneous Connectivity—Allows for clients to use standard Oracle SQLand procedure calls to seamlessly access non-Oracle data sources via a trans-parent gateway.

Lesson 1: Oracle Networking 5

Page 21: Oracle 9i DBA Fund - II

Additional Oracle Net features include dead connection detection and tracing anddiagnostic tools. Oracle Net’s dead connection detection feature automaticallydetects abnormally terminated client sessions and handles the rollback and releaseof database resources the session was using (for example, locks and latches).Oracle Net’s tracing and diagnostic tools will be covered in more detail later inthe course.

TASK 1A-1Describe Oracle Net Architecture

1. What are the disadvantages to running a database on a client-serverconfiguration?

Each client requires special software to connect to the server, each of whichwould have to be configured individually. Also, older mainframe-style serverscould support only a limited number of users before performance started todegrade significantly, and the rapid fire development and release of newerversions of client software made it almost impossible to manage a largenumber of clients.

2. In an N-tier configuration, what is the purpose of the middle tier?

The application server resides at the middle tier and contains all the pro-gram code required to run the application. Users on client machines issuesimple commands to the application, which connects to the database on theclients’ behalf and returns the data to the clients.

3. What is the purpose of the Oracle listener?

a. Allows clients to only require a single address to access any servicethey need.

b. Allows for clients to use standard Oracle SQL and procedure callsto seamlessly access non-Oracle data sources.

✓ c. Brokers connection requests from clients to the database server.

d. Allows for a client and server with different protocols tocommunicate.

dead connectiondetection:

A feature of Oracle Net thatautomatically detects

terminated client sessionsand handles the release of

database resources.

6 Oracle9i Database: Fundamentals II

Page 22: Oracle 9i DBA Fund - II

The User Connection ProcessThere are two connection types in Oracle9i. One way to describe them is thatthey are either single-task or two-task. Single-task means that the user and serverprocesses are one and the same; the user is connected directly to the database,and the connection happens in a single task. The request is made and the connec-tion granted. In a two-task connection, the user and server processes are separate,usually across a network, and the user must pass a request through the network toconnect to the server. The response is returned with a simple yes or no, and thenthe user connects to the database. If an error occurs during the connection processor the connection is lost, then the user must submit the request again. Figure 1-3shows the difference between a single-task connection and a two-task connection.

Figure 1-3: Single-task and two-task configurations.

A more detailed connection process is shown in Figure 1-4. In this graphic, youcan see both single-task and two-task connections.

Single-task and Two-taskConfigurations

single-task connection:A connection where theclient user and serverprocess are one in the same.

single-task connection:A connection where theclient and server processesare separate, usually througha network.

The User ConnectionProcess

Lesson 1: Oracle Networking 7

Page 23: Oracle 9i DBA Fund - II

Figure 1-4: The user connection process.

In Figure 1-4, the single-task connection is shown by the user process using thebequeath connection. It’s called the bequeath connection because the connectionrequest goes directly to the dedicated server process and is handed, orbequeathed, a connection. This type of connection is made when the user con-nects to the database from the very same machine where the database resides.

You can also see in Figure 1-4 that a two-task connection requires some addi-tional steps. This is because the connection request must be passed through thenetwork to the database server. Since it is possible, and highly probable, thatthere will be both multiple clients and multiple databases residing on the samenetwork, every connection request must be routed from a client to the properdatabase in a timely fashion. Regardless of networking environment, when a cli-ent makes a connection request through the network to a remote Oracle database,there is a certain usual sequence of events that takes place. Figure 1-5 shows thegeneral flow of a connection request with an explanation of each step.

bequeath connection:A single-task database

connection where the clientand server reside on the

same machine.

Connection Request Path

8 Oracle9i Database: Fundamentals II

Page 24: Oracle 9i DBA Fund - II

Figure 1-5: An example of a possible database connection request path.

The following steps are taken to establish a connection between a client and adatabase:

1. The user initiates a connection request with a connect string containing username, password, and net service name.

2. The net service name is resolved to a connect descriptor that provides thenetwork location of the appropriate listener process.

3. The connection request is sent to the listener with the service name of thetarget database.

4. The listener determines where to direct the connection request based on theservice name received and returns that network address back to the client.

5. The client connects directly to the database server at the network addressgiven by the listener process.

Step 1: The User Initiates a Connection RequestWhether from a custom application or from a tool such as SQL*Plus, the usermust provide a user name, password, and net service name when requesting asession with a remote database. A net service name is simply an alias for the des-tination database the client wishes to connect to. Following is an example connectstring from someone using a net service name:

sqlplus scott/tiger@dev

In this example, someone is invoking SQL*Plus from the command line followeddirectly by the connect string. The user name being provided is scott followed bya forward slash and then the password tiger.

If the database were local to the user, this might be all that was necessary toconnect. However, when the database is remote, you need to somehow tell yourclient application where it is located on the network. Hence the at symbol (@)followed by the net service name dev. In and of itself, dev does not give enoughinformation to specify a destination service or the means to reach this service.Instead, this net service name maps to a fully qualified connect descriptor, and isresolved during the connection process.

net service name:An alias for a destinationdatabase a client wishes toconnect to.

connect descriptor:The full connection definitionfor a net service name.

Lesson 1: Oracle Networking 9

Page 25: Oracle 9i DBA Fund - II

Step 2: The Net Service Name is Resolved to a ConnectDescriptorSince the listener process that knows exactly where each database that it supportsis located, a client needs only to contact the listener to figure out where it shouldgo to find the target database. The connect descriptor tells the client exactly towhich listener it should send its request, and where that listener is located on thenetwork. Consider the following connection request:

connect scott/tiger@dev

In this example, the characters after the at symbol (@) make up the net servicename, which in this case is dev. To proceed with the connection request, theOracle client must be able to translate this net service name to a network addresswhere the listener process is located. Oracle9i provides multiple methods ofresolving connect descriptors, and the names resolution method used will behighly dependent on the business requirements of the environment. In general,full connect descriptors for all net service names are stored in a specific location,such as in a file on the local client (tnsnames.ora) or in a centralized database onthe network. To resolve the net service name, the Oracle client would perform asimple lookup to find the full connect descriptor for the specified net servicename. You will learn about specific names resolution methods later in this lesson.

Whatever method is used to resolve the connect descriptors, most methods storethe information in a similar format. The following is an example connect descrip-tor for the dev net service name:

dev=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=dev01.company1.com)(PORT=

1521)))(CONNECT_DATA=(SERVICE_NAME=devdb)

))

In this example, you can see that using the dev net service name resolves to acomplete connect descriptor. Although it is technically legitimate to pass theentire connect descriptor at connect-time, typing such a large amount of text torequest a database connection is extremely cumbersome and highly error-prone.Using the net service name eliminates these issues and simplifies the connectstring that needs to be passed when requesting a database connection.

The ADDRESS entry in the connect descriptor tells the client where on the net-work it can find an appropriate listener process. In this case, the client wouldcontact the DEV01.COMPANY1.COM server at port number 1521.

10 Oracle9i Database: Fundamentals II

Page 26: Oracle 9i DBA Fund - II

Step 3: The Connection Request is Sent to the ListenerOnce the connect descriptor is resolved, the client now has the address of a lis-tener as well as the network protocol to use to reach it. The listener process,which is constantly running, listens for client connection requests and thenhandles them appropriately. It can be configured to listen for one or moredatabases. Depending on your requirements, you can configure a separate listenerfor each database on the network, or you can configure a single, centralized lis-tener to listen for multiple databases.

Upon contacting the listener process at the network location specified by theADDRESS entry in the connect descriptor, the client would pass to the listener theinformation specified by the CONNECT_DATA entry. The CONNECT_DATA tellsthe listener the service name of the database the client would like to connect toand may also include additional connection-specific information required by theclient. A service name may or may not be the actual name of its database; it issimply another alias which the listener will use to uniquely identify the databaseon the network. Oracle makes use of a database service name to allow multipledatabases on the same network with identical system identifiers (SIDs). Forexample, you could have two databases on the same network that both have SIDscalled DEV. Since the listener identifies each database by its service name only,and not the SID, the listener process will be able to tell them apart as long as theservice names are different.

Step 4: The Listener Determines Request DestinationOnce the listener receives a connection request and is passed the service namefrom the connect descriptor, the listener process will perform a quick lookup inits configuration to determine the location on the network where the appropriatedatabase resides. For our example, the client passes the service name DEVDB.The listener process looks in its configuration settings to determine the locationon the network where the DEVDB database service resides. The database may beon the same server where the listener is running or may be on a completely dif-ferent server.

Regardless of where the database resides, the listener process will contact thetarget database to retrieve the network address of an existing server process forthat database. If no free server process exists, the listener will instruct the data-base to spawn a new server process. Once the listener has determined thenetwork address of the intended server process, which is now known as a servicehandler, it will pass that network address back to the client. For the standardTCP/IP protocol, the network address of the service handler will usually includethe service name of the database and the port number assigned to the serverprocess.

Step 5: The Client Connects to the DatabaseUpon receiving the network address of the service handler, the client will com-municate directly with the server process without further intervention from thelistener. The requested connection has been established and the server processwill interact with the database on behalf of the client. The listener process willcontinue listening for other connection requests, and the entire connection processis now complete.

Do not confuse the netservice name with theservice name. The netservice name refers to theconnect string that a clientwould use to determinewhere the appropriatelistener resides on thenetwork. The service namerefers to the target databaseand is set by the database’sSERVICE_NAMESinitialization parameter.

system identifier:The identifying name for adatabase.

Lesson 1: Oracle Networking 11

Page 27: Oracle 9i DBA Fund - II

TASK 1A-2Identify the Steps in the User Connection Process

1. True or False? Connect descriptors can be specified directly on the con-nect string instead a net service name.

True. There are several alternatives to supplying a net service name in aconnect string and specifying the connect descriptor instead is technicallylegitimate.

2. Why do you think the concept of net service names was invented?Doesn’t this just add another unnecessary layer to the already complexprocess of connecting to a database?

While technically you can bypass net service names, in practice they makelife much simpler. Although some initial configuration is required, net servicenames are easy to maintain and can greatly simplify the command stringthat needs to be passed at connection time. Consider this connect stringwhich specifies a connect descriptor directly:

sqlplus scott/tiger@(description=(address=(protocol=tcp)(host=rnd.acme.org) (port=1521)) (connect_data=(service_name=dev.acme.org))

A connection request such as this is too cumbersome to use on a regularbasis and is extremely error prone. By storing the full definition of a connectdescriptor, either locally in the tnsnames.ora file or in a centralized namingserver, the connect descriptor can be easily maintained and resolved ondemand when a connection request is initiated.

3. What is the role of the listener in establishing a database connectionusing the bequeath method?

Absolutely nothing. When a database connection is established using thebequeath method, the client contacts the database directly, and the connec-tion is immediately established with a simple hand-off, or bequeath, to theserver process that will support the user connection. The listener is usedonly for connections that are requested through the network.

Oracle Net Layered ArchitectureWhen a client is connected to the database, whether that client be an end usermachine or an application server, all communications between the client and thedatabase server must pass through the network stack. The network stack is aseries of layers, one on the client side and one on the server side, that handles allmessages between the client and server. As a message traverses through the layersfrom the client to the server and back, each layer fulfills a certain responsibilitybefore passing the message to the next layer. Figure 1-6 shows the standardOracle client communication stack. The layers that come into play for each con-nection will depending on the type of connection and the connection protocolused.

Oracle CommunicationsStack

network stack:A series of layers that a

network connection betweena client and server must

pass through.

12 Oracle9i Database: Fundamentals II

Page 28: Oracle 9i DBA Fund - II

Figure 1-6: A typical Oracle communication stack.

In this figure, the client has established a connection to the database server. Whenthe client sends a request to database, such as a SELECT statement, the requestmust travel down through each of the layers on the client side, across to theserver where the database resides, then up through the stack layers on the serverside to the RDBMS. Each layer in the stack plays a role in ensuring that therequest is sent to the database server properly, performs any character or datatypeconversions as necessary, and ensures that the request reaches the database intactand uncompromised by malicious individuals or programs. Once the request isreceived by the database, the database will perform the action requested, and thensend the results back to the client using the reverse route.

You should also see in Figure 1-6 two optional components: names resolution andsecurity services. Names resolution is used to resolve net service names to con-nect descriptors, as described earlier in this lesson. The optional security servicescan be configured if a secure connection between the client and the database isrequired, such as when the database connection occurs across a wide-area net-work open to the general public, rather than within a closed-circuit local areanetwork. These security services provide the ability to encrypt database connec-tions and also checksum the information being passed so the database server willknow that it received the information in the exact same form as it was sent.

The Standard Oracle Communication Stack LayersThe OCI layer on the client side and the corresponding OPI layer on the databaseside perform virtually the same function. The abbreviation OCI stands for OracleCall Interface. This is the application program interface Oracle has provided toallow custom applications to make SQL calls to the database server directly, with-out requiring name resolution. The OPI layer on the database side stands forOracle Program Interface and performs the same function in that it provides theinterface for connections on the network to access the database. The main differ-ence between the OCI and OPI layers is that the OCI layer is designed to allowinteraction with a custom application. Oracle even provides the appropriate proce-dural routines in several different programming languages, such as C++ and Java,to make calls directly to the OCI layer. The OPI layer, on the other hand, isaccessible only by the database and cannot be directly accessed by an application.

application programinterface:An interface provided by asoftware vender that acceptsprocedural calls from acustom application to thevendor’s software.

Lesson 1: Oracle Networking 13

Page 29: Oracle 9i DBA Fund - II

The OCI layer is completely optional. If an application developer wishes, he orshe can design an application to make standard Oracle Net connection requestsusing net service names. However, doing so will force an additional dependencyon several other components of the Oracle client software, such as the namesresolution mechanisms. By using the OCI, the application can be designed withas few dependencies as possible, which can provide greater flexibility if the appli-cation needs to be transported from one machine or network to another.

The presentation layer handles translation between client and servers with differ-ent codepages and languages, which can occur if the client and server are runningdifferent operating systems. This layer is called the presentation layer because theclient will present its request to the network stack, and the presentation layer willdetermine what conversions, if any, will be required for the request to be under-stood by the receiving server. The specific type of presentation layer used by theOracle stack is called Two-Task Common (TTC), which is designed specificallyto handle character and data format conversions between a client and the Oracledatabase.

The Oracle Net foundation layer is responsible for establishing and maintainingthe connection between the client application and database server, as well asexchanging messages between them. This layer makes up the core of Oracle’snetworking functionality and is built on a technology called the Transparent Net-work Substrate (TNS). The TNS enables direct computer-to-computer connectionsregardless of the network protocol used, without requiring additional communica-tion support from other services or devices. This layer receives client applicationrequests and resolves all generic computer-level connectivity issues, such asnames resolution, determining which protocol to use for the connection, and han-dling connection interruptions between the client and database.

Once the Oracle Net foundation layer has determined the appropriate protocol touse for the client’s request, the request is forwarded to the Oracle protocol sup-port layer. This layer has the responsibility of mapping TNS functionality toindustry-standard network protocols. This ensures that the proprietary messageformat used by Oracle and the TNS component is translated into something thatcan be understood by the network and transported to the database server. Cur-rently, the Oracle protocol support layer can interface with the followingprotocols:

• TCP/IP

• TCP/IP with Secure Socket Layer (SSL)

• Named Pipes

As you will notice in Figure 1-6, the combination of the Oracle Net foundationlayer and the Oracle protocol support layer make up what is collectively knownas Oracle Net. While the OCI and Presentation – TTC layers are optional, allconnection requests must be passed through, at a minimum, the Oracle Net foun-dation layer and Oracle protocol support layer.

The network protocol layer is actually the network itself. Once the Oracle proto-col support layer has properly translated the request and passed it to the networkprotocol layer, it is the responsibility of the components that make up the networkto send the request to the target database. Depending on how the network is con-figured, the request may be sent directly to the target server, or it may be passedthrough several hops from one network device to another, before reaching its finaldestination. Once the request reaches the target server, the request is handed overto the Oracle protocol layer on the target server to be translated back to a stan-dard TNS request before forwarding it up the database’s communication stack.

14 Oracle9i Database: Fundamentals II

Page 30: Oracle 9i DBA Fund - II

If the Oracle client involved in the connection resides on the same machine as thedatabase, the network protocol layer can be bypassed by using a bequeath con-nection to the database. However, the use of a net service name will force the useof the network protocol layer, even if the client is on the same machine as thedatabase. This means that the connection will be routed through the server’s net-working components, network card included, to reach the database.

The Java Client Communication StackThe standard Oracle communication stack is used when the client is connecting tothe database via the TNS layer or by making calls to the OCI interface. However,Oracle also provides database connectivity to clients that make calls to the data-base through a JDBC driver. JDBC stands for Java Database Connectivity and isan industry standard connectivity interface for applications that make use of Javaprogramming on the client.

In order for an application to make calls through JDBC, the client machine musthave the appropriate JDBC driver installed. The JDBC driver is special softwarethat accepts standard calls from the client software and passes them to the data-base through the Java client communication stack. Oracle provides two types ofJDBC drivers, the JDBC OCI driver and the JDBC thin driver. The JDBC OCIdriver behaves much in the same way as the standard OCI interface; the only dif-ference being that the Java client will pass connection information and databaserequests from within Java routines, as opposed to some other language such asC++. When connecting to the database using the JDBC OCI driver, the Oraclestack will look almost identical to the standard Oracle communication stack; theonly difference is that the client is making calls to the JDBC OCI layer instead ofthe standard OCI layer. Figure 1-7 shows the Oracle communication stack forclients using the JDBC OCI driver. Notice that the only difference between thestack layers shown here and the layers shown in Figure 1-6 is that the client ismaking use of the JDBC OCI driver instead of the standard OCI applicationinterface.

Figure 1-7: The Oracle communication stack for JDBC OCI connections.

The JDBC thin driver is somewhat different in that it provides database connec-tivity to very small Java applications, such as Java applets. Using the JDBC thindriver, a Java applet can connect directly to the database through Java sockets,which bypasses most of the communication stack and can greatly improve con-

Java DatabaseConnectivity:An industry standardconnectivity interface forapplications that make use ofJava programming on theclient to connect to adatabase source, also knownas JDBC.

Communication Stack forJDBC OCI Connections

Communication Stack forJDBC Thin Clients

Lesson 1: Oracle Networking 15

Page 31: Oracle 9i DBA Fund - II

nection performance. The only other network support required by the JDBC thindriver is a lightweight Java implementation of the Presentation – TTC layer anda Java version of the Oracle Net layers, called JavaNet. Figure 1-8 shows theOracle communication stack that is used for JDBC thin clients.

Figure 1-8: The Oracle communication stack for JDBC thin clients.

In this figure, you will see that the communication stack for JDBC thin clientshas fewer layers than the standard Oracle communication stack. The OCI layer isnot used, and the Presentation layer is using a Java implementation of TTC. TheOracle Net layers have been replaced with JavaNet, which is a Java version ofthe Oracle Net components. Both the names resolution and security service com-ponents have been eliminated, which reduces the amount of network trafficrequired to establish and sustain a connection to the database. You should alsosee that the only networking protocols supported by the JDBC thin driver is TCP/IP, which must be used throughout the connection between client and server.

The Web Client Communication StackIn addition to the Two-Task Common presentation, Oracle also supports HTTPand FTP presentations, which allows Web clients to connect directly to the data-base using a Web browser. For example, a client machine using only a browsercan connect directly to the Oracle database and access the XML DB features ofOracle9i. The combination of the Web client connectivity and XML DB allow aclient machine to access and manipulate XML documents in the database. Figure1-9 shows the communication stack for Web clients to access the database.

Communication Stack forWeb Clients

16 Oracle9i Database: Fundamentals II

Page 32: Oracle 9i DBA Fund - II

Figure 1-9: The Oracle communication stack for Web clients.

For this type of connection, the client has only a Web browser and the standardTCP/IP protocol, both of which are used by most end users to access the Internet.On the database side, the communication stack makes use of Oracle’s TCP/IPprotocol support and a presentation layer that supports both HTTP and FTP. TheOracle9i database server itself provides the XML DB features and stores XMLdocuments right in the database. The only network protocol supported for Webclient connections is TCP/IP.

TASK 1A-3Describe Oracle Net Layered Architecture

1. In a client-server application connection, in which layer of the OracleNet stack are naming resolution methods applied?

a. Oracle Protocol Support

✓ b. Oracle Net Foundation layer

c. Network Protocol

d. Presentation – TTC

2. What is the advantage of developing an application to use the OCI layerinstead of using standard Oracle Net connection requests through netservice names?

Using standard Oracle Net connection requests through net service namesforces an additional dependency on several other components of the Oracleclient software, such as the names resolution mechanisms. By using the OCI,the application can be designed with as few dependencies as possible, whichcan provide greater flexibility if the application needs to be transported fromone machine or network to another.

Lesson 1: Oracle Networking 17

Page 33: Oracle 9i DBA Fund - II

3. Which layer of the Oracle communication stack is responsible for estab-lishing and maintaining the connection between the client applicationand the database server?

a. Network protocol layer

✓ b. Oracle Net Foundation layer

c. Presentation layer

d. Protocol support layer

4. Describe the communication stack layers that are involved for connect-ing a JDBC thin client to the database.

Using the JDBC thin driver, a Java applet can connect directly to the data-base through Java sockets, which bypasses most of the communication stackand can greatly improve connection performance. The only other networksupport required by the JDBC thin driver is a lightweight Java implementa-tion of the Presentation – TTC layer and a Java version of the Oracle Netlayers, called JavaNet.

Additional Networking OptionsIn addition to the standard Oracle Net configuration, Oracle supports a widerange of additional options that can enhance the security and functionality of theOracle Net and Oracle database environments. These options provide expandedscalability, enhanced database connection control, multi-protocol connectivity,enhanced connection security, and support for connections between Oracle andnon-Oracle databases. Some of these options come readily available with thebasic installation of Oracle, while others must be purchased and licensedseparately.

Connection ManagerIn addition to the capabilities and features of Oracle Net, Oracle has includedanother networking service, Connection Manager (CMAN). CMAN is design tosupport a large number of concurrent users in a 3-tier environment and canhandle more than 1,000 concurrent users. Connection Manager can be installed onany node that has Oracle Net and more or less functions as a virtual traffic copfor database connections. Oracle recommends that CMAN be configured on themiddle tier of a 3-tier architecture to take advantage of all the features itprovides. These features include:

• Connection Pooling

• Multi-protocol Connectivity

• Secure Network Access

18 Oracle9i Database: Fundamentals II

Page 34: Oracle 9i DBA Fund - II

Connection pooling refers to the technique of managing connections in a specificway to provide support for a large number of users. This added functionalityworks in conjunction with Oracle Shared Server (OSS) and provides increasedscalability and more efficient use of resources. As shown in Figure 1-10, to poolconnections CMAN will spawn a set number of connections to the database, andeach individual connection will support requests from multiple clients. As newconnection requests are sent to the database, CMAN will determine which pre-spawned connection is the least busy and refer the client to that connection. IfCMAN determines that all pooled connections are busy, it can spawn additionaldatabase connections to support the increased workload. By using this technique,the Oracle database can support hundreds of client requests with only a fewactual connections to the database.

Figure 1-10: Connection pooling by CMAN.

In Figure 1-10, several clients are connected to the database, but only two actualconnections to the database are necessary. This is because CMAN has pooled allthe client requests and is utilizing the absolute minimum number of connectionsto support the existing workload. Each individual connection to the database cansupport dozens of actual end users. The CMAN utility has the responsibility ofaccepting database requests from the clients, deciding which pooled connection isthe least busy to handle the request, or to spawn a new connection if all existingconnections are too busy. CMAN also has the responsibility of ensuring that theresults of each database requests, such as the result set of a query issued by aclient, is returned to the user that placed the request.

Connection Manager also supports multi-protocol connectivity. That is, your cli-ents can be using one type of protocol while your server uses another. Theprotocol conversion takes place automatically and is completely transparent to theuser. CMAN supports the following protocols:

• APPC (LU6.2)

• DECnet

• Named Pipes (Microsoft Networking)

• SPX/IPX

• TCP/IP

The protocol conversion can take place in both directions between the client andserver. Connection Manager also provides logging and tracing features to assist introubleshooting network problems in a multi-protocol environment.

Connection Pooling byConnection Manager

connection pooling:The technique of poolingmultiple client connectionsinto a group of fewerdatabase connections.

multi-protocolconnectivity:A configuration that supportsseveral different clientprotocols to connect to asingle database.

Lesson 1: Oracle Networking 19

Page 35: Oracle 9i DBA Fund - II

Connection Manager can provide additional security measures for networkconnections. It can be used as a stand-alone utility or in conjunction with Ora-cle’s Advanced Networking Option. CMAN can also be used for connectionauditing and as a soft firewall for incoming connections. You can configure theservice to decide whether to accept or reject connections based on the originand/or destination of the request, or even the database name that the connectionrequest is intended for. When CMAN is configured to function as a soft firewall,only those connections that are configured as permissible will be allowed toconnect. In other words, CMAN will always err on the side of caution: unlessyou specifically state that a connection from a certain client to a certain databaseis allowed, that connection will be immediately refused. That which is not spe-cifically granted is denied.

Oracle Advanced Security OptionData security is always a high priority for most companies. The Oracle databaseis a major investment, and the data it holds is usually critical to the owning com-pany’s livelihood and success. The most vulnerable component of the system isthe network. There are three major risks involved when running an Oracle data-base across a network (as with most databases), and each must be identified andaddressed before the system is considered safe from security breeches. Theserisks include:

• Data privacy

• Data integrity

• Authentication

Ensuring data privacy involves protecting data and passwords from theft or dis-closure to an unauthorized person or entity. User account passwords are stored inthe database in an encrypted form, but they are transmitted through the networkunencrypted during normal operations. Once a security breech occurs in the net-work, unencrypted data and/or passwords can be easily retrieved by the intruderand used maliciously for the intruder’s own purposes. To prevent such intrusions,Oracle Advanced Security provides data encryption capabilities when sendinginformation across the network. Data encryption involves executing a series ofprograms that scramble data to be transmitted using a specific key, which is usu-ally a long string of seemingly random characters. The receiving system willunscramble the data using the same key. Special hardware is required to imple-ment encryption with the Oracle database. Oracle Advanced Security iscompatible with much of the hardware available in the open market and also sup-ports four of the major encryption algorithms, which are:

• Data Encryption Standard (DES)

• Triple-DES (3DES) encryption

• RC4 from RSA Data Security, Inc (RSA RC4) privacy

• Advanced Encryption Standard (AES)

The DES encryption algorithm has been a standard of the U.S. government formany years and has been a requirement by law for certain systems in someindustries. Triple-DES encryption is similar to DES but encrypts and decryptsdata with three passes of the algorithm. Each pass through the data can use a dif-ferent key with a different length. 3DES supports 112- and 168-bit key lengths.The RC4 algorithm was developed by a company called RSA Data Security, anduses 40-, 56-, 128-, and 256-bit encryption keys. The AES algorithm is a rela-tively new encryption standard certified by the Federal Information Processing

20 Oracle9i Database: Fundamentals II

Page 36: Oracle 9i DBA Fund - II

Standard (FIPS). This algorithm uses 128-, 192-, and 256-bit key lengths. In gen-eral, the longer and more complicated the key used to scramble the data, theharder it will be for an intruder to break the code. Without the proper key, anintruder would only retrieve a meaningless stream of characters.

Ensuring data integrity involves protecting data from being modified or haltedduring transmission. An intruder intercepting data transmissions between a clientand a server can divert the transmission to another location, thereby causing datadisruption. The intruder can also modify the data and place it back in the networkstream, causing data modification. To ensure data integrity, Oracle AdvancedSecurity provides cryptographic checksumming capabilities, which can create adigital signature for each packet of data sent to the database across the network.This process involves using a hash value, called a checksum, which is recorded atthe end of each data packet. When the receiving end reads the packet, the samehashing algorithm is used to determine if the data had changed between the timeit was sent and the time it was received. While not impossible, it is highlyunlikely that a packet of data can be changed and still have a valid checksum. Inaddition to this checksumming, data packets are labeled sequentially in the orderthey are sent to hinder reordering of the packets. As the packets are received, thesystem checks the order of the packets to ensure the sequence has not beenaltered in any way. Both checksumming and sequential labeling provide dataintegrity across the network.

Authentication refers to the process of making positive identification of all cli-ents, hosts, users, and servers prior to allowing data to be transferred across thenetwork. Within Oracle itself, basic security can be implemented through the useof privileges and roles. However, any and all efforts to secure data will be in vainif the need to identify the user is not included in security planning. To ensureproper security in identifying users, Oracle Advanced Security supports third-party authentication mechanisms above and beyond those already provided by theOracle database system. These third-party products are used to ensure that theuser, client, and server are correctly identified before allowing any data to betransmitted. There are three main types of these mechanisms, which are:

• Network authentication services

• Token cards

• Biometric devices

Network authentication services provide a secure and centralized method of userauthentication and eliminate the need for clients and hosts to verify identities toeach other. These services also provide the convenience of only requiring onepassword per user, even though each user might require access to several secureareas of the system. The user logs in with a single password, which the servicethen uses to authenticate the user based on the specific privileges granted to thatuser. The entire process is completely transparent to the client, server, andapplications.

Token cards provide a one-time password method of authentication. An accesscard and personal identification number (PIN) is provided to the client. The userlogs on with the card and the PIN to gain access to the system. The token cardsuse single-use access codes that change every 60 seconds. Also, to allow easyidentification of card use, no two security cards can ever by encoded with thesame code number.

checksum:A hash value generated byreading a single piece ofdata.

Lesson 1: Oracle Networking 21

Page 37: Oracle 9i DBA Fund - II

Biometric authentication methods require the use of special hardware that willpositively identify an individual before allowing access. Identity can be confirmedusing some biological aspect of the individual, such as a fingerprint or retinapattern. Biometric adapters must be installed on both the client and the server toallow authentication data to be passed between the two. While at one time thistype of security device was found only in the movies, the falling cost of suchtechnology is quickly becoming reachable by the general business community.

Heterogeneous ConnectivityIn today’s business world, it is common for many companies to take advantage ofdatabase software products from numerous vendors to support various datasystems. It can be greatly beneficial for the company to combine the data from allof these systems and transform it into top-notch information about all aspects ofthe company’s operation. However, doing so is not such an easy task. Each sys-tem usually stores its data in a different way, accesses the data differently, andhas different ways to handle errors. Although SQL is an industry-standard querylanguage, most database products have their own dialect of the language. Evensimple datatype translations and basic transaction management can be differentfrom one system to the next. To simplify this seemingly daunting task, Oracleprovides heterogeneous connectivity services to allow clients to use standardOracle SQL and procedure calls to seamlessly access non-Oracle data sources.

Oracle provides heterogeneous connectivity through the use of its Oracle Trans-parent Gateway products. A gateway is primarily an interface between the Oracledatabase and another non-Oracle relational database system. Each gateway thatOracle offers is designed to provide connectivity to a specific database system ona specific platform. For example, Oracle offers the Oracle Transparent Gatewayfor DB2 on IBM RS/6000, which allows the Oracle database to access data on aDB2 database that is running on an IBM RS/6000 server. For each third-partydatabase product you want to access, you must install the appropriate gateway.Figure 1-11 illustrates the use of Oracle Transparent Gateways to access non-Oracle databases.

Figure 1-11: The use of Oracle Transparent Gateways.

heterogeneousconnectivity:

A feature that allows anOracle client to use standard

Oracle SQL and procedurecalls to seamlessly access

non-Oracle data sources.

Oracle TransparentGateways

22 Oracle9i Database: Fundamentals II

Page 38: Oracle 9i DBA Fund - II

In this figure, the client is accessing the Oracle database using a standard OracleNet connection. The Oracle database is configured with four different TransparentGateways that allow the database to access the databases from four differentvendors. Using basic Oracle SQL and PL/SQL, the client can query and manipu-late the data in multiple non-Oracle databases simultaneously and can evencombine the results from all five databases into a single, highly-informativereport. For some very specific situations, Oracle’s flavor of SQL may not be suit-able to access the foreign database. To address this issue, Oracle provides a pass-through ability, which allows the user to force a vendor-specific SQL statement tobypass Oracle’s SQL processor and send the statement straight to the foreigndatabase. This allows the user to communicate with the foreign database using itsown language, if necessary. Figure 1-12 shows more detail about the architectureof Oracle’s Heterogeneous Services.

Figure 1-12: Heterogeneous Services architecture.

To access a foreign database, Oracle will send SQL statements from the database,through the appropriate Transparent Gateway, to a Heterogeneous Services agent.This agent is comprised of agent generic code and a driver native to the targetdatabase. The agent generic code is used for all Oracle Heterogeneous Serviceproducts and provides a common interface for Oracle to interact with variousnon-Oracle systems. The native driver is essentially an API provided by the third-party vendor that produced the non-Oracle database software. The driver interactswith the foreign database using its own native language, and returns the resultsback through the agent generic code to the gateway.

Accessing foreign databases from within Oracle is much like accessing datathrough a database link. A connection qualifier is added to the table name in theSQL statement. When executing the statement, Oracle uses the connection quali-fier to determine which gateway to send the statement to. The followingstatement provides an example query that accesses an Informix database throughOracle’s Transparent Gateway.

SELECT name_last, name_first, deptnoFROM emp@infrmx01WHERE name_last LIKE 'S%';

In this example, the user is querying the EMP table in an Informix database. Thedatabase link, infrmx01, has been defined to access the Transparent Gatewayfor Informix. When the query is issued, it is sent from the gateway to the Hetero-geneous Service agent for that Informix database. The agent queries Informix onbehalf of the user, then returns the results to the Oracle database, which in turnreturns the results to the client.

Heterogeneous ServicesArchitecture

Lesson 1: Oracle Networking 23

Page 39: Oracle 9i DBA Fund - II

TASK 1A-4Identify Additional Networking Options

1. Describe multi-protocol activity. Which protocols does Connection Man-ager support?

Multi-protocol connectivity is a feature where clients can use one type ofprotocol while your server uses another. All protocol conversions arehandled by Connection Manager and is completely transparent to the user.

Connection Manager supports the following protocols:

• APPC (LU6.2)

• DECnet

• Named Pipes (Microsoft Networking)

• SPX/IPX

• TCP/IP

2. You are configuring Connection Manager to decide which connections toaccept and which to reject. Which of the following can you not configureConnection Manager to consider in deciding on permitting connections?

✓ a. User name

b. Origin

c. Destination

d. SID

3. Describe connection concentration. How can you provide additional sta-bility with Connection Manager?

Connection concentration refers to the technique of managing connections ina specific way to provide support for a large number of users. In addition,multiple connection managers can be configured to run at the same time,allowing several thousand connections at once.

Additional stability can be provided by configuring multiple connection man-agers to run simultaneously. If the primary connection manager server hasfailed or is otherwise not available, another one will be.

24 Oracle9i Database: Fundamentals II

Page 40: Oracle 9i DBA Fund - II

4. If user account passwords are stored in an encrypted form within thedatabase, why must you worry about an intruder intercepting passwordsacross the network?

User account passwords are stored in an encrypted form within the data-base, but are sent across the network unencrypted when a user logs in. If anintruder intercepts a password, he or she can use the password to log inwith another person’s credentials.

5. Provide a real-world example where data integrity is compromised byan intruder intercepting data being transmitted across the network anddiverting it to a different location.

There are many possible situations where this could occur. An examplewould be a hacker breaking into a bank’s network and rerouting anotherperson’s deposits to a different account in an effort to steal the money.

Topic 1BBasic Oracle Net Server-side ConfigurationConfiguring the database server to accept incoming network connections consistsprimarily of configuring the listener process. The listener is an Oracle program,separate from the database server, that runs on the server or a middle tier. A lis-tener is so-called because it “listens” for client connection requests over one ormore addresses on behalf of one or more Oracle database instances. Upon receiv-ing a connection request from a client, the listener will send the requesting clientthe network address of a prespawned server process where the target databaseresides. If there is no prespawned server process available, it will direct the data-base to spawn a new dedicated server process for the client. The actual serverprocess that handles the connection request is referred to as a service handler.Once the listener hands a client process off to either a dispatcher or server pro-cess, the listener no longer has any part in the communications of that sessionand returns to the task of listening for connection requests.

Create a ListenerListener configuration information is stored in a file called listener.ora, which islocated in the ORACLE_HOME/network/admin directory. This file contains allthe configuration information necessary for a listener to accept connectionrequests and direct clients to the proper databases. A single listener.ora file can beused to configure multiple listeners on a single server. If this file does not exist,the listener process can still be started, but it will use a default configuration,which may or may not be correct for the environment. Figure 1-13 shows asample listener.ora file.

listener:A constantly running processthat listens on the networkfor incoming connectionrequests.

A Sample listener.ora File

Lesson 1: Oracle Networking 25

Page 41: Oracle 9i DBA Fund - II

Figure 1-13: A sample listener.ora file.

In this file, there are two main entries, LISTENER and SID_LIST_LISTENER.The LISTENER entry provides configuration information about the listener itself.This information tells the listener exactly where it is located and on which port itis listening. In this case, the listener is running on the server called ELEMENTKand is listening on port 1521, which is the default listener port. The SID_LIST_LISTENER entry tells the listener which databases it is listening for. For listenerconfiguration shown here, the listener is supporting a database with a systemidentifier (SID) of ORA92. The global database name (GLOBAL_DBNAME) isan additional identifier that the listener will use to identify the database on thenetwork.

For the entries in the listener.ora file, the word LISTENER is actually the nameof the listener process. To support multiple listeners, you must name each listenerdifferently in the listener.ora file, and all listeners must be listening on differentports. For example, to add another listener, you might add another entry calledLISTENER1, or even TEST1. You can name a listener anything you want, aslong as all the required entries for the listener exist in the listener.ora file. For alistener called TEST1, the SID list entry would be named SID_LIST_TEST1.

After a database starts up, it will attempt to dynamically register its presence witha listener process. It will first look in the default location for a listener with thedefault name of LISTENER, at the default of port 1521. You can designate a lis-tener for the database other than the default one by setting the database’sLOCAL_LISTENER initialization parameter. If the database finds the listener,and if the listener is configured to listen for that database, the database will tellthe listener its SID and service names. The service names for a database are setby its SERVICE_NAMES parameter. The listener will match the database’s SIDwith the SID values set in the listener.ora file. When a client process contacts thelistener with a connection request and passes along the service name of the data-base it wants to connect to, the listener will use the service name to look up theappropriate SID in its SID list, and pass its network address back to the client.

global database name:A database identifier to

uniquely identify a singledatabase on a network.

26 Oracle9i Database: Fundamentals II

Page 42: Oracle 9i DBA Fund - II

While the listener.ora file can be edited manually, Oracle recommends using thegraphical front-end tool, Net Manager. Net Manager provides a streamlined inter-face to simplify configuration of the network environment and is less prone toerror. It aids in the creation and modification of listeners, net service names,Oracle Names servers, and much more. While working with Net Manager, theutility simply edits the appropriate configuration files for you and eliminatesmuch of the guesswork of making network changes. The Net Manager interfaceis shown in Figure 1-14.

Figure 1-14: Oracle Net Manager.

On a Windows machine, each listener process requires its own dedicated Win-dows service. A Windows service is an interface provided by the Windowsoperating system to allow a process to interact with other components of thesystem. When starting a new listener for the first time, this service will be auto-matically created for the new listener. Additionally, this service is required to berunning to start the listener. If the service is stopped or disabled, any attempt tostart the listener will result in an error. The Services console can be found in dif-ferent places depending on which version of Windows is installed. On Windows2000 Professional, the Services console can be found in Control Panel→Administrative Tools→Services.

Lesson 1: Oracle Networking 27

Page 43: Oracle 9i DBA Fund - II

TASK 1B-1Configuring the Listener Process

Objective: To configure the listener process using the Oracle Net Man-ager utility.

1. From the desktop, launch the Oracle Net Manager utility by choosingStart→Programs→Oracle – OraHome92→Configuration And MigrationTools→Net Manager.

After a moment, the Oracle Net Manager utility will appear.

28 Oracle9i Database: Fundamentals II

Page 44: Oracle 9i DBA Fund - II

2. In the left pane, click the plus sign next to the Local icon to expand thetree.

3. Double-click the Listeners icon to show the listeners that are currentlyconfigured on your system. You should see one listener, named LISTENER,in the tree.

Lesson 1: Oracle Networking 29

Page 45: Oracle 9i DBA Fund - II

4. Click the LISTENER icon. You will see the right pane of the windowchange to show the configuration information for this listener.

Notice that the Port number for this listener is 1521. You will configure anew listener for your database, except using a different port so that the twolisteners do not conflict with each other.

5. To add a new listener, choose Edit→Create.

A dialog box will appear asking you to choose a listener name. The name

The value for the Host entryreflects the actual name ofyour computer system and

may be different than what isshown here.

30 Oracle9i Database: Fundamentals II

Page 46: Oracle 9i DBA Fund - II

LISTENER1 should already be chosen for you. Click OK.

The dialog box will disappear, and LISTENER1 will be added to the tree inthe left pane.

6. Notice in the right pane that no configuration information has beenadded for the listener. This information tells the listener process which portnumber to listen on, and for which databases. You will add this informationnow.

Lesson 1: Oracle Networking 31

Page 47: Oracle 9i DBA Fund - II

In the right pane, click the Add Address button. An Address1 tab willappear in the right pane.

7. In the Address1 tab, change the value for Port to 1522

32 Oracle9i Database: Fundamentals II

Page 48: Oracle 9i DBA Fund - II

8. Change the drop-down list at the top of the right pane to DatabaseServices.

The right pane will change to show that no database services have been setup for this listener and that Oracle8i release 8.1 databases will dynamicallyregister with the listener.

9. Click the Add Database button in the right pane. You will see a Data-base1 tab appear in the right pane.

10. The information currently displayed in the Database1 tab is incorrect foryour database.

Lesson 1: Oracle Networking 33

Page 49: Oracle 9i DBA Fund - II

For the Global Database Name, type ora92

For the Oracle Home Directory, type D:\oracle\ora92

For the SID, type ora92

11. To save the listener configuration, choose File→Save NetworkConfiguration.

To close the utility, choose File→Exit.

Congratulations! You have just configured a new listener process for your

34 Oracle9i Database: Fundamentals II

Page 50: Oracle 9i DBA Fund - II

database using the Oracle Net Manager utility.

The Listener Control (lsnrctl) UtilityThe Listener Control utility is a simple command line utility that is used to man-age the listeners configured on the system. When started, the utility provides itsown prompt from which you can issue commands. The command to start the Lis-tener Control utility from any platform is simply lsnrctl. You can also issuecommands directly via the operating system command line by using the syntaxlsnrctl command listener_name. In this syntax, command is any oneof several commands that can be issued to manage a listener process, andlistener_name is the intended listener that the command is for. If you do notspecify a listener name, it will default to the listener named LISTENER.

The following table lists the Listener Control and the purpose of each.

Command Purposechange_password Changes the password for the target listener. All commands that cause

changes to the listener require the password.exit Exits from the Listener Control utility. Identical to the quit

command.help Displays a list of available commands and short descriptions of those

commands.quit Exits from the Listener Control utility. Identical to the exit

command.reload Reloads the target listener using the current configuration in the

listener.ora file. Useful when changing settings and you do not wish tostop and restart the listener.

save_config Instructs Listener Control to save all new changes back to the listener.ora file.

services Displays a list of all current database services, instances, and servicehandlers for the current listener and their status.

set Used to set a number of different configuration parameters.show Used to show a number of different configuration parameters.start Starts the target listener.status Shows a status summary of the target listener.stop Stops the target listener.trace Enables or disables tracing for the target listener.version Shows the release version of the target listener.

Three of the commands listed in this table, help, set, and show, haveextended command options. When used alone, the help command will displaythe list of commands available for the Listener Control utility. To get specificinformation about a particular command, you would type:

help command

In this syntax, command is the command you wish to know more about. ListenerControl will display a short description about the specified command.

The set command is used to set a number of different configuration parameters.Its syntax is:

set config_param new_value

Listener ControlCommands

Lesson 1: Oracle Networking 35

Page 51: Oracle 9i DBA Fund - II

In this syntax, config_param is the configuration parameter you wish tochange, and new_value is the new value you wish to set it to. The show com-mand syntax is similar, but only the config_param argument is used:

show config_param

The show command will display the current setting of the specified configurationparameter.

For both the set and show commands, when used alone without a specifiedconfiguration parameter, they will display a list of available configurationparameters. Most parameters that can be changed with the set command can bedisplayed with the show command. The following table lists the configurationparameters that are available for the set command.

Parameter Descriptioncurrent_listener Sets the name of the target listener that all subsequent commands will

be set to.displaymode Sets the amount of output that will be displayed for the services

and status commands. Valid values include RAW, COMPAT,NORMAL, and VERBOSE. By default, the display mode isNORMAL.

log_directory The path where the listener log file will be written to.log_file The name of the listener log file.log_status Enables or disables listener logging. Valid values include ON and

OFF. By default, the log status is set to ON.password Specifies the password for the current Listener Control session.save_config_on_stop Instructs Listener Control to save all unsaved configuration changes for

the current listener back to the listener.ora file when the listener isstopped using the stop command.

trc_directory Sets the directory path where listener trace files will be written to iflistener tracing is enabled.

trc_file Sets the trace file name that the listener will be writing tracinginformation to if listener tracing is enabled.

trc_level Enables listener tracing at the specified trace level. Valid trace levelsinclude OFF, USER, ADMIN, and SUPPORT. By default, the lis-tener trace level is OFF.

All configuration parameters that can be changed with the set command can bedisplayed with the show command, with the exception of the passwordparameter. This parameter is used to set the password for the current ListenerControl session only, but it does not change the password of the listener; this isdone with the change_password command. In other words, thechange_password parameter is used to change the stored password for thetarget listener. When the password has been set, all administrative tasks for thatlistener will require the password prior to executing the task. To supply that pass-word, you would use the set password command, which will prompt you forthe password. This password is only validated against the actual listener passwordwhen you attempt to perform an administrative task on the listener, such as stop-ping it. Only then will the listener compare the value you supplied for theset password command to the value specified for the change_passwordcommand.

36 Oracle9i Database: Fundamentals II

Page 52: Oracle 9i DBA Fund - II

It should be noted that the listener password set by the change_passwordcommand will only protect the listener from unauthorized access through the Lis-tener Control utility. Since the listener is just a process that runs at the OS level,any user with enough privileges through the OS can kill the process or stop itscorresponding Windows service. Additionally, since the listener configuration isstored in a simple text file, it too can be compromised by any privileged userthrough the OS. For example, a user with Administrator or root privileges can killthe listener process, change its configuration in the listener.ora file, and restart it.It is up to the DBA to coordinate system and database security efforts with thecompany’s system, network, and security administrators to avoid such issues.

TASK 1B-2Using the Listener Control (lsnrctl) Utility

Objective: To use the Listener Control utility to manage the listenerprocess.

1. From the desktop, choose Start→Run. The Run dialog box will appear.

In the Run text box, type cmd and press Enter. A command window willappear.

Lesson 1: Oracle Networking 37

Page 53: Oracle 9i DBA Fund - II

2. At the command prompt, type lsnrctl and press Enter. This will launch theListener Control utility.

3. The standard Oracle installation comes with a pre-configured listenerprocess. However, in the previous activity, you created an additional listenerfor your system. You should now determine which listener process you areworking with before proceeding. At the lsnrctl prompt, type show current_listener and press Enter.

You will see that the name of the listener that you are currently workingwith is LISTENER.

4. To see the current configuration of this listener, you will use the statuscommand. First, you will format the output of this command by setting thedisplaymode option to compat, which will minimize the output to ashort summary. At the lsnrctl prompt, type set displaymode compat andpress Enter.

The utility will respond with the message “Service display mode isCOMPAT.”

At the prompt, type status and press Enter. The utility will display a sum-mary of the configuration of this listener. The uptime and number of service

38 Oracle9i Database: Fundamentals II

Page 54: Oracle 9i DBA Fund - II

handlers shown in your output may differ slightly from what is shown here.

5. To switch the listener that you are currently working with to your new lis-tener, type set current_listener listener1 and press Enter.

The utility will display the message “Current Listener is listener1.”

6. To see the current status of the new listener, type status and press Enter.

Since LISTENER1 is a brand new listener and has never been started before,the corresponding Windows service for this listener has not yet been created.Therefore, the lsnrctl utility will return the errors “TNS-12541: TNS:no lis-tener,” “TNS-12560: TNS:protocol adapter error,” and “TNS-00511: Nolistener.”

7. To start the LISTENER1 listener, type start and press Enter.

After a few moments, the utility will respond with a series of errors andmessages. This output shows you that the utility is attempting to find theWindows service related to this listener, but cannot find it. Once it realizes

Lesson 1: Oracle Networking 39

Page 55: Oracle 9i DBA Fund - II

that the service does not exist, it automatically creates a new one, and thenstarts the listener.

8. To shut down this listener, you would use the stop command. At the lsnrctlprompt, type stop and press Enter.

The utility will display messages stating that it connected to the listener atits network address, and that the command completed successfully.

9. Since this listener is not currently running, attempting to request its statuswill return an error. At the prompt, type status and press Enter.

The utility will display several error messages, indicating that the listenercould not be reached.

10. To start the listener again, type start and press Enter.

The listener will start, and the utility will display the listener’s current status.

40 Oracle9i Database: Fundamentals II

Page 56: Oracle 9i DBA Fund - II

11. The lsnrctl utility also allows you to change the password for a listener toprovide a minimal level of security against unauthorized access. At theprompt, type change_password and press Enter.

You will be prompted for your old password. Currently, there is no passwordfor this listener, press Enter.

You will then be prompted for your new password. Type ora92 and pressEnter. For security purposes, the characters you type will not be displayedon the screen. When prompted to re-enter the new password, type ora92and press Enter again.

The utility will display the message “Password changed for listener1.”

12. Now that the listener has been given a password, any administrative com-mands sent to the listener will generate an error if the proper password isn’tset for the current lsnrctl session. At the prompt, type reload and pressEnter.

Since the proper password has not been set for this lsnrctl session, the utilitywill display the error “TNS-01169: The listener has not recognized thepassword.”

13. To provide the password for this session, type set password and pressEnter.

The lsnrctl utility will prompt you to enter the password. Type ora92 andpress Enter.

The utility will display the message “The command completed successfully.”

14. Now that the session password has been set, administrative commands willbe allowed. At the prompt, type reload and press Enter.

The utility will display the message “The command completed successfully.”

15. To exit the lsnrctl utility, type exit and press Enter. You will be returned tothe command prompt.

To exit the command window, type exit and press Enter again. The com-mand window will close.

Lesson 1: Oracle Networking 41

Page 57: Oracle 9i DBA Fund - II

Configure the Listener ManuallyWhen configuring a new listener, or changing the configuration of an existinglistener, Oracle recommends that you use the Net Manager graphical interface toavoid human errors. However, since the Net Manager utility simply modifies net-work configuration files automatically on your behalf, it is a simple task tobypass the utility and make changes to the appropriate files manually. Doing sodoes introduce the possibility of human error, but if done correctly, manuallymaking changes can be done very quickly and efficiently. When making changesto existing configurations, it is recommended that you make a backup copy of theoriginal configuration file prior to making the changes. This will give you a quickescape window if your change was not successful.

TASK 1B-3Configuring the Listener Manually

Objective: To configure the listener process manually.

1. From the desktop, choose Start→Run. The Run dialog box will appear.

In the Run text box, type D:\oracle\ora92\network\admin and press Enter.A window will appear for the D:\oracle\ora92\network\admin folder.

42 Oracle9i Database: Fundamentals II

Page 58: Oracle 9i DBA Fund - II

2. Double-click the listener.ora file to open it. If the Open With dialog boxappears, select Notepad from the list of applications, and then click OK.The listener.ora file will open.

3. The simplest way to manually add a listener definition to the listener.ora fileis to copy the definition of an existing listener. In the listener.ora file, high-light the definition for LISTENER1 listener.

The value for the HOSTparameter may be differentthan the one shown here.

Lesson 1: Oracle Networking 43

Page 59: Oracle 9i DBA Fund - II

Choose Edit→Copy.

Move the insertion point to the blank line after the last line of the LIS-TENER1 definition. Press Enter to add a blank line, then choose Edit→Paste. Add another blank line after the new LISTENER1 definition youjust pasted.

In the definition you just pasted, change the name of the listener to LIS-TENER2

Change the port number for this listener to 1523

44 Oracle9i Database: Fundamentals II

Page 60: Oracle 9i DBA Fund - II

4. You have just added the definition for a new listener, called LISTENER2.You will now add the ora92 database to the list of databases this listener willservice.

Scroll down through the file to find the entry for SID_LIST_LISTENER1. This entry defines which databases the LISTENER1 listenerwill service. Highlight the entire SID_LIST_LISTENER1 entry. Copy theentry and paste a new one below it using the same method as the lis-tener definition.

Change the name of the new entry to SID_LIST_LISTENER2

5. Choose File→Exit. You will be asked if you want to save the changes.Click Yes. The file will close.

6. Now that you have added the appropriate definitions to the listener.ora file,you will now use the lsnrctl utility to start the listener.

From the desktop, choose Start→Run. In the Run text box, type cmd andpress Enter.

At the command prompt, type lsnrctl and press Enter. This will launch thelsnrctl utility.

7. You must first set the current listener to listener2. At the lsnrctl prompt, typeset current_listener listener2 and press Enter. The lsnrctl utility will dis-play the message “Current Listener is listener2.”

8. At the prompt, type start and press Enter.

Just as in the previous activity, the lsnrctl utility will first display the “Failedto open service” error message. This indicates that the Windows service for

Lesson 1: Oracle Networking 45

Page 61: Oracle 9i DBA Fund - II

LISTENER2 has not yet been created. The service will automatically be cre-ated, and the listener will start.

9. Exit from the lsnrctl utility, and then exit from the command prompt.Close all open windows.

Topic 1CBasic Oracle Net Client-side ConfigurationTo connect to a remote database, the client must specify a user name and pass-word to the database. However, the database must first be identified and locatedon the network. When submitting a connection request, the client specifies analias to represent the intended database, which is resolved to the location on thenetwork where a listener for that database resides. Depending on how the client isconfigured, the client will use that alias to perform a lookup, called a names reso-lution method, to find the correct network location of the listener.

When submitting a connection request, the client will determine which namesresolution method to use by looking in its local sqlnet.ora file. This file is foundin the ORACLE_HOME/network/admin folder and contains basic configurationinformation for all connections originating from the client. This file can be con-figured through the Profile icon in the Net Manager utility, or it can be manuallyconfigured. The NAMES.DIRECTORY_PATH parameter in the sqlnet.ora fileprovides a list of names resolution methods that the client is configured to use.The client will first attempt to use the first method listed for this parameter. If theattempt is unsuccessful, it will attempt to use the next method listed. If all of thelisted methods fail, the connection request fails and the client software will returnan error. Figure 1-15 shows a sample sqlnet.ora file.

names resolutionmethod:

A configured method that isused to translate a net

service name to the networkaddress where the intended

database resides.

46 Oracle9i Database: Fundamentals II

Page 62: Oracle 9i DBA Fund - II

Figure 1-15: A sample sqlnet.ora file.

Oracle supports several names resolution methods, each of which are designed tosupport different environments and connection requirements. The names resolu-tion methods supported include:

• Host naming

• Local naming

• Centralized naming

• External naming

For simple connectivity requirements, Oracle provides the host naming resolution,which is capable of resolving aliases based on the name of the server where thedatabase is hosted. The host name or IP address of the server is stored in a localHOSTS file on the client machine or can be determined by a simple DomainNames System (DNS) on the network. This method passes the responsibility ofnames resolution to the client’s host machine and is generally used for verysimple network environments with very few clients and very few databases.

While it is extremely simple to configure, the disadvantage to host naming is thatmany of the more advanced connection capabilities are not available with hostnaming. For example, host name resolution is limited only to the TCP/IP proto-col, while other names resolution methods can support multiple protocols.Additionally, advanced security features, such as encryption and checksummingare not available with host naming.

For local naming, which is by far the most commonly used names resolutionmethod, the client stores a connect descriptor for each database it might connectto in a configuration file called tnsnames.ora, stored locally in the ORACLE_HOME/network/admin folder. When requesting a connection to a database, theclient would look up the connect descriptor in the tnsnames.ora file to determinethe network location of the listener that serves the target database. Unlike hostnaming, local naming supports multiple protocols and can use most of theadvanced security options. The disadvantage to local naming is that each clientmachine must be configured individually. For larger network environments, thistask can be particularly daunting, especially if there are dozens of databases andhundreds of clients on the same network.

Names Resolution Methods

host naming:A names resolution methodthat uses the client’s HOSTSfile to locate the targetdatabase on the network.

local naming:A names resolution methodthat is used to resolve netservice names by looking uptheir connect descriptors in adefinition file stored locallyon the client’s machine.

Lesson 1: Oracle Networking 47

Page 63: Oracle 9i DBA Fund - II

To alleviate the pain of configuring potentially hundreds of client machines,Oracle also supports centralized naming, allowing the DBA to configure a single,centralized repository of connect descriptors. When a client requests a connectionto a database, the specified alias is resolved by contacting the centralized namesresolution system. This system then passes the network location of the target lis-tener back to the client. While host naming and local naming can both beconfigured with just the Net Manager utility, centralized naming requires somefairly involved configuration, and may be overkill for some smaller environments.However, in larger environments, where connectivity is key and there is a limitedDBA staff, centralized naming can greatly ease some of the administrative burdenof managing such a complex environment.

External naming is a method that passes the responsibility of names resolutioncompletely outside of the Oracle environment. With this method, third-party soft-ware is installed, possibly in a centralized location, to store database connectdescriptors. External naming is normally used in very large environments wheredatabases of different software vendors are running, and any of several dozen orhundred clients may connect to any database provided by a different vendor. Tosimplify the administration of such an environment, external naming provides acentralized repository for connection information for a variety of databases fromdifferent software vendors. This type of system is generally very expensive to setup and maintain and is usually only found in the most complex of environments.

TASK 1C-1Identify Names Resolution Methods

1. Which names resolution method would be best in an environment wherethere are several dozen individual Oracle client systems and each clientneeds the ability to connect to multiple Oracle databases on the net-work? Explain your answer.

A centralized naming method would be best for this type of environment. Allconnection definitions could easily be stored in a central repository whereconnection information can be quickly looked up on demand. This greatlyreduces the maintenance overhead of configuring each client separately,especially in an environment that is constantly changing, such as when cli-ents and servers are constantly added, removed, or relocated within theenterprise.

centralized naming:A names resolution method

that stores all the connectdescriptors in a centrally-

located repository. All clientsneeding to resolve connect

descriptors contact thecentral repository.

external naming:A names resolution methodsimilar to external naming,

except the central repositoryis a non-Oracle, third-party

product.

48 Oracle9i Database: Fundamentals II

Page 64: Oracle 9i DBA Fund - II

2. Which names resolution methods can be configured using the Oracle NetManager utility? Choose all that apply.

✓ a. Host naming

✓ b. Local naming

c. Centralized naming

d. External naming

3. To configure host naming, which component of a networking environ-ment has the responsibility of resolving a connect descriptor?

a. The remote host where the application resides.

✓ b. The local host where the client resides.

c. The local host where the database resides.

d. The remote host where the Names server resides.

Configure Host NamingHost naming is the easiest resolution method to configure, and it provides simpledatabase connectivity for simple environments. When using the host namingmethod, the location of the listener is determined by using the host name of theserver where it resides. The host name or IP address of the server is stored in alocal HOSTS file on the client machine, or it can be determined by a simpleDomain Names System (DNS) on the network.

For Windows systems, the HOSTS file is stored in the C:\winnt\system32\drivers\etc or C:\windows\system32\drivers\etc folder, while on Unix systems, it is foundin the /etc directory. To configure host naming, the host name and/or IP addressof the target server is stored along with the alias for the target database. For hostnaming, the alias used must be the same as what is specified by the SERVICE_NAMES initialization parameter of the target database. You would also add thevalue HOSTNAME as the first option listed for the NAMES.DIRECTORY_PATHparameter in the client’s sqlnet.ora file.

When connecting to a database using host naming, the client first looks in itslocal sqlnet.ora file to determine which names resolution option to use. Uponfinding that the HOSTNAME value is the first listed, it will look in the HOSTSfile to find the host name or IP address of the target server where the listenerresides. The client would then contact that listener and pass along the specifiedalias. The listener would resolve that alias to the location on the network wherethe database resides, and pass that information back to the client. The clientwould then contact that server directly to connect to the database.

DNS:(Domain Names System) Aserver that is used to resolvematching host names to theirrespective IP addresses.

Lesson 1: Oracle Networking 49

Page 65: Oracle 9i DBA Fund - II

The TNSPING UtilityFor testing Oracle Net connections, Oracle provides the tnsping utility. This util-ity is similar to the standard ping utility, which sends out a small data packetacross the network to a specified server and times how long it takes for the targetserver to respond. The tnsping utility performs the same action with a databasealias. It is a command line utility that accepts a database alias, resolves the aliasusing the names resolution methods configured for the client, and attempts tocontact the listener at the resolved location. Like the ping utility, it too times howlong it takes for the target to respond.

This utility can be very handy for multiple purposes. It can be used to determineif your current client configuration is correct. If the configuration is correct, theping will succeed. If it is not correct, however, the ping will fail, usually with anerror that can indicate where your configuration is incorrect. The utility can alsobe used to help troubleshoot slow network connections. If a user is complainingthat it takes too long to connect to a specific database, you can use the tnspingutility from the user’s client machine as part of your troubleshooting process. Ifthe utility is showing abnormally long response times between the client machineand the listener, it is a good indication of where the problem resides. Figure 1-16shows a sample output from the tnsping utility.

Figure 1-16: The tnsping utility.

In this figure, the tnsping utility resolved the ora92 alias using host naming. Itthen contacted the listener at the host server specified by the client’s HOSTS file,then returned the total amount of time for the entire process to complete. For thiscase, the entire process completed in 220 milliseconds. Notice in the output thatthe SID parameter is set to only an asterisk (*), but the HOST parameter is set toora92. This is because the Oracle client is not really aiming at a specific data-base on the host server. Rather, it believes that ora92 is the host server, and isattempting to connect to any database it might find there. If multiple databasesreside on the target server, the listener will direct the client to connect to the firstdatabase listed in the listener.ora file’s SID_LIST_<LISTENER_NAME> param-eter for that target server.

tnsping utility:A utility that is used to timethe round trip of a network

packet from the client to thelistener and back.

50 Oracle9i Database: Fundamentals II

Page 66: Oracle 9i DBA Fund - II

TASK 1C-2Configuring Host Naming

Objective: To configure the Oracle client to use host naming.

1. From the desktop, open the command prompt.

2. At the command prompt, type tnsping ora92 and press Enter.

The output shows the method that was used to resolve the ora92 connectstring. The message “Used TNSNAMES adapter to resolve the alias” indi-cates that the Oracle Net client used local naming by looking up the ora92entry in the tnsnames.ora file. You will change the names resolution methodto use HOSTNAME instead of TNSNAMES.

3. Leaving the command open, launch the Oracle Net Manager by choosingStart→Programs→Oracle – OraHome92→Configuration and MigrationTools→Net Manager.

Lesson 1: Oracle Networking 51

Page 67: Oracle 9i DBA Fund - II

After a moment, the Oracle Net Manager utility will appear.

4. In the left pane, to expand the tree, click the plus sign next to the Localicon. In the tree, click the Profile icon.

The right pane will change to show the names resolution methods configuredfor your Oracle Net client. The current settings reflect the parameters thatare currently set in your sqlnet.ora file.

52 Oracle9i Database: Fundamentals II

Page 68: Oracle 9i DBA Fund - II

5. In the Selected Methods list box in the right pane, select the HOSTNAMEentry. Click the Promote button twice to move HOSTNAME to the topof the list.

6. Choose File→Save Network Configuration to save your changes.

7. Choose File→Exit to close the Oracle Net Manager.

8. You will now modify your system’s hosts file to include the ora92 connectstring.

From the desktop, choose Start→Run. In the Run text box, type C:\winnt\system32\drivers\etc and click OK.

A window for the C:\winnt\system32\drivers\etc folder will appear. Your Windows directory maybe named either winnt orwindows, depending on howyour system was configured.

Lesson 1: Oracle Networking 53

Page 69: Oracle 9i DBA Fund - II

9. Double-click the hosts file. If the Open With dialog box appears, selectNotepad from the list of applications, and click OK. The hosts file willopen.

10. Move the insertion point to the end of the word localhost. Press Tab,and then type ora92 and press Enter.

11. Choose File→Exit. You will be asked if want to save the changes. ClickYes. The hosts file will close.

Close the C:\winnt\system32\drivers\etc window.

54 Oracle9i Database: Fundamentals II

Page 70: Oracle 9i DBA Fund - II

12. In the command window, type tnsping ora92 and press Enter.

The output will now show that the HOSTNAME adapter was used to resolvethe alias. You have successfully configured your client to use the host namesresolution method.

13. Exit the command window.

Configure Local NamingConfiguring local naming is slightly more involved than host naming, but pro-vides much more flexibility and many more options. When local naming is used,the client requests a connection to a specific database by specifying a user name,password, and a net service name. The client determines the location of theappropriate listener by translating the net service name to a complete connectdescriptor stored in the client’s tnsnames.ora file, which is located in theORACLE_HOME/network/admin folder. Once the connect descriptor is resolved,the client can then contact the listener. The advantage over host naming is thatthe net service name for a particular database can be anything you want; you arenot limited to what is specified by the SERVICE_NAMES parameter of the targetdatabase. As a matter of fact, you can have several different net services namesthat point to the same database if you wish. Local naming also supports the useof many of the advanced security features of Oracle, such as encryption andchecksumming.

To configure local naming, you would add the value TNSNAMES as the firstentry in the NAMES.DIRECTORY_PATH parameter in the client’s sqlnet.ora file.You would then add any connect descriptor you want in the client’s tnsnames.orafile. Each time the client issues a connection request, the client will first look inthe tnsnames.ora file to resolve the connect descriptor. Figure 1-17 shows asample tnsnames.ora file.

A Connect Descriptor

Lesson 1: Oracle Networking 55

Page 71: Oracle 9i DBA Fund - II

Figure 1-17: A sample tnsnames.ora file.

In this figure, you will see that the first entry in the file is a connect descriptorfor the ORA92 net service name. To use this net service name, the client wouldissue a connect request such as the one shown here:

connect scott/tiger@ora92

When such a request is issued, the client will first look in its sqlnet.ora file todetermine how to resolve the net service name. The NAMES.DIRECTORY_PATH parameter would specify TNSNAMES as its first option. The client wouldthen look in its tnsnames.ora file to find the connect descriptor for ORA92. In theconnect descriptor, the HOST and PORT parameters specify the name of theserver and port number, respectively, where the target listener is located. Uponcontacting the listener, the client will pass the value specified by the SERVICE_NAME parameter, which is ORA92 in this case. The listener would look in itsconfiguration to find the network location of a database that uses ORA92 as aservice name and pass that network location back to the client. The client wouldthen connect directly to that database. If the tnsnames.ora file contains multipledefinitions for the same net service name, the first one listed in the file will beused for names resolution.

As with host naming, local naming can easily be configured using the Net Man-ager utility. The Profile page is used to specify TNSNAMES for the NAMES.DIRECTORY_PATH parameter in the sqlnet.ora file, and the Service Namingsection is used to add or change net service names to the tnsnames.ora file. TheNet Manager utility also provides a Net Service Name Wizard to automate andsimplify the process of adding net service names. Of course, the sqlnet.ora andtnsnames.ora files can be configured manually, if you like. Figure 1-18 shows theService Naming section of the Net Manager utility.

56 Oracle9i Database: Fundamentals II

Page 72: Oracle 9i DBA Fund - II

Figure 1-18: Local naming configuration using Net Manager.

TASK 1C-3Configuring Local Naming

Objective: To configure the Oracle client to use local naming.

1. From the desktop, launch the Net Manager utility.

2. You will first configure your client to use local naming as the first namesresolution method.

Click the plus sign next to the Local icon to expand the tree.

Click the Profile icon to display the list of naming methods currentlyconfigured for your client.

Lesson 1: Oracle Networking 57

Page 73: Oracle 9i DBA Fund - II

3. In the Selected Methods list box in the right pane, select TNSNAMES.Click the Promote button to move TNSNAMES to the top of the list.

4. You will now add a new net service name for your client.

Double-click the Service Naming icon to display a list of net servicenames currently configured for your client.

5. On the toolbar at the far left of the Oracle Net manager window, click thelarge plus sign.

58 Oracle9i Database: Fundamentals II

Page 74: Oracle 9i DBA Fund - II

The Net Service Name Wizard will appear.

6. In the Net Service Name text box, type localdb and click Next.

Lesson 1: Oracle Networking 59

Page 75: Oracle 9i DBA Fund - II

7. On the Protocol page, if necessary, select TCP/IP (Internet Protocol) andclick Next.

8. On the Protocol Settings page, you are prompted for the Host Name of theserver where the target database is located. Since the database resides on thesame machine as your client, in the Host Name text box, type localhost

Leave the Port Number to its default of 1521 and click Next.

60 Oracle9i Database: Fundamentals II

Page 76: Oracle 9i DBA Fund - II

9. On the Service page, there are two options for the database version,(Oracle8i or later) Service Name, and (Oracle8 or Previous) SID. The Ser-vice Name option is already selected for you. In the Service Name text box,type ora92 and click Next.

10. The Oracle Net Manager utility now has all the information it needs to cre-ate the new net service name. On the Test page, you can test your newconnection to confirm that your settings were correct. To test your new netservice name, click the Test button.

The Connection Test window will appear showing that the test has started.After a few moments, the window will show a message that states the con-nection test was successful.

11. When you are finished looking at the results of the test, click Close to closethe Connection Test window.

Lesson 1: Oracle Networking 61

Page 77: Oracle 9i DBA Fund - II

In the Net Service Name Wizard window, click Finish to return to theOracle Net Manager.

You will see that the localdb net service name has been added to your cli-ent’s configuration.

12. Choose File→Save Network Configuration to save your changes.

Choose File→Exit to close the Oracle Net Manager.

13. You will now use your new localdb net service name to connect to thedatabase.

From the desktop, choose Start→Programs→Oracle – OraHome92→

62 Oracle9i Database: Fundamentals II

Page 78: Oracle 9i DBA Fund - II

Application Development→SQL Plus to launch the SQL*Plus utility.

14. In the Log On dialog box, type system for User Name, ora92 for Pass-word, and localdb for Host String. Click OK.

After a moment, you will be connected to the ora92 database as the systemuser. You have successfully configured your client to locate and connect to

Lesson 1: Oracle Networking 63

Page 79: Oracle 9i DBA Fund - II

the database using the local names resolution method.

15. At the SQL*Plus prompt, type exit and press Enter to close SQL*Plus.

Troubleshooting Connection IssuesTroubleshooting network problems can sometimes be a daunting and frustratingordeal. However, the task of isolating problems and eliminating them can begreatly simplified by using a checklist. Depending on the problem itself, youwould generally start from the most global possibility to the most local, eliminat-ing possibilities as you go. Troubleshooting is not so much finding what’s wrong,as it is eliminating what’s not wrong. Whatever is left is usually the problem.

The situation most commonly experienced with network problems is not beingable to connect with whatever it is you want to connect to, whether it may befrom your client to the database using simple host naming or centralized or exter-nal naming and Advanced Security Option. However, these situations are oftenthe symptoms or the consequences of another, root problem. It is the job of theDBA to track down that problem and resolve it.

Developing a checklist for troubleshooting can greatly reduce the time it takes inisolating and resolving problems. You can quickly move through the checklist,ruling out possibilities, to arrive at the core of the problem. You can then takecorrective action to get the connection working as soon as possible. The follow-ing table provides an example troubleshooting checklist. The checklist youdevelop may be more or less extensive and may include other steps to matchyour specific requirements.

Item to Check ActionIs the database operational? Check the server to ensure the database is up and running.Is the problem widespread or related toone workstation or program?

Verify connectivity from other clients that log in to the sameserver or using the same program. Check with the networkadministrators for overall network problems.

64 Oracle9i Database: Fundamentals II

Page 80: Oracle 9i DBA Fund - II

Item to Check ActionCan you make a connection from theclient to the server?

Verify connectivity using PING and TNSPING. Testconnectivity from the client to the database by attempting tolog in.

Are the network protocols and Oraclenetwork protocol adapters installed onboth the client and server?

Ensure all required files exist and are configured correctly.

Is the listener operational and listeningfor the target database?

Use the lsnrctl utility to check the status of the targetlistener.

In many cases, connectivity issues are the result of something so blatantly obvi-ous that it becomes easy to miss. For example, if the database is not up andrunning, then no client will be able to connect. However, if only a single useractually uses that database, that person will probably be the only one complainingabout connection problems. It is almost too easy to jump to conclusions that it isthe client configuration that is incorrect, when it is really the database that has theproblem.

Once you have established that it truly is a single client that is having connectionproblems, you can begin to drill down to determine exactly what that client’sproblem is. This is where the tnsping utility becomes extremely useful. All Oracleclient installations have this utility, and can be used to test connections from theclient to the target listener. Any errors returned from the tnsping utility will usu-ally lead you straight to the root of the problem. The following table lists three ofthe most common errors that tnsping may return.

Error DescriptionTNS-03505: Failed to resolve name The service name did not match a valid name listed

in the tnsnames.ora file. Typically this results froman incorrectly entered service name at theapplication level.

TNS-12541: No listener Indicates the listener has not been started (or hasfailed) on the server. This can also happen if theactual port the listener is listening on is differentfrom that listed in the tnsnames.ora file.

TNS-12154: TNS: Could not resolve servicename

Indicates name resolution was not possible. Usuallyresults when the tnsnames.ora file is unavailable orempty. This error is different than TNS-03505 whereresolution was possible but was not successful.

If the steps in your checklist do not lead you to the root of the problem, you canenable logging and tracing for network connections using Oracle Net.

Common Errors Fromtnsping

Lesson 1: Oracle Networking 65

Page 81: Oracle 9i DBA Fund - II

Oracle Net Logging and TracingOracle log and trace files are used to obtain information on the interactionbetween the various network components. The trace files can then be analyzed todetermine the cause of the problems you are having. Logging and tracing providea useful means of generating detailed information for every aspect of the connec-tion processes. In addition, if the problem cannot be resolved using traditionalmeans, you can forward the log and trace files to Oracle Support for assistance.

Since logging and tracing can generate huge files in a very short time, Oraclerecommends that you begin your troubleshooting on the client side only. If youcannot isolate the problem there, move to the middle tier and try it there. If theproblem is still not resolved, then you should move to the server and enable log-ging and/or tracing database wide.

When logging is enabled, anytime Oracle Net encounters errors, the error mes-sages are written to a log file. The error entries include the number anddescription of the errors in the form of an error stack. The error stack contains alist of errors that begin at the most general error and drill down to the specificerror that occurred. The log also contains the date and time the errors were writ-ten to the file. By examining the log file, you can determine which errorsoccurred and why. The following list is a sample error stack from an Oracle Netlog file:

TNS-12206: TNS: received a TNS error during navigationTNS-12545: Connect failed because target host or object does notexist

In this error stack, the error TNS-12206 tells you that a client unsuccessfullyattempted to connect to the host. The error TNS-12545 tells you why it wasunsuccessful.

Log files tend to grow quite large if logging is left enabled for extended periodsof time. You should periodically purge old information in the log files or movethe files to another location for record keeping purposes. Newer entries areappended to the end of the log file. When you are investigating connection prob-lems, you would start at the bottom of the file and work your way backwardsuntil you pinpoint the exact origin of the errors.

The server creates two types of log files. One type is for incoming connections,the other for the listener process. If no sqlnet.ora file exists on the server, loggingwill be disabled. However, the default configuration for the listener is to havelogging enabled.

To enable logging on the server for incoming connections using Net Manager,you would only need to provide the directory in which to store the log file. Thiswill assign the directory to the LOG_DIRECTORY_SERVER parameter in thesqlnet.ora file. The file name of the log will default to sqlnet.log.

To enable logging for the listener process using Net Manager, you would provideboth the directory and file name of the log file. This will automatically configurerequired parameters in the listener.ora file. These parameters are:

• LOGGING_listener_name

• LOG_DIRECTORY_listener_name

• LOG_FILE_listener_name

Oracle Net logging:A feature that, when enabled,

allows Oracle to log allinformational entries to a

specified log file fortroubleshooting purposes.

Oracle Net tracing:A feature that, when enabled,allows Oracle to write out to

a trace file every internalstep taken to establish a

database connection, usuallygenerates much more

detailed output than standardlogging.

66 Oracle9i Database: Fundamentals II

Page 82: Oracle 9i DBA Fund - II

The LOGGING_listener_name parameter is set with the values of ON or OFF,and enables or disables logging for the listener. The LOG_DIRECTORY_listener_name and LOG_FILE_listener_name parameters provide the directory and filename of the log file, respectively. The parameters include the listener name toallow you to configure logging when you have multiple listeners. By default, lis-tener logging is enabled, and the log file is stored in the ORACLE_HOME/network/log folder and is named listener.log. The log file for the listener containsinformation about each client connection request and most of the LSNRCTL com-mands issued to the listener. It will also include date and time information whenthe listener was started and stopped.

The client will only generate log files that contain information on connectionsrequested from that client. These files will contain date and time information foreach connection request and any errors encountered during the connectionprocess. Client-side logging can also be configured using Net Manager, whichwill use the information provided to assign values to the LOG_FILE_CLIENTand LOG_DIRECTORY_CLIENT parameters in the sqlnet.ora file on the client.These parameters specify the file name of the log and the directory to store it in.

Trace files include detailed information for analyzing connectivity problems withOracle Net. These files include information on the protocol stack and the routinesused within each of the layers to make the connection. Not all layers of the stackare used for all connections. Therefore, you will not find entries in the trace filefor every layer every time a connection is processed. Each layer may call routinesin one or more of the other layers during the connection process.

Tracing is disabled by default. Since intensive tracing can impact performance, itis recommended that you enable tracing only when necessary to troubleshoot con-nection problems that are not resolved through logging. In addition, tracing canresult in very large trace files and will require additional storage space on disk,more so than logging. You can control the depth of the details generated in thetrace files by providing a trace level. The common levels for tracing are USER,ADMIN, and SUPPORT. USER level tracing will produce the least detailed infor-mation, while SUPPORT will provide most detailed. The tracing level mostcommonly used by DBAs is ADMIN. The SUPPORT level tracing is usually usedwhen you need to generate very in-depth, detailed trace files to forward to OracleSupport when a network problem cannot be resolved by the DBA.

As with logging, tracing can also be configured with the Net Manager utility. Forboth the client and the server, you can specify the levels, directories, and filenames of the trace files to be generated. This will automatically configure thenecessary parameters in the sqlnet.ora files. The parameters that will be set forthe client are:

• TRACE_LEVEL_CLIENT

• TRACE_DIRECTORY_CLIENT

• TRACE_FILE_CLIENT

• TRACE_UNIQUE_CLIENT

The TRACE_LEVEL_CLIENT parameter specifies the tracing level, and defaultsto OFF. The TRACE_DIRECTORY_CLIENT parameter specifies the directory tostore the trace files in and defaults to ORACLE_HOME\network\trace. The nameof the log file is determined by the TRACE_FILE_CLIENT parameter, anddefaults to sqlnet.trc. The TRACE_UNIQUE_CLIENT parameter, when set to ONwill ensure that each subsequently generated trace file will have a unique namefrom all other trace files in the destination directory. This is done by appendingthe process ID (PID) to the end of each file name.

Lesson 1: Oracle Networking 67

Page 83: Oracle 9i DBA Fund - II

The sqlnet.ora file on the server has identical parameters to handle tracing, withthe exception that each parameter ends with _SERVER. The parameters are:

• TRACE_LEVEL_SERVER

• TRACE_DIRECTORY_SERVER

• TRACE_FILE_SERVER

• TRACE_UNIQUE_SERVER

In addition to the standard connection tracing, you can also use Net Manager togenerate trace files for listener activity on the server. The utility will automati-cally set the required parameters in the listener.ora file, which function in thesame manner as the incoming connection trace parameters. The tracing param-eters to set for each listener process are:

• TRACE_DIRECTORY_listener_name

• TRACE_FILE_listener_name

• TRACE_LEVEL_listener_name

TASK 1C-4Configuring Client and Server Tracing

Objective: To configure tracing for both the client and database server.

1. From the desktop, launch the Oracle Net Manager.

2. Click the plus sign next to the Local icon to expand the tree.

In the tree, click the Profile icon. The right pane will change to show thecurrent naming methods for your Oracle client.

3. In the right pane, click the drop-down list and select General.

68 Oracle9i Database: Fundamentals II

Page 84: Oracle 9i DBA Fund - II

The right pane will change to show additional configuration options for theclient.

4. The Tracing tab is used to enable tracing for both the database server andthe client by automatically adding the pertinent parameters to the sqlnet.orafile.

If your Oracle client resided on a separate computer from the databaseserver, then server-side tracing would be configured only on the databaseserver machine and client side tracing only on the client machine. Since yourdatabase and server both reside on the same machine, you can configuretracing for both using the same sqlnet.ora file.

In the Client Information section, click the Trace Level drop-down list,and select Admin.

In the Trace Directory text box, type D:\oracle\ora92\network\trace

In the Trace File text box, type client_trace

The Unique Trace File Name feature instructs the Oracle client to add theprocess ID of each database connection to its trace file. This will ensure thatthe trace file names will be unique, and will not be overwritten by subse-

Lesson 1: Oracle Networking 69

Page 85: Oracle 9i DBA Fund - II

quent connections. Check the Unique Trace File Name check box.

In the Server Information section, click the Trace Level drop-down listand select Admin.

In the Trace Directory text box, type D:\oracle\ora92\network\trace

In the Trace File text box, type server_trace

5. Choose File→Save Network Configuration to save your changes.

Choose File→Exit to close the Oracle Net Manager.

70 Oracle9i Database: Fundamentals II

Page 86: Oracle 9i DBA Fund - II

6. To see the affects of the tracing, you will now connect to your database. Theentire connection process will generate output to your specified trace files atthe Admin level of detail.

From the desktop, choose Start→Programs→Oracle – OraHome92→Application Development→SQL Plus.

In the Log On dialog box, type system for User Name, ora92 for Pass-word, and ora92 for Host String. Click OK.

After a moment, SQL*Plus will connect to your database. Since all you needis a single connection to generate some basic client and server tracing, youcan simply close the connection. At the SQL*Plus prompt, type exit andpress Enter.

7. From the desktop, choose Start→Run. In the Run text box, type D:\oracle\ora92\network\trace and click OK.

A window for the D:\oracle\ora92\network\trace folder will appear. You willsee two or three files that end with the filename extension .trc. These are thetrace files that were generated from your SQL*Plus session.

Note: The process ID numbers used in the trace file names on your systemwill most likely be different than what is shown here. A trace file that includes“_1” before the .trc extension is a continuation of the first trace file of thesame name. For example, the contents of the client_trace_508_1.trc file is acontinuation of the contents in the client_trace_508.trc file.

8. Double-click the first client_trace*.trc file. If the Open With dialog boxappears, select Notepad from the list of applications and click OK. Thefile will open in a Notepad window.

Take a moment to look through the trace file. Keep in mind that the con-tent of this file shows what is happening within the Oracle client whiletrying to contact the database server and establish a connection.

Lesson 1: Oracle Networking 71

Page 87: Oracle 9i DBA Fund - II

When you are done looking at the trace file, close the Notepad window.

9. Double-click the server_trace*.trc file. The file will open in a Notepadwindow.

Take a moment to look through the trace file. Keep in mind that the con-tent of this file shows what is happening within the Oracle database serverwhile trying to establish a connection for an incoming connection request.

When you are done looking at the trace file, close the Notepad window.

Close the D:\oracle\ora92\network\trace folder window.

10. The final file to check is the log file generated by the listener process. Thisfile is found in the D:\oracle\ora92\network\log folder.

From the desktop, choose Start→Run. In the Run text box, type

72 Oracle9i Database: Fundamentals II

Page 88: Oracle 9i DBA Fund - II

D:\oracle\ora92\network\log and click OK to open a window for thisfolder.

11. Your system currently has three listener processes configured, therefore youhave three listener log files. As defined in the tnsnames.ora file, the ora92net service name contacts the default listener, named simply LISTENER, atport 1521.

Double-click the listener.log file to open it. If the Open With dialog boxappears, select Notepad from the list of applications and click OK. Thefile will open in a Notepad window.

The listener process will log all incoming connection requests, includingthose that are not honored due to privilege settings or misconfigurations.Take a moment to browse through this file. See if you can find the exactmoment in time your last connection request contacted the listener.

Lesson 1: Oracle Networking 73

Page 89: Oracle 9i DBA Fund - II

When you are done looking through the log file, close the Notepad window.

12. Close the D:\oracle\ora92\network\log folder window.

Topic 1DOracle Shared ServerThe two types of configurations to handle users’ requests for data include single-task and two-task configurations. In a single-task configuration, the user andserver processes are actually a single, combined process. The one processexecutes both the application code and the Oracle code, when processing arequest. Very few systems are capable of handling a single-task configuration.Two-task is the most commonly found configuration among Oracle setups. Theuser process and server process are separate. The user process handles the appli-cation code, while the server process handles the interaction with the database onbehalf of the user process. The server process can be either a dedicated or ashared process. It is considered dedicated because it will serve only a single userprocess at a time. A shared server process can handle multiple user connectionssimultaneously. A client/server environment is a common example of a two-taskconfiguration. The client handles the application or user process, while the serverhandles the Oracle code to manipulate data in the database. Figure 1-19 illustratesa client-server environment with a dedicated server configuration.

A Dedicated ServerConfiguration

shared server process:A single server process that

can support databaserequests from multipleclients simultaneously.

74 Oracle9i Database: Fundamentals II

Page 90: Oracle 9i DBA Fund - II

Figure 1-19: A dedicated server configuration.

A shared server configuration is a variation of the two-task configuration. Figure1-20 illustrates the shared server concept, in which Oracle can handle multipleconnections for multiple clients. In a dedicated server environment, the serverprocess must idly wait for data requests from the user process for as long as theuser process is logged in. This can become a waste of resources if the user pro-cess remains idle for long periods of time. In a shared server environment, youcan save in resource consumption by having several users connect to a singleserver process. There are fewer processes that must exist to support the workload,and those that do exist never remain idle for long.

Figure 1-20: An Oracle shared server configuration.

An Oracle Shared ServerConfiguration

Lesson 1: Oracle Networking 75

Page 91: Oracle 9i DBA Fund - II

It is important to note that while a shared server handles multiple connections tothe database, a user process can still request a dedicated server, which is alsoshown in Figure 1-20. Some processes require a dedicated server, such as con-necting to start and stop the database or any other administrative action thatrequires the SYSDBA or OSDBA roles. In addition, some user processes, such aslarge batch jobs, run much more efficiently with a dedicated server because thereis very little idle time involved with that specific type of workload.

The Connection Process in Oracle Shared ServerOracle Shared Server requires the use of a listener, of course. In a standard con-figuration, the listener waits for user processes to make a request, and then passesthe address of the server process back to the user process. The main difference inOSS is that the listener does not direct the user process straight to the server; allrequests from user processes are handled by dispatchers. Upon receiving a con-nection request, the listener performs a direct hand-off of the connection to adispatcher process. The user and dispatcher processes are then connected, and theuser will submit all database requests directly to the dispatcher. The dispatcherplaces the request from the user in a request queue in the SGA. The shared serverprocesses monitor the request queue and pick up any incoming requests. Anavailable server process will execute the command and place the results into thedispatcher’s response queue. The dispatcher will then pick up the results andreturn them back to the requesting user. Figure 1-21 illustrates how these compo-nents work together.

Figure 1-21: The connection process in Oracle Shared Server.

dispatcher:A background process in ashared server configuration

that accepts databaserequests from user processes

and passes them to sharedserver processes.

Oracle Shared ServerConnection Process

76 Oracle9i Database: Fundamentals II

Page 92: Oracle 9i DBA Fund - II

A request for data in a shared server configuration follows this sequence ofevents:

1. A user process places a request for a connection to the listener.

2. The listener performs a direct hand-off of the connection to a dispatcherprocess.

3. The user process issues a SQL command to the dispatcher process.

4. The dispatcher process places the SQL command in the request queue.

5. The SQL command is picked up by the first available shared server process,which executes the statement in the database.

6. The shared server process places the results of the SQL command in theresponse queue of the requesting dispatcher.

7. The dispatcher picks up the results of the SQL command from the responsequeue.

8. The results are returned to the requesting user process.

One way to look at the shared server configuration is to compare it to arestaurant. A customer (user process) walks in to the restaurant and is greeted bya host or hostess (listener). The host or hostess leads the customer to a seat,where he can make his request. A waitress (dispatcher) takes the customer’sorder, writes it on a ticket, and places the ticket on the chef’s ticket holder(request queue). An available chef (server process) will cook the food in thekitchen (database), and then place the prepared meal on the counter (responsequeue). The waitress (dispatcher, again) picks up the order and delivers it back tothe customer (user process). As the customer eats the meal, the chef can continuecooking meals for other customers.

This system is obviously much more efficient than having a dedicated chef foreach individual customer that places an order. While in real life this would bevery nice for the customer, it would be very costly for the restaurant. The restau-rant reduces its cost by having a single chef that can cook for several customersat once. A single waiter or waitress can pass orders back and forth between thekitchen and the dining room as needed.

TASK 1D-1Describing Oracle Shared Server Architecture

1. List and describe the three types of configurations to handle user’srequests for data.

• Single-task configuration—User and server processes are a single, com-bined process. Handles both the application code and the Oracle code.

• Two-task configuration—User and server processes are separate. Userprocess handles application code, while server process handles Oraclecode.

• Shared server configuration—Modified two-task configuration. Eachshared server process is capable of connecting to multiple user pro-cesses to handle requests to the database.

Lesson 1: Oracle Networking 77

Page 93: Oracle 9i DBA Fund - II

2. What is the main benefit of using a shared server configuration? Why?

The main benefit of using a shared server configuration is that multiple userprocesses can share a single server process, thus reducing the amount ofmemory resources consumed. This will help systems that have a larger clientbase to allow more users to connect and execute transactions, but still keep-ing resource consumption low.

3. True or False? Once you have Oracle Shared Server configured on yoursystem, all connections to the database must use a shared serverprocesses. Explain your answer.

False. A user process can still request a dedicated server. Some processesrequire a dedicated server, such as connecting to start and stop the data-base, or simply connecting as SYS with the SYSDBA role.

78 Oracle9i Database: Fundamentals II

Page 94: Oracle 9i DBA Fund - II

4. How does the role of listener in a shared server configuration differ fromthat of a dedicated server configuration?

In a dedicated server configuration, when a user process requests a connec-tion to the database, the listener provides the user process with the addressof the appropriate server. In a shared server configuration, the listener pro-vides the user process with the address of an available dispatcher for thatnetwork.

5. Identify and describe the numbered steps in the following picture.

The user process issues a SQL command to the dispatcher process. 3

The shared server process places the results of the SQL command in theresponse queue of the requesting dispatcher. 6

The listener performs a direct hand-off of the connection to a dispatcherprocess. 2

The dispatcher process places the SQL command in the response queue. 4

The results are returned to the requesting user process. 8

The SQL command is picked up by the first available shared server process,which executes the statement in the database. 5

A user process places a request for a connection to the listener. 1

The dispatcher picks up the results of the SQL command in the responsequeue. 7

Lesson 1: Oracle Networking 79

Page 95: Oracle 9i DBA Fund - II

Configuring Oracle Shared ServerThe majority of tasks required to configure Oracle Shared Server centers on set-ting various initialization parameters, which take effect when the database isstarted up. When shared server is configured, the contents of the SGA and theProgram Global Area (PGA) differ slightly from what you would find in a dedi-cated server environment. The PGA is the memory area at the operating systemlevel on the server that stores a user’s session data while the user is logged in. Inthe dedicated server configuration, the PGA consists of:

• Stack space to store information on local variables used by the process orruntime area.

• User session data, to include resource usage and security information such asa user’s privileges.

• Information on the state of the cursors that contain runtime memory valuesfor the SQL commands.

In Oracle Shared Server, only the stack space is found within the PGA. The otherinformation required for a user’s session, the session data and cursor-state infor-mation, is found in an area of the SGA known as the User Global Area (UGA).Each user will have a private User Global Area within the SGA. Because of thisextra information stored in the SGA, it is recommended that you increase the sizeof the SGA to accommodate for the additional processing space required to housethe UGAs.

You would set the following initialization parameters to configure Oracle SharedServer:

• LOCAL_LISTENER

• DISPATCHERS

• MAX_DISPATCHERS

• SHARED_SERVERS

• MAX_SHARED_SERVERS

LOCAL_LISTENERThe dispatcher processes must be registered with the listener process in order forthe listener to be aware that OSS has been configured for the database. TheLOCAL_LISTENER parameter specifies the service name for the listener, or mul-tiple listeners, with which the dispatchers must register. The values given to thisparameter in the initialization file must exactly match the service name specifiedin the connect descriptor as it is shown in the client’s tnsnames.ora file. Forinstance, the following is an example service name shown in the tnsnames.orafile:

O92SHARED =(DESCRIPTION =(ADDRESS_LIST =(ADDRESS = (PROTOCOL = TCP)(HOST = elementk)(PORT = 1521))

)(CONNECT_DATA =(SERVICE_NAME = ora92oss)

))

PGA:(Program Global Area) The

memory area at the OS levelon the server that stores a

user’s session data while theuser is connected to the

database.

UGA:(User Global Area) The

memory area at the OS levelon the server that exists only

in a shared serverconfiguration.

OSS ConfigurationParameters

80 Oracle9i Database: Fundamentals II

Page 96: Oracle 9i DBA Fund - II

To ensure that OSS will work as expected, this entry must be exactly as Oraclewill expect to find it, including all keywords and spaces. In addition, theLOCAL_LISTENER parameter must be assigned a value that matches theSERVICE_NAME parameter in the connect descriptor. For example, the param-eter must be set as follows:

LOCAL_LISTENER = ora92oss

If the LOCAL_LISTENER parameter is not listed in the parameter file, or is ini-tialized incorrectly, Oracle will resort to defaults in an attempt to configure thelistener for OSS. First, Oracle will look on port 1521 for any default TCP/IPlistener. If Oracle still cannot find a proper listener, the LOCAL_LISTENERparameter will default to match the ORACLE_SID parameter. It is for this reasonthat you should check and double-check that both the LOCAL_LISTENERparameter and the tnsnames.ora file are configured correctly. If there is one smallmistake in either location, OSS might not work, and the exact reason will be verydifficult to track down.

DISPATCHERSThe DISPATCHERS parameter specifies the number of dispatchers that are auto-matically spawned when the database is started up. The default value is null,which results in no dispatchers spawned at start up. You can also configure thesystem to accept connections from multiple network protocols, and assign one ormore dispatchers to each protocol.

For each dispatcher, you can list only one of the following specifications to setthe network protocol:

• PROTOCOL—Specifies the network protocol the dispatcher will use.

• ADDRESS—Specifies the actual network address to listen on.

• DESCRIPTION—Specifies a network description in Oracle Net syntax.

The following is an example of a correct assignment of the DISPATCHERS ini-tialization parameter:

DISPATCHERS = "(PROTOCOL=TCP)(DISPATCHERS=3)"

For multiple network protocols, the parameter will list each protocol separately,assigning each one a specific number of dispatchers. The following is an exampleof assigning the DISPATCHERS multiple network protocols:

DISPATCHERS = "(PROTOCOL=TCP)(DISPATCHERS=3) ⇒(PROTOCOL=IPC)(DISPATCHERS=2)"

The DISPATCHERS attribute (shown in parenthesis) indicates the number of dis-patchers to spawn at startup. If this keyword is left uninitialized, or omittedcompletely, the attribute will default to 1 dispatcher to be spawned at startup. Youcan also supply additional network attributes to the ADDRESS and DESCRIP-TION attributes. This is to support the possibility of having a host with multipleOracle homes. The additional attributes you can set include, but are not limitedto:

• SESSIONS—The maximum number of network sessions to be supported byeach dispatcher.

• LISTENER—The network name of an address or list of addresses for alistener.

• SERVICE—The service name for the dispatcher to register with.

The double right arrow (⇒)indicates that the syntaxshould be typed as if on asingle line. The double rightarrow is not part of thesyntax.

Lesson 1: Oracle Networking 81

Page 97: Oracle 9i DBA Fund - II

When the database starts up, Oracle will spawn the number of dispatchers perprotocol as specified in the DISPATCHERS parameter. Each process will benamed with a d for “dispatcher”, a number, and the database SID. For example, ifa database with the SID ora92 has three TCP dispatchers, they would be named:

ora_d001_ora92

ora_d002_ora92

ora_d003_ora92

An important point to remember is that this parameter does not set an absolutestatic number of dispatchers for the database; it only indicates the number of dis-patchers to start with. Oracle will create addition dispatchers to handle theconnection load if it is deemed necessary. In addition, this parameter can bedynamically modified for the current instance with the ALTER SYSTEMcommand.

MAX_DISPATCHERSThis parameter specifies the overall maximum number of dispatchers that are tobe created for the database. The default value is either 5 or the value of DIS-PATCHERS, whichever is higher. The following is an example of properly settingthis parameter:

MAX_DISPATCHERS = 3

SHARED_SERVERSThe SHARED_SERVERS parameter specifies the number of shared server pro-cesses to spawn when the database is started. The following is an example of thisparameter in the initialization file:

SHARED_SERVERS = 3

As with the dispatcher process, these server processes will be spawned at data-base start up, and named. The name of each process will include an s for “sharedserver”, a number, and the database system identifier. If you have specified thatthree shared servers for the ora92 database are to be spawned at start up, thoseserver processes would be named:

ora_s001_ora92

ora_s002_ora92

ora_s003_ora92

The default value for this parameter is 0, which indicates that no shared serverswill be started for the database. Also, you can modify this parameter using theALTER SYSTEM command for the current instance.

MAX_SHARED_SERVERSThis parameter specifies the maximum number of shared server processes that areto be created for the database. The default for this parameter is 20, or two timesSHARED_SERVERS, whichever is higher. The following is an example of set-ting this parameter in the initialization file:

MAX_SHARED_SERVERS = 10

This parameter cannot be changed dynamically with the ALTER SYSTEM com-mand for the current instance. It can only be modified in the parameter file orspfile, which requires the database to be restarted for the parameter to take effect.

82 Oracle9i Database: Fundamentals II

Page 98: Oracle 9i DBA Fund - II

TASK 1D-2Configure Oracle Shared Server

1. Which of the following is found within the PGA in a shared server con-figuration? Choose all that apply.

a. Cursor-state information

b. User session data

✓ c. Stack space

d. Shared SQL area

2. Where is the user session data stored in a shared server configuration?

a. Temporary tablespace

b. System Global Area (SGA)

c. Program Global Area (PGA)

✓ d. User Global Area (UGA)

3. True or False? All users must share the User Global Area within theSGA. Explain your answer.

False. Each user will have a private User Global Area within the SGA.

4. Give an example of setting the DISPATCHERS parameter for aninstance on a network that uses TCP protocol. This instance will spawnfive dispatchers at startup.

dispatchers="(PROTOCOL=TCP)(DISPATCHERS=5)"

5. What happens if you set the value of SHARED_SERVERS to 0?

Setting the SHARED_SERVERS parameter to 0 will cause the database tospawn 0 shared servers at instance startup, which basically disables OracleShared Server.

Monitoring and Tuning Oracle Shared ServerConfiguring Oracle Shared Server consists mainly of setting initialization param-eters to enable the feature and sizing the SGA to accommodate the additionalmemory requirements. When monitoring and tuning OSS, you are checking toensure you have set those initialization parameters to appropriate values for yoursystem. You may find that you have to experiment with different combinations ofsettings before finding the right configuration for your system’s needs.

Lesson 1: Oracle Networking 83

Page 99: Oracle 9i DBA Fund - II

There are five data dictionary views used to monitor a shared serverconfiguration. These views are closely related to the parameters listed in the pre-vious section. The views are:

• V$CIRCUIT

• V$DISPATCHER

• V$SHARED_SERVER

• V$SHARED_SERVER_MONITOR

• V$QUEUE

V$CIRCUITThe V$CIRCUIT view contains information about each OSS connection. If thereis a problem with a specific process in the database, you can use this view togather information on the specific user.

V$DISPATCHERYou can monitor all your dispatchers with the V$DISPATCHER data dictionaryview. The most important columns in this view are the STATUS, IDLE, andBUSY columns. The STATUS column has several possible values. The followingtable lists those values and their descriptions.

Dispatcher Status DescriptionWAIT Idle.SENT Currently sending a message.RECEIVE Currently receiving a message.CONNECT Establishing a connection.DISCONNECT Processing a request to disconnect.BREAK Processing a break.OUTBOUND Establishing an outbound connection.

The IDLE and BUSY columns provide the amount of time the dispatcher spentidle or busy. You would determine the current total busy rate for the dispatchersof each network by taking the ratio of total time busy to the total time the dis-patcher existed. The following formula is used to determine the busy rate foreach dispatcher:

busy / (busy + idle)

This formula simply gives you the ratio of time spent busy to the total time thedispatcher has been up and running. The following query will accessV$DISPATCHER for the total dispatcher busy rate for each protocol configured:

SELECT network,SUM (busy) / (SUM (busy) + SUM (idle)) * 100 rate

FROM v$dispatcherGROUP BY network/

The following shows a sample output from this query, which in this case indi-cates that only a single dispatcher is configured, and it has a busy rate of justunder 35 percent.

NETWORK RATE-------------------------------------------------- ------(ADDRESS=(PROTOCOL=tcp)(HOST=elementk)(PORT=1030)) 34.25

OSS Data Dictionary Views

84 Oracle9i Database: Fundamentals II

Page 100: Oracle 9i DBA Fund - II

If the current workload as determined by the busy rate is consistently low, youcan consider reducing the number of dispatchers you have to conserve processmemory. If the workload is consistently at 50 percent or above, you should con-sider adding dispatchers. You can add dispatchers dynamically using the ALTERSYSTEM command. For example, to increase the number of dispatchers from 1 to5, for both the current instance and subsequent database restarts, you would usethe following statement:

ALTER SYSTEMSET DISPATCHERS = "(PROTOCOL=TCP)(DISPATCHERS=5)" SCOPE=BOTH;

Bear in mind that the new dispatchers are only available to subsequent logins.Users currently logged in will not be able to use the new dispatchers. Also, youcannot dynamically change the number of dispatchers such that there will be lessdispatchers than specified by DISPATCHERS in the parameter file, or to a num-ber higher than the MAX_DISPATCHERS parameter.

V$SHARED_SERVERThis view is used to monitor the shared server processes. As with the dispatchers,you would monitor the shared servers by determining the current workload on theservers. You would determine the busy rate by using the same formula used forthe dispatcher busy rate. If the total workload of the shared servers exceeds 50percent, you should add shared servers. Shared server processes can be added bychanging the SHARED_SERVERS parameter. The following is an example ofincreasing shared servers from three to five using the ALTER SYSTEM commandfor the current instance and all subsequent restarts:

ALTER SYSTEM SET SHARED_SERVERS = 5 SCOPE=BOTH;

V$SHARED_SERVER_MONITORThe V$SHARED_SERVER_MONITOR view provides information that can behelpful in deciding the best value for the MAX_SHARED_SERVERS parameter.The columns found in this view are listed in the following table.

COLUMN DESCRIPTIONMAXIMUM_CONNECTIONS Maximum number of connections that each dispatcher can

support (OS dependent).MAXIMUM_SESSIONS Highest number of shared server sessions in use at one time

since the instance started.SERVERS_STARTED Total number of additional shared servers started since instance

startup (above and beyond the specified number at instance startup).

SERVERS_TERMINATED Total number of shared servers stopped since instance startup.SERVERS_HIGHWATER The highest number of shared servers since database creation.

The column to watch in this view is SERVERS_HIGHWATER. You should setthe MAX_SHARED_SERVERS parameter to a value above SERVERS_HIGHWATER to be sure your system can handle more connections than youwould ever expect.

Lesson 1: Oracle Networking 85

Page 101: Oracle 9i DBA Fund - II

V$QUEUEThe V$QUEUE view provides information on the request and response queuesused by the dispatcher and shared server processes. You would use this view todetermine the average wait time for a connection waiting in the response queuefor dispatcher or shared server processes. The following query will access theV$QUEUE view and generate this information:

SELECT network,'DISPATCHER' wait,DECODE (SUM(totalq),0,'NO RESPONSES',SUM(wait)

/SUM(totalq)) responsesFROM v$queue,

v$dispatcherWHERE v$queue.TYPE = 'DISPATCHER'

AND v$queue.paddr = v$dispatcher.paddrGROUP BY networkUNIONSELECT ' ' network,

'SERVERS' wait,DECODE (totalq,0,'NO RESPONSES',wait/totalq) responses

FROM v$queueWHERE TYPE = 'COMMON'ORDER BY 1 desc/

The following shows a sample output from this query:

Network Waiting For: Responses---------------------------- ------------ ----------------(ADDRESS=(PROTOCOL=tcp) DISPATCHER NO RESPONSES(HOST=elementk)(PORT=1030))

SERVERS NO RESPONSES

This output shows that there are few or no sessions that are currently usingshared server connections, and therefore, there are no waits. If you find that con-nections are forced to excessively wait in the request or response queues fordispatchers or shared servers, you should increase the numbers of these processesaccordingly.

TASK 1D-3Describe Methods to Monitor and Tune Oracle SharedServer

1. How would you determine whether or not more dispatchers need to beadded to your configuration?

You would determine whether or not you need to add dispatchers by deter-mining the overall busy rate of the dispatcher processes. You would use thefollowing formula with values from the IDLE and BUSY columns of theV$DISPATCHER view:

busy / (busy + idle)

If the results of this formula show that the dispatchers are busy 50 percentof the time or more, you should add dispatchers.

86 Oracle9i Database: Fundamentals II

Page 102: Oracle 9i DBA Fund - II

2. In the parameter file, the DISPATCHERS parameter is set to 5, and theMAX_DISPATCHERS parameter is set to 20. What value can youdynamically set the DISPATCHERS parameter using the ALTERSYSTEM command?

The DISPATCHERS parameter cannot be dynamically set to a value lessthan its original value at instance startup or greater than the MAX_DISPATCHERS parameter. Therefore, using the ALTER SYSTEM command,you can dynamically set the DISPATCHERS parameter to any value between5 and 20, inclusive.

3. Which column of the V$SHARED_SERVER_MONITOR view will pro-vide information to help in setting the MAX_SERVERS parameter?

a. MAXIMUM_CONNECTIONS

b. SERVERS_STARTED

c. MAX_SERVERS

✓ d. SERVERS_HIGHWATER

4. How would you determine if connections were forced to excessively waitin the request or response queues for available dispatchers or sharedservers? How would you resolve this problem?

You would determine the overall average wait time for connections in therequest and response queues by looking in the V$QUEUE data dictionaryview. If connects are excessively waiting for dispatchers or shared servers,you would increase the numbers of these processes as needed.

Configuring the Listener for Web ClientsAs you learned earlier in this lesson, Web clients can connect directly to the data-base through the network. This is made possible by communicating with thedatabase through a specialized communications stack as shown in Figure 1-22

Figure 1-22: The communication stack for Web clients.

Lesson 1: Oracle Networking 87

Page 103: Oracle 9i DBA Fund - II

In this figure, the client uses a Web browser to connect to the database throughthe network. Since the client needs almost no additional configuration, you onlyneed to configure the database to accept connections from Web clients. This con-sists mainly of configuring the listener handle Web client connection requests andconfiguring at least one dispatcher to act as a service handler for the database.

Figure 1-22 actually shows only a simplified version of the communicationsstack; some pieces have been simplified for clarity. When Web clients connect toa network, they primarily make use of the HTTP or FTP protocols. These proto-cols are both considered Internet Inter-ORB Protocols (IIOP). In general, IIOP isa presentation protocol designed to implement CORBA technologies across theinternet. CORBA stands for Common Object Request Broker Architecture, andwhile it sounds fancy, it is really just an attempt to provide an industry-wide stan-dard of accessing various types of data sources through a network. The equivalentpresentation layer on the server side is called General Inter-ORB Protocol(GIOP). Figure 1-23 illustrates the communications stack configured to supportIIOP and GIOP.

Figure 1-23: The communications stack with the IIOP and GIOP layers.

In this figure, the client machine accesses the Internet in general using IIOP pro-tocols, specifically HTTP or FTP. All requests from the client are sent through theIIOP presentation layer using industry-standard object requests. The requests aresent to the database through the network using TCP/IP and are translated by thedatabase using the standard TCP/IP protocol support layer. The request is thensent through the database’s GIOP presentation layer to hand off to the database.

To support Web client connections, the database server must have Oracle SharedServer configured with at least one available dispatcher. The listener can be con-figured to listen for both traditional database requests and for Web client requests.The IIOP protocol is used by the client to contact the listener, which is listeningon a specially configured port for Web connections. The listener will hand theconnection off to the appropriate dispatcher that is configured to receive requestsfrom the GIOP layer.

To configure the GIOP layer on the database side, you would simply include thePRESENTATION argument with the set value for the DISPATCHERS initializa-tion parameter. This argument is set to Oracle’s predefined GIOP presentationlayer that is included with the Oracle software. For example, the following showsthe DISPATCHERS parameter correctly configured to support Web client connec-tions through the GIOP presentation layer.

IIOP:(Internet Inter-ORB Protocol)

A presentation protocoldesigned to implement

CORBA technologies acrossthe Internet.

CORBA:(Common Object Request

Broker Architecture)Architecture that provides an

industry-wide standard ofaccessing various types of

data sources through anetwork

The Communications Stackwith the IIOP and GIOP

Layers

88 Oracle9i Database: Fundamentals II

Page 104: Oracle 9i DBA Fund - II

dispatchers="(address=(protocol=tcp)(host=elementk)) ⇒(presentation=oracle.aurora.server.SGiopServer)"

In this example, a single dispatcher will be configured with the TCP/IP protocolon the ELEMENTK server. This dispatcher will be configured to support Webclient requests from the GIOP presentation layer. The presentation layer usedhere, oracle.aurora.server.SGiopServer, is the standard presentationincluded with the Oracle software. Once the dispatcher is configured, the databaseis ready to support database requests from Web clients.

Configuring the listener to listen for Web client connections consists of adding anew network address to the listener.ora file. This network address must be differ-ent than the address used to support traditional Oracle Net connections. Thefollowing shows an example listener.ora configured for Web client connections.

LISTENER=(DESCRIPTION_LIST=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=elementk)(PORT=1521))

)(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=elementk)(PORT=2481))

(PROTOCOL_STACK=(PRESENTATION=GIOP)(SESSION=RAW))

))

In this example, the listener is listening on port 1521 for standard Oracle Netrequests and on 2481 for Web client requests. Port 2481 is the standard port forWeb clients not using Secure Socket Layer (SSL), and 2482 clients using SSL.The SESSION argument is set to RAW to ensure that the format of the datapackets sent by the client remain in their raw form and are not transformed inany way until it reaches the TCP/IP protocol support layer on the database side.

Once the listener and dispatcher are configured, connecting to the database is assimple as navigating to a Web site through the browser. The Web site addressuses the following format:

sess_iiop://hostname:port/service_name

For our example, the Web site address would be formed as shown here:

http://elementk:2481/ora92

When the client issues a connection request to the listener on 2481 using HTTPor FTP protocols, the listener will identify it as a Web client and pass the connec-tion to the pre-configured dispatcher through the GIOP presentation layer for thedatabase. The dispatcher will access the database on behalf of the Web client andreturn all results to the client machine.

Web clients can also be configured to directly contact dispatchers at pre-assignedports. Each dispatcher can be assigned a port by specifying a host and port num-ber for the ADDRESS keyword of the DISPATCHERS parameter. For example, adispatcher can be configured specifically to listen on port 2481. The client cannavigate directly to that port and completely bypass the listener. In some cases,this can reduce the amount of time it takes to connect to the database because theneed to contact the listener has been eliminated.

Lesson 1: Oracle Networking 89

Page 105: Oracle 9i DBA Fund - II

TASK 1D-4Configure the Listener for Web Clients

1. What is IIOP?

IIOP stands for Inter-ORB Protocol. IIOP is a presentation protocoldesigned to implement CORBA technologies across the Internet. CORBAstands for Common Object Request Broker Architecture, which provides anindustry-wide standard of accessing various types of data sources from anetwork.

2. True or False? IIOP connection requests can bypass the listener anddirectly contact dispatchers through the network. Explain your answer.

True. IIOP clients can be configured to directly contact dispatchers at pre-assigned ports. Each dispatcher can be assigned a port by specifying a hostand port number for the ADDRESS keyword of the DISPATCHERSparameter.

3. Which argument must be included with the DISPATCHERS initializa-tion parameter to configure the GIOP layer for the database server?

a. ADDRESS

b. CONNECTION

c. LAYER

✓ d. PRESENTATION

SummaryIn this lesson, you learned about the features of Oracle Net and how to con-figure both the Oracle database server and the client to establish connectionsto the database. You also learned how to configure Oracle Shared Server toimprove the scalability of the Oracle database and accept large numbers ofconcurrent connections. Additionally, you learned about the additional net-working options that are available for Oracle and the features they provide.

90 Oracle9i Database: Fundamentals II

Page 106: Oracle 9i DBA Fund - II

Lesson Review1A In an N-tier environment, what is the easiest way to scale the environ-

ment to keep up with user demands?

a. Add another tier.

✓ b. Add more application servers.

c. Add more database servers.

d. Add more memory to each client’s machine.

In which situation could you connect to the database with a bequeathconnection?

a. When connecting to the database from a client machine.

b. When connecting to the database from a Java applet.

c. When connecting to the database directly from the Web.

✓ d. When connecting to the database from the same machine where thedatabase resides.

Which protocols does the Oracle protocol support layer currently sup-port? Choose all that apply.

✓ a. Named Pipes

✓ b. TCP/IP

✓ c. TCP/IP with SSL

d. UDP

True or False? When using 3DES encryption for database connections,each pass through the data to be transmitted must use the same key,which must have a length of 128 bits. Explain your answer.

False. When using 3DES encryption for database connections, each passthrough the data to be transmitted can use a different key with a differentlength. 3DES supports 112- and 168-bit key lengths.

1B In which directory is the listener.ora file stored?

✓ a. ORACLE_HOME/network/admin

b. ORACLE_HOME/network/config

c. ORACLE_HOME/rdbms/admin

d. ORACLE_HOME/sqlplus/admin

Lesson 1: Oracle Networking 91

Page 107: Oracle 9i DBA Fund - II

True or False? The set password command for the Listener Controlutility is used to change the permanent, stored password for the listener.Explain your answer.

False. The set password command is used to set the password for thecurrent Listener Control session only, but it does not change the password ofthe listener; this is done with the change_password command.

Even if you set an administrative password for the listener, how can thesecurity and integrity of the listener process be compromised by anunscrupulous individual?

Since the listener is just a process that runs at the OS level, any user withenough privileges through the OS can kill the process or stop its correspond-ing Windows service. Additionally, since the listener configuration is storedin a simple text file, it too can be compromised by any privileged userthrough the OS. A user with Administrator or root privileges can kill thelistener process, change its configuration in the listener.ora file, and restartit.

1C When submitting a connection request, how does the client determinewhich names resolution method to use?

a. By contacting the DNS server.

b. By contacting the listener.

✓ c. By looking in its local sqlnet.ora file.

d. By looking in its local tnsnames.ora file.

In which folder is the HOSTS file stored on a Windows NT system?

a. C:\winnt\network\admin

b. C:\winnt\system32\admin\etc

c. C:\winnt\system32\com

✓ d. C:\winnt\system32\drivers\etc

On which page of the Net Manager utility would you specifyTNSNAMES for the NAMES.DIRECTORY_PATH parameter to bewritten to the local sqlnet.ora file?

a. Local

✓ b. Profile

c. Service Identification

d. Service Naming

92 Oracle9i Database: Fundamentals II

Page 108: Oracle 9i DBA Fund - II

Describe the cause of the following connection error and the first stepsyou would take to resolve it?

• TNS-03505: Failed to resolve name

The service name did not match a valid name listed in the tnsnames.ora file.Typically this results from an incorrectly entered service name at the appli-cation level. The first step should be to ensure that the client or applicationis using the correct service name, and that the service name has the appro-priate connect descriptor.

1D What happens after a user process issues a SQL command to the dis-patcher process?

The dispatcher process places the SQL command in the request queue to bepicked up by the next available shared server process.

Describe the difference in the user’s PGA when connected to a sharedserver connection as opposed to a dedicated connection.

In a dedicated server connection, the PGA consists of stack space to storeinformation on local variables, user session data such as resource usage andsecurity information, and cursor state information. In a shared server con-nection, only the stack space is found within the PGA. The other informationis found in an area of the SGA known as the User Global Area (UGA), andeach user will have a private UGA within the SGA.

What query to the V$DISPATCHER view will give you the total dis-patcher busy rate for each protocol configured?

SELECT network, SUM(busy) / (SUM(busy) + SUM(idle)) * 100rateFROM v$dispatcherGROUP BY network;

How can Web clients be configured to directly contact dispatchers atpre-assigned ports?

Each dispatcher can be assigned a port by specifying a host and port num-ber for the ADDRESS keyword of the DISPATCHERS parameter. The clientcan navigate directly to that port and completely bypass the listener.

Lesson 1: Oracle Networking 93

Page 109: Oracle 9i DBA Fund - II

94 Oracle9i Database: Fundamentals II

Page 110: Oracle 9i DBA Fund - II

Backup and RecoveryOverview

OverviewThere are several different types of failures that can affect the Oracle data-base and its clients, some of which can result in costly downtime orunavailability of the database. In this lesson, you will learn about the typesof failures Oracle is susceptible to, how to build a solid backup and recov-ery strategy to protect the database from failures, and how to minimizedowntime in the event that failures occur. Additionally, you will learn thebasics about cold and hot database backup and recovery techniques, andyou’ll explore the mechanisms that Oracle has in place to support thesetypes of operations.

ObjectivesTo describe the basic concepts of database backup and recovery in Oracle9i, youwill:

2A Describe the types of failures that may occur in an Oracle9i databaseand the features provided to resolve them.

Failures in an Oracle database can be very costly. Every minute of down-time could translate into tens of thousands of dollars of lost revenue for acompany. You will learn about the types of failures that can occur andhow Oracle reacts to each type of failure.

2B Perform a cold backup of the database, and use that backup torestore and recover the database after a failure.

Cold backups allow you to create a complete copy of your database thatis guaranteed to be consistent. When recovering the database from a coldbackup, the database will look exactly as it did at the point in time thedatabase was shut down for the backup. In this topic, you will learn howto perform a cold backup of the database and how to use that coldbackup to restore and recover the database after a failure.

2C Describe the mechanisms in place to back up and recover an Oracle9idatabase with minimal data loss.

Oracle provides mechanisms that allow you to perform backups andrecoveries of the database while the database stays up and running. Thisminimizes downtime and can minimize the mean time to recovery. In thistopic, you will learn how to configure your database to support hot back-ups and learn the process that is used to perform a hot recovery.

Data Filesnone

Lesson Time4 hours, 30 minutes

LESSON

2

Lesson 2: Backup and Recovery Overview 95

Page 111: Oracle 9i DBA Fund - II

Topic 2AIntroduction to Backup and RecoveryThere are several different types of failures that can affect the Oracle databaseand its clients, some of which can result in costly downtime or unavailability ofthe database. These failures can have varying affects on the database, dependingon the scope and severity of the failure. Some types of failures only affect singleusers or single transactions, while other failures can affect the availability of theentire database. The failures that can occur within an Oracle database, rangingfrom the least to most severe, include:

• Statement failure

• Transaction failure

• Session failure

• Instance failure

• Media failure

Statement FailureWhen statement failure occurs, a single SQL statement, usually a SELECT state-ment, from a single Oracle client has failed. This type of failure can occur for awide variety of reasons. It is possible that the statement issued from the clientwas syntactically incorrect, or the statement referenced an object that either didn’texist or the user didn’t have privileges to access. Statement failure can also occurif a statement performs a large amount of sorting in the temporary tablespace,and the temporary tablespace runs out of space during the operation. This type offailure usually has no damaging affects on the database, therefore no recovery isrequired. The client issuing the statement will simply receive an error stating thereason why the statement failed.

Transaction FailureTransaction failure differs from statement failure only in that transaction failureoccurs while a client is in the middle of manipulating the data. The client wouldissue a DML statement to perform one or more INSERT, UPDATE, or DELETEoperations on the data, and the entire transaction failed. To recover from transac-tion failure, Oracle makes use of undo segments in the database. As a transactionexecutes, the data that is to be changed is first copied to the undo segments. Oncethe transaction is committed, the undo segment the transaction was using isreleased. If the transaction fails, Oracle will automatically rollback the entiretransaction using the original copies of the data in the undo segment to return thedata to its original state before the transaction started.

Each transaction can consist of one or more DML statements in the database. Fordata consistency, Oracle treats every transaction as an atomic unit of work. Thismeans that the entire transaction is successful or the entire transaction is rolledback; Oracle does not allow the partial completion of a transaction. A transactionstarts when the first DML statement is issued, and completes when the transactionis committed. There can be any number of DML operations between the firstDML statement and the commit. For example, the following series of statementsconsist of a single transaction, which ends when the COMMIT statement is issued.

Types of Failures

undo segments:Database segments that

temporarily hold the originalversions of changed data

from a transaction in casethe transaction needs to berolled back and the original

version replaced.

96 Oracle9i Database: Fundamentals II

Page 112: Oracle 9i DBA Fund - II

INSERT INTO dept VALUES(10,'Data Quality Assurance');

DELETE FROM empWHERE emp_id = 3483;

UPDATE empSET salary = salary * 1.1;

COMMIT;

In this example, the transaction starts when the first statement is issued, which isthe INSERT statement that creates a row in the DEPT table. The transaction con-sists of a total of three DML statements, and is complete when the COMMITstatement is issued. If the transaction fails at any point after the INSERT state-ment begins and before the COMMIT is issued, all changes will be rolled back. Atransaction can be committed by either explicit or implicit commits. An explicitcommit occurs when the client issues the COMMIT statement. An implicit commitoccurs when some new activity requires that all transactions within the session becommitted. All DDL statements cause an implicit commit.

A transaction failure can be caused by any number of reasons, but is usuallycaused by the shortage of database resources. For example, a long-running trans-action may generate so much undo information that it causes the undo segmentextent to grow to the point that the tablespace is full. If the undo segment cannotextend, the transaction will fail. Oracle automatically handles all transaction fail-ures through the use of the undo segments, so no DBA intervention is necessary.If a transaction fails, the client issuing the transaction will receive an error statingwhy the transaction failed.

Session FailureSession failure occurs when a client loses its connection to the database com-pletely, and usually occurs when any component of a database connection, suchas client, server, or network, becomes unavailable. For example, if the client losesits connectivity to the network, or if the client machine crashes entirely, it willalso have lost contact with the database. Depending on the failure, a trace fileconcerning the error may be generated, and the client may either receive an errorback immediately from Oracle that states what the error is, or the error will bereturned the next time the client attempts to access the database. Of course, if thesession failure occurred because the client machine crashed completely, then therewill be no error returned, but the reason for the session failure will be obvious tothe user.

Session failure may actually cause lesser failures, such as the failure of any state-ments or transactions the client was currently issuing to the database. Statementfailure has no affect on the database, and transaction failure will be rolled backautomatically by Oracle using the undo segments. The only other action that mustoccur is releasing any database or system resources consumed by the client con-nection, such as PGA space in memory and locks and latches in the database.Such resource “cleanup” is handled by the process monitor (PMON) backgroundprocess. If PMON detects that any client has lost connectivity to the database, itwill immediately attempt to release all resources consumed by the failed process,thus freeing up the resources to be used by other new or existing databaseconnections.

Lesson 2: Backup and Recovery Overview 97

Page 113: Oracle 9i DBA Fund - II

Instance FailureInstance failure is the most widespread type of failure that can occur in an Oracledatabase. It is equivalent to a crash of the database and affects all sessions cur-rently connected to the database. If the instance cannot stay up and running forany reason, the entire SGA is deallocated from memory and the database stopsrunning, and all sessions connected to the database will immediately fail. Wheninstance failure occurs, you are guaranteed to have database downtime.

The instance can fail for a variety of reasons. The Oracle instance consists of theentire System Global Area (SGA) and its set of required background processes.Five of these background processes, database writer (DBWR), log writer(LGWR), process monitor (PMON), server monitor (SMON), and checkpoint(CKPT) are required. If any one of the required background processes fail, theinstance will fail. If the server where the database is running crashes, this willalso result in instance failure.

Instance failure is automatically resolved the next time the instance is started up.Upon startup, Oracle will detect that the last shutdown of the database was notclean, and it will attempt to perform instance recovery. This involves rolling for-ward all transactions that had not yet been written to the datafiles, and rollingback all transactions that had not yet been committed. All necessary actions takenby Oracle to accomplish instance recovery will be annotated in the alert log. Ifthe only failure involved is instance failure, then there should be no damage doneto the database, and unplanned downtime will be the only negative result. Onceinstance recovery is complete, the database can be opened to make it available tousers. You will learn more about the mechanisms that Oracle uses to performinstance recovery later in this lesson.

Media FailureWhile instance failure is the most widespread, media failure is actually the mostdamaging, and can usually cause the most downtime. Media failure occurs whena hardware component of the server where the database resides, usually a disk ordisk array, has failed, become damaged, or has become otherwise unavailable.

Media failure may not necessarily cause instance failure, but it may. If the diskmedia in question contains the Oracle binary executables, the datafiles of theSYSTEM tablespace, all copies of the control file, or the current online redo log,then the instance will fail and will not be able to be restarted until the affectedfiles were restored and recovered. However, if the disk contains one or moredatafiles of non-SYSTEM tablespaces, then the instance can usually stay up andrunning, but Oracle will automatically take the affected datafiles offline. Oraclewill write error messages to the alert log for each of these datafiles at everyattempt to write to them until the datafiles are recovered.

Media failure is considered the most severe type of failure because, while it maynot cause instance failure, it can result in the actual loss of data. Instance recov-ery is the most widespread failure because it affects all sessions, but can usuallybe resolved very quickly by simply restarting the instance. Media failure usuallyrequires additional steps to restore the database to its original state, and if notdone properly, the loss of data can be permanent and extremely costly. Even ifthe instance is up and running, if the core data that an application depends on isunavailable, the application can no longer function. This is also considereddowntime.

98 Oracle9i Database: Fundamentals II

Page 114: Oracle 9i DBA Fund - II

TASK 2A-1Identify Types of Failures

1. Match the scenario on the left with its type of failure on the right.

d A query fails because theuser’s desktop lost contactto the database serverthrough the network.

a. Instance failure

c A query fails due to insuf-ficient sort space in theTEMP tablespace.

b. Media failure

a The host server crashed. c. Statement failureb A disk volume containing

a control file becomescorrupted.

d. Session failure

2. How does the database server handle session failure?

Any uncommitted transactions initiated by the session are rolled back, andthe process monitor (PMON) background process will deallocate anyresources that were utilized by the failed session, such as memory, locks, andlatches. Depending on the failure itself, Oracle may or may not generate atrace file containing any details it has about the session and why it failed. Ingeneral, the client that encountered the failed session will return some kindof error, either immediately when the failure occurs, or at the next attempt toaccess the database.

3. How does the database server handle instance failure?

In general, instance failure is resolved immediately once the instance isrestarted. Upon startup, Oracle will detect that the last shutdown of thedatabase was not clean, and it will attempt to perform instance recovery.This involves rolling forward all transactions that had not yet been writtento the datafiles and rolling back all transactions that had not yet beencommitted. All necessary actions taken by Oracle to accomplish instancerecovery will be annotated in the alert log.

4. How does the database server handle media failure?

Media failure may not necessarily cause instance failure, but it may. If thedisk media in question contains the Oracle binary executables, the datafilesof the SYSTEM tablespace, all copies of the control file, or the currentonline redo log, then the instance will fail, and could not be restarted untilthe affected files were restored and recovered. If the disk contained one ormore datafiles of any non-SYSTEM tablespaces, than the instance can usu-ally stay up and running, but Oracle will automatically take the affecteddatafiles offline. Oracle will write error messages to the alert log for each ofthese datafiles at every attempt to write to them until the datafiles arerecovered.

Lesson 2: Backup and Recovery Overview 99

Page 115: Oracle 9i DBA Fund - II

Backup and Recovery BasicsProviding a stable and safe database environment consists of two primary objec-tives: minimizing unplanned downtime and preventing the loss of critical data. Toreach these objectives, you must design and implement a sound backup andrecovery strategy that matches the requirements of the system. It is important toremember that failure will happen, and you must consider not if, but when, it willhappen. Regardless of how much money you spend on your high-performancesystem, or how many backups you take, or how many redundancies you buildinto the system, failure will happen. You can only push the limits of hardware sofar for so long before something fails. The best you can hope for is configuringthe system to keep the risk of failure to a minimum and have a recovery plan inplace to recover the database as quickly as possible when a failure does occur.

When designing your backup and recovery strategy, there are two very importantconcepts you must take into consideration. These are mean time between failures(MTBF) and mean time to recovery (MTTR). The mean time between failuresrefers to the amount of time that you can expect between failures of the database,the longer the better. You must ask yourself, how long will the database stayoperational until the next failure? Is the MTBF for your system so short that your24x7 database is crashing twice a day? If it is, backing up your system five timesa day will not increase the amount of time your database stays up. It could bethat your system is experiencing hardware problems, a bug in the operating sys-tem, or even a bug in the Oracle software. You must investigate the issue todetermine why it is failing and take steps to keep your database up for as long aspossible.

Mean time to recovery refers to the amount of time it takes for you to get yourdatabase back up and running, with all of its data, when a failure does occur. Adatabase that crashes twice a day is an issue. However, if all you have to do isrestart the instance, then you can probably have the database up and running in avery short time. But let’s say a database experiences failures only once a month,but when it does, it takes eight hours to recover from it. The MTTR of your data-base has a direct dependency on how you configured your backups and recoveriesto perform and whether or not you have planned for every possible failure. Thefailures that take the longest to recover from are usually the ones you didn’t planfor. Since you didn’t plan for it, you probably didn’t take the necessary stepsahead of time to recover from it.

A strong backup and recovery strategy encompasses taking steps to increaseMTBF and decrease MTTR. To increase MTBF, you should analyze your systemon a regular basis to ensure that it is configured in such a way to be resilient tofailure. You should ensure that you have multiple mirrors of the control files, andthat they are all stored on separate disks. If one disk fails, you still have anothervalid copy of the current control file. The same goes for redo logs; they shouldbe mirrored, with each mirror on a separate disk. If you lose a log file memberbecause of media failure, you still have another copy. You should ensure that theOS and the Oracle software are both running the latest patches for their versions.This will help avoid any unexpected bugs when making changes to the system,such as updating device drivers.

To decrease MTTR, you should find ways to reduce the amount of time torecover after a failure. This involves determining what steps must be taken foreach type of failure your database is susceptible to, and preparing sufficient stepsahead of time to recover from them. To keep MTTR at a minimum, you shouldhave your plan in place and regularly run recovery drills simulating various types

MTBF:(Mean time between failures)The average amount of timethat passes between failures

of a system.

MTTR:(Mean time to recovery) The

average amount of time ittakes to recover a system

after a failure.

100 Oracle9i Database: Fundamentals II

Page 116: Oracle 9i DBA Fund - II

of failures so you will know ahead of time what to do for each scenario. Recov-ery drills will also help to identify any issues with your recovery process, andyou can revise your recovery plans to take these issues into consideration. Thebetter prepared you are, the shorter your MTTR.

Hot and Cold Backups and RecoveriesA backup of the database can be performed either while the database is shutdown, known as a cold backup, or while it is up and running, known as a hotbackup. Performing a cold backup is the simplest type of backup, but it requiresthat the database be shut down. If the database is shut down cleanly (not with theABORT option), none of the control files, datafiles, or redo log files are open oraccessed by an instance, and the database is guaranteed to be in a consistent state.To perform the backup, you merely have to shut down the database and makecopies of all the data files, control files, and redo log files to another location,then start the database up again. Recovering the database from a cold backup isjust as simple. You would shut down the database, if it is running, and replace allof the datafiles, control files, and redo log files from their backup copies, thenstart up the database.

While cold backups and recoveries are simple to perform, they provide extremelylimited capabilities. Since the database must be shut down, there is guaranteeddowntime until the backup is complete. If the database is very large, it may takea very long time to copy all of the datafiles, which may be more than the busi-ness rules the database can allow. Also, when recovering the database after afailure, you cannot just copy one or two datafiles from the backup set. You mustrestore all of the files from the backup set, which means that you can onlyrecover the database to the point in time when the cold backup was taken. Figure2-1 illustrates a recovery from a full backup.

Figure 2-1: Recovering from a cold backup.

cold backup:A full backup of the databasewhile the database is shutdown.

hot backup:A backup of the database,either full or partial,performed while the databaseremains up and running.

Recovering From a ColdBackup

Lesson 2: Backup and Recovery Overview 101

Page 117: Oracle 9i DBA Fund - II

In this figure, the database was shut down at 4:00 A.M., and a cold backup wasperformed. The database was started up again and continued to operate normally.At 3:00 P.M., a media failure occurred, and the database lost some datafiles.Regardless of which datafiles were lost, in order to recover you must restore allof the files from the cold backup taken at 4:00 A.M. Once the database is startedup again after the restore, the data will look as it did at 4:00 A.M. All changes tothe data that occurred between 4:00 A.M. and 3:00 P.M. will be lost.

Hot backups and recoveries provide much more in the way of flexibility andcapability. The database can stay up and running while a hot backup is per-formed, which minimizes database downtime. Additionally, you can perform truepoint-of-failure recovery. This means that if the database experiences media fail-ure at 3:00 P.M., as it did in Figure 2-1, you can still recover all changes thatoccurred between the last backup and the point in time when the failure occurred.

To keep track of all changes in the database, Oracle uses a sequential numberingsystem to assign a system change number (SCN) and timestamp to everytransaction. During the normal operation of the database, the checkpoint process(CKPT) will update the control file and the headers of all the datafiles with thelatest system change number (SCN) and timestamp on a regular basis. Thisallows Oracle to ensure that all datafiles are kept up to date, using the control fileas a reference point. If the header of a datafile shows a lower SCN than the con-trol file, Oracle will assume that the datafile is missing some changes, and willwrite an error in the alert log stating that the datafile in question needs recovery.Any process that attempts to write to the datafile will receive an error and thattransaction will fail.

When performing a hot backup, you would place each tablespace in backupmode. Doing so causes the checkpoint process to defer updating the datafile head-ers for that tablespace with the latest SCN. The files will remain open, and theircontents can be updated by Oracle, but you will be allowed to make a copy ofthe datafiles while the database is running. Once the copy is complete, thetablespace can be taken out of backup mode, and CKPT will resume updating thedatafile headers for that tablespace.

In order to perform hot backups, the database must be running in a special modecalled ARCHIVELOG mode. As changes are made to the database, the modifieddatablocks are written to the datafiles, but the changes are also recorded in theredo log. This is normal behavior, even when the database is inNOARCHIVELOG mode. When the database is running in ARCHIVELOGmode, the redo log files are regularly copied to another location to archive thechanges. If the database ever suffered media failure, you would only need torestore the affected datafiles from the last backup, and apply the archived changesto the datafiles to bring them up to date with the rest of the database. Figure 2-2illustrates a recovery from a hot backup.

SCN:(System Change Number) A

sequential numbering systemOracle uses to track every

change in the database.

Recovery From a HotBackup

102 Oracle9i Database: Fundamentals II

Page 118: Oracle 9i DBA Fund - II

Figure 2-2: Recovery from a hot backup.

In this figure, a hot backup of the database was performed at 4:00 A.M. The data-base remained open, and each tablespace was placed in hot backup mode as thedata files were copied. The database continued to operate normally until mediafailure occurred at 3:00 P.M., which caused the database to lose some datafiles.Only the affected datafiles were restored from the backup and set back to theiroriginal locations. Then, all archived changes were applied to the datafiles tobring them up to date with the rest of the database. The database was recoveredto the point in time when the failure occurred, and no changes were lost. Addi-tionally, the database remained up and running throughout the entire process. Thedatafiles that were affected by the media failure were not accessible by users untilthey were recovered, but the data in the rest of the database remained availablefor general use.

While the mechanisms to make hot backups and recoveries possible add com-plexity to the database, they allow much more flexibility than cold backups andrecoveries. In addition to the ability to keep the database up and running, youhave the capability of backing up only a tablespace at a time. This allows you tospread out your backups across multiple sessions if the database is very large. Forexample, instead of shutting down the database for four hours to perform a coldbackup, the backup can be broken up across several days where each day youwould back up only one or two tablespaces. Additionally, when performing coldbackups, any media failure requires that you restore the entire backup set from athe cold backup. With hot backups, only the affected datafiles need to be restored,which can greatly reduce the mean time to recovery. With cold backups, allchanges between the time the backup was taken and the time the failure occurredare lost. Whereas with hot backups, these changes can be pulled from the archiveand applied to the affected datafiles.

It is important to note that there is a distinct difference between restore andrecover. When a datafile is lost, such as when media failure occurs, the datafile isrestored from its backup using standard OS commands. When the database isrecovered, archived changes are applied to a restored datafile to bring it up todate with the rest of the database. You will learn more about the mechanisms thatmake hot backups and recoveries possible later in this lesson.

Lesson 2: Backup and Recovery Overview 103

Page 119: Oracle 9i DBA Fund - II

Complete and Incomplete RecoveriesWhen performing a recovery of the database, you can perform either a completeor incomplete recovery. In a complete recovery, all of the latest changes to thedatabase are applied to any datafiles that are not up to date. When a completerecovery is performed, the contents of the entire database are updated to reflectthe way the database should look at the very instant just before the failureoccurred. This type of recovery is usually desirable in most situations, especiallyfor a live, transactional database where every transaction must be preserved.

In an incomplete recovery, not all of the latest changes are applied to the databaseduring recovery. When an incomplete recovery is performed, the state of the data-base is brought back to some point in time in the past. Any changes to the dataafter that particular point in time would be lost. This type of recovery would bedesirable if a transaction or series of transactions needed to be undone, such as auser deleting all the rows in a table and then committing the transaction. In thiscase, the database can be restored to a point in time before the data was deleted.

However, there is one very important caveat regarding recoveries. The Oracledatabase is very consistency-minded. The entire database must be consistent at alltimes, which means that all datafiles must constantly be at the same SCN andtimestamp. Therefore, when performing an incomplete recovery you must bringthe entire database back to the same point in time. You cannot, however, recoverjust a single datafile or tablespace to a different point in time than the rest of thedatabase. An incomplete recovery is performed using the same mechanisms andcommands as a complete recovery, except with an incomplete recovery, you donot apply all of the changes that have been archived. You can stop applying thechanges at any point, so long as the headers of all of the datafiles have the sameSCN and timestamp.

TASK 2A-2Describe Backup and Recovery Basics

1. Define the terms MTBF and MTTR. How do these concepts influenceyour backup and recovery strategy?

MTBF stands for mean-time between failures, which indicates how muchtime passes between one major failure and the next. MTTR stands for mean-time to recovery, which indicates the total amount of time required betweena failure and a resolution to that failure.

To improve database uptime and availability, it should be the DBA’s goal tomaximize the amount of time between failures and minimize the amount oftime between a failure and its resolution. The amount of downtime a particu-lar database can allow will be highly dependent on the businessrequirements for that database and will play heavily into the backup andrecovery strategy. A database that can tolerate the occasional failure mayrequire only a moderate backup and recovery strategy, but a database thatcannot allow any downtime whatsoever will require a very in-depth highavailability and backup and recovery strategy.

complete recovery:A database recovery whereall changes to the database

are recovered right up to thepoint of failure.

incomplete recovery:A database recovery where

not all changes to thedatabase are recovered.

104 Oracle9i Database: Fundamentals II

Page 120: Oracle 9i DBA Fund - II

2. What is the difference between a restore and a recovery?

When a datafile is lost, such as when media failure occurs, the datafile isrestored from its backup using standard OS commands. When the database isrecovered, archived changes are applied to a restored datafile to bring it upto date with the rest of the database.

3. What is the difference between a complete and incomplete recovery?Describe an example situation where each one would be desirable.

In a complete recovery, all of the latest changes to the database are appliedto any datafiles that are not up to date. When a complete recovery is per-formed, the contents of the entire database are updated to reflect the way thedatabase should look at the very instant just before the failure occurred. Thistype of recovery is usually desirable in most situations, especially for a live,transactional database where every transaction must be preserved.

In an incomplete recovery, not all of the latest changes are applied to thedatabase during recovery. When an incomplete recovery is performed, thestate of the database is brought back to some point in time in the past. Anychanges to the data after that particular point in time would be lost. Thistype of recovery would be desirable if a transaction or series of transactionsneeded to be undone, such as a user deleting all the rows in a table andthen committing the transaction. In this case, the database can be restored toa point in time before the data was deleted. However, doing so would meanthat the entire database was brought back to that point in time, not just thatone table.

Instance and Media Recovery StructuresOracle includes a fairly complex set of mechanisms to support instance andmedia recovery. These mechanisms are tightly integrated into the operation of thedatabase and allow Oracle to recover the database from most types of failure.Regardless if the database suffered instance failure or media failure, some or allof the mechanisms play a role in recovery. The primary recovery structures forthe database include:

• Undo segments

• Redo log buffer

• Redo log files

• System Monitor (SMON) process

• Log writer (LGWR) process

• Archiver (ARCH) process

• Checkpoint (CKPT) process

• Database writer (DBWR) process

• Control file

First, you will learn the purpose of each of these mechanisms separately, and thenyou will see how they all work together as a seamless system.

Instance and MediaRecovery Structures

Lesson 2: Backup and Recovery Overview 105

Page 121: Oracle 9i DBA Fund - II

Undo SegmentsUndo segments are used to rollback, or undo, changes to data and play a criticalrole during recovery. When performing DML operations on data, Oracle will storethe original version of each row of data to be changed in an undo segment. Thisoriginal version, or before image, is used for multiple purposes, including:

• Data consistency during DML operations.

• Rollback of unwanted changes.

• Rollback of transactions after statement or session failure.

• Rollback of uncommitted transactions during instance or media recovery.

To ensure data consistency during DML operations, such as INSERT, UPDATE,or DELETE statements, the process executing the statement will acquire a lock onthe rows to be modified, and then the before image is copied into an undosegment. All changes to the data will take place in the actual datablocks wherethe row resides, but the original versions of the rows in the undo segments willbe preserved for the duration of the transaction. If another process tries to queryfrom those same rows, it will detect that a DML lock has been placed on them,and will read the before image from the undo segment instead of the changedversion in the original datablocks. Once the DML operation is complete and acommit is issued, either explicitly or implicitly, the DML locks and the undo seg-ment are released and the changes are made permanent. This guarantees that noother user will be able to see the affects of a DML operation until it iscommitted. Figure 2-3 illustrates the basic concept of undo segment operation.

Figure 2-3: Basic undo segment operation.

In this figure, the UPDATE statement is changing the value of the SALARY col-umn for the employee with an EMP_ID of 4. The original value of 90000 in theSALARY column is first copied to an undo segment to preserve it, and then thechange is made in the actual row.

Another use of an undo segment is to cancel a transaction that could not com-plete for one reason or another. During a rollback operation, Oracle will copy thebefore image back to the original datablocks they came from, and then release alllocks on the rows. It could be that a user issued a series of DML statements,looked at the results, then changed his or her mind and manually rolled back thechanges using the ROLLBACK statement. It could also be that a transaction sim-ply failed due to either statement or session failure. For example, let’s say a userexecutes a large UPDATE statement that makes use of several subqueries. Thesubqueries caused extensive sorting in the temporary tablespace, so much so that

In previous versions ofOracle, undo segments wereknown as rollback segments.

before image:The original version of databefore it was changed by a

transaction.

Basic Undo SegmentOperation

106 Oracle9i Database: Fundamentals II

Page 122: Oracle 9i DBA Fund - II

the temporary tablespace fills up and Oracle can no longer allocate more sortspace. The statement will fail and will be rolled back using the before image ofthe data in the undo segments. When session failure occurs, all transactions thatwere currently open by that session will be rolled back.

Rollback segments are also used during instance and media recovery. This ishandled by a roll forward, roll back technique. During recovery, the database isrolled forward in time, re-enacting all changes to the database from the lastknown good state of the database up to the point of failure. During this roll for-ward, all transactions that had not yet been written to the datafiles will be flushedto the datafiles. Once the database has been rolled forward to the point of failure,any uncommitted transactions that exist in the undo segments will be rolled back.This allows Oracle to ensure that the database will be consistent before allowingit to be opened for general use.

Redo Log BufferThe redo log buffer is an area of memory within the SGA. As data is changed,redo entries are written to the redo log buffer along with their associated SCNsand timestamps of when the changes occurred. The redo log buffer acts primarilyas an in-memory staging area where Oracle can store the redo information fromeach change prior to writing the changes to the redo log files. The redo informa-tion that is generated from each change is used during the roll forward phase ofdatabase recovery. As the database rolls forward, the redo information is used tore-enact the changes that had occurred between the last known good state of thedatabase and the point of failure.

There is some impact to database performance to generate redo information forchanges to the data. In addition to the resources needed to just complete a singlechange, Oracle must also take time to generate the redo entries for the change.While it is not possible to disable redo logging instance wide, you can disable itat the object level. Most segments in the database, such as tables and indexes,have a segment attribute that can be set to either LOGGING or NOLOGGING. If itis set to LOGGING, which is the default, full redo log generation will occur foreach change. Setting the attribute to NOLOGGING will eliminate the redo genera-tion for the object, which can improve performance slightly. It is important toremember though, that objects that are set to NOLOGGING will not be recover-able in the event of a failure. For very large transactions, disabling redo loggingcan improve performance, but the performance impact is usually considered a fairtrade off in comparison with recoverability. Without redo logging, it is possible tolose critical changes to the database in the event of a failure. The followingexample shows a CREATE TABLE statement with the NOLOGGING attribute.

CREATE TABLE emp(empid NUMBER,lname VARCHAR2(64),fname VARCHAR2(64)

)TABLESPACE hrNOLOGGING;

Redo Log FilesFrom time to time, the contents of the redo log buffer are written out to the redolog files. The redo log files are configured in groups and work in a cyclical fash-ion, with one redo log group acting as the current group and the others standingby. Once the redo log buffer is full of changes, they are written out to the currentredo log group. Once this group is full, the current log group is switched out and

The current redo log groupis sometimes referred to asthe online redo log group, orjust the online redo log.

Lesson 2: Backup and Recovery Overview 107

Page 123: Oracle 9i DBA Fund - II

the next group in line becomes the current group. This allows Oracle to infinitelygenerate redo information without being restricted by the size of a single log file.As each log file group is switched in as the current log group, Oracle assigns anever-increasing log sequence number to the group. This log sequence number isused to track which log group contains which changes in the event a recovery isneeded.

The redo log files are configured in groups, and each group can have one or morelog file members. All members of a single redo log group capture the same redoinformation as it is written from the log buffer to the current redo log group,allowing each log file member of a single group to act as mirrors of each other.This provides the ability to separate the log file members of a single group acrossmultiple disks. If the disk where one log file member resides suffers media failureand the log file member is lost, Oracle can continue generating changes as longas at least one other log file member in the group is available. If all members ofthe current redo log group are lost, the instance will crash. Figure 2-4 illustrates aconfiguration of three redo log groups, each with two log file members.

Figure 2-4: Redo log groups and their log file members.

The minimum redo log configuration is two groups, each group having one logfile member each. For performance reasons, it is recommended that you configureat least three redo log groups. The size of the log file members can be manuallyset when they are created, but should be sized appropriately for your system. Logfile members that are sized too small for a busy system will cause the log files tofill up very quickly, which results in excessive log switching and can hurtperformance. It is also recommended that you configure at least two members foreach log file group so you can place each member per group on separate disks,just in case your system experiences media failure where one of your log filemembers reside.

Redo Log Groups and TheirMembers

108 Oracle9i Database: Fundamentals II

Page 124: Oracle 9i DBA Fund - II

System Monitor (SMON) ProcessThe system monitor (SMON) background process is responsible for initiatinginstance recovery after a failure. When the instance is started, Oracle tries todetermine if instance recovery is necessary. If instance recovery is needed,SMON signals all other background processes to start their specific recovery-related activities. SMON also has some other non-recovery related duties, such asperiodically cleaning up unused temporary segments in the tablespaces, and coa-lescing free extents in dictionary-managed tablespaces.

Log Writer (LGWR) ProcessIt is the job of the log writer (LGWR) background process to read the redo logentries from the redo log buffer and write them to all members of the currentredo log group. The LGWR process will perform this task when the followingconditions are encountered:

• When a user issues a COMMIT statement.

• Every three seconds, even if no user issued a COMMIT statement.

• When the redo log buffer is at least one-third full.

If LGWR cannot write to the current redo log group, usually when the currentlog is full and the logs cannot be switched for some reason, then the instance willhang until the logs are switched and LGWR can continue writing. This is arequired background process, and as such, if it were to die for any reason wouldcause the instance to crash.

Archiver (ARCH) ProcessAs LGWR writes out changes from the log buffer to the current redo log group,the redo log group will fill. Once the current log group is full, Oracle switchesthe current log group out and the next log group in line becomes the current loggroup. If the database is running in ARCHIVELOG mode, the archiver (ARCH)process will begin to archive the now-full log group that was just switched out bycopying it to the location specified by the LOG_ARCHIVE_DEST parameter. Thefile that is created by the archiver process is called an archive log. Regardless ofthe number of log file members there are in a log group, only one archive log iscreated per group.

The archive process is optional and only exists when the database is running inARCHIVELOG mode. When the database is running NOARCHIVELOG mode,none of the redo log groups are archived as they fill. If all log groups have filledand switched out, Oracle will begin writing to the first log group again, overwrit-ing the redo information it once contained. Enabling ARCHIVELOG mode allowsyou to make a physical copy of the changes in a log group before its changes areoverwritten. As each archive log is created, it is renamed with the log group’slatest log sequence number, allowing Oracle to track which archive log containswhich changes for which SCNs. If a database had to be restored from a backup,the changes stored in the archive logs can be used to roll the database forward tothe point in time when the failure occurred. Even if the database backup was per-formed weeks or months ago, as long as you kept all of the archive logs sincethat backup, you could restore your database right up to the point of failure.

archive log:A copy of a redo log that hasbeen filled and switched outas the current log group.Archive logs are used toapply changes to a backup tobring it up to date duringrecovery.

Lesson 2: Backup and Recovery Overview 109

Page 125: Oracle 9i DBA Fund - II

Checkpoint (CKPT) ProcessAt regular intervals, and when certain conditions exist, the database will performa checkpoint. During this checkpoint, all modified datablocks in the buffer cacheare written out to the datafiles. These modified datablocks can hold changes fromboth committed or uncommitted transactions. During a checkpoint, the checkpoint(CKPT) process updates the control file and the headers of all the datafiles withthe current SCN and timestamp. This guarantees that all changes up to the currentSCN will be written to the disk. A checkpoint is triggered by the following condi-tions:

• Manually with the ALTER SYSTEM CHECKPOINT command.

• A redo log switch, either automatically through normal operations or manu-ally with the ALTER SYSTEM SWITCH LOGFILE command.

• As determined by the LOG_CHECKPOINT_INTERVAL and LOG_CHECKPOINT_TIMEOUT initialization parameters.

• When a tablespace is taken offline NORMAL (as opposed to IMMEDIATE).

• At the start of a tablespace-level hot backup.

• When the database is closed properly (using NORMAL, IMMEDIATE, orTRANSACTIONAL shutdown modes).

A checkpoint is similar to a bookmark for the database. Since all changes prior tothe last checkpoint are guaranteed to be on disk, only changes that were gener-ated after the last checkpoint are needed for the roll forward phase of instancerecovery. If the database performs checkpoints often, fewer changes will beneeded for the roll forward phase, thereby reducing the amount of time that isneeded to recover the database. If the database performs checkpoints infrequently,more time will be needed for instance recovery since more changes will need tobe applied during the roll forward phase. The database can be tuned, through acombination of parameter settings and proper redo log file sizing, to control howoften a checkpoint will perform. Too frequently, checkpointing can affect perfor-mance, especially if there are many datafiles that CKPT must update. However,too infrequently, checkpointing can cause extremely slow recovery time in theevent of instance failure. The LOG_CHECKPOINTS_TO_ALERT initializationparameter can be set to TRUE, which causes Oracle to write an entry in the alertlog for every checkpoint. This information can be extremely useful in determin-ing how often your database is performing checkpoints. The default value for thisparameter is FALSE.

Database Writer (DBWR) ProcessThe database writer (DBWR) background process has one job and one job only:to write modified datablocks from the buffer cache to the datafiles. At everycheckpoint, DBWR will write out all modified datablocks, whether the modifica-tions were committed or not. If a data modification was committed, the changewas already written to the datafile, so therefore it will not need to be re-createdduring the roll forward phase of recovery. If the modification was not committed,it will be rolled back using the undo segments during the rollback phase ofrecovery. DBWR is a required process.

110 Oracle9i Database: Fundamentals II

Page 126: Oracle 9i DBA Fund - II

It’s important to note that a transaction is not considered to be committed justbecause its changes were written to a datafile. A transaction can be committedand recovered after a failure, even if the changes never actually made it from thebuffer cache to the datafiles. Conversely, changes that have made it to thedatafiles may or may not be committed. A transaction is only considered commit-ted when a COMMIT statement for the transaction exists in the redo log files,regardless of whether or not the changes made it to the datafiles.

Control FileThe control file is the single most important file in the database, both for normaloperations and for recovery operations. It contains the current file structure andthe most current SCN for the database, along with a list of the most recentarchive log files that have been generated for the database. A database can haveone or more copies of the control file, which are found at the location specifiedby the CONTROL_FILES parameter. The parameter CONTROL_FILE_RECORD_KEEP_TIME determines how long the information in the control filewill be kept before it is over written with new information. This is particularlyimportant for the archive log information, which is ever-growing for databases inARCHIVELOG mode.

Each copy of the control file contains identical information, but it is recom-mended that you configure multiple copies to eliminate a single point of failure.If all copies of the control file (or the only copy) become corrupted or lost, thedatabase would crash and could not restart until a valid control file exists.

During recovery, Oracle uses the SCN in the control file as a reference point todetermine which datafiles need recovery. If the header of a datafile contains anSCN that is lower than what is contained in the control file, that datafile willneed to be recovered. As the roll forward phase of recovery begins, Oracleapplies the missing changes to the datafile, and the SCN for that datafileincrements. Once the SCN for that datafile matches that of the control file, thedatafile is considered to be recovered, and once all datafiles are recovered, thedatabase can then be opened for general use.

Putting it all TogetherEach individual structure plays an important role in the database recovery pro-cess, but it is the combination of all structures working together that provideOracle the ability to recover from most types of failures. Figure 2-5 illustrateshow all the structures work together. The undo segments were left out of the fig-ure for clarity.

Instance and MediaRecovery Structures

Lesson 2: Backup and Recovery Overview 111

Page 127: Oracle 9i DBA Fund - II

Figure 2-5: Instance and media recovery structures.

When a transaction executes, a server process acting on behalf of a user willmodify data in the buffer cache, and the before images of each row changed arestored in the undo segments. Additionally, as the changes to the datablocks aremade, an entry for each change is recorded in the log buffer. Once the log bufferbecomes at least one-third full or the user commits the transaction, the log writer(LGWR) process writes the contents of the log buffer to the current redo loggroup. Once the current redo log group becomes full, Oracle performs a logswitch; the current group is rotated out and the next group in line becomes thecurrent log group. If the database is running in ARCHIVELOG mode, thearchiver (ARCH) process will copy the full redo log group that was switched outto an archive destination.

To ensure that modified datablocks are written to the datafiles regularly, Oraclewill perform checkpoints at regular intervals and when triggered by specificconditions. During a checkpoint, the database writer (DBWR) process will writeall modified datablocks from the buffer cache to the datafiles. Additionally, thecheckpoint process (CKPT) will update the control file and the headers of all thedatafiles with the current SCN and timestamp.

During a recovery operation, the sequence of events to recover the database isalmost identical to when the database is operating normally. The only differenceis that the redo information in the redo and archive logs becomes the source ofthe changes rather than a user process.

First, Oracle must determine at what point is the last known good state of thedatabase. In the case of instance failure, the last known good state is the verylatest checkpoint just prior to the failure. All transactions before this point intime, committed or uncommitted, are guaranteed to be written to the datafiles,while all transactions after this point in time may exist only in the redo logsand/or undo segments. In the case of media failure, where datafiles are com-pletely lost, the last known good state is usually a restored backup of the affectedfiles.

112 Oracle9i Database: Fundamentals II

Page 128: Oracle 9i DBA Fund - II

Once the last known good state of the database is determined, Oracle can beginthe roll forward phase of recovery. During this phase, any transactions not guar-anteed to be written to the datafiles are re-enacted in the database. To do this,Oracle pulls the information for the transactions from either the redo log files forinstance recovery, or from the archive logs for media recovery. As the transac-tions are processed, they are immediately written to the datafiles by DBWR, andthe SCNs of the target datafiles are updated if necessary.

Once the database has been rolled forward from the last known good state up tothe point of failure, Oracle begins the roll back phase of recovery. During thisphase, any transaction that exists in the redo log that does not have a correspond-ing COMMIT is considered an uncommitted transaction. As a result of the rollforward phase, the before images for these transactions should already reside inthe undo segments. Since no COMMIT was found for these transactions, the trans-actions are rolled back. Once the rollback phase is complete, the database hasbeen recovered and can be opened for general use.

TASK 2A-3Identify Instance and Media Recovery Structures

1. Which component of the Oracle database is used as the reference pointto determine whether or not the database needs recovery?

✓ a. Control file

b. Data dictionary

c. Redo logs

d. SYSTEM tablespace datafile

2. Which background process updates the datafiles and control files withthe current system change number (SCN)?

✓ a. CKPT

b. DBWR

c. LGWR

d. SMON

Lesson 2: Backup and Recovery Overview 113

Page 129: Oracle 9i DBA Fund - II

3. True or False? A transaction is considered committed when the changeddatablocks are written to the datafiles. Explain your answer.

False. A transaction is considered committed when the redo information hasbeen written to the redo logs along with its corresponding COMMITstatement. This will ensure that the transaction can be recovered after anytype of failure, even if a failure occurs before the DBWR process has achance to write the changes to the datafiles.

4. What would be the affect on the database if Oracle did not have abuilt-in redo logging mechanism?

Without the built-in redo logging mechanism, there would be no record ofthe exact transactions that took place when changes to data are made. If aserious failure in the system requires the database to be restored frombackup, those transactions would not be available to allow a re-enactment ofthe changes. The database could only be recoverable to the point in timewhen the last database backup was generated, and any changes thatoccurred after that point in time would be lost. The ability to log all transac-tions someplace outside of the datafiles provides the abilities to apply thelatest changes to the database if the datafiles had to be restored from thelast backup, providing the database with true point-of-failure recoverability.

Topic 2BCold Backup and Recovery ConceptsPerforming a cold backup is as simple as shutting down the database cleanly andmaking a copy of the spfile, control file, datafiles, and redo log files. Once thecopies are done, you simply start the database back up. While this method ofbackups requires database downtime, it can be used to create a backup that isguaranteed to be consistent with absolutely no loss of data or transactions.

Prior to shutting down the database, you would need to know the exact namesand locations of all the files you intend to copy. The V$PARAMETER view pro-vides the locations of the spfile and control files. The following query can beused to find this information.

SELECT name, valueFROM v$parameterWHERE name IN ('control_files','spfile');

While a database may have multiple mirrors of the control file, you only need tobackup one of them, since all the mirrors are identical. There is no harm, how-ever, in backing up all of them. Control files take up very little space, and if onebackup copy is bad, you would still have others you could use to recover from.

The DBA_DATA_FILES view provides a list of all datafiles in the database. Italso provides the sizes of the datafiles, which can be useful in determiningwhether or not the location where you intend to store your backup has sufficientspace. The following query can be used to find the names, locations, and sizes ofyour datafiles.

SELECT file_name, bytes/1024/1024 mbFROM dba_data_files;

Finding Files to Backup

114 Oracle9i Database: Fundamentals II

Page 130: Oracle 9i DBA Fund - II

The DBA_DATA_FILES can also be very useful for dynamically generating thecopy commands that make up your backup script. You would spool the output toa file and copy the information into your script. A query similar to the followingcan create the copy commands for each of your datafiles.

SELECT ('copy '||file_name||' F:\oracle\cold_bup\wkly')FROM dba_data_files;

This query is intended for use on a Windows operating system. It can easily bemodified for other operating systems, such as Unix. The output of this query maylook something like this:

('COPY'||FILE_NAME||'F:\ORACLE\COLD_BUP\WKLY')--------------------------------------------------copy D:\ORACLE\ORADATA\ORA92\SYSTEM01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\UNDOTBS01.DBFF:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\CWMLITE01.DBFF:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\DRSYS01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\EXAMPLE01.DBFF:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\INDX01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\ODM01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\TOOLS01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\USERS01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\XDB01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\RMAN01.DBF F:\oracle\cold_bup\wklycopy D:\ORACLE\ORADATA\ORA92\OEM01.DBF F:\oracle\cold_bup\wkly

The V$LOGFILE view provides the names and locations of all log file membersof all redo log groups. For a cold backup, all log file members should beincluded in the backup. The following query can be used to determine the loca-tion of the redo log files.

SELECT memberFROM v$logfile;

Just as with the DBA_DATA_FILES view, a dynamic SQL query can be usedwith V$LOGFILE to dynamically create the copy commands for your backupscript. The following query will do just that.

SELECT ('copy '||member||' F:\oracle\cold_bup\wkly')FROM v$logfile;

TASK 2B-1Performing a Cold Database Backup

Objective: To perform a full, cold backup of the database.

1. Before backing up the database, you should identify the files that should beincluded in your backup set. The backup set should include the spfile, con-trol file, datafiles, and redo log files. The names and locations for these filesare found in the V$PARAMETER, DBA_DATA_FILES, and V$LOGFILEdata dictionary view. You will query these views to identify which filesshould be backed up.

From the desktop, launch SQL*Plus from the Start menu.

Lesson 2: Backup and Recovery Overview 115

Page 131: Oracle 9i DBA Fund - II

In the Log On dialog box, type sys for User Name, ora92 for Password,and ora92 as sysdba for Host String. Click OK.

2. You will first query the V$PARAMETER view. This view will give you thelocations of the spfile and control files.

First, format the output of your query by typing the following com-mands at the SQL*Plus prompt. Press Enter after each command.

COLUMN name FORMAT a15COLUMN value FORMAT a50

At the prompt, issue the following query:

SELECT name, valueFROM v$parameterWHERE name IN ('control_files','spfile');

The results of your query will show you the names and locations of thespfile and control files for your database.

For the spfile name and location, %ORACLE_HOME% is the environmentvariable for the location of your Oracle Home directory, and is currently setto D:\oracle\ora92. The %ORACLE_SID% is the environment variable forthe system identifier (SID) for your database and is currently set to ora92.Therefore, the name and location of your spfile is D:\oracle\ora92\database\spfileora92.ora.

The control_files parameter shows that all three of your control files arelocated in the D:\oracle\oradata\ora92 folder.

3. You will now query the DBA_DATA_FILES view to determine the namesand locations of all the datafiles that currently exist for your database.

First, format the output of your query with the following command:

COLUMN file_name FORMAT a50

116 Oracle9i Database: Fundamentals II

Page 132: Oracle 9i DBA Fund - II

Issue the following query:

SELECT file_nameFROM dba_data_files;

The output will show the names and locations of all the datafiles in yourdatabase. You will see that all your datafiles are currently stored in theD:\oracle\oradata\ora92 folder.

4. You will now query the V$LOGFILE view to determine the names and loca-tions of your redo log files.

First, format the output of your query with the following command:

COLUMN member FORMAT a50

Issue the following query:

SELECT memberFROM v$logfile;

The output will show the names and locations of the redo logs for yourdatabase. Like your datafiles, all of your redo logs are currently stored in theD:\oracle\oradata\ora92 folder.

5. Before taking a cold backup of the database, you must first shut it down.

At the SQL*Plus prompt, type shutdown immediate; and press Enter.

Lesson 2: Backup and Recovery Overview 117

Page 133: Oracle 9i DBA Fund - II

After a few moments, the output will state that the database was closed, dis-mounted, and the instance shut down.

6. Now that you have identified the names and locations of all the files youneed to backup, you will need to identify the location where you will copythe files to.

Leaving the SQL*Plus window open, choose Start→Run. In the Run textbox, type D:\oracle and click OK. A window for the D:\oracle folder willappear.

Choose File→New→Folder. Name the new folder cold_bup

7. You will first create a backup of the spfile.

From the D:\oracle folder, double-click the ora92 folder. The window willchange to show the contents of the ora92 folder.

Double-click the database folder. You will see a list of files. SelectSPFILEORA92.ORA. Choose Edit→Copy.

Press Backspace to move back to the ora92 folder. Press Backspaceagain to move back to the D:\oracle folder.

Double-click the cold_bup folder to open it.

Choose Edit→Paste.

118 Oracle9i Database: Fundamentals II

Page 134: Oracle 9i DBA Fund - II

You will see a copy of your SPFILEORA92.ORA file appear in the cold_bupfolder.

8. You will now create backups of all your control files, datafiles, and redo logfiles.

From the cold_bup folder, press Backspace to move back to the D:\oraclefolder.

Double-click the oradata folder. Double-click the ora92 folder.

You will see a list of the control files, datafiles, and redo log files for yourdatabase.

Choose Edit→Select All. All the files in the ora92 folder will behighlighted.

Choose Edit→Copy.

Press Backspace twice to move back to the D:\oracle folder.

Double-click the cold_bup folder to open it.

Lesson 2: Backup and Recovery Overview 119

Page 135: Oracle 9i DBA Fund - II

Choose Edit→Paste.

A progress meter will appear while the files are copied. It will take a fewminutes to copy all of the files to the backup destination.

Once the file copies are finished, the backup is complete. Close the cold_bup window.

9. You will now start up the database.

At the SQL*Plus prompt, type startup and press Enter.

After a few moments, the output will show that the instance was started, andthe database was mounted and opened.

10. Type exit and press Enter to close the SQL*Plus window.

Cold Recovery ConceptsWhen recovering the database from a cold backup, it’s important to rememberthat you must restore all files from the cold backup, including the control filesand redo log files, and not just the one or two files that you lost due to mediafailure. The current files can be discarded, and the backed up copies are put intheir places. It is recommended that you restore the spfile, even if the originalwas not lost. This is because the current spfile may contain parameter assign-ments that have been changed since the last backup. If the current spfile is usedwith the backup copy of the database, the database may not start up correctly, andif it does, it may not perform as expected. If you can confidently say that noparameters have changed since the last backup, then you can decide whether ornot you need to restore the spfile.

The DBVerify UtilityOracle provides a useful utility, called DBVerify, that can be used to determinewhether or not datafiles contain any block corruptions. This command-line utilitycan be run against any datafile, regardless if the datafile is currently part of a livedatabase or if it is just a backup copy of a live datafile. DBVerify scans a datafile

120 Oracle9i Database: Fundamentals II

Page 136: Oracle 9i DBA Fund - II

for any corruption, and reports on its findings, which is displayed on the screen,and can optionally be sent to a log file. You can instruct the utility to scan anentire datafile or just a portion of the file by specifying starting and endingdatablock numbers. You can even instruct the utility to scan a single segment inthe database.

To use the DBVerify utility, you would run its executable (dbv) from the com-mand line and pass arguments that specify the name of the datafile you want toscan, the optional starting and ending datablocks, and the path and file name ofthe optional log file. If you do not include starting and ending datablocks,DBVerify will automatically scan the entire datafile. The arguments that can bepassed to DBVerify are shown in the following table.

Argument Purposefile The path and file name of the datafile to verify.start The datablock number to start scanning from. If omitted, DBVerify will start

at the first datablock in the file.end The datablock number at which to stop scanning. If omitted, DBVerify will

stop after the last datablock in the file.blocksize The size in bytes of the datablocks in the datafile. The default value is

2048.logfile The path and file name of the log file to generate. If omitted, no log file

will be generated.feedback Instructs DBVerify to output a period (.) to the screen for each datablock

verified. The default is 0, which means no feedback is displayed.parfile Specifies an optional parameter file that contains additional arguments.userid User name and password of the database user to use when logging into

the target database if you are scanning a segment specified by thesegment_id argument.

segment_id Specifies the segment to scan.

The following example shows DBVerify scanning a datafile for corruption:

C:\>dbv file=d:\oracle\oradata\ora92\users01.dbf blocksize=8192

DBVERIFY: Release 9.2.0.1.0 - Production on Sun Sep 7 20:01:422003

Copyright (c) 1982, 2002, Oracle Corporation. All rightsreserved.

DBVERIFY - Verification starting : FILE =d:\oracle\oradata\ora92\users01.dbf

DBVERIFY - Verification complete

Total Pages Examined : 3200Total Pages Processed (Data) : 457

Lesson 2: Backup and Recovery Overview 121

Page 137: Oracle 9i DBA Fund - II

Total Pages Failing (Data) : 0Total Pages Processed (Index): 0Total Pages Failing (Index): 0Total Pages Processed (Other): 57Total Pages Processed (Seg) : 0Total Pages Failing (Seg) : 0Total Pages Empty : 2686Total Pages Marked Corrupt : 0Total Pages Influx : 0

C:\>

If any corruption in the file is found, the output would show the number ofblocks data or index blocks that were corrupted. To scan a specific segment in thedatabase, you would use the following syntax:

dbv userid=username/pwd segment_id=tsn.segfile.segblock

In this syntax, username/pwd specifies the database user and password to login to the database with. If you are scanning a specific segment, you must executeDBVerify from the same machine where the database resides. Therefore, you can-not specify a connect string for a remote database.

For the segment_id argument, tsn represents the tablespace number,segfile represents the target file number, and segblock represents the blocknumber where the header of target segment resides. The values you need tospecify can be determined by querying the appropriate data dictionary views forthe segment in question, such as DBA_TABLES and DBA_SEGMENTS. Thefollowing example shows DBVerify scanning a single segment:

C:\>dbv userid=system/ora92 segment_id=5.5.5897

DBVERIFY: Release 9.2.0.1.0 - Production on Sun Sep 7 20:23:002003

Copyright (c) 1982, 2002, Oracle Corporation. All rightsreserved.

DBVERIFY - Verification starting : SEGMENT_ID = 5.5.5897

DBVERIFY - Verification complete

Total Pages Examined : 11Total Pages Processed (Data) : 10Total Pages Failing (Data) : 0Total Pages Processed (Index): 0Total Pages Failing (Index): 0Total Pages Processed (Other): 0Total Pages Processed (Seg) : 1Total Pages Failing (Seg) : 0Total Pages Empty : 0Total Pages Marked Corrupt : 0Total Pages Influx : 0

C:\>

In this example, a single segment that resides at block number 5897 in datafile 5of tablespace 5 was scanned for corruption.

122 Oracle9i Database: Fundamentals II

Page 138: Oracle 9i DBA Fund - II

The DBVerify utility is extremely useful in determining whether or not thebackup copies of your datafiles are valid. After performing a user-managedbackup of the database, it is recommended that you use DBVerify to scan thebackup copies of all the datafiles to ensure that the copies are valid. If a file iscorrupt, it would be better to know immediately rather than when you restore thecorrupted backup copies after media failure.

TASK 2B-2Perform a Cold Database Recovery

Objective: To perform a cold recovery of the database using the latestfull, cold backup set.

1. Before performing a cold recovery, you will first simulate disk failure on thedisk where the control files, datafiles, and redo log files reside.

From the desktop, launch SQL*Plus from the Start menu.

In the Log On dialog box, type sys for User Name, ora92 for Password,and ora92 as sysdba for Host String. Click OK.

2. At the SQL*Plus prompt, type shutdown immediate; and press Enter.

After a few moments, the output will state that the database was closed, dis-mounted, and the instance shut down.

3. Leaving the SQL*Plus window open, choose Start→Run. In the Run textbox, type D:\oracle\oradata\ora92 and click OK.

Lesson 2: Backup and Recovery Overview 123

Page 139: Oracle 9i DBA Fund - II

A window for the D:\oracle\oradata\ora92 window will open.

4. Choose Edit→Select All. All the files in the window will be selected.

Press Shift+Delete. A question box will appear asking if you are sure youwant to delete these 17 files. Click Yes. All of your control files, datafiles,and redo log files will be permanently erased from the disk. This simulatescomplete disk failure.

5. Switch back to the SQL*Plus window.

At the SQL*Plus prompt, type startup and press Enter.

After a few moments, you will see the instance start, but a message will

124 Oracle9i Database: Fundamentals II

Page 140: Oracle 9i DBA Fund - II

appear stating that Oracle could not identify the control file. The alert logwill contain more information.

6. Choose Start→Run. In the Run text box, type D:\oracle\admin\ora92\bdump and click OK.

A window for the D:\oracle\admin\ora92\bdump folder will appear.

Double-click the alert_ora92.log file. The alert log will open in a Notepadwindow. Scroll to the bottom of the file.

The last several lines in the alert log shows the reason why the database

Some trace files besides thealert log may exist in theD:\oracle\admin\ora92\bdumpdirectory. This is normal.

Lesson 2: Backup and Recovery Overview 125

Page 141: Oracle 9i DBA Fund - II

could not be mounted. The operating system could not find CONTROL01.CTL file in the D:\oracle\oradata\ora92 directory. Upon further investigation,you realize that the entire disk where that control file resides has crashed.

Close the alert_ora92.log file.

7. A new disk has been installed, and you will now restore all the necessaryfiles from your last cold backup. Before doing so, you must first shut downthe instance.

At the SQL*Plus prompt, type shutdown immediate; and press Enter. Aftera moment, the output will show that the instance was shut down.

8. Leaving the SQL*Plus window open, choose Start→Run. In the Run textbox, type D:\oracle\cold_bup and click OK. A window for the cold_bupfolder will appear.

Select SPFILEORA92.ORA. Choose Edit→Invert Selection. All filesexcept the SPFILEORA92.ORA file will be selected.

Choose Edit→Copy.

Press Backspace to move back to the D:\oracle folder.

Double-click the oradata folder to open it. In the oradata folder, double-click ora92 folder to open it.

Choose Edit→Paste. A progress meter will appear while the files are

126 Oracle9i Database: Fundamentals II

Page 142: Oracle 9i DBA Fund - II

restored. It will take a few minutes to complete the copies.

Once the copies are complete, close the ora92 window.

9. At the SQL*Plus prompt, type startup and press Enter.

After a few moments, you will see the instance start, and the database mountand open. You have successfully performed a cold recovery of the databasefrom the last cold backup.

10. Type exit and press Enter to close the SQL*Plus window.

Close all open windows.

Topic 2CHot Backup and Recovery ConceptsWhile hot backups are more complicated than cold backups, the ability to backup the database while it remains up and running provides much more power andflexibility. With hot backups, you can back up either the entire database or asingle tablespace at a time. This allows you to spread your backups over a longerperiod of time, which can be very handy if your database is very large. Addition-ally, you have the ability to restore just a single tablespace, or even a single

Lesson 2: Backup and Recovery Overview 127

Page 143: Oracle 9i DBA Fund - II

datafile, in the event of a media failure, instead of having to restore the entiredatabase, which can drastically reduce the MTTR for your database. Most impor-tantly, hot backups provide the ability to restore the database right up to the pointof failure, with little or no loss of critical data.

To perform hot backups, the database must be running in ARCHIVELOG mode.When the database is in ARCHIVELOG mode, the redo logs are copied by thearchiver process to an archive destination. If media failure causes the loss of oneor more datafiles, you can restore just those datafiles from the last hot backup,and then apply the changes stored in the archive logs to the datafiles to bringthem up to date with the rest of the database.

To configure the database in ARCHIVELOG mode, you must first tell Oraclewhere to send the archive logs, and what format to use for the archive log filenames. The LOG_ARCHIVE_DEST initialization parameter specifies the archivelog destination, and the LOG_ARCHIVE_FORMAT parameter specifies the filename format.

The LOG_ARCHIVE_DEST parameter can be set to any valid file systemdirectory. The value assigned to this parameter can include OS-level environmentvariables, as long as the translated string of characters resolves to a directory onthe file system that Oracle can find and write to. If this parameter is not set, thearchive logs will be written to an OS-dependent default location. It is recom-mended, however, that you set this parameter explicitly to ensure that you havecomplete control over where the files are written to. You can use the ALTERSYSTEM command to set this parameter for the current instance, in the spfile forfuture restarts, or both. The following is an example of the ALTER SYSTEMcommand to set the LOG_ARCHIVE_DEST parameter for both the currentinstance and future restarts:

ALTER SYSTEM SET log_archive_dest='%ORACLE_BASE%\oradata\archive'SCOPE=BOTH;

In this example, the LOG_ARCHIVE_DEST parameter is set to the oradata\archive subdirectory under the directory specified by the %ORACLE_BASE%environment variable, which is set at the OS level. If the %ORACLE_BASE%parameter is set to D:\oracle, then the archive log destination will becomeD:\oracle\oradata\archive.

Optionally, you can configure multiple archive log destinations. To configure mul-tiple archive log destinations, you would not use the LOG_ARCHIVE_DESTparameter, but instead use a series of LOG_ARCHIVE_DEST_n parameters,where n is a sequential number to uniquely identify each archive destination.Oracle can support up to 10 archive log destinations, each with its own archiverprocess. To configure two archive log destinations, you would configure theLOG_ARCHIVE_DEST_1 and LOG_ARCHIVE_DEST_2 parameters, as shownin the following example:

ALTER SYSTEM set log_archive_dest_1 ='location=D:\oracle\oradata\archive\' SCOPE = BOTH;

ALTER SYSTEM set log_archive_dest_2 ='location=E:\oracle\oradata\archive\' SCOPE = BOTH;

Notice that the first archive destination is set to the D drive, while the seconddestination is set to the E drive. Also, the syntax for this parameter is slightlydifferent than the LOG_ARCHIVE_DEST parameter. For any of the LOG_ARCHIVE_DEST_n parameters, you must include the keyword LOCATION tospecify the path where archive logs will be sent. Additionally, the LOG_

Environment variables inWindows are surrounded by

percent signs (%), whileenvironment variables in

Unix are preceded by adollar sign ($).

128 Oracle9i Database: Fundamentals II

Page 144: Oracle 9i DBA Fund - II

ARCHIVE_DEST parameter must be set to null if any of the LOG_ARCHIVE_DEST_n parameters are set. For example, you cannot set both LOG_ARCHIVE_DEST and LOG_ARCHIVE_DEST_2. If you want multiple archive destinations,you must use only the LOG_ARCHIVE_DEST_n parameters.

For each archive destination that is configured, Oracle will automatically spawn anew archiver process, up to the maximum number of archiver processes specifiedby the LOG_ARCHIVE_MAX_PROCESSES parameter. For example, if youconfigure five archive log destinations, and you have specified five or more forthe LOG_ARCHIVE_MAX_PROCESSES parameter, Oracle will spawn exactlyfive archivers. However, if you only specify two for the LOG_ARCHIVE_MAX_PROCESSES, Oracle will only spawn two archivers, regardless of the number ofarchive destinations you have configured. If less archive processes are spawnedthan there are archive destinations configured, Oracle will attempt to double upthe workload on some of the archivers. For performance reasons, you should setLOG_ARCHIVE_PROCESSES to at least the number of archive destinations youhave configured.

The LOG_ARCHIVE_FORMAT parameter is used to specify the file name for-mat for the archive logs. This parameter uses variables to ensure that eacharchive log has a unique name to avoid overwriting existing archive logs. Thefollowing table lists the four pattern variables and their usage.

Pattern Variable Usage%s The log sequence number of the redo log that the archive log was generated

from.%S The same as %s, but fixed length and left-padded with zeros. The fixed length

is OS dependent.%t The thread number. Will always have a value of 1, except when the instance is

part of a Real Application Cluster (RAC) configuration.%T The same as %t, but fixed length and left-padded with zeros. The fixed length is

OS dependent.

The LOG_ARCHIVE_FORMAT parameter can be set only in the spfile and canbe assigned any combination of four pattern variables plus any additional envi-ronment variables or literal characters you wish to include. For example, thefollowing is an ALTER SYSTEM command to set the LOG_ARCHIVE_FORMAT parameter using the %S pattern variable and the $ORACLE_SIDenvironment variable in a Unix environment.

ALTER SYSTEM SET log_archive_format='log_$ORACLE_SID_%S.arc'SCOPE=SPFILE;

In this example, if the $ORACLE_SID variable was set to ora92, and the logsequence number of the redo log being archived was 17, the name of the archivelog to be generated would be log_ora92_00017.arc. Including the $ORACLE_SIDenvironment variable can be useful to identify exactly which database a list ofarchive logs came from. This can be handy if you have several databasesarchiving their log files to the same or similar directory structure. The defaultLOG_ARCHIVE_FORMAT parameter is OS dependent.

Another parameter which can be set is the LOG_ARCHIVE_START parameter.This parameter accepts only the values TRUE or FALSE and is optional, but it ishighly recommended that you set it. If this LOG_ARCHIVE_START is left set toits default of FALSE, the archiver process will only archive the redo logs whentold to do so by the ALTER SYSTEM ARCHIVE LOG ALL command. This

LOG_ARCHIVE_FORMATPattern Variables

Lesson 2: Backup and Recovery Overview 129

Page 145: Oracle 9i DBA Fund - II

means that the DBA must constantly monitor the database and manually archivethe redo logs with the ALTER SYSTEM ARCHIVELOG ALL command when itbecomes necessary to do so. If Oracle does not archive the logs, then it cannotperform the log switch, and the database will completely freeze up until it can. Ifthis parameter is set to TRUE, then the archiver process will automatically archiveredo logs as they are switched out. This parameter can only be set for futurerestarts in the spfile.

Just setting the LOG_ARCHIVE_DEST, LOG_ARCHIVE_FORMAT, and LOG_ARCHIVE_START parameters does not yet mean the database is inARCHIVELOG mode. To determine whether or not the database is in archive logmode, you can issue the command ARCHIVE LOG LIST from the SQL*Plusprompt. To use this command, you must log in to the database as either SYS oranother user that has SYSDBA privileges. The output of this command indicateswhether the database is in ARCHIVELOG or NOARCHIVELOG mode, whetheror not the automatic archiving is enabled, and the log archive destination. It alsoshows the log sequence numbers of the current log group, the next log group tobe archived, and the oldest log sequence number from all log groups. Figure 2-6shows the output of the ARCHIVE LOG LIST command for a database that hasthe appropriate parameters set, but is still in NOARCHIVELOG mode.

Figure 2-6: The output from the ARCHIVE LOG LIST command.

After setting the appropriate parameters, you can then enable ARCHIVELOGmode. First, the database must be shut down cleanly, meaning that the instancemust not have been aborted either through instance failure or the SHUTDOWNABORT command. The database must then be started up using the STARTUPMOUNT command. Once in the mount mode, you would enable archive loggingby issuing the ALTER DATABASE ARCHIVELOG command. Once this com-mand is executed, you can open the database for general use. It is recommendedthat once you enable ARCHIVELOG mode that you manually switch the redologs a few times to ensure that the logs are archiving, and that they are beingarchived to the correct location. The following sample output shows the sequenceof events to enable ARCHIVELOG mode for a database.

130 Oracle9i Database: Fundamentals II

Page 146: Oracle 9i DBA Fund - II

SQL> connect sys/ora92 as sysdbaConnected.SQL> archive log list;Database log mode No Archive ModeAutomatic archival EnabledArchive destination D:\oracle\oradata\archiveOldest online log sequence 37Current log sequence 39SQL> shutdown immediate;Database closed.Database dismounted.ORACLE instance shut down.SQL> startup mount;ORACLE instance started.

Total System Global Area 135338868 bytesFixed Size 453492 bytesVariable Size 109051904 bytesDatabase Buffers 25165824 bytesRedo Buffers 667648 bytesDatabase mounted.SQL> alter database archivelog;

Database altered.

SQL> alter database open;

Database altered.

SQL> archive log listDatabase log mode Archive ModeAutomatic archival EnabledArchive destination D:\oracle\oradata\archiveOldest online log sequence 37Next log sequence to archive 39Current log sequence 39SQL>

Once the database is in ARCHIVELOG mode, you can begin performing hotbackups. Upon opening the database, Oracle will spawn the ARCH process tohandle copying the redo logs to the archive destination specified by the LOG_ARCHIVE_DEST or LOG_ARCHIVE_DEST_n parameters as they are filled andswitched out. The archive logs will be named using the naming pattern specifiedby the LOG_ARCHIVE_FORMAT parameter. If the LOG_ARCHIVE_STARTparameter is set, Oracle will automatically archive the redo logs without requiringintervention from the DBA.

Lesson 2: Backup and Recovery Overview 131

Page 147: Oracle 9i DBA Fund - II

TASK 2C-1Configuring Archivelog Mode

Objective: To configure the database in archivelog mode to enable theability to perform hot backups.

1. From the desktop, launch SQL*Plus from the Start menu.

In the Log On dialog box, type sys for User Name, ora92 for Password,and ora92 as sysdba for Host String. Click OK.

2. Before changing the configuration of the database, you should determine thecurrent configuration.

At the SQL*Plus prompt, type ARCHIVE LOG LIST; and press Enter.

The output will show that the database is currently in No Archive Mode.Currently, hot backups cannot be performed for this database.

3. You will now modify the appropriate initialization parameters to configurethe database to support archive log mode. These parameters include LOG_ARCHIVE_DEST and LOG_ARCHIVE_START. You will leave LOG_ARCHIVE_FORMAT at its default setting. At the prompt, issue thefollowing commands.

ALTER SYSTEM SET log_archive_dest= ⇒'D:\oracle\ora92\database\archive' ⇒SCOPE=spfile;

ALTER SYSTEM SET log_archive_start=TRUE SCOPE=spfile;

The log sequence numbersfor your system may be

slightly different than what isshown here.

The double right arrow (⇒)indicates that the command

is intended to be typed on asingle line.

132 Oracle9i Database: Fundamentals II

Page 148: Oracle 9i DBA Fund - II

Oracle will respond with the message “System Altered” after each command.

4. You must now restart the database to have these changes take affect.

At the prompt, type shutdown immediate; and press Enter.

After a moment, the output will show that the database has been closed anddismounted, and the instance shut down.

5. You must bring the database up to the mount stage to enable ARCHIVELOGmode.

At the prompt, type startup mount and press Enter.

After a moment, you will see that the instance is started and the database ismounted.

6. To enable ARCHIVELOG mode, type ALTER DATABASEARCHIVELOG; and press Enter.

Oracle will display the message “Database altered.”

7. You can now open the database for general use.

At the prompt, type ALTER DATABASE OPEN; and press Enter.

Lesson 2: Backup and Recovery Overview 133

Page 149: Oracle 9i DBA Fund - II

After a moment, Oracle will display the message “Database altered.”

8. To verify that the database is indeed in ARCHIVELOG mode with automaticarchiving enabled, type ARCHIVE LOG LIST; and press Enter.

The output will show you that the database is in ARCHIVELOG mode, thatautomatic archiving is enabled, and that full redo logs will be archived to theD:\oracle\ora92\database\archive folder.

9. To verify that your settings are correct, you will force a log switch. This willcause the archiver process to copy the current online redo log to the archivelog destination.

At the prompt, type ALTER SYSTEM SWITCH LOGFILE; and pressEnter.

Oracle will display the message “System altered.”

10. Leaving the SQL*Plus window open, choose Start→Run. In the Run textbox, type D:\oracle\ora92\database\archive and click OK. A window forthe D:\oracle\ora92\database\archive folder will open.

You will see a single archive log file. This shows that you have indeed con-figured the database in ARCHIVELOG mode with the proper settings. Hot

134 Oracle9i Database: Fundamentals II

Page 150: Oracle 9i DBA Fund - II

backups can now be performed for this database.

Close the archive window.

11. At the SQL*Plus prompt, type exit and press Enter to close SQL*Plus.

Hot Recovery ConceptsOne of the most important aspects of database recovery is recognizing whenrecovery is necessary. Many times a media failure will be discovered by a userwhile simply attempting to access data in a datafile that has become corrupted orno longer exists. Other times, such as when one or more datafiles of the SYS-TEM tablespace experience a failure, the instance will just crash. You mustremember that the mean time to recovery refers to the amount of time it takes torecover the database after a failure and not the discovery of the failure. It isentirely possible for media failure to occur and go unnoticed for hours or days.Of course, if no users try to access a file that has suffered media failure, then nousers have been affected by the failure. However, if a user discovers media failurebefore the DBA does, it is essentially too late.

One of the most important files that the DBA should be monitoring on a regularbasis is the alert log, which is located in the directory specified by theBACKGROUND_DUMP_DEST parameter. Oracle writes a steady stream ofinformation to this file, which includes entries for database startups and shut-downs, major ALTER SYSTEM and ALTER DATABASE commands, and anyinternal errors or media issues the database encounters. If media failure were tooccur, Oracle would immediately write entries concerning the failure to the alertlog.

Depending on the failure and its related errors, Oracle may also write to the alertlog for the paths and file names of any additional traces files that may have beengenerated. These trace files usually include more detailed information about errorsthan what is included in the alert log. Some background process may also gener-ate trace files. If a required background process fails, the instance will crash, andthe background process will generate a trace file that includes the related errors

Lesson 2: Backup and Recovery Overview 135

Page 151: Oracle 9i DBA Fund - II

that caused the process to fail. In some cases, media failure might cause theinstance to crash, while in other cases, instance failure might cause a datafile tobecome corrupted due to DBWR partially writing datablocks at the moment offailure. Either way, the alert log and trace files are a great place to start monitor-ing for and researching media failure.

If the instance is still up and running after media failure, another place you canlook to determine which files need recovery is the data dictionary. TheV$RECOVER_FILE view lists all datafiles that need recovery and why. The fol-lowing table lists the columns of this view and their descriptions.

Column DescriptionFILE# File ID number.ONLINE Left over from previous versions of Oracle and is obsolete. Will

always show the same value as ONLINE_STATUS column.ONLINE_STATUS Online status of the datafile.ERROR Reason why the datafile needs recovery. Will be null if the reason is

unknown.CHANGE# SCN where recovery must start.TIME Time of the starting recovery SCN.

The most important column of this view is the ERROR column, which tells youexactly why the file needs recovery. For example, if this column shows the value'FILE NOT FOUND', then either the file was accidentally deleted from the filesystem, or the entire disk where the file resides has gone offline or crashed. TheFILE# column lists only the ID number of each datafile that needs recovery. Youcan use the file ID to look up the actual path and name of the file in theV$DATAFILE view. The file ID also resides in the DBA_DATA_FILES view, butthis view is only available while the database is open; the V$DATAFILE view isavailable when the database is in the mounted state.

Once you have determine why a datafile needs recovery, you can decide whatsteps to take next. If the datafile exists but is simply offline due to other errors,then you can simply begin the recovery process to bring the file up to date withthe rest of the database, and then bring the datafile or tablespace online. If the fileis completely missing, then you must first restore it from a hot backup beforeinitiating recovery. If the entire disk where the file resides is damaged or unus-able, then you must restore the datafile to a different location.

Once the datafiles in question are in place, you can begin the recovery processwith the RECOVER command. You can perform the recovery at the datafile,tablespace, or database levels. If you issue the RECOVER DATAFILE command,only the specified datafile will be recovered, while RECOVER TABLESPACEcommand will recover all datafiles that make up the specified tablespace. If youissue the RECOVER DATABASE command, all datafiles in the database that needrecovery will be recovered. In most cases, using the RECOVER DATABASE com-mand is easiest for a large database since it will cause Oracle to automaticallyrecover all datafiles that need recovery without having to list each datafile ortablespace separately.

During the recovery process, Oracle will compare the SCN in the control filewith the SCNs in the datafiles being recovered. If any datafile SCNs are lowerthan what is shown in the control file, then Oracle will determine where the redoinformation necessary for recovery resides, either in the current online redo log oran archived log. If the redo information resides in the current online redo log,

The V$RECOVER_FILEColumns

136 Oracle9i Database: Fundamentals II

Page 152: Oracle 9i DBA Fund - II

Oracle will automatically apply the changes without requiring interaction with theDBA. If the redo information has already been archived, Oracle will use theCHANGE# column of the V$RECOVER_FILE view along with theV$ARCHIVED_LOG view to determine which archive log contains the change,and then prompt the DBA for the path and location of that log. As a convenience,Oracle will suggest the name and location of the archive log’s last knownlocation. If the file still resides there, the DBA can accept the suggestion andapply that archive log. If the file has been moved to another location, then the filemust either be restored to its original location or the DBA must specify thearchive log’s current location.

Oracle begins the roll forward phase of recovery by applying the changes fromthe redo information to the target datafiles. After each change is applied, Oraclewill compare the datafile’s SCNs with what is listed in the control file. If allchanges in the current archive log have been applied but the datafile still needsrecovery, Oracle will prompt for the next archive log in the sequence. This pro-cess repeats until all available redo information has been applied to the affecteddatafiles. When the SCNs of the datafiles match that of the control files, and onlythen, will Oracle consider the datafiles recovered. Once the roll forward phase iscomplete, Oracle will perform the rollback phase by rolling back all recoveredtransactions that were executed just prior to the media failure but not yet commit-ted when the failure occurred. Since those transactions were not committed, anychanges from those transactions will be lost.

Hot Recovery RestrictionsThere are two very important rules for hot recovery that you must remember. Thefirst rule is that you can only perform a complete recovery when performing a hotrecovery of the database, regardless of at which level it is performed. The entiredatabase must be in a consistent state, meaning all datafile headers must show thesame SCN that is shown in the control file. You cannot recover a datafile ortablespace to a different point in time than the rest of the database. If you attemptto bring a tablespace online after performing an incomplete recovery (by notapplying all the redo or archive logs), then Oracle will return an error. Thetablespace or datafile cannot be brought back online until it is completelyrecovered.

The second rule refers to the situations in which hot recoveries can be performed.The database can remain open in most hot recovery scenarios, but the SYSTEMtablespace must always be online. If something were to happen to cause the SYS-TEM tablespace to come offline, such as media failure where the SYSTEMdatafiles reside, the instance would immediately crash. As such, it is impossible toperform a hot recovery for the datafiles of the SYSTEM tablespace. You willneed to restore the datafile from backup if they are missing, then start up thedatabase and bring it to the mount state. Only then can you perform a recovery ofthe SYSTEM tablespace.

Lesson 2: Backup and Recovery Overview 137

Page 153: Oracle 9i DBA Fund - II

TASK 2C-2Describe Hot Database Recovery

1. Where could the DBA look to determine which files have been affectedby media failure? Choose all that apply.

✓ a. Alert log

b. Core dump file

✓ c. Trace files

✓ d. V$RECOVER_FILE

2. True or False? It is possible to perform a recovery of the SYSTEMtablespace while the database is up and running. Explain your answer.

False. If the SYSTEM tablespace requires recovery, then the database mustbe down and cannot be opened until the tablespace is recovered.

3. A user issues an UPDATE statement to change the values in the EMPtable that resides in the USERS tablespace. While the statement wasrunning, the disks that hold the datafiles for the USERS tablespacefailed. Once the USERS datafiles are restored, you begin a recovery ofthe tablespace. Upon completion of the recovery, what has become of thechanges made by the UPDATE statement?

During recovery, Oracle will apply all changes found in the redo log orarchive logs to the datafiles being recovered. At the end of the recovery,Oracle will determine that there is no COMMIT statement associated withthe changes and will, therefore, rollback the transaction.

SummaryIn this lesson, you learned about the types of failures that may occur in anOracle9i database and the features provided to resolve them. You alsolearned how to create a cold backup of the database and how to use thatbackup to restore the database after a failure. Finally, you learned about themechanisms in place to back up and recover an Oracle9i database withminimal data loss.

138 Oracle9i Database: Fundamentals II

Page 154: Oracle 9i DBA Fund - II

Lesson Review2A Which database component plays the biggest role in handling transac-

tion failure?

a. Database buffer cache

b. Log writer

c. Redo log buffer

✓ d. Undo segment

What advantages does performing hot backups have over performingcold backups?

Cold backups require that the database be shut down during the backup pro-cess while hot backups allow the database to be up and running.Additionally, you have the capability of backing up only a tablespace at atime, which allows you to spread out the backups across multiple sessions ifthe database is very large. With cold backups, any media failure requiresthat you restore the entire backup, while a hot backup only requires that themissing files be restored. Also, after a database is recovered from a coldbackup, the contents of the database will look exactly as it did when thebackup was performed, while a hot backup can recover the database rightup to the point of failure.

Each redo log group in your database consists of two redo log filemembers. What will happen if media failure causes the loss of one logfile member of one log file group?

In this scenario, the Oracle database will stay up an running. Since each logfile member in a single group contains the same information, Oracle will beable to keep generating changes and switching redo logs as long as at leastone redo log member is available in each group. The primary purpose ofmultiplexing the redo log files is to ensure the database is durable enough towithstand losing a single log file member without crashing.

2B Which data dictionary views could you use to determine the names andlocations of the files that you need to back up as part of a full, colddatabase backup? Choose all that apply.

✓ a. DBA_DATA_FILES

b. DBA_TABLESPACES

✓ c. V$PARAMETER

✓ d. V$LOGFILE

True or False? When restoring the database from a cold backup, youmust restore only the files that were lost due to media failure. Explainyour answer.

False. You must restore all files from the cold backup, including the controlfiles and redo log files, not just the files that were lost due to media failure.

Lesson 2: Backup and Recovery Overview 139

Page 155: Oracle 9i DBA Fund - II

2C You have properly set the LOG_ARCHIVE_DEST and LOG_ARCHIVE_FORMAT initialization parameters, and you have properlyenabled ARCHIVELOG mode while the database was in MOUNT state,but Oracle is not archiving any redo logs. In fact, the database is com-pletely frozen. Why?

Even though ARCHIVELOG mode has been set and a valid path and filename pattern has been specified for the archive logs, Oracle will not auto-matically archive the redo logs unless the LOG_ARCHIVE_STARTparameter is set to TRUE. If Oracle cannot archive the filled redo logs, itcannot perform a log switch, and the database will freeze up until it can.The DBA must either manually archive the redo logs with the ALTERDATABASE ARCHIVELOG ALL command or set the LOG_ARCHIVE_START parameter to TRUE and restart the instance.

What is the most important column of the V$RECOVER_FILE view?

✓ a. ERROR

b. FAILURE_REASON

c. ONLINE_STATUS

d. TIME

140 Oracle9i Database: Fundamentals II

Page 156: Oracle 9i DBA Fund - II

User-managed Backup andRecovery

OverviewUser-managed backup and recovery of the Oracle database involves manu-ally performing all the steps required to create a valid database backup, aswell as all the steps to perform a recovery in the event of media failure.Earlier in the course, you learned that performing a cold backup simplyinvolves making copies of all necessary Oracle files while the database isshut down. Since cold backups are fairly straight-forward, this lesson willfocus on performing hot backups and recoveries. In this lesson, you willlearn how to perform backups of the tablespaces and control file, and howto perform both complete and incomplete recoveries under various mediafailure scenarios. Finally, you will learn about the special backup and recov-ery considerations for read-only tablespaces and also how to recover thedatabase if the instance crashes while a hot backup is running.

ObjectivesTo perform user-managed backups and recoveries of the database, you will:

3A Perform user-managed hot backups of the database.

A user-managed full database backup consists of manually backing up allcritical database files, including the control file, spfile, password file, andthe datafiles of all the tablespaces. In this topic, you will learn the stepsnecessary to manually perform a full database backup. You will also learnhow to recover the database in the event of instance failure while a data-base backup is running.

3B Perform a complete recovery of the database after a failure.

There are two types of recovery, complete and incomplete. During a com-plete recovery, the database is recovered up to the point in time when themedia failure occurred, which guarantees that there will be no loss ofchanges to the data. In this topic, you will learn how to perform a com-plete recovery.

3C Perform incomplete recoveries of the database to recover from vari-ous failure scenarios.

During an incomplete recovery, the database is recovered to a point intime prior to the point in failure, which usually results in the loss ofchanges to the data. An incomplete recovery may be required under cer-tain circumstances, or it can be performed intentionally for a specificpurpose. In this topic, you will learn how to perform incomplete recover-ies and when you would need to perform one.

Data Filesbup_status.sqlget_trace.sqlhot_backup_database.sqlrestore_database.sqllogfiles.sql

Lesson Time6 hours, 30 minutes

LESSON

3

Lesson 3: User-managed Backup and Recovery 141

Page 157: Oracle 9i DBA Fund - II

Topic 3AUser-managed BackupsA database backup set includes the control file, spfile, password file, and thedatafiles of all the tablespaces. The spfile and password file can both be backedup any time using OS-level commands, even if the database is up and running.You will learn how to back up the control file later in this topic. This section willfocus on backing up the datafiles that make up the Oracle tablespaces.

To perform a backup of the database manually, you would back up eachtablespace individually, first placing each one into backup mode and then copyingtheir datafiles using OS-level commands. Once the datafiles are copied, youwould take the tablespaces out of backup mode. The ALTER TABLESPACEcommand is used to place a tablespace in or out of backup mode, as shown in thefollowing syntax:

ALTER TABLESPACE tablespace_name [BEGIN|END] BACKUP;

The database must be configured in ARCHIVELOG mode to place tablespacesinto hot backup mode. If the database is running in NOARCHIVELOG mode,and you issue the ALTER SYSTEM command to place a tablespace in hot backupmode, Oracle will return an error.

Since the backups are performed at the tablespace level, you can schedule thetablespace backups in a round-robin fashion, backing up one tablespace at a time.You would place a tablespace in backup mode, copy its datafiles, and then take itout of backup mode, repeating the process for each tablespace sequentially. Thiscan be especially handy if your database is so large that you cannot back up allthe datafiles during a single scheduled maintenance window. You can performbackups of one or two tablespaces a night, and perhaps over a period of oneweek, the entire database would be backed up.

Once a tablespace is in hot backup mode, you would copy the tablespace’sdatafiles using OS-level commands. The following example script can be runfrom the SQL*Plus prompt to perform a user-managed hot backup of thetablespaces.

connect sys as sysdba

ALTER TABLESPACE SYSTEM BEGIN BACKUP;host copy D:\ORACLE\ORADATA\ORA92\SYSTEM01.DBF f:\dbbackupALTER TABLESPACE SYSTEM END BACKUP;

ALTER TABLESPACE UNDOTBS1 BEGIN BACKUP;host copy D:\ORACLE\ORADATA\ORA92\UNDOTBS01.DBF f:\dbbackupALTER TABLESPACE UNDOTBS1 END BACKUP;

ALTER TABLESPACE EXAMPLE BEGIN BACKUP;host copy D:\ORACLE\ORADATA\ORA92\EXAMPLE01.DBF f:\dbbackupALTER TABLESPACE EXAMPLE END BACKUP;

ALTER TABLESPACE INDX BEGIN BACKUP;host copy D:\ORACLE\ORADATA\ORA92\INDX01.DBF f:\dbbackup

ALTER TABLESPACE Syntax

backup mode:A special mode for

tablespaces that allows themto be copied while the

database is up and running.

142 Oracle9i Database: Fundamentals II

Page 158: Oracle 9i DBA Fund - II

ALTER TABLESPACE INDX END BACKUP;

ALTER TABLESPACE TOOLS BEGIN BACKUP;host copy D:\ORACLE\ORADATA\ORA92\TOOLS01.DBF f:\dbbackupALTER TABLESPACE TOOLS END BACKUP;

ALTER TABLESPACE USERS BEGIN BACKUP;host copy D:\ORACLE\ORADATA\ORA92\USERS01.DBF f:\dbbackupALTER TABLESPACE USERS END BACKUP;

exit

There is one small but very important difference between a tablespace in hotbackup mode and a tablespace not in hot backup mode. While a tablespace is inhot backup mode, all changes to datablocks that are stored in the tablespace arestill written from the buffer cache to the datafiles by the DBWR process whencheckpoints occur. However, the checkpoints are deferred for tablespaces in hotbackup mode. That is to say that CKPT does not update the headers of thedatafiles of a tablespace while that tablespace is in hot backup mode. Thedatafiles will still contain the SCN that was current at the point in time when thetablespace was placed in hot backup mode. Since the control file tracks the cur-rent SCN for the entire database, once a tablespace is taken out of hot backupmode, Oracle simply advances the tablespace’s datafile headers to the latestcheckpoint to bring them up to date with the rest of the database. While thetablespace is in hot backup mode, its datafiles may be changing while the OS iscopying them, which creates an inconsistent copy of the files. However, this iseasily rectified during Oracle’s recovery mechanisms when the backup datafilesare restored and recovered.

The V$BACKUP data dictionary view shows which datafiles are currently in hotbackup mode and the SCN and timestamp of the tablespace the last time it wasplaced in hot backup mode. The following table shows the columns of theV$BACKUP view and their descriptions.

Column DescriptionFILE# The file ID number.STATUS Current status of the datafile. Values include ACTIVE if the datafile is in hot

backup mode, or NOT ACTIVE if the datafile is not in hot backup mode.CHANGE# The SCN of the datafile when it was last placed in hot backup mode.TIME The timestamp of the datafile when it was last placed in hot backup mode.

Since the V$BACKUP view contains only the file number of each datafile, it ismuch easier to identify the tablespaces and their datafiles by joining this viewwith the V$DATAFILE and V$TABLESPACE views to provide a complete listingof tablespaces with their datafiles. The following is an example query of thesethree views showing the backup status of all the tablespaces and their datafiles.

Lesson 3: User-managed Backup and Recovery 143

Page 159: Oracle 9i DBA Fund - II

SELECTt.name tablespace_name,f.name file_name,b.status

FROMv$backup b,v$datafile f,v$tablespace t

WHEREb.file# = f.file# andf.ts# = t.ts#;

TASK 3A-1Hot Backup Tablespaces

Objective: To perform hot backups of the tablespaces.

1. Before beginning the tablespace hot backup, you will create a folder to storethe backed up datafiles.

From the desktop, choose Start→Run. In the Run text box, type D:\oracleand click OK. A window for the D:\oracle directory will open.

Choose File→New→Folder. Name the new folder hot_bup

2. Leaving the D:\oracle window open, launch SQL*Plus from the Startmenu.

In the Log On dialog box, type sys for User Name, ora92 for Password,and ora92 as sysdba for Host String. Click OK.

3. Before setting any tablespaces to backup mode, you should determine thecurrent backup status of the tablespaces.

At the prompt, type edit C:\079176\bup_status.sql and press Enter.

The bup_status.sql script will open. This script queries from the

144 Oracle9i Database: Fundamentals II

Page 160: Oracle 9i DBA Fund - II

V$BACKUP, V$DATAFILE, and V$TABLESPACE data dictionary views.

Close the bup_status.sql script.

At the prompt, type @C:\079176\bup_status.sql and press Enter to executethe script.

The output will show that none of the tablespaces are currently in backupmode.

4. You will back up the EXAMPLE and SYSTEM tablespaces. At the prompt,issue the following commands:

ALTER TABLESPACE example BEGIN BACKUP;ALTER TABLESPACE system BEGIN BACKUP;

Lesson 3: User-managed Backup and Recovery 145

Page 161: Oracle 9i DBA Fund - II

After each command, Oracle will display the message “Tablespace altered.”

5. Type @C:\079176\bup_status.sql and press Enter.

You will see that the values in the STATUS column for EXAMPLE andSYSTEM tablespaces have changed to ACTIVE. You can now begin backingup the datafiles for these tablespaces.

6. Switch to the D:\oracle folder.

Double-click the oradata folder to open it, and then double-click theora92 folder.

Select EXAMPLE01.DBF, and then, while holding the Ctrl button, selectSYSTEM01.DBF as well.

146 Oracle9i Database: Fundamentals II

Page 162: Oracle 9i DBA Fund - II

Choose Edit→Copy.

Press Backspace twice to move back to the D:\oracle folder. Double-clickthe hot_bup folder to open it.

Choose Edit→Paste to begin copying the datafiles to your hot backupfolder.

A status bar will appear while the files are copied. It will take a fewmoments until the copies are complete.

Once the copies are complete, close the hot_bup window.

7. At the SQL*Plus prompt, disable backup mode for the EXAMPLE andSYSTEM tablespaces with the following commands:

ALTER TABLESPACE example END BACKUP;ALTER TABLESPACE system END BACKUP;

Oracle will display the message “Tablespace altered” after each command.

8. At the prompt, type @C:\079176\bup_status.sql and press Enter.

The output will show that the EXAMPLE and SYSTEM tablespaces are nolonger in backup mode.

9. At the prompt, type exit and press Enter.

Lesson 3: User-managed Backup and Recovery 147

Page 163: Oracle 9i DBA Fund - II

Backing Up the Control FileAs you learned earlier, the control file contains information about the databasecritical to its operation, such as the datafile and redo log file layout and the cur-rent system change number. Without the control file, the database simply cannotoperate, which is why you should configure the database with multiple copies ofthe control file, as specified by the CONTROL_FILES initialization parameter.However, if media failure were to cause the loss of all copies of the control file,it will be very difficult and time consuming to recover the database.

In addition to multiplexing the control file, you should also back up the controlfile. This should be done on a regular schedule and any time the physical struc-ture of the database changes, such as adding datafiles or tablespaces. Oracleprovides two methods of backing up the control file, both of which can be usedwhile the database is up and running. You can back up the control file by creatingan image copy or by creating a trace file that contains the CREATECONTROLFILE command that can be used to re-create the control file.

To create an image copy of the control file, you would use the ALTERDATABASE command with the BACKUP CONTROLFILE option and specify thename and path of the backup control file you want to create. Even if your data-base contains multiple copies of the control file, you only need to create a singlebackup since all of the current copies are identical. The following is an exampleof the ALTER DATABASE command used to create an image copy of the controlfile.

ALTER DATABASE BACKUP CONTROLFILE TO 'F:\dbbackup\control.bak';

In this example, Oracle will read from one of the live control files to create asingle backup control file called control.bak in the F:\dbbackup directory. Thissingle backup control file can be used to restore all copies of the control file ifthey are lost. If a previously-created backup control file already exists in thebackup location with the same name as the backup you are trying to create,Oracle will return an error. However, you can force Oracle to overwrite the previ-ous backup by including the REUSE keyword with the ALTER DATABASEcommand, as shown in the following example.

ALTER DATABASE BACKUP CONTROLFILE TO 'F:\dbbackup\control.bak'REUSE;

To create a trace file that contains the CREATE CONTROLFILE command, youwould specify the keyword TRACE with the ALTER DATABASE BACKUPCONTROLFILE command instead of a path and file name. For example, thefollowing command will generate a trace file that contains the appropriate com-mands to re-create the control file.

ALTER DATABASE BACKUP CONTROLFILE TO TRACE;

In this example, Oracle will create a trace file in the directory specified by theUSER_DUMP_DEST parameter. This trace file will contain the necessary com-mands required to re-create the control files and get the database up and runningin the event that media failure causes the loss of all copies of the current controlfile. Figure 3-1 shows an example control file trace file generated by the ALTERDATABASE BACKUP CONTROLFILE command.

Backing Up the Control File

148 Oracle9i Database: Fundamentals II

Page 164: Oracle 9i DBA Fund - II

Figure 3-1: A control file trace file.

The trace file can be extremely useful when it is necessary to re-create the controlfile if you do not have a valid backup control file you can restore from. Tore-create the control file, you would start the database in the nomount state, andthen execute the CREATE CONTROLFILE command. If the command is verylengthy, such as when you have a very large database with numerous datafiles,the trace file can be extremely useful in getting the database up and running againwith as minimal down time as possible. Without the trace file, you would need toknow the exact names and locations of all your log files and datafiles.

When a session creates a trace file, either through a command or some othersession-specific error, Oracle writes the file to the directory specified by theUSER_DUMP_DEST parameter. The file will be named using an OS-specificnaming convention, but usually includes the name of the database and the currentsession’s OS-level process ID. The name of the trace file could be something likeora92_ora_2636.trc. This naming convention is used to reduce the possi-bility of an existing trace file being written to by another session.

If the USER_DUMP_DEST contains a large number of trace files, it could bevery difficult to locate the trace file generated by your session when you issuedthe ALTER DATABASE command. It is possible, however, to piece together thepath and location of the trace file you just generated by querying from the datadictionary. The following query will provide the name and path of the trace filethat would be generated for the current session. Every session would generate thesame directory path, but with a different file name, depending on the process IDfor that session.

SELECT a.VALUE||'\'||LOWER(d.name)||'_ora_'||b.spid||'.trc' ASfile_nameFROM v$parameter a, v$process b, v$session c, v$database dWHERE a.name = 'user_dump_dest' AND

b.addr = c.paddr ANDc.TYPE = 'USER' ANDc.audsid = USERENV('SESSIONID' ) ANDc.username IS NOT NULL;

Lesson 3: User-managed Backup and Recovery 149

Page 165: Oracle 9i DBA Fund - II

The V$PARAMETER view contains the value set for the USER_DUMP_DESTparameter, and the V$DATABASE view contains the name of the database. TheV$SESSION view contains the session IDs for all sessions connected to the data-base, along with the memory address for the session’s corresponding OS-levelprocess. The USERENV function can be used to determine various pieces ofinformation about the current session. In this case, it is being used to determinethe session ID for the current session. This session ID is matched up to theAUDSID column of the V$SESSION view. Once the current session is found, thequery matches the memory address of the session’s OS-level process inV$SESSION to the corresponding process in V$PROCESS. That view is used tofind the server process ID in the SPID column of the V$PROCESS view. All thepieces are finally put together in the select list in the form of a path and file namewhere you could find the trace file generated by the current session. The follow-ing shows sample output from this query:

ORA92> @get_trace.sql

FILE_NAME------------------------------------------------D:\oracle\admin\ora92\udump\ora92_ora_2636.trc

With a little creativity, this query can be used within a backup script to back upthe control file to trace, then automatically find the trace file and copy it to thebackup location along with the rest of the backup datafiles and control files.

TASK 3A-2Backing Up the Control File

Objective: To perform backups of the control file using multiple methods.

1. Launch SQL*Plus from the Start menu and log in as sys.

2. You will first back up the control file to a standard image copy.

At the prompt, issue the following command:

ALTER DATABASE BACKUP CONTROLFILE TO ⇒'D:\oracle\hot_bup\control.bak';

150 Oracle9i Database: Fundamentals II

Page 166: Oracle 9i DBA Fund - II

Oracle will display the message “Database altered.”

3. Choose Start→Run. In the Run text box, type D:\oracle\hot_bup and clickOK.

You will see three files. The *.DBF files are backups of datafiles you createdearlier in this lesson. The CONTROL.BAK file is the backup copy of thecontrol file. Close the hot_bup window.

4. You will now generate a trace file that can be used as a script to re-createthe control file.

At the SQL*Plus prompt, issue the following command:

ALTER DATABASE BACKUP CONTROLFILE TO TRACE;

Lesson 3: User-managed Backup and Recovery 151

Page 167: Oracle 9i DBA Fund - II

Oracle will display the message “Database altered.”

5. To determine the current path and file name of the trace file that was gener-ated, type @C:\079176\get_trace.sql and press Enter.

Oracle will display the path and file name of the trace file that wasgenerated. The file name on your system may be different from what isshown here.

6. Choose Start→Run. In the Run text box, type D:\oracle\admin\ora92\udump and click OK. A window for the udump folder will appear.

7. The udump folder will contain one or more trace files. Find and open thefile that was identified by the get_trace.sql script.

The trace file contains a SQL script that can be edited and used to re-createthe control file in the event that all control files for the database are lost.Take a few moments to browse through the file and see its contents.

Oracle generates trace filesfor a variety of reasons. Your

udump folder may containmany more trace files than

what is shown here. This isnormal and to be expected.

152 Oracle9i Database: Fundamentals II

Page 168: Oracle 9i DBA Fund - II

Close the trace file when you are done reading it.

8. At the prompt, type exit and press Enter.

Close all open windows.

Read-only TablespacesIn Oracle, tablespaces can be set to a read-only status, which guarantees that thetablespace will not be written to for any reason. A tablespace is set to read-onlyor read-write with the ALTER TABLESPACE command, as shown in the follow-ing syntax.

ALTER TABLESPACE tablespace_name READ [ONLY|WRITE];

When the ALTER TABLESPACE command is issued to set a tablespace to read-only, a checkpoint is issued, and the datafile headers for that tablespace areupdated one last time with the latest SCN from the control file. The datafiles arethen frozen, and any process that tries to write to the tablespace will receive anerror. The STATUS column of the DBA_TABLESPACES view indicates whichtablespaces are set to read-only.

Once a tablespace is in read-only mode, the datafiles for that tablespace need tobe backed up only once. Since the datafiles are guaranteed to remain static, thereis no need to include these datafiles in every database backup. Additionally, youdo not need to place a read-only tablespace into backup mode; you can simplyuse any appropriate OS-level command to make a copy of the datafiles. Once thetablespace is set back to read-write mode, you should immediately back up thetablespace, then resume including the tablespace in regular database backups.

It’s important to note that any time you change the status of a tablespace fromread-write to read-only, or vice versa, that you back up the control file. Thisensures that your latest control file backup contains the most current status infor-mation about all tablespaces in the database. If you place a tablespace in read-only and you do not back up the control file, loss of the control file at a later

Setting a Tablespace toRead-only or Read-write

Lesson 3: User-managed Backup and Recovery 153

Page 169: Oracle 9i DBA Fund - II

point will make a recovery very difficult, since Oracle will have no way of know-ing which tablespaces are supposed to be read-only. Additionally, when thecontrol file is backed up as a trace file, the trace file contains all the correct com-mands needed to recover the database, including any read-only tablespaces.

TASK 3A-3Identify Backup Considerations for Read-onlyTablespaces

1. How many times must you back up a read-only tablespace? Explainyour answer.

A tablespace in read-only mode only requires to be backed up once, as longas that backup occurs after the tablespace was placed in read-only mode.Once the tablespace is placed in read-write mode, it should be backed upimmediately. All future backups of the tablespace should follow the samelogic as all other tablespaces. If the tablespace is placed in read-only modeagain, only one backup of the tablespace after that point in time isnecessary.

2. Why is it important to immediately backup the control file after settinga tablespace from read-write to read-only, or vice versa?

The control file is read during recovery to determine the current status of alldatafiles in the database. If a media failure occurs that results in the loss ofall copies of the current control file, you must recover using a backup con-trol file. If you place a tablespace in read-only and you do not back up thecontrol file, loss of the control file at a later point will make a recovery verydiffıcult, since Oracle will have no way of knowing which tablespaces aresupposed to be read-only.

Resolving a Failed Hot BackupIf the database experiences instance failure when one or more tablespaces are inbackup mode, then the backup is considered a failed hot backup. However, thevalidity of your backup files will depend on when the instance failure occurred. Ifinstance failure occurred after the files have completed copying but before youhad the chance to issue the ALTER TABLESPACE...END BACKUP commands,then the backup copies are valid, and they can be used to restore and recover thedatabase in the event of media failure. However, if the instance crashed whileyou were still in the process of copying the files, then those copies will beinvalid, and you must discard those copies and back up the database again.

When a tablespace is placed in hot backup mode, checkpoints are deferred forthat tablespace, which means that the datafile headers will not contain the mostcurrent SCN from the control file. If the instance were to crash with thetablespace in hot backup mode, then the files will still contain the old SCN. Uponrestarting the instance, Oracle will detect the old SCN in the affected datafiles,

154 Oracle9i Database: Fundamentals II

Page 170: Oracle 9i DBA Fund - II

and will assume that the datafiles need recovery. However, since the data in thetablespace is actually current, you only need to take the tablespace out of backupmode. This will cause Oracle to checkpoint the tablespace’s datafiles and advancethe SCNs in the datafile headers to match that of the control file.

The V$BACKUP view lists which datafiles are currently in backup mode. Thisview can be queried while the database is in the mount state. You can take thedatafiles of a tablespace out of backup mode using any one of three possiblestatements. You can take a single datafile out of backup mode using the ALTERDATABASE DATAFILE command, as shown in the following syntax.

ALTER DATABASE DATAFILE 'path_and_file_name' END BACKUP;

In this example, only a single datafile is being taken out of backup mode. If thespecified datafile is the only one in the tablespace, then the entire tablespace willbe taken out of backup mode. If the tablespace contains multiple datafiles, thenonly the specified datafile will be taken out of backup mode, but no others willbe affected. This command can only be used if the database is in the mountedstate, but not open. If you issue this command while the database is open, thenOracle will return an error.

If the tablespace contains many datafiles, it will probably be much easier to takethe entire tablespace out of backup mode with the ALTER TABLESPACEcommand. With this command, as shown in the following example, all datafilesbelonging to the specified tablespace will be taken out of backup mode.

ALTER TABLESPACE tablespace_name END BACKUP;

The simplest method, of course, is to take all datafiles of all tablespaces out ofbackup mode with a single command. This can be done with the ALTERDATABASE END BACKUP command. This command takes all tablespaces out ofbackup mode simultaneously and eliminates the time-consuming need to specifyeach tablespace or datafile individually.

If you are not sure whether any tablespaces were in hot backup mode at the timethe instance failure occurred, you can also resolve the problem by simply per-forming a standard recovery by issuing the RECOVER DATABASE command.Oracle will perform its normal recovery operations by rolling the database for-ward to the point of failure using the redo log information, then rollback anyuncommitted transactions. After the recovery is complete, which should be veryquickly, the database can be opened as usual. Once the database is opened, youshould immediately determine whether your database backup set is valid. If it isnot, or if you are not sure, then you should immediately discard that backup setand create a new one.

TASK 3A-4Resolve a Failed Hot Backup

Objective: To resolve a failed hot backup in the event of failure while atablespace is in backup mode.

1. You will first simulate instance failure while a hot backup is in progress.This can be done by issuing the SHUTDOWN ABORT command whiletablespaces are in backup mode.

Launch SQL*Plus from the Start menu and log in as sys.

Resolving a Failed Backup

Lesson 3: User-managed Backup and Recovery 155

Page 171: Oracle 9i DBA Fund - II

2. Before setting any tablespace to backup mode, you should determine thecurrent statuses of the tablespaces.

At the SQL*Plus prompt, type @C:\079176\bup_status.sql and press Enter.

The output will show that no tablespaces are currently in backup mode.

3. You will now put several tablespaces in backup mode.

At the prompt, issue the following commands. After each command, Oraclewill display the message “Tablespace altered.”

ALTER TABLESPACE system BEGIN BACKUP;ALTER TABLESPACE undotbs1 BEGIN BACKUP;ALTER TABLESPACE example BEGIN BACKUP;ALTER TABLESPACE tools BEGIN BACKUP;ALTER TABLESPACE users BEGIN BACKUP;

156 Oracle9i Database: Fundamentals II

Page 172: Oracle 9i DBA Fund - II

4. To confirm which tablespaces are currently in backup mode, execute thebup_status.sql script again by typing @C:\079176\bup_status.sql andpressing Enter.

The output will show that the SYSTEM, UNDOTBS1, EXAMPLE, TOOLS,and USERS tablespaces are now in backup mode.

5. To simulate instance failure, type shutdown abort and press Enter.

Oracle will simply display the message “ORACLE instance shut down.”

6. Since the instance was aborted while several tablespaces were in backupmode, the tablespaces will not be consistent with the rest of the databaseupon startup. This means that any attempt to open the database withoutaddressing this issue will fail.

At the prompt, type startup and press Enter.

The output will show that Oracle was able to start the instance and mountthe database, but could not open the database because the tablespaces thatwere in backup mode at the time of the failure require some sort ofrecovery.

7. To resolve the failed hot backup, you will take all tablespaces out of hotbackup mode with a single command.

At the prompt, type ALTER DATABASE END BACKUP; and press Enter.

Lesson 3: User-managed Backup and Recovery 157

Page 173: Oracle 9i DBA Fund - II

Oracle will display the message “Database altered.”

8. You can now open the database.

Type ALTER DATABASE OPEN; and press Enter.

After a few moments, Oracle will display the message “Database altered.”

9. To confirm that all tablespaces have been taken out of backup mode, type@C:\079176\bup_status.sql and press Enter.

The output will show that no tablespaces are currently in backup mode. Toresolve a hot backup after a failure, you would take the tablespaces out ofbackup mode while the database is mounted but not open. The ALTERDATABASE END BACKUP command can be used to take all tablespaces outof backup mode simultaneously.

10. Exit SQL*Plus.

158 Oracle9i Database: Fundamentals II

Page 174: Oracle 9i DBA Fund - II

Topic 3BUser-managed Complete RecoveryDuring a complete recovery, the database is recovered up to the point in timewhen the media failure occurred, which guarantees that there will be no loss ofchanges to the data. A complete recovery should be the goal of most databaserecovery scenarios, if it is at all possible. When performing a user-managed com-plete recovery, you must first manually restore any datafiles that have been lostdue to media failure. This can be done through simple OS-level commands tocopy backup datafiles to their original locations. If a tablespace has multipledatafiles, and only one is lost due to media failure, you only need to restore themissing datafile. This allows you to restore only those files you need, which candrastically reduce your mean time to recovery. Figure 3-2 illustrates a datafile thathas been restored from backup after a media failure.

Figure 3-2: A datafile that has been restored after media failure.

In this figure, the INDX_01.DBF datafile was restored from backup. The SCNstored in the header of this datafile (328644) indicates the last SCN that was writ-ten to the datafile when the INDX tablespace was put into backup mode just priorto the datafile being backed up. Since the control file shows a later SCN(454143), upon recovery, Oracle will determine that the newly-restored datafile ismissing some changes that need to be applied in order to bring it up to date withthe rest of the database.

The actual database recovery is initiated with the RECOVER command fromSQL*Plus and can be performed at the file, tablespace, or database levels, knownas recovery targets. If recovery is performed at the file level, only the targetdatafile is recovered, while if the recovery is performed at the tablespace level, allrestored datafiles that make up the target tablespace are recovered. If the recovery

A Restored Datafile

The RECOVER commandis identical to the ALTERDATABASE RECOVERcommand.

Lesson 3: User-managed Backup and Recovery 159

Page 175: Oracle 9i DBA Fund - II

is performed at the database level, all restored datafiles in the database thatrequire recovery are recovered. Naturally, a database-level recovery requires theleast amount of keystrokes and can be very convenient if multiple datafiles havebeen lost across several tablespaces. The following shows the syntax of theRECOVER command.

RECOVER {DATABASE |TABLESPACE tablespace_name |DATAFILE 'path_and_file_name'};

If you wish to recover multiple tablespaces, you can list the specific tablespacesseparated by commas, and the same technique can be used for datafiles. However,you cannot include both the TABLESPACE and DATAFILE options within asingle RECOVER command. If you wish to perform such an operation, you mustdo so with separate RECOVER commands.

The RECOVER command can be used with the DATABASE option if the databaseis mounted but not open. The RECOVER command can be executed withTABLESPACE or DATAFILE options while the database remains up and running,providing the ability to perform hot recoveries, but the target of the recoverymust be offline to perform the recovery. For example, if you intend to recover atablespace, you must take the entire tablespace offline using the ALTERTABLESPACE command. If you intend to recover a single datafile, you musteither bring that single datafile offline using the ALTER DATABASE DATAFILEcommand or bring the entire tablespace offline. The tablespace or datafile that isbeing recovered will be unavailable while the recovery is being performed, butthe rest of the database can stay operational during the recovery process. The fol-lowing statements provide examples of the ALTER TABLESPACE and ALTERDATABASE DATAFILE commands to bring recovery targets offline.

ALTER TABLESPACE example OFFLINE;ALTER DATABASE DATAFILE 'D:\oracle\oradata\ora92\indx_01.dbf'OFFLINE;

Upon initiating recovery, Oracle will compare the SCN for the recovery targetwith the database’s latest SCN in the control file. If Oracle finds any datafiles inthe recovery target that have an SCN lower than what is shown in the controlfile, it will determine that those datafiles need recovery. Oracle will use adatafile’s SCN to find the redo information necessary to recover by looking in theV$LOG and V$LOG_HISTORY data dictionary views. If Oracle determines thatthe only changes needed for recovery reside in the current online redo log, thosechanges will automatically apply those changes to restore the file.

If Oracle determines that any of the changes reside in archive logs, Oracle willimmediately prompt the DBA for the name and location of the archive log thatcontains the earliest required SCN. It will also suggest the path and file name ofthat archive log as it was last known to Oracle at the time the log was archived.This path and file name may or may not be valid, depending on whether or notthe archive log has been moved to reclaim storage space. If the path and filename are valid, the DBA can simply press Enter to accept the suggestion, or theDBA can type in the true path and file name. If Oracle finds the specified file, itwill read from the file and apply the necessary changes to the restored datafile. Ifall the changes found in the archive log have been applied, but the datafiles stillneed recovery, Oracle will prompt for the next archive log in the sequence. Theentire process will repeat until all datafiles in the database have been recovered tothe point where their SCNs match what is shown in the control file.

160 Oracle9i Database: Fundamentals II

Page 176: Oracle 9i DBA Fund - II

To simplify the process of specifying archive logs, you can include the FROMclause with the RECOVER command to provide a specific directory path wherethe required archive logs can be found. This path can be, and usually is, differentfrom the archive log destination where the logs were originally archived to. If theFROM clause is omitted, Oracle will automatically assume that the archive logswill be found in the location specified by the LOG_ARCHIVE_DEST or LOG_ARCHIVE_DEST_1 parameters. You can also supply the AUTOMATIC optionwhich instructs Oracle to find and apply all necessary archive logs found in thespecified location. This eliminates the need to manually type the path and filename for each archive log that needs to be applied. The following RECOVERcommand illustrates the use of the FROM clause and AUTOMATIC option torecover the entire database.

RECOVER DATABASE AUTOMATIC FROM 'D:\oracle\oraarch';

In this example, Oracle will initiate the recovery of all datafiles in the databasethat require recovery. Oracle will look for the required archive logs in theD:\oracle\oraarch directory and will automatically apply them as they are found.If a required archive log is not found in the specified location, Oracle will haltthe recover and prompt the DBA for the correct file name and location again.

While performing the recovery, the DBA can specify the AUTO option at anypoint to instruct Oracle to automatically apply all archive logs found in the speci-fied location. For example, the DBA can issue the RECOVER DATABASEcommand and allow Oracle to suggest at least the first archive log it needs toperform the recovery. Upon seeing the location and file name of the requiredarchive log, the DBA may see that the location and file name is valid and canspecify the AUTO option instead of just pressing Enter. This instructs Oracle toaccept the suggested archive log and continue applying all required archive logsfound in that same location.

Only when the database is recovered to a consistent state, meaning the headers ofall datafiles show the same SCN, will Oracle consider the database recovered andwill display the message “Media recovery complete.” Once media recovery iscomplete, the DBA can bring the recovery target online, whether the target be adatafile, a tablespace, or the entire database. The following example shows theoutput from an automatic database recovery using the RECOVER DATABASEAUTOMATIC command.

SQL> RECOVER DATABASE AUTOMATIC;

ORA-00279: change 64688 generated at 01/26/03 19:20:58 neededfor thread 1ORA-00289: suggestion : /oracle/oradata/oraaarch/ora92_1_903.arcORA-00280: change 64688 for thread 1 is in sequence #903Log applied.ORA-00279: change 64695 generated at 01/26/03 19:24:05 neededfor thread 1ORA-00289: suggestion : /oracle/oradata/oraarch/ora92_1_904.arcORA-00280: change 64695 for thread 1 is in sequence #904ORA-00278: log file "/oracle/oradata/oraarch/arcr_1_903.arc" nolonger needed for this recoveryLog applied.Media recovery complete.

Lesson 3: User-managed Backup and Recovery 161

Page 177: Oracle 9i DBA Fund - II

In this example, Oracle searched the location specified by the LOG_ARCHIVE_DEST or LOG_ARCHIVE_DEST_1 parameters for the required archive logs.Upon finding the necessary logs, Oracle automatically applied the archive logs toall datafiles that needed recovery, and displayed the message “Media recoverycomplete” once all datafiles in the database were consistent with the control file.The database can now be opened with the ALTER DATABASE OPEN command.

TASK 3B-1Recover a Tablespace After a Failure

Objective: To recover a tablespace after a failure.

1. Earlier in this lesson, you performed a hot backup of the EXAMPLEtablespace. In this activity, you will simulate the loss of the datafile thatmakes up this tablespace, and then perform a restore and recovery of thedatafile from the hot backup.

Launch SQL*Plus from the Start menu and log in as sys.

2. At the prompt, issue the following query:

SELECT table_name, tablespace_nameFROM dba_tablesWHERE owner='OE';

The output shows a list of tables owned by the user OE. All of the tables arestored in the EXAMPLE tablespace.

3. You will create a new table in the OE schema, and store it in theEXAMPLE tablespace. At the prompt, issue the following command:

CREATE TABLE oe.test_recovery( col1 NUMBER(5) )TABLESPACE example;

162 Oracle9i Database: Fundamentals II

Page 178: Oracle 9i DBA Fund - II

Oracle will display the message “Table created.” Remember, this table didnot exist when the EXAMPLE tablespace was backed up.

4. To insert a row into this table, issue the following statements:

INSERT INTO oe.test_recovery VALUES (5);COMMIT;

Oracle will display the messages “1 row created” and “Commit complete.”

To see the row of data you just inserted into the test table, issue the follow-ing query:

SELECT *FROM oe.test_recovery;

The output will show the value 5 in the COL1 column. This row did notexist when the EXAMPLE tablespace was backed up.

5. To see the complete list of tables owned by OE, issue the following queryagain:

SELECT table_name, tablespace_nameFROM dba_tablesWHERE owner='OE';

Lesson 3: User-managed Backup and Recovery 163

Page 179: Oracle 9i DBA Fund - II

The output will show that the TEST_RECOVERY table is currently stored inthe EXAMPLE tablespace.

6. The redo information generated by the CREATE TABLE and INSERT state-ments were stored in the current online redo log. If you force a log switch,the current redo log will be archived to be used in the event that a recoveryis necessary any time in the future.

At the prompt, type ALTER SYSTEM SWITCH LOGFILE; and pressEnter.

Oracle will display the message “System altered.”

Issue the statement a second time to switch the logs again.

7. You will now simulate loss of the datafile that makes up the EXAMPLEtablespace.

First, determine the name of the EXAMPLE datafile by issuing the fol-lowing query:

SELECT file_nameFROM dba_data_filesWHERE tablespace_name='EXAMPLE';

The output shows that the EXAMPLE tablespace is made up of the

164 Oracle9i Database: Fundamentals II

Page 180: Oracle 9i DBA Fund - II

EXAMPLE01.DBF datafile, which is found in the D:\oracle\oradata\ora92folder.

8. To shut down the database, type shutdown immediate and press Enter.

The output will show that the database was closed and dismounted, and theinstance shut down.

9. Leaving the SQL*Plus window open, choose Start→Run. In the Run textbox, type D:\oracle\oradata\ora92 and click OK. A window for theD:\oracle\oradata\ora92 folder will appear.

In the list of datafiles, select EXAMPLE01.DBF and press Shift+Delete. Aquestion box will appear asking if you are sure you want to delete theEXAMPLE01.DBF file. Click Yes.

Your database just suffered a loss of the EXAMPLE01.DBF datafile.

10. Leaving the ora92 window open, switch back to the SQL*Plus window.

At the prompt, type startup and press Enter.

The output will show the instance start and the database mount. However,the database will not open because it cannot find the EXAMPLE01.DBFdatafile.

11. You will now restore the datafile from backup, and perform a completerecovery of the database using the redo information stored in the online andarchived redo logs.

Switch back to the ora92 window.

Press the Backspace key twice to move back to the D:\oracle folder.

Double-click the hot_bup folder to open it.

Lesson 3: User-managed Backup and Recovery 165

Page 181: Oracle 9i DBA Fund - II

The folder will contain the backup copies of the control file, and theexample and system datafiles.

12. Select EXAMPLE01.DBF. Choose Edit→Copy.

Press the Backspace key to move back to the D:\oracle folder.

Double-click the oradata folder to open it. Double-click the ora92 folderto open it.

Choose Edit→Paste to paste a copy of the datafile in the ora92 folder.

A progress meter will appear while the EXAMPLE01.DBF file is copied.Once the copy is complete, close the ora92 folder.

13. Now that the EXAMPLE01.DBF datafile has been restored, you must nowrecover the database.

At the prompt, type RECOVER DATABASE; and press Enter.

Oracle detects that the changes needed to recover this datafile have beenarchived already, and prompts you for the name and path of the requiredarchive log.

To accept the suggested archive log, press Enter. If Oracle prompts foradditional logs, keep pressing Enter to accept the suggested logs. Aftereach log, Oracle will display the message “Log applied.”

Once all archived changes have been applied to the database, Oracle will

The log sequence numbershown on your system may

be different from what isshown here.

166 Oracle9i Database: Fundamentals II

Page 182: Oracle 9i DBA Fund - II

display the message “Media recovery complete.”

14. The EXAMPLE tablespace has been recovered, and you may now open thedatabase.

At the prompt, type ALTER DATABASE OPEN; and press Enter.

After a moment, Oracle will display the message “Database altered.”

15. To ensure that your TEST_RECOVERY table has been recovered, issue thefollowing query once more:

SELECT table_name, tablespace_nameFROM dba_tablesWHERE owner='OE';

The output will show that your TEST_RECOVERY table is there.

16. To ensure that your data is intact, issue the following query:

SELECT *FROM oe.test_recovery;

Lesson 3: User-managed Backup and Recovery 167

Page 183: Oracle 9i DBA Fund - II

The output will show that the row you inserted into the TEST_RECOVERYtable has also been recovered.

17. You have just perform a user-managed complete recovery of your database.

Exit from SQL*Plus.

Close all open windows.

Trial RecoveryOccasionally, a database recovery may fail in mid-operation for one reason oranother, such as block corruption in the backup sets or archive logs. This requiresthat the entire operation be restarted, and can be very time-consuming, especiallyif the database is very large, and can increase your mean time to recovery. Inorder to avoid this problem, Oracle provides the ability to execute a trial recoveryto determine if a problem will be encountered during an actual recovery. The trialrecovery is much faster than an actual recovery, and if any problems are reportedduring trial recovery, those problems can be dealt with ahead of time.

To execute a trial recovery, you would simply include the option TEST with theRECOVER command. The recovery process will appear to execute as normal,prompting for archive logs as it proceeds, except that no changes are actuallywritten to the datafiles. All changes from the archive logs are stored only in thedatabase buffers, but will be rolled back at the end of the trial recovery. All errorsthat are encountered during trial recovery are recorded in the alert log. The TESToption can be included with any type of recovery that can be performed with theRECOVER command. The following statement shows an example RECOVER com-mand with the TEST option.

RECOVER DATABASE TEST;

If the trial recovery detects only a few corrupted blocks, you can choose to pro-ceed with the actual recovery, and direct the recovery process to allow thosecorruptions. This is done with the ALLOW n CORRUPTION clause of theRECOVER command. The n specifies the number of corrupt blocks to allow dur-ing the recovery. To recover a database and allow three corrupt blocks (foundduring trial recovery), you would issue the following command.

RECOVER DATABASE ALLOW 3 CORRUPTION;

It’s important to note that the ALLOW n CORRUPTION clause is provided onlyas a means to move past a block corruption issue to finish the recovery process.Since you have instructed Oracle to allow those block corruptions during therecovery process, the corruptions will still exist when you bring the recovery tar-get online. Any subsequent attempts to access those datablocks through normaldatabase operations will result in an error and will need to be rectified. Blockcorruption can be handled multiple ways, which you will learn about later in thecourse.

trial recovery:A test recovery of the

database that is used todetermine whether or not a

real recovery will besuccessful.

168 Oracle9i Database: Fundamentals II

Page 184: Oracle 9i DBA Fund - II

TASK 3B-2Perform a Trial Recovery

Objective: To perform a trial recovery.

1. In this activity, you will simulate the loss of a datafile, and then perform atrial recovery of the tablespace. This will allow you to determine if therecovery will encounter corruption issues without actually performing therecovery.

Launch SQL*Plus from the Start menu, and log in as sys.

2. Take the EXAMPLE tablespace offline by issuing the following state-ment:

ALTER TABLESPACE example OFFLINE;

Oracle will display the message “Tablespace altered.”

3. Leaving the SQL*Plus window open, open a window to the D:\oracle\oradata\ora92 folder.

In the list of datafiles, select EXAMPLE01.DBF and press Shift+Delete. Aquestion box will appear asking if you are sure you want to delete theEXAMPLE01.DBF file. Click Yes.

Your database just suffered a loss of the EXAMPLE01.DBF datafile.

4. Leaving the ora92 folder open, switch back to the SQL*Plus window.

At the prompt, issue the following statement:

ALTER TABLESPACE example ONLINE;

Lesson 3: User-managed Backup and Recovery 169

Page 185: Oracle 9i DBA Fund - II

Oracle will display error messages stating that the EXAMPLE01.DBFdatafile could not be identified.

5. You will now restore the datafile from the hot backup of the database youcreated earlier.

Switch back to the ora92 folder.

Navigate to the D:\oracle\hot_bup folder.

Copy the EXAMPLE01.DBF backup datafile from the D:\oracle\hot_bupfolder to the D:\oracle\oradata\ora92 folder. It may take a few momentsfor the copy to complete.

Close the ora92 folder.

6. You will now run a trial recovery of the EXAMPLE tablespace. This willhelp to identify potential problems that might arise during an actualrecovery. At the SQL*Plus prompt, issue the following command:

RECOVER TABLESPACE example TEST;

Oracle will return several messages.

The first message listed, starting from the bottom, states that test recoverycannot apply redos that may modify the control file. This means that the trialrecovery successfully completed. The recovery started with the earliestrequired entry in the redo logs, and stopped when it reached the last knownentry in the redo log. If any more redo entries were applied, the datafilewould contain a later SCN than the control file, and the controlfile wouldhave to be modified to support it, which is not allowed in trial recovery.

The next message, stating that the test recovery was canceled due to errors,is purely informational. The third message from the bottom states the SCNrange that was tested during the trial recovery. This range starts from theearliest known redo entry required for the data file that was restored, andends with the current SCN known to the control file.

The final message states that the test recovery did not corrupt any datablock. This means that the trial recovery was successful in that it did notencounter any corrupted data blocks during the recovery process. If a block

If you do not receive the lasttwo errors and instead

receive the following error,“ORA-10570: Test recovery

complete,” then issue thefollowing command before

moving on with this activity:CONNECT sys as

sysdba.

170 Oracle9i Database: Fundamentals II

Page 186: Oracle 9i DBA Fund - II

was found to be corrupted, the DBA could optionally skip that corruptedblock and move on with the recovery using the ALLOW n CORRUPTIONclause of the RECOVER command. The trial recovery provides a way for theDBA to identify those suspect blocks prior to running an actual recovery.

7. Before bringing the EXAMPLE tablespace back online, you must first per-form an actual recovery of the tablespace. At the SQL*Plus prompt, issuethe following command:

RECOVER TABLESPACE example;

After a moment, Oracle will display the message “Media recoverycomplete.”

8. Bring the tablespace back online by typing the following command atthe SQL*Plus prompt:

ALTER TABLESPACE example ONLINE;

Oracle will display the message “Tablespace altered.”

9. Exit from SQL*Plus.

Close all open windows.

Restoring Datafiles to New LocationsMany times when media failure occurs, the original location where a datafile waslocated is no longer available, such as when a disk fails. Under these circum-stances, you must restore the datafile to a new location. Once the file is restored,you would rename the file within Oracle using the ALTER DATABASERENAME FILE command. The command does not actually rename the file, butrather changes Oracle’s internal pointer to the file so Oracle can find it in its newlocation. The following example illustrates the use of this command to changeOracle’s pointer to the INDX01.DBF datafile.

ALTER DATABASE RENAME FILE'F:\oracle\oradata\ora92\indx01.dbf'TO'G:\oracle\oradata\ora92\indx01.dbf';

In this example, the F disk has failed and is no longer available. Because of this,the INDX01.DBF datafile was restored to the G disk. The ALTER DATABASERENAME FILE command is used to change Oracle’s pointer to this newlocation. Once the file is restored, you can perform recovery as normal, thenbring the recovery target online.

Renaming a Datafile inOracle

Lesson 3: User-managed Backup and Recovery 171

Page 187: Oracle 9i DBA Fund - II

Recovering a Datafile Without a BackupOne of the most difficult tasks a DBA can face is recovering a lost datafile thathas not yet been backed up. It could be that a datafile was recently added to atablespace, but the DBA had not yet had a chance to back up the datafile or for-got to add the datafile to the backup routine. Under most circumstances, a mediafailure would be disastrous and would almost certainly require the tablespace tobe dropped and re-created, which guarantees the loss of data. However, it is pos-sible to recover a lost datafile without a valid backup if all three of the followingconditions exist:

• The database is running in ARCHIVELOG mode.

• All archive logs that have been generated since the datafile was created areavailable.

• A valid control file is available, meaning the current control file or a validbackup control file that was created after the datafile was added to thedatabase.

To perform this recovery, you must first bring the affected tablespace offline withthe IMMEDIATE option. If you do not include this option, Oracle will attempt toperform a checkpoint as the tablespace goes offline, but will fail since a datafileis missing. The following example shows the use of the IMMEDIATE option withthe ALTER TABLESPACE command.

ALTER TABLESPACE indx OFFLINE IMMEDIATE;

Once the tablespace is offline, you will create a new, empty datafile to take theplace of the missing datafile. You will then apply to the new datafile all of thearchive logs that have been generated by the database since the original datafilewas created. To create the empty datafile, you would use the ALTERDATABASE CREATE DATAFILE command, and specify both the original filename and the new file name, as shown in the following example.

ALTER DATABASE CREATE DATAFILE'D:\oracle\oradata\ora92\indx01.dbf'AS'F:\oracle\oradata\ora92\indx01.dbf';

In this example, the D disk has crashed, causing the loss of the INDX01.DBFdatafile, but there was no valid backup of the datafile. A new, empty datafile iscreated on the F disk, and Oracle automatically changes its pointer for theINDX01.DBF datafile to point to the new datafile. Essentially, this command hasjust restored the INDX01.DBF datafile, and datafile recovery can now begin usingnormal recovery commands. As Oracle recovers the datafile, all archive logs thathave been generated since the original datafile was created will be applied to thenew datafile to bring it up to date with the rest of the database.

Creating an Empty Datafile

172 Oracle9i Database: Fundamentals II

Page 188: Oracle 9i DBA Fund - II

TASK 3B-3Restore Datafiles to New Locations

Objective: To restore datafiles to new locations in the event that the origi-nal location is no longer available.

1. You will first simulate the loss of the disk where the EXAMPLE01.DBFdatafile is stored.

Launch SQL*Plus and log in as sys.

2. At the prompt, issue the following query:

SELECT file_nameFROM dba_data_filesWHERE tablespace_name='EXAMPLE';

The output will show that the EXAMPLE01.DBF datafile is currently storedin the D:\oracle\oradata\ora92 folder.

3. To shut down the database, type shutdown immediate and press Enter.

The output will show that the database has been closed and dismounted, andthe instance shut down.

4. Leaving the SQL*Plus window open, open a window to the D:\oracle\oradata\ora92 folder.

Delete the EXAMPLE01.DBF datafile from this folder.

5. Leaving the ora92 window open, switch back to the SQL*Plus window.

At the prompt, type startup and press Enter.

The output will show that the instance was started and the database opened,

Lesson 3: User-managed Backup and Recovery 173

Page 189: Oracle 9i DBA Fund - II

but the database could not be opened. This is because theEXAMPLE01.DBF datafile could not be found. Your database just sufferedthe loss of a disk that contained one of its datafiles.

6. The original disk with the EXAMPLE01.DBF datafile was lost, therefore,you must restore the datafile to a new location. Since it is assumed that yoursystem has only a single disk, you will simulate restoring the datafile by cre-ating a new folder on the D drive.

Switch back to the ora92 folder.

In the oradata folder, create a new folder called new_loc

7. In the D:\oracle\hot_bup folder, copy the EXAMPLE01.DBF backupdatafile to the D:\oracle\oradata\new_loc folder.

Once the file is copied, close the new_loc window.

8. Before recovering the database, you must change Oracle’s internal pointer tothe EXAMPLE01.DBF datafile. This is done with the ALTER DATABASERENAME FILE command.

At the SQL*Plus prompt, issue the following command:

ALTER DATABASE RENAME FILE'D:\ORACLE\ORADATA\ORA92\EXAMPLE01.DBF'TO'D:\ORACLE\ORADATA\NEW_LOC\EXAMPLE01.DBF';

174 Oracle9i Database: Fundamentals II

Page 190: Oracle 9i DBA Fund - II

Oracle will display the message “Database altered.”

9. You will now recover the database using the redo information stored in thearchived redo logs.

At the prompt, type RECOVER DATABASE and press Enter.

Oracle detects that the changes needed to recover this datafile have beenarchived already, and prompts you for the name and path of the requiredarchive log.

To accept the suggested archive log, press Enter. If Oracle prompts foradditional logs, keep pressing Enter to accept the suggested logs. Aftereach log, Oracle will display the message “Log applied.”

Once all archived changes have been applied to the database, Oracle willdisplay the message “Media recovery complete.”

10. To open the database, type ALTER DATABASE OPEN; and press Enter.

Oracle will display the message “Database altered.”

11. To verify location of the EXAMPLE01.DBF datafile, issue the followingquery again:

SELECT file_nameFROM dba_data_filesWHERE tablespace_name='EXAMPLE';

The output will show that the EXAMPLE01.DBF datafile is now stored inthe D:\oracle\oradata\new_loc folder, instead of the D:\oracle\oradata\ora92folder. You have successfully restored a datafile to a new location and recov-

Lesson 3: User-managed Backup and Recovery 175

Page 191: Oracle 9i DBA Fund - II

ered the database after the loss of a disk.

12. Exit from SQL*Plus.

Topic 3CUser-managed Incomplete RecoveryWhen an incomplete recovery is performed, the database is recovered to a pointin time prior to the point of failure. This is done by not applying all redo infor-mation to the database, from either the archive logs or the current online redolog. An incomplete recovery may be required, and in some cases desired, in cer-tain situations, which include:

• Loss of all copies of the current control file.

• Loss of current redo log group.

• A gap in the archive log sequence during normal recovery.

• Intentional point-in-time recovery.

As you learned earlier, the SCN recorded in the control file is considered themost current SCN for the database and is used as a reference point during data-base recovery. If the headers of any datafiles contain SCNs that are lower thanthat of the control file, then Oracle determines that those files require recovery.During recovery, the SCNs in the target datafiles are incremented as changes fromthe redo or archive logs are applied. Only when the SCNs in the target datafilesmatch the SCN in the control file will Oracle consider the datafiles recovered.Losing the current control file means that you have lost that reference point, andOracle will not know when the datafiles are completely recovered. In this case,you must apply all available redo information to the datafiles, but since Oraclehas no idea when to stop recovering the datafiles, Oracle will never know whenthe recovery is done. Such an operation is considered an incomplete recovery.

Another situation in which you may need to perform an incomplete recovery islosing part or all of the redo stream. If media failure causes the loss of the cur-rent online redo log group, the LGWR will not be able to write the redo logbuffer out to that redo log group, and will summarily terminate the instance.Upon restarting the instance, instance recovery will begin, and Oracle willattempt to begin the roll forward phase of recovery using the redo informationfrom the current redo log group. Since that group is no longer there, any changesit may have contained, committed or uncommitted, will be lost. You must termi-nate the recovery and open the database without applying those missing changes.

Incomplete RecoveryScenarios

176 Oracle9i Database: Fundamentals II

Page 192: Oracle 9i DBA Fund - II

In addition to losing the current redo log group, a missing archive log couldresult in a situation where an incomplete recovery is required just to get the data-base open and running again. If media failure causes the loss of any part of thedatabase, such as a datafile, you would restore the datafile from backup as nor-mal, then start applying the archived redo logs to recover the datafile. However, ifan archive log is missing, you will not be able to move on to the next one in thesequence. The recovery must halt, and any changes contained in the missingarchive log, and all archive logs that were generated after the missing log, couldnot be applied and would be lost.

An incomplete recovery may be necessary or desired if you wish to intentionallybring the contents of the database back to a certain point in time. It could be thata user accidentally deleted or truncated all the rows in a large table, and youwant to recover this table without having to manually reload its contents. It couldalso be that you wish to undo a large number of changes that occurred to thedatabase, such as in a development environment, where you want to keep a singleversion of the database as a test case for a project. In this case, you would restoreall the datafiles from a hot backup, then recover the database by applying thearchive logs as normal, but stop when the database has reached the targeted pointin time. In such a scenario, it’s important to remember that you cannot recoveronly part of the database, such as a single datafile or tablespace, to a differentpoint in time than the rest of the database. You must bring the entire databaseback to the same point in time by restoring all of its datafiles from backup, thenrolling forward.

Incomplete Recovery CommandsDuring a user-managed incomplete recovery, you can perform cancel-based, time-based, or change-based recovery. This is done by including the UNTIL clausewith the RECOVER command, which tells Oracle when to stop applying redoinformation to the database. The following syntax shows the RECOVER commandwith the UNTIL clause.

RECOVER DATABASE UNTIL {CANCEL | TIME date | CHANGE n}

In this syntax, CANCEL indicates that you want Oracle to continually applyarchive logs until you issue the CANCEL command. Prior to applying an archivelog to the database, Oracle will prompt you for the name and location of therequired archive log, along with a suggested name and location. At this point, youhave the option of accepting the suggestion, supplying a different name and loca-tion for the log, or issuing the CANCEL command. Upon issuing the CANCELcommand, Oracle will stop applying the archive logs and terminate recovery. Thefollowing example shows a RECOVER command for cancel-based recovery:

RECOVER DATABASE UNTIL CANCEL;

The TIME option allows you to specify a specific date and time to recover thedatabase to. The date and time you specify must be a point in time after the data-base backup set was generated, but before the current time. In other words, if thelast database backup completed today at 4:15 A.M., and the time is currently 3:00P.M., then the only valid date and time you could specify would be between 4:15A.M. and 3:00 P.M. today. When specifying the TIME option, Oracle will applyall redo information from the archive logs necessary to recover the database tothe point in time specified. After the recovery is finished and the database is

Incomplete RecoveryCommands

Lesson 3: User-managed Backup and Recovery 177

Page 193: Oracle 9i DBA Fund - II

opened, its contents will look exactly as it did at the time you specified in theRECOVER command. All changes to the database that occurred after your speci-fied time will be lost. When specifying the date and time for time-based recovery,you must use the following date format, regardless of the default date format foryour database:

'YYYY-MM-DD:HH24:MI:SS'

The following example shows a RECOVER command for time-based recovery:

RECOVER DATABASE UNTIL TIME '2003-05-04:13:25:00';

Change-based recovery is the most precise type of incomplete recovery that youcan perform. For change-based recovery, you would specify the exact SCN thatyou wish to stop the recovery at. Oracle will recover the database to the SCN justprior to, but not including, the SCN specified in the RECOVER command. Forexample, if the SCN specified in the RECOVER command is 43987, then the data-base will be recovered to the SCN 43986. The SCN specified must be higher thanthe highest SCN shown in your backup datafiles and, of course, must also belower than the highest SCN ever generated by your database, because Oracle can-not restore the database up to a change that has not happened yet. The followingexample shows a RECOVER command for change-based recovery:

RECOVER THE DATABASE UNTIL CHANGE 43987;

Repercussions of Incomplete RecoveryPrior to attempting an incomplete recovery, either intentionally or as a result of afailure, it is important to understand the repercussions of performing such arecovery. As stated earlier, an incomplete recovery results in the loss of changesto the database. However, the pitfalls do not end there.

After performing an incomplete recovery, the control file must be updated withthe new current SCN for the database. All changes that had occurred after thisnew current SCN must be invalidated so they can never be applied to thedatabase. In order to ensure both of these things happen, you must open the data-base using the RESETLOGS option after an incomplete recovery. Doing so willupdate the control file with the new SCN, and will set the log sequence numbersfor the redo log groups back at 1. The following example shows the command toopen the database and reset the logs after an incomplete recovery:

ALTER DATABASE OPEN RESETLOGS;

The RESETLOGS option can only be used after an incomplete recovery, specifi-cally with RECOVER command that includes the UNTIL clause. If you attempt toopen the database with this option after a complete recovery, Oracle will returnan error.

When opening the database with the RESETLOGS option, you have essentiallycreated a new incarnation of the database. This new incarnation is a completelydifferent version of the database from its original version prior to the recovery.While it may contain mostly the same data, you have basically caused the data-base to shift to a new timeline in its life. Figure 3-3 illustrates this concept.

incarnation:A new version of a databasecreated when the database isopened with the RESETLOGS

option.

RESETLOGS Creates a NewDatabase Incarnation

178 Oracle9i Database: Fundamentals II

Page 194: Oracle 9i DBA Fund - II

Figure 3-3: RESETLOGS creates a new database incarnation.

In the timeline at the top half of this figure, the database has been operating nor-mally, and a hot backup was performed when the current log sequence numberwas 3000. The database continued to operate normally until media failure causedthe database to crash at log sequence 4500. The timeline in the bottom half of thefigure shows the steps that were taken to get the database up and running again.

The DBA restored the database from the hot backup, which means the databaselooked the way it did at log sequence 3000, and then performed a recovery of thedatabase using the RECOVER command. However, during the recovery, the DBArealized that there was a gap in the archive logs. Since essential redo informationwas missing, the recovery could not proceed to the next archive log. The DBAperformed an incomplete recovery and was forced to open the database using theRESETLOGS option. Upon opening the database with RESETLOGS, the controlfile was updated with the new SCN and the log sequence number was reset backto 1. Because the database is now a new incarnation of its old self, the archivelogs generated between the missing log and log sequence 4500 are now useless.These logs can never be applied to the new incarnation of the database. Addition-ally, all backups of the database created prior to the log reset are also useless.Because of this, it is essential that you immediately create a new full backup afteropening the database with the RESETLOGS option. If you do not, and anothermedia failure occurs, you are almost guaranteed to lose all changes to the data-base that had occurred after the log reset, and you will be right back to squareone.

Lesson 3: User-managed Backup and Recovery 179

Page 195: Oracle 9i DBA Fund - II

TASK 3C-1Describe Incomplete Recovery Concepts

1. Which of the following failures would require an incomplete recovery?Choose all that apply.

✓ a. Loss of all copies of the current control file.

b. Loss of the Oracle executable.

c. Loss of the SYSTEM datafile.

✓ d. Loss of the current redo log group.

2. What are the three types of user-managed incomplete recovery that canbe performed for an Oracle9i database?

✓ a. Cancel-based

✓ b. Change-based

c. Commit-based

✓ d. Time-based

3. Why should you immediately perform a full back up of the databaseafter opening the database using the RESETLOGS option?

Upon opening the database using the RESETLOGS option, you have essen-tially created a new incarnation of the database. Any backups that weregenerated before the point in time when the RESETLOGS option was issuedcannot be used to recover the current incarnation of the database. To beable to perform a complete recovery of the database in its current incarna-tion, you should ensure that you have a full backup of the database that wasgenerated after the RESETLOGS option was issued.

4. Define the word incarnation in terms of the Oracle database.

When opening the database with the RESETLOGS option, you have createda new incarnation of the database. This new incarnation is a completely dif-ferent version of the database from its original version prior to the recovery.This causes the database to shift to a new timeline in its life. All backupsand archive logs from the old incarnation that were generated after the pointin time when the RESETLOGS option was issued will be invalidated andcannot be used to restore or recover the new incarnation of the database.

Loss of Control FileIf media failure causes the loss of all copies of the current control file, theinstance will immediately crash. However, the database can be recovered using abackup copy of the file or a newly created control file using the script stored in acontrol file backup trace file. Either one will require an incomplete recovery anda RESETLOGS to get the database open again.

180 Oracle9i Database: Fundamentals II

Page 196: Oracle 9i DBA Fund - II

To recover using a backup control file, you would simply restore the backup fileto all locations indicated by the CONTROL_FILES initialization parameter. Sinceall copies of the current control file are identical, you can use a single backupcopy to restore all the original copies. If the original locations of the control filesare unavailable, such as when a disk completely fails, you can simply restore thebackup control file to new locations and change the assigned value for theCONTROL_FILES parameter to point to the new locations.

Once all copies of the control files are restored, you would bring the database upto the mount state, then initiate an incomplete recovery. The backup control filewill not have the most current SCN for the database, so you must specify in theRECOVER command that you are performing the recovery using a backup controlfile to instruct Oracle to ignore the SCN listed in the newly-restored control files.Additionally, since Oracle will not know when to stop applying redo informationto the database, you must also indicate the stopping point for recovery yourselfusing cancel-based, time-based, or change-based recovery. To apply all availablechanges to the database, it is recommended that you use cancel-based recovery.This will ensure that Oracle will attempt to continue recovering the databaseindefinitely. Once Oracle runs out of changes to apply, meaning there are no morearchive logs or redo logs that have changes the database needs, Oracle will stopthe recovery with an error. The following command illustrates the use of theRECOVER command to perform cancel-based recovery with a backup control file.

RECOVER DATABASE USING BACKUP CONTROLFILE UNTIL CANCEL;

During the roll forward phase of recovery, Oracle will prompt for the necessaryarchive logs to recover the database. Once Oracle prompts for an archive log thathas not yet been generated, you would cancel the recovery using the CANCELcommand, and Oracle will display the message “Media recovery cancelled.” Youcan then open the database using the RESETLOGS option.

Occasionally, when Oracle prompts for an archive log that has not yet been gen-erated, and you issue the CANCEL command, Oracle may return the followingerror:

ORA-01547: warning: RECOVER succeeded but OPEN RESETLOGS wouldget error belowORA-01152: file 1 was not restored from a sufficiently old backupORA-01110: data file 1: 'D:\ORACLE\ORADATA\ORA92\SYSTEM01.DBF'

While this error may initially be somewhat confusing, it simply means thatOracle believes there are more changes that can be applied to the database, eventhough you have applied all available archive logs. It is possible that the currentonline redo log contains the missing changes, but Oracle did not have a chance toarchive this log prior to the media failure that caused the instance to crash. If youget this error after stopping the recovery, you can simply start the recovery again,and specify the current online redo log instead of an archive log. Oracle will readthe log and apply any changes it contains to the database. If you do not knowwhich log group was current when the database crashed, you could initiate recov-ery, and then specify the first log group. If Oracle returns an error stating that itcould not find the changes it needed, you would simply initiate recovery againand specify the second log group. You would repeat this process until Oraclefound the changes it needed to recover the database.

Cancel-based RecoveryWith Backup Control File

Lesson 3: User-managed Backup and Recovery 181

Page 197: Oracle 9i DBA Fund - II

Once the database has been recovered using all available redo information, youwould open the database with the RESETLOGS option. You must remember thatthis creates a new incarnation of the database, which invalidates all previous data-base backups. It is recommended that you perform a full database backup,including the control files, immediately after opening the database with theRESETLOGS option.

To recover the database using a control file backup trace file, you would performall of the steps as using a standard backup control file, but with some additionalsteps. The control file backup trace file contains the CREATE CONTROLFILEcommand that can be used to manually re-create the control file in the event thatall copies of the control file are lost. First, you would need to edit the trace file toremove any unnecessary comments, and possibly tailor the CREATECONTROLFILE command to suit your needs. Then you would start up thedatabase in the nomount state, which is required when manually creating the con-trol file. You would then execute the CREATE CONTROLFILE command in thetrace file, which can be done by executing the edited trace file like a normal SQLscript, as shown in the following example.

SQL> startup nomount;ORACLE instance started.

Total System Global Area 135338868 bytesFixed Size 453492 bytesVariable Size 109051904 bytesDatabase Buffers 25165824 bytesRedo Buffers 667648 bytesSQL>SQL> @D:\oracle\hot_bup\control.trc

When executing the CREATE CONTROLFILE command, Oracle will automati-cally re-create a copy of the control file in each location specified by theCONTROL_FILES initialization parameter. If a location specified by this param-eter cannot be reached, such as a disk not being available, Oracle will return anerror and no control file will be created. Once the control files have beenre-created, you can initiate incomplete recovery using the same process that isused with a standard backup control file copy.

TASK 3C-2Recovering After Loss of Control File

Objective: To recover the database after a complete loss of all copies ofthe current control file.

Note: The control file is critical to the operation of the Oracle database. Useextreme caution and follow the directions in this activity very carefully. Failure todo so may result in the complete loss or corruption of the current control filesand/or the backup control file, which may render your database useless. It is rec-ommended that you read through the entire activity first before actually beginningthe activity on a live database.

1. You will first simulate the loss of all copies of the current control file.

Launch SQL*Plus and log in as sys.

182 Oracle9i Database: Fundamentals II

Page 198: Oracle 9i DBA Fund - II

2. Force a log switch by issuing the following command:

ALTER SYSTEM SWITCH LOGFILE;

Oracle will display the message “System altered.”

3. Create a new backup copy of the current control file by issuing the fol-lowing command:

ALTER DATABASE BACKUP CONTROLFILE TO'D:\oracle\hot_bup\control.bak' REUSE;

Oracle will display the message “Database altered.”

4. To shut down the database, type shutdown immediate; and press Enter.

5. After the database is shut down, leave SQL*Plus open, and choose Start→Run. In the Run text box, type D:\oracle\oradata\ora92 and click OK. Awindow for the D:\oracle\oradata\ora92 folder will appear.

Delete all three control files from the folder. The files are namedCONTROL01.CTL, CONTROL02.CTL, and CONTROL03.CTL. Be carefulnot to delete any other files in this folder.

6. Switch back to the SQL*Plus window.

At the prompt, type startup and press Enter.

The instance will start, but the database will not mount, and Oracle will dis-play the message “ORA-00205: error in identifying controlfile, check alertlog for more info.”

Lesson 3: User-managed Backup and Recovery 183

Page 199: Oracle 9i DBA Fund - II

7. Leaving the SQL*Plus window open, open a window to the D:\oracle\admin\ora92\bdump folder from the Run text box.

Open the alert_ora92.log file, and scroll to the very bottom. The alert logwill show that the CONTROL01.CTL control file could not be found.

When you are done looking at the alert log, close Notepad and the windowfor the bdump folder.

8. You will now use your backup control file to restore all three of the currentcontrol files.

Open a window to the D:\oracle\hot_bup folder from the Run text box.

Copy the CONTROL.BAK file into the D:\oracle\oradata\ora92 folder.

Rename the CONTROL.BAK file to CONTROL01.CTL

Copy the CONTROL.BAK file into the D:\oracle\oradata\ora92 foldertwo more times. Rename the new copies to CONTROL02.CTL andCONTROL03.CTL respectively.

Once you have restored all three of your control files, the ora92 folder

184 Oracle9i Database: Fundamentals II

Page 200: Oracle 9i DBA Fund - II

should look similar to what is shown here. Close the ora92 window.

9. You will now mount the database and perform an incomplete databaserecovery.

At the prompt, type ALTER DATABASE MOUNT; and press Enter.

After a moment, Oracle will display the message “Database altered.”

10. To begin recovery, issue the following command:

RECOVER DATABASE USING BACKUP CONTROLFILE UNTIL CANCEL;

Oracle will determine the SCN that is required for recovery, and will ask forthe archive log that contains that change.

11. Press Enter to accept the suggested archive log.

One of two possibilities may occur. Oracle will either find the suggestedarchive log, apply it to the database, and ask for another log, or it will dis-play a message stating that the specified archive log could not be found. Ifthe specified archive log is found and applied, press Enter again to applythe next archive log. Keep pressing Enter repeatedly until Oracle dis-

Lesson 3: User-managed Backup and Recovery 185

Page 201: Oracle 9i DBA Fund - II

plays the message that the archive log could not be found.

12. After failing to find the last archive log, Oracle may also display the follow-ing messages:

ORA-01547: warning: RECOVER succeeded but OPEN RESETLOGSwould get error belowORA-01152: file 1 was not restored from a sufficiently oldbackupORA-01110: data file 1: 'D:\ORACLE\ORADATA\ORA92\SYSTEM01.DBF'

If these messages are not displayed, then skip the remainder of this stepand go to step 13 to continue.

The ORA-01547 and ORA-01152 errors occur because the very last changesthat need to be applied to the database are still in the current redo log andhave not yet been archived. You will begin the recovery again, and you willspecify the online redo log for recovery instead of an archive log.

At the prompt, issue the following command:

RECOVER DATABASE USING BACKUP CONTROLFILE UNTIL CANCEL;

186 Oracle9i Database: Fundamentals II

Page 202: Oracle 9i DBA Fund - II

Again, Oracle will detect the SCN required for recovery and suggest anarchive log.

Instead of pressing Enter to accept the suggested archive log, typeD:\oracle\oradata\ora92\redo01.log and press Enter.

If Oracle states that it needs changes generated later than what is containedin REDO01.LOG, then issue the RECOVER DATABASE USINGBACKUP CONTROLFILE UNTIL CANCEL; command again. This time,specify D:\oracle\oradata\ora92\redo02.log as the archive log to apply. Ifnecessary, repeat the process again for the D:\oracle\oradata\ora92\redo03.log.

Once all the required changes have been applied to the database, Oracle willdisplay the messages “Log applied” and “Media recovery complete.”

Lesson 3: User-managed Backup and Recovery 187

Page 203: Oracle 9i DBA Fund - II

13. The database has been recovered, so you can now open the database. Butsince you performed an incomplete recovery, you must open the databasewith the RESETLOGS option.

At the prompt, type ALTER DATABASE OPEN RESETLOGS; and pressEnter.

After a few moments, Oracle will display the message “Database altered.”You have just recovered from a complete loss of all copies of the currentcontrol file.

14. To see the current log sequence number, type ARCHIVE LOG LIST; andpress Enter.

The output will show that the current log sequence number has been reset to1. Also, the oldest online log sequence has been set to 1, which means thatall archive log history has been removed from the control file.

15. Since you now have a new incarnation of the database, the previous controlfile backup is useless. You should immediately back up the control file incase there is another failure in the near future.

At the prompt, issue the following command:

ALTER DATABASE BACKUP CONTROLFILE TO'D:\oracle\hot_bup\control.bak' REUSE;

Oracle will display the message “Database altered.”

16. Exit from SQL*Plus.

Close all open windows.

Your system may show thatthe oldest online log

sequence number has beenset to 0, instead of 1.

188 Oracle9i Database: Fundamentals II

Page 204: Oracle 9i DBA Fund - II

Loss of the Current Online Log GroupLosing a redo log group as a result of media failure can have different affects onthe database, depending on which group was lost. If a non-active redo log groupwas lost, meaning a log group that has already been archived, there will be noimmediate affect on the database, and there will probably be no loss of data. Thelog writer process will continue to write redo information from the log buffer tothe current log group without a problem. However, once the current log groupfills and Oracle attempts to switch the logs, if the next log group in the sequencecannot be found, the instance will crash.

If media failure results in the loss of the current redo log group, the instance willcrash immediately. Although the changes written to the current log group mayhave been committed, Oracle will not have had the chance to archive thosechanges. All changes stored in the current log group will be permanently lostwith no hope of recovery. Your only recourse is to perform a point in time recov-ery of the database to bring the entire database back in time to the moment justbefore any of those lost changes were actually generated. Figure 3-4 illustratesthis concept.

Figure 3-4: Recovery after loss of the current redo log group.

In the top part of this figure, the database has been operating normally, perform-ing log switches and archiving the logs as usual. Then, a media failure occurredcausing the loss of the current redo log group, which happened to be logsequence 25. The instance crashed and all changes in this log group were perma-nently lost.

The bottom part of Figure 3-4 shows the steps that were taken to recover thedatabase. The last full hot backup was restored, and the archive logs were appliedto recover the datafiles. However, the database can only be recovered to the pointin time just prior to log sequence 25 becoming the current log group, whichmeans you can only recover up to and including log sequence 24.

Recovery After Loss ofCurrent Redo Log Group

Lesson 3: User-managed Backup and Recovery 189

Page 205: Oracle 9i DBA Fund - II

For loss of the current redo log group, it is recommended that you performcancel-based recovery to ensure that all available redo information is applied tothe database. Once all available redo information has been applied, you mustopen the database with the RESETLOGS option. When the RESETLOGS com-mand is issued, Oracle will reset the log sequence number to 1, and automaticallyre-create any missing archive logs in the correct location using the informationfound in the control file. This will ensure that the new incarnation of the databasecan remain up and running.

TASK 3C-3Recover From the Loss of the Current Online Log Group

Objective: To recover the database from the loss of the current onlineredo log group.

1. To recover the database from the loss of the current online redo log group,you must have a full hot backup of the database available. You will createthis backup now.

Launch SQL*Plus and log in as sys.

2. At the prompt, type @C:\079176\hot_backup_database.sql and press Enter.This will launch a script that will perform a hot backup of all tablespaces,and store the datafile copies in the D:\oracle\hot_bup folder. A blank com-mand prompt window will appear as the datafiles are copied to thedestination folder.

It will take several minutes for the hot backup to complete. Once it’s com-plete, the command prompt window will disappear, you will be returned tothe SQL*Plus prompt, and Oracle will display the message “Backupcomplete.”

190 Oracle9i Database: Fundamentals II

Page 206: Oracle 9i DBA Fund - II

3. To demonstrate the affect of losing the current online redo log, you will cre-ate a table with a single row, force a log switch, then add another row to thetable. You will then simulate the loss of the current redo log group. Allchanges that occurred before the log switch can be recovered, but allchanges stored in the current group will be lost.

To determine which redo log group is the current group, type @C:\079176\logfiles.sql and press Enter.

The STATUS column in the output will show which log group is the currentgroup. Additionally, the SEQ# column will show the log sequence number ofeach group. The sequence number increments infinitely, and is used to iden-tify the log file once it is archived. In the example shown here, the currentlog group is log group 2, with a log sequence number of 2.

4. You will now create a small table.

At the prompt, issue the following command:

CREATE TABLE test_log_fail (col1 VARCHAR2(5));

Oracle will display the message “Table created.”

Insert a row into the table with the following statements:

INSERT INTO test_log_fail VALUES('A');COMMIT;

Oracle will display the messages “1 row created” and “Commit complete.”The redo information generated from the CREATE TABLE and INSERTstatements was first stored in redo log buffer, then written to the current redolog group.

5. You will now force a log switch. The current online redo log will bearchived, and Oracle will switch to the next log group.

The log sequence numbershown in your output may bedifferent from what is shownhere.

Lesson 3: User-managed Backup and Recovery 191

Page 207: Oracle 9i DBA Fund - II

At the prompt, type ALTER SYSTEM SWITCH LOGFILE; and pressEnter.

Oracle will display the message “System altered.”

To see which log group is now current, type @C:\079176\logfiles.sql andpress Enter.

The output will show that Oracle has switched to the next redo log group.The redo log that contains the CREATE TABLE command and INSERTstatement has been archived. In this example, log group 3 is now the currentlog group, which also has a log sequence number of 3. Log group 2 hasbeen archived.

6. You will now insert another row into the table.

At the prompt, issue the following statements:

INSERT INTO test_log_fail VALUES('B');COMMIT;

Oracle will display the messages “1 row created” and “Commit complete.”

7. At the prompt, type @C:\079176\logfiles.sql and press Enter.

The redo information for the CREATE TABLE command and the firstINSERT statement is stored in log group 2, which has been archived. Theredo information for the last row inserted was stored in the current onlinelog group, which is now log group 3. Losing the current online log groupwill mean that all changes stored in that log group are permanently lost.However, all changes in the previous group can be recovered from thearchive log.

Make a note of which log group is current, along with its log sequencenumber from SEQ# column.The group number of the

current log group may bedifferent from the log

sequence number. This isnormal.

192 Oracle9i Database: Fundamentals II

Page 208: Oracle 9i DBA Fund - II

8. You will now simulate the loss of the current online redo log group.

At the prompt, type shutdown abort and press Enter.

Oracle will display the message “ORACLE instance shut down.”

9. Leaving SQL*Plus open, open a window to the D:\oracle\oradata\ora92folder from the Run text box.

In the ora92 folder, find the redo log file of the current online redo loggroup. In the used example here, the file would be REDO03.LOG. SelectREDO03.LOG.

Choose File→Rename. Change the .LOG extension to .OLD

A question box will appear asking if you are sure you want to change thefile extension. Click Yes.

10. Leaving the ora92 folder open, switch back to the SQL*Plus window.

At the prompt, type startup and press Enter.

The output will show that the instance was started and the databasemounted, but the database could not be opened because Oracle could notfind the current online redo log group.

Lesson 3: User-managed Backup and Recovery 193

Page 209: Oracle 9i DBA Fund - II

11. To recover from this type of loss, you must restore all datafiles from backupand perform an incomplete recovery up to the last archive log that wasgenerated. All changes stored in the current log group will be lost.

To perform a full restore of all datafiles, type @C:\079176\restore_database.sql and press Enter.

A blank command prompt will appear while the backed up datafiles are cop-ied to their original locations. The restore will take a few minutes tocomplete.

Once the restore is complete, the command prompt will disappear, andOracle will display the message “Database restored.”

12. You will now perform the incomplete recovery of the database. At theprompt, issue the following command:

RECOVER DATABASE UNTIL CANCEL;

Oracle will detect which archive log contains the changes needed forrecovery. You will apply all archive logs up to, but not including, the logsequence number of the current log group, which you should have madenote of in step 7 from the SEQ# column of the logfiles.sql output. In theexample used here, the current log sequence number was 3.

Press Enter to accept the suggested archive logs until Oracle asks for thelog sequence number of the current log group. Do not press Enter forthe current log group. Instead, type CANCEL and press Enter.

Oracle will display the message “Media recovery cancelled.”

194 Oracle9i Database: Fundamentals II

Page 210: Oracle 9i DBA Fund - II

13. The database has been recovered to include all available changes. The cur-rent online redo log group is no longer available, therefore its changes willbe lost.

At the prompt, type ALTER DATABASE OPEN RESETLOGS; and pressEnter.

After several moments, Oracle will display the message “Database altered.”

14. To see which changes were recovered and which were lost, you will nowquery from the TEST_LOG_FAIL table.

At the prompt, type SELECT * FROM test_log_fail; and press Enter.

The output will show that only the first row, containing the value A, wasrecovered. The second row, containing the value B, which was only stored inthe current online redo log group, was lost.

15. Exit from SQL*Plus.

16. In the ora92 folder, you will see your original redo log file that you renamedwith the .OLD extension. However, you will also see that Oracle automati-cally created a new file for the current online redo log when the ALTERDATABASE OPEN RESETLOGS command was issued.

Close the ora92 window.

Lesson 3: User-managed Backup and Recovery 195

Page 211: Oracle 9i DBA Fund - II

Read-only TablespacesThere are some special considerations that you must take into account whenrecovering a database that contains read-only tablespaces. Depending on the cir-cumstances involved with the recovery, you may need to perform some extrasteps in order to recover after media failure. The recovery steps will be deter-mined by whether you are recovering the database using the current control fileor a backup control file.

When you are using the current control file for recovery, recovering a databasethat contains read-only tablespaces is identical to performing any standard data-base recovery after media failure. You would simply take the following steps:

1. Restore only the lost datafiles from backup.

2. Mount the database.

3. Recover the database.

4. Open the database.

As long as you are using the current control file as the reference point, thissimple recovery can be done for any tablespaces in the database, regardless ofwhether the tablespace is in read-write or in read-only. It can even be done if atablespace changed from read-write to read-only, or vice versa, after the lastbackup was performed. The current control file will know which tablespaces arein read-only and when they were set to read-only. The recovery process willhandle applying all redo information to the appropriate datafiles. If the status of atablespace had changed since the last backup, such as a read-only tablespacebeing set to read-write, Oracle will know to apply the pertinent redo informationto the tablespace at the right point in time during recovery.

Things become increasingly more difficult if you must recover the database usinga backup control file. Chances are, if you have to restore your control file frombackup, the entire database is down and will need recovery after you haverestored the control file. The steps you take to perform the recovery will dependon whether the status of the tablespaces in question have changed since the lastbackup (from read-only to read write, and so on), and what the backup controlfile knows about the tablespaces that need the recovery.

If a tablespace was in read-only at the time the last backup was taken, and thetablespace was still in read-only at the point of failure, and you are recoveringwith a backup control file, then you only have one additional step to take to per-form a recovery of the database. The steps you would take are as follows:

1. Restore all datafiles and the control file from backup.

2. Mount the database.

3. Take all read-only datafiles offline.

4. Perform cancel-based, time-based, or change-based incomplete recovery withthe USING BACKUP CONTROLFILE clause.

5. Open the database using the RESETLOGS option.

In this case, you are including the USING BACKUP CONTROLFILE, UNTIL,and RESETLOGS options only because you are recovering the database with abackup control file. However, the main difference between this recovery and arecovery using the current control file is that you must take the datafiles from anyread-only tablespaces offline during the recovery. This is because the

Read-only TablespaceRecovery With Current

Control File

196 Oracle9i Database: Fundamentals II

Page 212: Oracle 9i DBA Fund - II

RESETLOGS option causes Oracle to update the headers of all datafiles whileopening the database. If a read-only tablespace is left online, the ALTERDATABASE OPEN RESETLOGS command will fail since Oracle cannot write tothe read-only datafiles. Once the database has been opened, you can then bringthe read-only tablespaces online.

If the status of a tablespace had changed after its last backup but before themedia failure, and you are recovering with a backup control file, then the recov-ery process will be slightly different. If the tablespace was in read-write modeduring the last backup, but had changed to read-only mode prior to the mediafailure, then you would follow these steps to recover the database:

1. Restore all datafiles and control file from backup.

2. Mount the database.

3. Perform cancel-based, time-based, or change-based incomplete recovery withthe USING BACKUP CONTROLFILE clause.

4. Open the database using the RESETLOGS option.

In this case, both the control file and the tablespace in question were backed upwhile the tablespace was still in read-write mode. This means that after restoringthe backup control file, Oracle will read the newly-restored control file andbelieve that the tablespace is currently in read-write mode. Although thistablespace was in read-only at the point of failure, you should leave thistablespace online so Oracle can apply its changes for the period of time while thetablespace was in read-write mode. During the roll forward phase of recovery,Oracle will apply all pertinent redo information to the tablespace up to the pointin time that the tablespace was put in read-only. After this point in time, therewill be no more redo information that needs to be applied to that tablespacebecause no changes in the tablespace could have occurred. However, Oracle willnot set the tablespace back to read-only until after the database is opened with theRESETLOGS option.

In the final scenario, the tablespace was in read-only mode at the time of thedatabase backup, but was set to read-write mode prior to the point of failure, andyou are recovering the database using the backup control file. In this case, thebackup control file only knows that the tablespace was in read-only. Once thecontrol file is restored and the database is mounted, Oracle will believe thetablespace is still in read-only and will not try to apply any redo informationfrom the archive logs to the tablespace. Therefore you should not use this backupcontrol file to recover the tablespace. You should only use a backup control filethat was created at a point in time after the tablespace was set to read-write. Thiswill allow Oracle to apply the pertinent redo information to recover thetablespace. To perform a recovery in this scenario, you would take the followingsteps:

1. Restore all datafiles from backup.

2. Restore the backup control file that was generated after the tablespace inquestion was set to read-write.

3. Mount the database.

4. Perform cancel-based, time-based, or change-based incomplete recovery withthe USING BACKUP CONTROLFILE clause.

5. Open the database using the RESETLOGS option.

Lesson 3: User-managed Backup and Recovery 197

Page 213: Oracle 9i DBA Fund - II

If you do not have a backup control file from after the tablespace was set to readonly, you will need to re-create the control file manually using the commandsfound in the control file backup trace file. In this case, you will need to edit thetrace file to indicate that the tablespace in question is currently in read-writemode. You would then take the following steps to perform the recovery:

1. Restore all datafiles from backup.

2. Start up the databases in the nomount state.

3. Execute the CREATE CONTROLFILE command found in the control filebackup trace file to re-create the control file.

4. Mount the database.

5. Perform cancel-based, time-based, or change-based incomplete recovery withthe USING BACKUP CONTROLFILE clause.

6. Open the database using the RESETLOGS option.

In this case, you are manually re-creating the control file, which gives you theopportunity to tell Oracle exactly what you want it to know about the tablespaces.By editing the trace file, you take out any information that would indicate that thetablespace in question is currently in read-only mode. This enables Oracle towrite to the tablespace so it can apply the necessary redo information to itsdatafiles. However, re-creating the control file should only be used as an absolutelast resort when recovering the database. You should take sufficient steps to pro-tect the control file against media failure by multiplexing it across multiple disks.You should also maintain the habit of backing up the control file every time thestructure of the database changes, such as adding tablespaces or datafiles, or whenthe status of a tablespace changes from read-write to read-only or vice versa.

TASK 3C-4Identify Recovery Considerations for Read-onlyTablespaces

1. The USERS tablespace was placed in read-only mode at 4:00 P.M. Thelast backup of the control file and the USERS datafiles occurred at 5:00P.M. A disk failure results in the loss of all the datafiles of the USERStablespace and all copies of the control file. How would you recoverfrom this failure?

Since the current control file is lost, you must use the backup control file forthis recovery. Since the control file was backed up after the tablespace wasplaced in read-only mode, the backup control file knows that the USERStablespace is in read-only mode. You only need to restore the backup controlfile and the USERS datafiles, take the USERS datafiles offline, and perform astandard database recovery, then open the database using the RESETLOGSoption. Once the database is open, you can bring the USERS tablespaceback online to make it available for use.

198 Oracle9i Database: Fundamentals II

Page 214: Oracle 9i DBA Fund - II

2. When performing a recovery of the database using a backup control file,why must all read-only datafiles first be taken offline?

Recovering the database using the backup control file consists of an incom-plete recovery, and will require opening the database with the RESETLOGSoption. When the RESETLOGS option is specified with the ALTERDATABASE OPEN command, Oracle will write updated information to theheaders of all datafiles. If any datafiles of read-only tablespaces are online,Oracle will also attempt to update the headers of these files, but the processwill fail, causing the ALTER DATABASE OPEN command to fail as well.Taking read-only datafiles offline will ensure that Oracle does not try towrite to the files, and the ALTER DATABASE OPEN command willsucceed.

3. Given the following scenario, which control file would you use to recoverthe EXAMPLE tablespace? Explain your answer.

• A full, hot backup was executed at 10:00 A.M. All tablespaces were inread-write mode at that time, with the exception of the EXAMPLEtablespace, which was in read-only mode.

• The hot backup included all datafiles, a standard backup of the controlfile, and a backup of the control file to trace.

• The EXAMPLE tablespace was placed in read-write mode at 1:00 P.M.

• The database suffered media failure at 3:00 P.M., which resulted in theloss of all copies of the current control file and all the datafiles of theEXAMPLE tablespace.

In this scenario, as in most recovery scenarios, the ideal solution is to usethe current control file, since it will contain the most current informationabout all datafiles in the database. However, since the current control file isnot available in this case, this is not an option.

The backup control file that was created at 10:00 A.M. only contains infor-mation about the datafiles as they existed at that point in time. Since theEXAMPLE tablespace was in read-only mode at the time the backup wastaken, the backup control file will reflect that information. If the backup con-trol file is used for recovery, the EXAMPLE tablespace will be treated as ifit’s still in read-only mode, and none of the transactions that occurred inthat tablespace after it was set to read-write mode will be recovered.

Since there is currently no control file, current or backup, that contains theinformation that the EXAMPLE tablespace was ever in read-write mode, theonly other option is to create a new control file by using the script stored inthe control file backup trace file generated at 10:00 A.M. The script can bemodified to reflect the existing configuration of the database and can be usedto create a new control file that will allow the full recovery of theEXAMPLE tablespace.

Lesson 3: User-managed Backup and Recovery 199

Page 215: Oracle 9i DBA Fund - II

Tablespace Point-in-Time RecoveryAs you learned earlier, you cannot recover just a single datafile or tablespace to adifferent point in time than the rest of the database. There may be some occa-sions, however, where you may want to do just that. You may need to bring asingle tablespace back to a certain point in time, say just before a user dropped acritical table, but you want to preserve the current changes in all othertablespaces.

This type of operation is not possible within a single database. You can performthis type of recovery by using a hot backup of the original database to create aclone database. This clone database is created by restoring the hot backup of theoriginal database to a different location, possibly on a different server, and per-forming a cancel-based, time-based, or change-based recovery. You have theoption of restoring the entire backup if you like. At a minimum, however, youmust restore the following files:

• All backup copies of the datafiles of the affected tablespace you wish torecover.

• All backup copies of the datafiles of the SYSTEM tablespace taken from thesame backup set as the affected tablespace datafiles previously listed.

• A parameter file.

• Some form of the control file from the original database (backup control fileor control file trace file).

• All archive logs generated that include the time the backup in question wasperformed until the point in time to which you wish to recover the affectedtablespace.

Figure 3-5 illustrates the concept of creating a clone database from a database hotbackup.

Figure 3-5: Cloning a database for tablespace point-in-time recovery.

clone database:A database created by

restoring and recovering thehot backup of another

database to another location.

Tablespace Point-in-TimeRecovery

200 Oracle9i Database: Fundamentals II

Page 216: Oracle 9i DBA Fund - II

In this figure, a hot backup of the database was performed, which included thecontrol file, all datafiles, and the archive logs. This backup also included theparameter file, which has been excluded for clarity. The backup files wererestored to another server, essentially creating a clone database that is identical tothe original database. The archive logs were applied to clone database to performa point-in-time recovery. The recovery was stopped at the precise moment wherethe DBA wanted to recover the database to, using the BACKUP CONTROLFILEand UNTIL TIME options.

Once the database is restored to the point in time desired, you would open theclone database with the RESETLOGS option, and then use one of several methodsto move the data in the target tablespace back over to the original database. Forexample, you can use the export and import utilities, transportable tablespaces,the SQL*Plus COPY command, or pull the data from the clone back to the origi-nal database through a database link. The method you use will be dependent onthe amount of data you wish to capture and how fast you need to get it back tothe original database. In most cases, transportable tablespaces is the fastest andeasiest method to use if you want to move entire tablespaces back to the originaldatabase.

TASK 3C-5Describe Tablespace Point-in-Time Recovery

1. Is it possible to recover a tablespace to a different point in time thanthat of the rest of the database? Explain your answer.

Technically, it is not possible to recover a tablespace to a different point intime than that of the rest of the database. Oracle will only consider atablespace recovered when it is consistent with the rest of the database. Ifyou stop a tablespace recovery before it becomes consistent with the data-base, Oracle will return an error when you attempt to bring the tablespaceonline.

2. When cloning a database for the purpose of performing a tablespacepoint-in-time recovery, at a minimum, what files from the original data-base are required?

The files you would need to clone the original database include:

• All backup copies of the datafiles of the affected tablespace you wish torecover.

• All backup copies of the datafiles of the SYSTEM tablespace taken fromthe same backup set as the affected tablespace datafiles previouslylisted.

• A parameter file.

• Some form of the control file from the original database (backup controlfile or control file trace file).

• All archive logs generated that include the time the backup in questionwas performed until the point in time to which you wish to recover theaffected tablespace.

Lesson 3: User-managed Backup and Recovery 201

Page 217: Oracle 9i DBA Fund - II

SummaryIn this lesson, you learned how to perform a user-managed full hot backupof the database and how to use that backup to perform a user-managed com-plete recovery of the database after a failure. Additionally, you learned howto perform a user-managed incomplete recovery to recover the database aftervarious failure scenarios, such as loss of the control file or the current redolog group.

Lesson Review3A What happens internally in the database when a tablespace is placed in

hot backup mode?

While a tablespace is in hot backup mode, all changes to datablocks that arestored in the tablespace are still written from the buffer cache to the datafilesby the DBWR process when checkpoints occur. However, the checkpoints aredeferred for tablespace in hot backup mode. This means that CKPT does notupdate the headers of the datafiles of a tablespace while that tablespace isin hot backup mode. When the tablespace is taken out of hot backup mode,Oracle simply advances the tablespace’s datafile headers to the latest check-point to bring them up to date with the rest of the database.

What happens when the following command is issued?

ALTER DATABASE BACKUP CONTROLFILE TO TRACE;

Oracle will generate a trace file in the directory specified by the USER_DUMP_DEST parameter. This trace file will contain the necessarycommands required to re-create the control files and get the database up andrunning in the event that media failure causes the loss of all copies of thecurrent control file.

If the instance crashes while a tablespace is in hot backup mode, whywill Oracle assume the tablespace requires recovery upon instancestartup?

When a tablespace is placed in hot backup mode, checkpoints are deferredfor that tablespace, which means that the datafile headers will not containthe most current SCN from the control file. If the instance were to crash withthe tablespace in hot backup mode, then the files will still contain the oldSCN. Upon restarting the instance, Oracle will detect the old SCN in theaffected datafiles, and will assume that the datafiles need recovery.

3B What is wrong with the following command?

RECOVER TABLESPACE example, DATAFILE'D:\oracle\oradata\ora92\users01.dbf;'

You cannot include both the TABLESPACE and DATAFILE options within asingle RECOVER command.

202 Oracle9i Database: Fundamentals II

Page 218: Oracle 9i DBA Fund - II

True or False? Even if you include the ALLOW n CORRUPTION clausewith the RECOVER command, the block corruptions will still exist in thedatafiles after the recovery is complete. Explain your answer.

True. The ALLOW n CORRUPTION clause is provided only as a means tomove past a block corruption issue to finish the recover process. The corrup-tions will still exist when you bring the recovery target online. Anysubsequent attempts to access those datablocks through normal databaseoperations will result in an error.

What step must you take from within Oracle after restoring a datafile toa location that is different from its original location?

a. Bring the tablespace online.

✓ b. Change Oracle’s internal pointer to the file.

c. Bring the tablespace offline.

d. Recover the tablespace

3C The current time is 8:15 A.M. The last hot backup of your database wascompleted today at 6:30 A.M. Which one of the following times is validto use for an incomplete recovery?

a. 7:15 P.M.

b. 8:38 A.M.

c. 8:25 P.M.

✓ d. 8:14 A.M.

You have restored the control file from backup and applied all archivelogs that were generated between the point in time the backup wastaken and the point of failure. However, when issuing the CANCEL com-mand, Oracle returned the following error. Why? How would youresolve it?

ORA-01547: warning: RECOVER succeeded but OPEN RESETLOGSwould get error belowORA-01152: file 1 was not restored from a sufficiently oldbackupORA-01110: data file 1: 'D:\ORACLE\ORADATA\ORA92\SYSTEM01.DBF'

This error is caused by Oracle believing that there are more changes thatcan be applied to the database, even though you have applied all availablearchive logs. It is possible that the current online redo log contains the miss-ing changes, but Oracle did not have a chance to archive this log prior tothe media failure that caused the instance to crash. To work through thiserror, the recovery can be started again and the current online redo loggroup can be specified for recovery instead of an archive log. If the currentlog group contains the changes, Oracle will apply them to the database.

Lesson 3: User-managed Backup and Recovery 203

Page 219: Oracle 9i DBA Fund - II

Which type of user-managed incomplete recovery is recommended formedia failure that causes the loss of the current redo log group?

a. Change-based recovery

b. Time-based recovery

✓ c. Cancel-based recovery

d. Manual-based recovery

You are performing a recovery of a database that contains a read-onlytablespace. The tablespace was read-write during the last hot backup,but was set to read-only prior to the point of failure. You are perform-ing the recovery with a backup control file. At what point during therecovery process will Oracle put the tablespace back in read-only.

a. When the ALTER TABLESPACE command is found in the archivelogs during recovery.

✓ b. When the database is opened with the RESETLOGS option afterrecovery.

c. Just prior to starting recovery.

d. None of these; the tablespace will remain offline throughout theentire process.

204 Oracle9i Database: Fundamentals II

Page 220: Oracle 9i DBA Fund - II

Recovery Manager Backups

OverviewManually performing all backup and recovery operations for the database isconsidered user-managed backup and recovery. However, Oracle provides apowerful utility called Recovery Manager, better known as RMAN, whichprovides the capability to create a centralized solution to handle all backupand recovery operations for all Oracle databases in a single environment. Inthis lesson, you will learn about the features RMAN provides and its archi-tecture and process flow. You will also learn how to configure RMAN, howto use it to perform server-managed hot and cold backups, and how to main-tain its centralized information repository.

ObjectivesTo perform backups of the database using RMAN, you will:

4A Describe the RMAN environment and the basic steps RMAN uses toback up and recover an Oracle9i database.

RMAN provides a powerful, centralized solution to simplify backup andrecovery operations for all Oracle databases in an environment. In thistopic, you will learn about the features of RMAN, its centralized informa-tion repository, and the process flow RMAN uses to perform backups andrecoveries. You will also learn about the different types of backup setsthat RMAN creates and how to decide which type of backup set to usefor various backup and recovery strategies.

4B Configure the RMAN environment, and prepare a database forRMAN backups.

Before you can take advantage of the backup and recovery capabilitiesthat RMAN provides, you must first configure the RMAN environment.This includes preparing the RMAN repository and the target databases. Inthis topic, you will learn how to set up the RMAN components, and howto configure RMAN to begin backing up and recovering databases.

4C Back up the database using RMAN.

RMAN provides a wealth of options to choose from when backing up atarget database. You can perform hot and cold backups, image copy back-ups, and incremental hot backups. You can also back up the archive logsand automatically delete them from the disk after they are backed up. Inthis topic, you will learn how to perform all of these backups using theRMAN utility.

Data Filesnone

Lesson Time7 hours

LESSON

4

Lesson 4: Recovery Manager Backups 205

Page 221: Oracle 9i DBA Fund - II

4D Maintain and manage the RMAN recovery catalog.

The RMAN recovery catalog provides RMAN with a wealth ofcapabilities. In this topic, you will learn how to create and managebackup and recovery scripts in the recovery catalog and how to generateRMAN reports and lists about target databases and their backups. Youwill learn how to add backup information about user-managed backups tothe recovery catalog and also how to delete obsolete backups and purgetheir related entries from the catalog. Finally, you will learn how tobackup the recovery catalog itself using various techniques.

206 Oracle9i Database: Fundamentals II

Page 222: Oracle 9i DBA Fund - II

Topic 4ARMAN ArchitectureThe Recovery Manager utility, better known as RMAN, is a powerful utility thatprovides a comprehensive suite of features to simplify all Oracle backup andrecovery operations for an environment. It can be installed and configured on anyserver on the network and can perform cold and hot backups and recoveries ofany and all Oracle databases on that same network, regardless of which platformthe target database is installed on. This allows the DBA to configure a single,centralized backup and recovery solution.

RMAN maintains its own centralized repository to store backup and recoveryinformation for all databases in the environment that RMAN supports. It has itsown command-line interface to perform all operations, or it can be invoked fromthe Oracle Enterprise Manager graphical interface. Using the command-line inter-face, the DBA can create and execute backup and recovery scripts and can storethem in RMAN’s repository for use at any time. Backup and recovery jobs canbe scheduled using any third-party scheduling utility to execute these storedscripts. With OEM, the DBA can easily configure custom backup and recoveryjobs and can schedule them to execute using OEM’s scheduling features, whicheliminates the need to even write RMAN scripts. RMAN can also be configuredto work with third-party backup utilities, collectively called the media-management layer (MML), such as Legato Networker or Veritas NetBackup. Forthese utilities, RMAN would initiate a backup or restore job and make customcalls to an application program interface (API). The API would instruct the MMLutility to back up files directly from disk to tape or restore files from tape to disk.RMAN would maintain all information about each backup and recovery operationin its own repository, regardless if RMAN performed the operation itself, or if theoperation was performed by an MML utility.

To provide maximum power and flexibility, RMAN has several configurationparameters that can be set globally for all backup and recovery operations for theenvironment, and several target-specific parameters that can be set to customizeoperations based on the target being backed up or recovered. The DBA can alsoconfigure certain conditions that allow RMAN to optimize certain backup andrecovery operations. For example, the DBA can instruct RMAN to back up alldatafiles that have not been backed up since a certain date or time using a singlecommand. This is especially useful if multiple datafiles have been added to adatabase, but a full backup was already created for that database just recently.Instead of backing up the entire database again, the DBA can instruct RMAN tobackup these new datafiles in a single operation without having to list each fileseparately.

To minimize the size of the backup files created for a database backup, RMANwill only back up datablocks in each datafile that have changed since the datafilewas created. For example, let’s say a new tablespace was created with a singledatafile that was sized to 50 megabytes. If only 10 megabytes of the datafile wereever allocated to segments, such as tables and indexes, then only those 10 mega-bytes are added to the backup. Any datablocks within the file that have neverchanged will not be added to the backup. It’s important to note that datablocksthat have changed may or may not have data in them. If a table was created thatallocated 20 megabytes in the file, then the table was subsequently dropped, those20 megabytes of datablocks will be empty, but will be considered changeddatablocks. Those blocks will be added to the backup set even if they are empty.

RMAN Features

MML:(Media-management layer)Third-party backup utilitiesthat can integrate with RMANto help perform backup andrecoveries of the database.

Lesson 4: Recovery Manager Backups 207

Page 223: Oracle 9i DBA Fund - II

To minimize the impact on a target database during a hot backup, RMAN doesnot have to put tablespaces into backup mode. This can greatly reduce theamount of redo information the target database would generate while thetablespaces were in backup mode. Additionally, RMAN can perform incrementalbackups of datafiles, which allows RMAN to back up only those datablockswhich have actually changed since the last time the database was backed up. Thiscan greatly reduce the amount of time it takes to back up a very large and activedatabase. Hot incremental backups can be performed on databases that are run-ning in ARCHIVELOG mode, and cold incremental backups can be performed ondatabases running in NOARCHIVELOG mode.

Performing restore and recovery operations is where RMAN shows its real power.During a user-managed restore and recovery, the DBA would need to determineexactly which files were lost and need recovery and which backup copies arevalid to use for recovery. The DBA would also need to identify and locate theappropriate archive logs a recovery operation will need, all of which takes time.RMAN can automatically inspect the target of the recovery and within secondsdetermine which files need to be restored, then look in its repository to locatewhere in the backup location those files reside, automatically restore them, andthen identify, locate, and restore all archive logs required to perform the recovery.This entire operation can be performed with a single command from the DBA.Additionally, RMAN can automatically detect datablock corruption, either withina live datafile or within a backup datafile, and take steps to correct the problem,all while keeping the live datafile online.

RMAN also has the ability to automatically clone an entire database from a hotbackup of an original database with a few simple commands. This allows theDBA to easily duplicate a database one or more times from a single database. Italso provides RMAN with the capability to automatically perform tablespacepoint-in-time recoveries of the original database. With a few simple commandsand some minor preparation, the DBA can use RMAN to create a clone of theoriginal database, recover the clone database to a specific point in time, and pre-pare the clone to create a transportable tablespace set to copy the recovered databack to the original database. All operations for tablespace point-in-time recoveryare handled automatically by RMAN and can easily be repeated multiple times ifnecessary.

TASK 4A-1List and Describe RMAN Features

1. How can RMAN be used to simplify the automation of database backupprocedures?

Using the command-line interface, the DBA can create and execute backupand recovery scripts and can store them in RMAN’s repository for use atany time. Backup and recovery jobs can be scheduled using any third-partyscheduling utility to execute these stored scripts. With OEM, the DBA caneasily configure custom backup and recovery jobs and schedule them toexecute using OEM’s scheduling features, which eliminates the need to evenwrite RMAN scripts.

208 Oracle9i Database: Fundamentals II

Page 224: Oracle 9i DBA Fund - II

2. True or False? Every database in an environment requires its ownRMAN configuration to allow backing up that database with RMAN.Explain your answer.

False. RMAN can be installed and configured on any server on the networkand can perform cold and hot backups and recoveries of any and all Oracledatabases on that same network, regardless of which platform the targetdatabase is installed on. This allows the DBA to configure a single, central-ized backup and recovery solution.

3. What feature does RMAN provide to reduce the amount of time it takesto perform a backup of a large database?

RMAN can perform incremental backups of datafiles, which allows RMAN toback up only those datablocks which have actually changed since the lasttime the database was backed up. This can greatly reduce the amount oftime it takes to back up a very large and active database. Hot incrementalbackups can be performed on databases that are running in ARCHIVELOGmode, and cold incremental backups can be performed on databases runningin NOARCHIVELOG mode.

4. How does RMAN simplify the restore and recovery process of a data-base that has experienced media failure?

RMAN can automatically inspect the recovery target and, within seconds,determine which files need to be restored, then look in its repository tolocate where in the backup location those files reside, automatically restorethem, and then identify, locate, and restore all archive logs required to per-form the recovery. This entire operation can be performed with a singlecommand from the DBA.

The RMAN RepositoryAt the core of the RMAN architecture is the RMAN repository, which RMANuses to store all pertinent information about each database in the environment itsupports. For each database, the repository includes the database’s current physi-cal structure, such as the names and locations of all datafiles, control files, andarchive logs. It also includes the entire backup and recovery history for eachdatabase, which includes the names and locations of all backup sets, and informa-tion about every incarnation of each database if the database was ever openedwith the RESETLOGS option. Figure 4-1 illustrates the concept of the RMANrepository.

The RMAN Repository

Lesson 4: Recovery Manager Backups 209

Page 225: Oracle 9i DBA Fund - II

Figure 4-1: The RMAN repository.

In this figure, RMAN connects to each target database in the environment to per-form backup and recovery operations. All information pertaining to each targetdatabase and its backups and recoveries are stored in the RMAN repository.RMAN requires the repository to perform almost all of its operations, and thisrepository can be decentralized by storing RMAN information in each target data-base’s control file, or it can be centralized in a single database schema known asthe recovery catalog.

The Control File as the RepositoryWhen using the control file of each target database as the repository, each controlfile holds only the pertinent backup and recovery information for its owndatabase. Using the control file may be ideal for smaller environments wherethere are only a few databases that need to be backed up. The control file con-tains the following information to support RMAN operations:

• Basic information about the database, such as the database name and data-base incarnations.

• Basic RMAN configuration parameters specific for that target database.

• Names and locations of redo log groups and their file members.

• Names of tablespaces and names and locations of their datafiles.

• Archive log history.

• Names and locations of backup files.

• Information about corruptions found in backup files.

210 Oracle9i Database: Fundamentals II

Page 226: Oracle 9i DBA Fund - II

The control file may expand to hold the information necessary to support RMANinformation. How much it grows will depend on how often the database generatesarchive logs, how often the target database is backed up, and the size of the tar-get database. To limit the size of the control file, Oracle stores both non-circularreuse records and circular reuse records. Noncircular reuse records are kept in thecontrol file indefinitely and are used to store information about the database itself,datafiles, and online redo logs. This information is critical to the operation of thedatabase and is never overwritten.

Circular reuse records are continuously generated by the target database and con-tain information that is not critical for database operation. This informationincludes the log sequence number history, archive log history and datafile backupinformation. These records are considered circular because Oracle will overwritethe information after a specific period of time, which can be set to restrict thegrowth of the control file by the CONTROL_FILE_RECORD_KEEP_TIMEintialization parameter. The default value for this parameter is 7, which meansthat any circular reuse records that are older than seven days are eligible foroverwriting. Prior to writing any new information to a circular reuse record in thecontrol file, Oracle will first look to see if any older records have expired. If theyhave, Oracle will reuse those records by overwriting the old information. If norecord is expired, Oracle will expand the size of the control file to accommodatethe new records. Any time the control file must be expanded, Oracle will make anentry in the alert log. The higher the value you set for the CONTROL_FILE_RECORD_KEEP_TIME parameter, the more information Oracle will keep in thecontrol file, and the larger the control file may grow. The lower the value, the lessinformation Oracle will keep in the control file, which causes Oracle to overwriteinformation more often. The value you choose for this parameter will depend onthe requirements of your backup and recovery strategy. If you need to keepbackup and recovery information longer, you can increase this parameter. Youshould not need to worry about the overall size of the control file; even if youkeep backup information for several weeks, the control file will still stay rela-tively small compared to most datafiles. The V$CONTROLFILE_RECORD_SECTION data dictionary view provides a current listing of all the information inthe control file. The following example query shows a typical output from thisview.

SQL> SELECT type, record_size, records_used2 FROM v$controlfile_record_section;

TYPE RECORD_SIZE RECORDS_USED-------------------- ----------- ------------DATABASE 192 1CKPT PROGRESS 4084 0REDO THREAD 104 1REDO LOG 72 3DATAFILE 180 13FILENAME 524 17TABLESPACE 68 14TEMPORARY FILENAME 56 1RMAN CONFIGURATION 1108 5LOG HISTORY 36 57OFFLINE RANGE 56 7ARCHIVED LOG 584 65BACKUP SET 40 33BACKUP PIECE 736 33

Lesson 4: Recovery Manager Backups 211

Page 227: Oracle 9i DBA Fund - II

BACKUP DATAFILE 116 53BACKUP REDOLOG 76 0DATAFILE COPY 660 4BACKUP CORRUPTION 44 0COPY CORRUPTION 40 0DELETED OBJECT 20 15PROXY COPY 852 0BACKUP SPFILE 36 30DATABASE INCARNATION 56 2

23 rows selected.

The Recovery Catalog as the RepositoryInstead of using a decentralized method of storing the RMAN repository, RMANalso allows you to create a centralized repository in a standard Oracle databaseschema, which is called the recovery catalog. It is recommended that the recov-ery catalog, rather than control files, be used as the repository in all the simplestof backup and recovery environments. The contents of the recovery cataloginclude:

• Stored backup and recovery scripts.

• RMAN persistent configuration settings, some of which are target databasespecific.

• Backup and recovery history of each target database.

• Backup retention policies for each target database.

• Names and locations of all current control files and datafiles for each targetdatabase.

• Names and locations of all backups generated for each target database.

• Names, locations, and SCN ranges of all archive logs for each targetdatabase.

The recovery catalog contains all of the same backup and recovery related infor-mation as the control file, but has several advantages over using the targetdatabases’ control files. A single recovery catalog can store backup and recoveryinformation for all Oracle databases in the environment, and the information foreach target database in a location independent from the target database itself. Ifthe target database’s control file is unavailable due to media failure, then RMANcannot be used to recover that database. The recovery catalog stores informationabout all incarnations of each target database, which allows you to recover adatabase from any incarnation of that database. Since the recovery catalog con-tains a complete history for each target database, historical lists and reports canbe generated from the recovery catalog about each database and their backups.

The recovery catalog also contains self-configuration information for the RMANutility, such as global configuration parameters that RMAN will use for everybackup and recovery operation for all target databases. It may also contain con-figuration parameters that are specific to each target database, allowing the DBAto customize backup and recovery operations per database. Additionally, therecovery catalog can be used as a convenient location to store RMAN backup andrecovery scripts, which can be executed from within RMAN itself simply bypassing the name of the script.

recovery catalog:A database schema that can

act as the backup andrecovery information

repository for RMAN.

212 Oracle9i Database: Fundamentals II

Page 228: Oracle 9i DBA Fund - II

TASK 4A-2Describe the RMAN Repository and its Contents

1. True or False? The RMAN utility requires a repository to store backupinformation for each database it backs up. Explain your answer.

True. RMAN must be able to store and retrieve backup information for alldatabases it backs up. This information is used during backup and recoveryoperations to determine which files need to be backed up or restored. Thisrepository can either reside in a centralized database schema known as therecovery catalog, or decentralized in the control files of the target databases.

2. Which initialization parameter specifies how long backup and recoveryinformation will be stored in the control file?

a. ARCHIVE_LAG_TARGET

✓ b. CONTROL_FILE_RECORD_KEEP_TIME

c. FAST_START_MTTR_TARGET

d. TIMED_STATISTICS

3. Name three or more types of information stored in the RMAN recoverycatalog.

RMAN stores an extensive amount of information in the recovery catalog,and includes, but is not limited to:

• Stored backup and recovery scripts.

• RMAN persistent configuration settings, some of which are target data-base specific.

• Backup and recovery history of each target database.

• Backup retention policies for each target database.

• Names and locations of all current control files and datafiles for eachtarget database.

• Names and locations of all backups generated for each target database.

• Names, locations, and SCN ranges of all archive logs for each targetdatabase.

RMAN Process FlowRegardless of whether the target database’s control file or the recovery catalog isused as the repository, RMAN uses a standard set of processes to performbackup, restores, and recoveries of the target database. If the recovery catalog isused, the target database must first be registered with the recovery catalog, whichis done manually by the DBA when preparing RMAN to support that target.Upon registering with the recovery catalog for the first time, RMAN will read allthe necessary information about the target database, such as names and locationsof all files and archive log history, and load that information into the recoverycatalog.

Lesson 4: Recovery Manager Backups 213

Page 229: Oracle 9i DBA Fund - II

Prior to most backup and recovery operations, RMAN will resynchronize therecovery catalog with the target database to obtain the most current informationabout the target to keep the recovery catalog up to date. If the control file is usedas the repository, registration and resynchronization of the target database is notnecessary, since a control file will contain only the information for its own data-base and will already be up to date. When resynchronizing the recovery catalog,RMAN will automatically determine whether it needs to perform a partial or fullresync with the target database. During a partial resync, RMAN will read thecontrol file of the target database to update the catalog with only data that haschanged since the last backup or recovery operation. During a full resync, RMANwill update all configuration entries for the target database, which includes filenames and locations and the archive log history.

The RMAN utility must have a valid Oracle user account and password for eachtarget database it supports, and the account must have the SYSDBA role. RMANuses this account to log in to the target database to read from the data dictionaryand control file and to start up and shut down the database during backup andrecovery operations. The user can be named anything you want, but it is recom-mended that you use the same user name for all target databases for simplicity,even if the passwords are different for each database.

The Backup Process FlowRMAN can perform both cold and hot backups of the target database and can doso when using either the control file or the recovery catalog as the RMANrepository. While a hot backup allows the database to stay up and running, anRMAN cold backup of the database requires that the database be mounted but notopened. As long as RMAN’s account for the target database has the SYSDBArole, you can shut down, mount, or open the target database right from withinRMAN.

Regardless of whether you are performing a hot or cold backup, or whether youare using the control file or recovery catalog as the repository, RMAN followsthese steps to perform a database backup:

1. Connect to the target database and the repository.

2. Shut down the target database and start up in mount mode, if performing acold backup.

3. Allocate a communication channel.

4. Issue a backup command, which can specify one or more datafiles, atablespace, the entire database, the control file, or the archive logs.

5. Locate the target files specified by the backup command.

6. Copy the target files to the backup location.

7. Update the entries in the repository.

8. Deallocate the communications channel.

For step one, RMAN connects to the target database using its assigned useraccount. If the control file is used as the repository, this is the only connectionthat is needed, since all the information RMAN needs can be read out of the datadictionary or directly from the control file. If the recovery catalog is used as therepository, RMAN connects to the database where the repository is located usingits assigned user account.

If RMAN is performing a cold backup, it will execute step two, which is to shutdown the database and start it back up in mount mode. If RMAN is performing ahot backup, the database can stay up and running.

RMAN Backup ProcessFlow

214 Oracle9i Database: Fundamentals II

Page 230: Oracle 9i DBA Fund - II

For all backup and recovery operations, RMAN must allocate a communicationchannel. This communication channel is a dedicated connection to the target data-base and is used to perform the work of copying files to the backup destination,restoring files, and performing recovery of the target database. This connection isadditional to the initial connection to the database, which is used solely to updatethe repository with the latest backup and recovery information for the target.When the channel is allocated for backups, it includes the backup destinationwhere the backups are to be created.

Once a channel has been allocated, the backup command can be issued for stepfour. This backup command can specify one or more datafiles, one or moretablespaces, the entire database, or the control file. The command can alsoinclude one, a range, or all archive logs to backup. You can instruct RMAN tobackup just the archive logs or perform any other type of backup and include thearchive logs with it. If Oracle has been configured to archive the redo logs tomultiple destinations, RMAN will only include one copy of each archive log inthe backup set. RMAN can also accept further instructions to delete the archivelogs from the source location to remove them from disk after they have beenbacked up. This provides a convenient method of automatically removing backedup archive logs so the DBA doesn’t have to do it manually.

Once the backup command is issued, RMAN will proceed to step five, whichinvolves looking in its repository to find the paths and file names of the files itmust back up. RMAN will verify that the specified files indeed exist in that loca-tion, and then proceed to step six, which is to copy target files to the backupdestination specified in the channel configuration. As the backup command isexecuted, RMAN will perform step seven, which is to update the repository withthe information about the newly created backup set. Once the backup operation iscomplete, the communication channel is automatically deallocated, meaning theOracle session in the target database for that channel is automaticallydisconnected.

The Restore Process FlowRMAN can restore lost files while the target database is either up or down. If therecovery catalog is used as the repository, then RMAN can restore the control fileof the target database. However, if the control file is used as the repository, thenRMAN will only be able to restore lost datafiles of the target database, but not alost control file. When performing a restore operation, RMAN follows thesesteps:

1. Connect to the target database and the repository.

2. Shut down the target database and start up in mount mode, if performing acold restore.

3. Allocate a communication channel.

4. Check the repository to determine the correct current configuration of thetarget database.

5. Compare the repository’s version of the target database’s configuration to thefiles that actually exist to determine which files are missing.

6. Find the backup files in their backup location.

7. Copy the backup files from their backup location to their original location, ifit is still available, or to an alternative location if the original location is notavailable.

8. Update the entries in the repository.

9. Deallocate the communications channel.

communication channel:A dedicated connectionbetween RMAN and thetarget database

RMAN Restore ProcessFlow

Lesson 4: Recovery Manager Backups 215

Page 231: Oracle 9i DBA Fund - II

Regardless of whether the control file or recovery catalog is used as the reposi-tory, RMAN will first determine what the correct configuration of the database issupposed to be by looking in the repository. It will then compare the list of filesin what it believes to be the correct configuration to the list of files that actuallyexist on the target database’s file system. If any files are missing, RMAN willautomatically locate backups of those files in the backup location and copy themback to their original location on the file system. If the original location on thefile system is not available due to media failure, the DBA must specify a newlocation where the files will go. Most of the restore process will be handled auto-matically, which can greatly reduce mean time to recovery. RMAN will notrestore any archive logs during the restore process unless specifically told to doso. The necessary archive logs can be restored automatically during the actualdatabase recovery process, which is usually more efficient, since RMAN candetermine exactly which archive logs it will need for recovery.

The Recovery Process FlowRMAN can perform any type of recovery, including datafile, tablespace, or wholedatabase recoveries. It can also perform complete or incomplete recoveries. Whenperforming database recovery, RMAN simply issues the same RECOVER com-mands the DBA would when performing user-managed recovery. The differenceis that RMAN will automatically determine which archive logs, if any, are neces-sary to perform the recovery, and automatically find and restore them frombackup as needed. RMAN can optionally delete all archive logs it restores as theyare applied to the database to keep disk usage at a minimum. Also RMAN willautomatically handle any read-only tablespace issues, such as taking the read-onlydatafiles offline prior to recovery, and bringing them back online after recovery.The automatic management of archive logs and read-only tablespaces can greatlysimplify the recovery process and reduce mean time to recovery. Once the recov-ery is complete, RMAN can open the database, including the RESETLOGS optionif necessary, and update the repository with the most up to date information aboutthe target database.

TASK 4A-3Describe the RMAN Process Flow

1. After connecting to both the target database and the repository, whatmust RMAN do before performing any backup or recovery operationson the target database?

a. Verify all control files and datafiles.

b. Update the repository.

c. Backup the control file.

✓ d. Allocate a channel.

216 Oracle9i Database: Fundamentals II

Page 232: Oracle 9i DBA Fund - II

2. How many server processes are invoked for each channel allocatedbetween RMAN and a target database?

a. Zero.

✓ b. One.

c. Two.

d. The number is dynamic based on the number of datafiles to bebacked up.

3. Exactly what does RMAN do when it performs a resync with a targetdatabase?

When resynchronizing the recovery catalog, RMAN will automatically deter-mine whether it needs to perform a partial or full resync with the targetdatabase. During a partial resync, RMAN will read the control file of thetarget database to update the catalog with only data that has changed sincethe last backup or recovery operation. During a full resync, RMAN willupdate all configuration entries for the target database, which includes filenames and locations and the archive log history.

Image Copies and Backup SetsWhen backing up the Oracle database, RMAN takes datafiles, control files, spfile,and archive log files as input and creates some sort of output which will be storedin the backup destination. The type of output generated will be determined by thecommands the DBA issues to RMAN and can be either image copies or backupsets. Image copies are standard bit-for-bit copies of the target files created in thesame way a file is copied by the OS. For each input file to be backed up, a singleoutput file is created. Since image copies created by RMAN are exactly identicalto their originals, they can be restored either automatically by RMAN or manu-ally through OS-level commands.

Backup sets are slightly more complex. A backup set is a logical object whichconsists of one or more physical backup pieces. As RMAN reads in the inputfiles to be backed up, RMAN will mesh the files together to create the backupset. The backup set will be broken down into one or more pieces depending onhow you have the backup operation configured. Figure 4-2 illustrates thisconcept.

image copy:A type of backup file createdby RMAN which is a bit-for-bit image of the original file.

RMAN Backup Sets

backup set:A logical object created byRMAN that contains multiplebackup pieces. Each backuppiece contains one or moreoriginal files from the targetdatabase.

Lesson 4: Recovery Manager Backups 217

Page 233: Oracle 9i DBA Fund - II

Figure 4-2: RMAN creating a backup set.

In this figure, RMAN is backing up a database that consists of four datafiles.RMAN meshes the files together to create a single, logical backup set, then splitsthe set into two backup pieces, which are RMAN-specific files that are stored inthe backup location. The information about the backup set and the names andlocations of the backup pieces are stored in the RMAN repository.

The number of backup sets and the number of pieces per set are determined bythe way RMAN is configured for that particular backup. By default, each backupset consists of exactly one backup piece, but the backup piece can contain anynumber of original Oracle files. For example, a database can contain 10 datafiles,but RMAN can back these up into a single backup set that contains one backuppiece, which in turn contains all 10 datafiles. If RMAN creates multiple pieceswithin a backup set, a single backed up file can span multiple pieces within thatset, but a single backed up file cannot span multiple backup sets. Additionally,control files may be included in a backup set with datafiles, but archive logscannot. For example, a backup set can contain datafiles or archive logs, but notboth. If you include archive logs with a database backup in one command,RMAN will automatically create one backup set for the datafiles and one backupset for the archive logs.

218 Oracle9i Database: Fundamentals II

Page 234: Oracle 9i DBA Fund - II

TASK 4A-4Describe How RMAN Creates Image Copies and BackupSets

1. True or False? Image copies of datafiles can be restored either automati-cally by RMAN or manually through OS-level commands. Explain youranswer.

True. Image copies are standard bit-for-bit copies of the target files createdin the same way a file is copied by the OS. For each input file to be backedup, a single output file is created. These files can be restored automaticallyby RMAN or manually through OS-level commands.

2. You are performing a backup operation that will include datafiles, thecontrol file, and archive logs, and you are not creating image copies.What is the minimum number of backup sets that will be created forthis operation?

a. 1

✓ b. 2

c. 3

d. 4

3. True or False? If your backup set is 100 GB, but you only need torestore a 5 MB file, you will still need to read through the entire 100 GBbackup set to find that small datafile. Explain your answer.

True. As RMAN resends the input files to be backed up, RMAN will mesh thefiles together to create the backup set. When recovering from a backup set,RMAN requires that all pieces of the set be available to read from, eventhough you may only need to restore a small datafile from it.

Topic 4BConfiguring the RMAN EnvironmentPrior to using RMAN to back up target databases, each target database must havean available user account on the target that RMAN can use to log in with. Forsimplicity, it is recommended that the user accounts on each database have thesame user names, even if each account uses a different password. Additionally,the RMAN utility must have access to at least one Oracle Net service name perremote target database that RMAN supports.

If you are using the control file of the target database as the RMAN repository,then no additional configuration is necessary. You would simply invoke RMANand issue the CONNECT command with the TARGET keyword to specify the username, password, and connect string for the target database. The syntax of theCONNECT command that uses the control as the repository is:

connect target username/password@connectstring

Lesson 4: Recovery Manager Backups 219

Page 235: Oracle 9i DBA Fund - II

Just as in the SQL language, RMAN commands are not case-sensitive. Anexample RMAN session that uses the control file as the repository is shown inFigure 4-3.

Figure 4-3: Using the control file as the RMAN repository.

Alternatively, you can invoke RMAN and connect to the target database in asingle command. For example, the following command issued from the commandprompt invokes RMAN and automatically connects to the ORA92 database usingthe rman user account:

rman target rman/buprec@ora92 nocatalog

In this example, the NOCATALOG keyword indicates that you are not specifyingconnection information for an RMAN recovery catalog. Therefore, RMAN willdefault to using the control file of the target database as the repository, as shownin Figure 4-4.

Figure 4-4: Invoking RMAN and connecting in a single command.

Once you have connected to the target database, you can start using RMAN toperform all backup and recovery operations for the target database. RMAN willuse the control file as the repository to store backup and recovery informationrelevant to the current target.

RMAN Connecting to TargetDatabase Using the Control

File

220 Oracle9i Database: Fundamentals II

Page 236: Oracle 9i DBA Fund - II

TASK 4B-1Using the Control File as the RMAN Repository

Objective: To use RMAN to connect to the target database using the con-trol file as the RMAN repository.

1. You will first create a database user, called rman, which the RMAN utilitywill use to connect to the database.

Launch SQL*Plus and log in as sys.

2. At the prompt, issue the following commands:

CREATE USER rman IDENTIFIED BY buprecDEFAULT TABLESPACE tools;

GRANT connect TO rman;

Oracle will display the messages “User created” and “Grant succeeded.”Exit from SQL*Plus.

3. Open a command prompt from the Start menu.

To simultaneously launch RMAN and connect to the target database andrepository, issue the following command at the command prompt:

rman target rman/buprec@ora92 nocatalog

The output will show that you have connected to the specified target data-base, which is currently the ORA92 database. The output will also show thatyou are currently using the control file of the target database instead of the

Lesson 4: Recovery Manager Backups 221

Page 237: Oracle 9i DBA Fund - II

recovery catalog as the RMAN repository.

4. To see the current datafile layout for the target database, type reportschema; and press Enter.

The output will show the names and sizes of all the datafiles in eachtablespace of the ORA92 database.

5. At the prompt, type exit and press Enter to exit from the RMAN utilityand return to the command prompt.

Exit from the command prompt.

Create the Recovery CatalogBefore connecting to and using the recovery catalog as the RMAN repository, therecovery catalog must be created within a user schema in a database. It is recom-mended that you store the recovery catalog in a database independent from thetarget databases you wish to back up. If a failure occurs that renders the targetdatabase inoperable, your recovery catalog will also be unavailable.

The user name of the database account you use for RMAN is unimportant, butthe account must at least have the RECOVERY_CATALOG_OWNER role, or anequivalent set of privileges, prior to creating the catalog. Additionally, the data-base objects that make up the recovery catalog will be created in the defaulttablespace you assign to the user. Therefore it is recommended that you create a

222 Oracle9i Database: Fundamentals II

Page 238: Oracle 9i DBA Fund - II

dedicated tablespace to store the recovery catalog in, and assign only the RMANuser to it. The RMAN user must also be given sufficient storage quota in thetablespace where the recovery catalog will be created. An empty recovery catalogis usually no more than 15 MB, depending on the default storage settings for thetablespace where the catalog is created, but will grow depending on the numberof target databases the catalog supports and how often the targets are backed up.In general, a 100 MB tablespace is recommended to start with, and you shouldgive the RMAN user an unlimited quota on this tablespace.

To connect to the database where the recovery catalog is located, you wouldinclude either the RCVCAT or CATALOG keywords, which are interchangeable,with the CONNECT command, and the user name, password, and connect stringfor the database. The first time you connect to the repository database, RMANwill display a message that the recovery catalog is not installed, as shown in Fig-ure 4-5.

Figure 4-5: Initial RMAN connection to the recovery catalog database.

Once connected to the repository database, you would create the recovery catalogby simply issuing the CREATE CATALOG command. When this command isissued, RMAN will automatically create all the objects that make up the recoverycatalog. If a recovery catalog already exists in the database for the specified user,RMAN will return an error. Figure 4-6 shows the output from the CREATECATALOG command.

Figure 4-6: The CREATE CATALOG command.

Creating the RMANRecovery Catalog

Lesson 4: Recovery Manager Backups 223

Page 239: Oracle 9i DBA Fund - II

Once the recovery catalog is created, you can connect to any target databasesimultaneously with the recovery catalog to begin backup and recovery operationsfor that target. A single RMAN command can invoke RMAN and connect to boththe target and recovery catalog. The order in which you specify the catalog andtarget connection information is unimportant; you can either specify the recoverycatalog connection information first or the target database connection informationfirst. However, you must specify correct user names passwords and connectstrings for both. An example RMAN session connecting to both the recoverycatalog and a target database is shown in Figure 4-7.

Figure 4-7: RMAN connecting to both target and recovery catalog databases.

In this example, the recovery catalog is located in the database specified by theRECCAT connect string, and the target database is specified by the ORA92 con-nect string. The user name rman with the password buprec was used for bothlocations.

TASK 4B-2Creating the Recovery Catalog

Objective: To create the RMAN recovery catalog to store the RMANrepository inside the database.

1. While it is not advisable to store your recovery catalog in the same databasethat must be backed up, for the purpose of this course, you will create atablespace in the ORA92 database to store the RMAN recovery catalog.

Launch SQL*Plus and log in as sys.

2. At the prompt, issue the following command:

CREATE TABLESPACE rman DATAFILE'D:\oracle\oradata\ora92\rman01.dbf' SIZE 100MEXTENT MANAGEMENT LOCAL UNIFORM SIZE 128k;

After a few moments, Oracle will display the message “Tablespace created.”

224 Oracle9i Database: Fundamentals II

Page 240: Oracle 9i DBA Fund - II

3. You will now configure the rman database user to support the creation of therecovery catalog. This includes setting the user’s default tablespace, settingthe user’s quota on that tablespace, and granting the appropriate privilegesrequired to create and own the recovery catalog.

At the prompt, issue the following commands:

ALTER USER rmanDEFAULT TABLESPACE rmanQUOTA UNLIMITED ON rman;

GRANT recovery_catalog_owner TO rman;

Oracle will display the messages “User altered” and “Grant succeeded.”

4. Leaving the SQL*Plus window open, open a command prompt from theStart menu.

You will now launch RMAN, and simultaneously connect to the target data-base and the database where the recovery catalog is stored. For this course,both refer to the ORA92 database. At the command prompt, issue the fol-lowing command:

rman rcvcat rman/buprec@ora92 target rman/buprec@ora92

The RMAN utility will launch and, after a moment, it will connect to theORA92 database as both the target and the recovery catalog database.RMAN will also display a message stating that the recovery catalog is notinstalled.

5. To create the recovery catalog, type create catalog; and press Enter.

Lesson 4: Recovery Manager Backups 225

Page 241: Oracle 9i DBA Fund - II

After several moments, RMAN will display the message “recovery catalogcreated.”

6. To exit from the RMAN utility, type exit and press Enter.

Close the command prompt.

7. You will now query the data dictionary to see a list of the tables that werecreated in the RMAN schema.

At the SQL*Plus prompt, issue the following commands to format theoutput of your query:

set pages 50COLUMN table_name FORMAT a30COLUMN tablespace_name FORMAT a15

Issue the following query:

SELECT table_name, tablespace_nameFROM dba_tablesWHERE owner='RMAN';

The output will show that 30 tables have been created in the RMANschema. These tables make up the main storage structures of the RMANrecovery catalog. You may have to scroll up to see all of the output.

8. Exit from SQL*Plus.

226 Oracle9i Database: Fundamentals II

Page 242: Oracle 9i DBA Fund - II

Register a Target DatabaseOnce the recovery catalog is created, each database to be supported must be reg-istered with the recovery catalog. When registering a target database, RMANreads basic information about the database from the data dictionary, such as thedatabase name, Oracle version, and incarnation and loads it into the recoverycatalog. RMAN then performs a full resync with the target database to load therecovery catalog with the target database’s datafile and control file layout, archivelog history, and other pertinent backup and recovery information.

To register a target database with the recovery catalog, you would first invokeRMAN and connect to both the recovery catalog and the target database, thenissue the REGISTER DATABASE command. The output from this command isshown in Figure 4-8.

Figure 4-8: The REGISTER DATABASE command.

TASK 4B-3Registering a Target Database

Objective: To register a target database in the RMAN recovery catalog.

1. You will first launch RMAN, and connect to both the recovery catalog andthe target database simultaneously.

Open a command prompt from the Start menu.

At the prompt, issue the following command:

rman rcvcat rman/buprec@ora92 target rman/buprec@ora92

Registering a Database withthe Recovery Catalog

Lesson 4: Recovery Manager Backups 227

Page 243: Oracle 9i DBA Fund - II

The output will show that you have connected to both the target databaseand the recovery catalog database.

2. To generate a list of the tablespaces that currently make up the target data-base, type report schema; and press Enter.

RMAN will display an error message stack. The errors state that the targetdatabase is not found in the recovery catalog. Before performing any opera-tions with RMAN against a target database while using the recovery catalogas the repository, you must first register the database with the recoverycatalog.

3. To register the target database with the recovery catalog, type register data-base; and press Enter.

The output will show that the database has been registered with the recoverycatalog, and a full resync was completed.

4. Now that the metadata information about the target database is now stored inthe recovery catalog, you will be able to generate a list of the tablespacesthat currently make up the target database.

At the prompt, type report schema; and press Enter.

RMAN will display a report of the database schema. This report consists ofall the datafiles in the database, and the size of each one. The report willalso show which datafiles contain rollback segments. This information may

228 Oracle9i Database: Fundamentals II

Page 244: Oracle 9i DBA Fund - II

be important during a recovery of those datafiles.

5. To exit from the RMAN utility, type exit and press Enter.

RMAN will display the message “Recovery Manager complete.”

Close the command prompt.

RMAN Configuration ParametersThe RMAN utility allows you to set default configuration parameters that persistacross all RMAN sessions for a particular recovery catalog. These persistentconfigurations help simplify the management of backup and restore operations byminimizing the amount of text required for execution. The configuration param-eters are stored in the recovery catalog and are initialized each time the RMANutility is started. Any changes to the configuration parameter values will be storedin the recovery catalog and will be used for each subsequent RMAN session untilthe parameter is changed again. All configuration settings can be modified byusing the CONFIGURE command from the RMAN prompt. Any configurationsettings specified in an RMAN script will override the default settings providedby the CONFIGURE command. The configuration settings that can be modifiedinclude:

• Retention policy

• Channel configuration and allocation

• Control file management

• Backup optimization

• Tablespace exclusions

Specifying a retention policy sets the maximum number of backup sets to main-tain in the recovery catalog. This retention policy can be specified as the numberof backups or as the number of days’ worth of backups. As new backup sets arecreated, older sets are marked as obsolete. You can then execute the DELETEOBSOLETE command to automatically find and delete all backup sets that aremarked obsolete. In this way, you will limit the amount of disk space consumedfor backups, and still keep a minimum number of current backups on hand. Toset the retention policy to maintain five sets of current backups, you would issuethe following command at the RMAN prompt:

CONFIGURE RETENTION POLICY TO REDUNDANCY 5;

RMAN ConfigurationParameters

retention policy:The policy used by RMAN todetermine which databasebackups in its recoverycatalog are still valid.

Lesson 4: Recovery Manager Backups 229

Page 245: Oracle 9i DBA Fund - II

To set the retention policy to maintain 30 days’ worth of current backups, youwould issue the following command at the RMAN prompt:

CONFIGURE RETENTION POLICY TO RECOVER WINDOW OF 30 DAYS;

The CONFIGURE command also allows you to specify default settings for yourchannel configurations. The channel configurations you can set include the devicetype and the directory and file name convention you wish to use for your backupsets. The channel configuration settings you specify will be used to automaticallyallocate and use channels for all backup and restore operations as necessary. Toconfigure the default channel settings for RMAN, you could issue any one of thefollowing commands at the RMAN prompt:

CONFIGURE DEFAULT DEVICE TYPE TO DISK;CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT'D:\oracle\oradata\ora92\ora92_bak\%d_%s_%p.bak';CONFIGURE DEVICE TYPE DISK PARALLELISM 4;

The first command sets the default device type to disk. This will ensure thatRMAN assumes that all backup and restore operations will occur on the localdisk unless otherwise specified. If you want the backups to be sent to a backuptape device that is attached to the server where the target database resides, youwould use TYPE 'sbt_tape'.

The second command sets the directory and file name format for all backup setsthat will be sent to the disk. The last command sets the number of channels toallocate for backup and restore operations. In this case, RMAN will automaticallyallocate four channels for all backup and restore operations that occur on thelocal disk.

If you include the FORMAT option, you can specify the directory path and filename pattern to use when creating backup sets. The file name pattern can includepattern variables to allow RMAN to generate the file name. Some of the availablefile name pattern variables are shown in the following table.

Variable Usage%d Specifies the name of the target database.%D Specifies the current day of the month using the format DD.%F Combines the database identifier (DBID), day, month, year, and a sequential

number into a unique and repeatable generated name.%M Specifies the month number using the format MM.%p Specifies the backup piece number within a single backup set. The first set will

automatically use the value 1, and the value is incremented for each subsequentpiece in the set.

%s Specifies the backup set number. This number is actually stored in the controlfile of the target database and is incremented for each backup set created forthe target database.

%t Specifies the timestamp of the backup set.%T Specifies a full year, month, and date using the format YYYYMMDD.%u Instructs RMAN to generate a unique name for each output file.%U Shorthand for %u_%p_%c. This combination guarantees uniqueness for all

backup sets generated for a single target database.%Y Specifies the current year using the format YYYY.

230 Oracle9i Database: Fundamentals II

Page 246: Oracle 9i DBA Fund - II

If you specify a file name pattern but do not use any pattern variables, everybackup set RMAN generates for the target database will have the same name, andwill probably overwrite older backup sets. If you do not specify a file name pat-tern at all, by default RMAN will use the %U pattern variable.

The RMAN utility also provides a simplified way to manage controlfile backupswith a control file autobackup feature. When this feature is enabled, RMAN willautomatically include the control file in every backup operation. Control fileautobackup is enabled by issuing the following command:

CONFIGURE CONTROLFILE AUTOBACKUP ON;

To set the path and file name of the backed up control file, you would issue thefollowing command:

CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO'%F';

For this command, you can specify any path and file name you like, but it mustinclude at least the %F substitution variable. The %F variable will automaticallyadd an identifying tag to the file name in the following format:

c-IIIIIIIIII-YYYYMMDD-QQ

In this format, c stands for control file, and IIIIIIIIII represents the data-base identifier of the database that the control file belongs to. The YYYYMMDDnotation represents the year, month, and date the control file backup occurred, andQQ represents the backup control file sequence number. The backup control filesequence number is a hexadecimal number which starts at 00 and has a maximumof FF (256), and increments each time the control file is backed up. Once thevalue of FF is reached, the control file sequence number recycles back to 00. Ifyou do not include at least the %F substitution variable, RMAN will return anerror.

If you specified the format for backup control files to be 'ORA_%F.bak', thefile name of your backup control file might look something like this:

ORA_c_1776372340_20020801-49.bak

Another default setting you can enable is backup optimization. When this param-eter is set to ON, RMAN will bypass any files that have already been backed upto the same device and that have not changed since their last backup. This canshorten the time it takes to perform a full database backup by skipping any filesthat do not need to be backed up. This setting applies to archive log backups, aswell as datafile backups. To set this parameter, you would issue the followingcommand:

CONFIGURE BACKUP OPTIMIZATION ON;

Another method of decreasing the time it takes for backing up a database is tospecify tablespaces that you do not want to back up. If you can set defaulttablespace exclusions with the CONFIGURE command, the tablespaces youspecify will be skipped for all backup and restore operations. This is useful if youhave large tablespaces that do not contain critical data that you do not wish toback up. This parameter can be set with the following command:

CONFIGURE EXCLUDE FOR TABLESPACE users;

If you wish to exclude more than one tablespace, you must list each tablespaceseparately with a new CONFIGURE command for each. The specified tablespacesare added to the list of excluded tablespaces, and the list is not overwritten. Addi-tionally, a tablespace exclusion is target database-specific, meaning that a

Lesson 4: Recovery Manager Backups 231

Page 247: Oracle 9i DBA Fund - II

tablespace that has been added to the exclusion list will only be excluded fromfuture backups of the target database RMAN is currently connected to. In theexample shown here, the USERS tablespace will be excluded for all future back-ups of the current target database. If RMAN connects to another database thatalso has a USERS tablespace, the exclusion will not apply for that databaseunless the DBA specifically adds the tablespace to the exclusion list.

To set any RMAN configuration parameter back to its original default, you canjust add the CLEAR keyword to the end of each command. The following com-mands will set each of the previously mentioned configuration parameters back totheir default values:

CONFIGURE RETENTION POLICY CLEAR;CONFIGURE DEFAULT DEVICE TYPE CLEAR;CONFIGURE CHANNEL DEVICE TYPE DISK CLEAR;CONFIGURE CONTROLFILE AUTOBACKUP CLEAR;CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISKCLEAR;CONFIGURE BACKUP OPTIMIZATION CLEAR;CONFIGURE EXCLUDE FOR TABLESPACE users CLEAR;

In this syntax, the command CONFIGURE CHANNEL DEVICE TYPE DISKCLEAR will reset the degree of parallelism back to one, meaning only onechannel will be allocated for each backup and restore operation. Also, whenspecifying the CLEAR keyword for the CONFIGURE EXCLUDE FORTABLESPACE command, only that tablespace is removed from the list ofexcluded tablespaces. You must specify each tablespace separately for each oneyou want to remove from the excluded list.

To see any of your backup configuration settings, you can use the SHOWcommand. With this command, you can specify any individual parameter, or youcan specify SHOW ALL to list all configuration parameters. It’s important to notethat the SHOW ALL command may or may not actually show all persistent con-figuration parameters. Many configuration parameters have default values, and ifthe DBA has not changed a parameter’s value from its default, more than likelythe SHOW ALL command will not list it. The SHOW ALL command primarilyprovides a list of all parameters that have been explicitly set by the DBA. Figure4-9 shows the output of the SHOW ALL command.

Figure 4-9: The SHOW ALL command.

232 Oracle9i Database: Fundamentals II

Page 248: Oracle 9i DBA Fund - II

TASK 4B-4Set the RMAN Configuration Parameters

Objective: To set the RMAN configuration parameters in preparation ofperforming RMAN backups of the target database.

1. You will first connect to the recovery catalog and the target database.

Open a command prompt from the Start menu.

At the prompt, issue the following command:

rman rcvcat rman/buprec@ora92 target rman/buprec@ora92

RMAN will launch and connect to both the recovery catalog and the targetdatabase.

2. To see the current settings of the configuration parameters, type show all;and press Enter.

The output will show all configuration parameters that are currently set forRMAN. This list is not all inclusive; if a parameter currently has no setting,it will not appear in the list.

3. You will set some configuration parameters to tailor the RMAN environmentfor your system. The changes you will make include:

• Destination path and file name format for backup sets.

• Control file autobackup.

• Backup control file path and file name format.

• Backup optimization.

• Tablespace exclusions.

To set the destination path and file name format for backup sets, issue thefollowing command at the RMAN prompt:

CONFIGURE CHANNEL DEVICE TYPE DISK FORMAT'D:\oracle\rman_bup\%d_%s_%p';

The output will show that RMAN stored the new parameter setting, and per-

Lesson 4: Recovery Manager Backups 233

Page 249: Oracle 9i DBA Fund - II

formed a full resync of the recovery catalog.

You should notice that RMAN accepts the path and format setting eventhough the D:\oracle\rman_bup folder does not yet exist. However, if thepath specified is still invalid when RMAN attempts to perform a backup, thebackup will fail. Therefore, you will create the D:\oracle\rman_bup foldernow.

Open a window to the D:\oracle folder. Choose File→New→Folder.Name the new folder rman_bup

Close the D:\oracle window.

4. You will now configure RMAN to automatically include the control file inall backups. This includes enabling control file autobackup, as well as settingthe path and file name format for the backed up control file.

At the prompt, issue the following commands. After each command,RMAN will store the new parameter setting and perform a full resync of thecatalog.

CONFIGURE CONTROLFILE AUTOBACKUP ON;CONFIGURE CONTROLFILE AUTOBACKUP FORMATFOR DEVICE TYPE DISK TO 'D:\oracle\rman_bup\%F';

5. Certain RMAN features can help reduce the amount of time required to backup the entire database, such as backup optimization and excluding non-critical tablespaces. You will enable backup optimization to direct RMAN tobypass datafiles that have already been backed up and have not changedsince the last backup. You will also set an exclusion for the EXAMPLEtablespace.

At the prompt, issue the following commands. After each command,

234 Oracle9i Database: Fundamentals II

Page 250: Oracle 9i DBA Fund - II

RMAN will store the new parameter setting and perform a full resync of thecatalog.

CONFIGURE BACKUP OPTIMIZATION ON;CONFIGURE EXCLUDE FOR TABLESPACE example;

6. To confirm all of your configuration changes, type show all; and pressEnter.

The output will show that the path and file name format for backup sets andthe control file have been set. You will also see that control file autobackuphas been enabled. Backup optimization has been enabled, and theEXAMPLE tablespace will be excluded from all backups.

These parameter settings will be used for all future backups of this targetdatabase until the settings are changed again.

7. Your RMAN environment is now ready to begin performing databasebackups.

Exit from RMAN and the command prompt.

Lesson 4: Recovery Manager Backups 235

Page 251: Oracle 9i DBA Fund - II

Topic 4CRMAN BackupsWhen performing a user-managed cold database backup, the database is shutdown completely and file copies are executed through OS-level commands. How-ever, for RMAN cold backups, the database must be shut down then started inthe mount state. This allows RMAN to log in to the database and read pertinentinformation from the data dictionary and control file to update the RMANrepository. However, the connection RMAN uses will only be able to see the verybasics of the data dictionary, but it will not be able to see its own schema objects.If the recovery catalog is stored in an independent database, you can use therecovery catalog for the cold backup. However, if the recovery catalog is storedin the target database, then the recovery catalog will be unavailable during thebackup, which means you must use the target database’s control file as theRMAN repository.

The DBA can shut down and mount the target database right from within theRMAN utility by issuing standard SHUTDOWN and STARTUP commands. Thisallows the DBA to perform all backup and recovery activities from a single util-ity and even write RMAN scripts that can handle all operations from withinRMAN itself. Figure 4-10 shows the RMAN utility shutting down and mountingthe target database.

Figure 4-10: Shutting down and mounting the target database from within RMAN.

Once the database is mounted, the backup can begin. During the backup process,RMAN will apply all persistent configuration parameters to the current operation,unless the parameters are explicitly overridden for the operation. If the parametersare set appropriately, then the set of commands to initiate a cold database backupmay simply consist of just the BACKUP command that specifies the target to backup, such as one or more datafiles, one or more tablespaces, the entire database,the control file, or one or more archive logs. The following command will backup the entire database to the backup location specified by the default channel con-figuration parameter:

The BACKUP Command

236 Oracle9i Database: Fundamentals II

Page 252: Oracle 9i DBA Fund - II

BACKUP DATABASE;

Regardless of the actual backup target or whether the operation is a hot or coldbackup, there are some steps that are always executed during an RMAN backup.First, RMAN must allocate a communications channel. This channel is a databaseconnection to the target database that allows RMAN to read the data dictionaryinformation about the backup target, such as the names and locations of datafiles.It is through this channel that the actual backup work is done, such as readingfrom the source files and writing to the pieces of the backup set that is to becreated.

Another operation that is always performed for every backup is a backup of thespfile. Regardless of the backup operation you are performing, RMAN willalways locate and include the spfile with each and every backup set created. Thisis to ensure that the spfile can always be restored even if a media failure causes atotal loss of the most critical files in the database. A database with all its datafilesthat cannot be restarted is even more worthless than a database that has lost all ofits datafiles but has retained the spfile. The lost datafiles can be restored, and theinstance restarted with the latest backup copy of the spfile. Without this backupcopy, you will have to manually re-create a standard parameter file to start thedatabase with, which may not include all the necessary parameters and settings toget the database back to the configuration it had at the point of failure. This cancreate performance problems in the recovered database and possibly increase yourmean time to recovery while you try to determine which parameters are incorrect.

If control file autobackup is enabled, a backup copy of the control file is alwayscreated for each and every backup operation. The control file backup that is cre-ated from a control file autobackup operation will always be contained within itsown backup set. For example, if you execute the BACKUP DATABASE com-mand, RMAN will create one or more backup sets to store the database backupin, and will also create an additional backup set to store the control file backupcopy generated by the control file autobackup feature. Even if your commandincludes the control file in its backup target, such as using the INCLUDINGCONTROLFILE clause, or even just the BACKUP CURRENT CONTROLFILEcommand, RMAN will still create one backup set for the specified target andanother backup set for the control file autobackup. This means that if you enablecontrol file autobackup, and your backup target includes a control file, RMANwill end up backing up the control file twice during the operation. This is notnecessarily a bad thing, since the control file is relatively small, and having morebackups is better than not having enough backups.

After the channel is allocated, RMAN will determine which files are to beincluded in the backup set, then locate those files on the file system. Using theFILESPERSET and MAXPIECESIZE parameters, RMAN will determine thenumber of backup sets to create and the number of backup pieces within each set.If these parameters have not been set, RMAN will default to creating one backupset that contains a single backup piece. That backup piece will contain all filesfor the backup target. Once the backup operation is complete, RMAN deallocatesthe communication channel and then updates its repository with the informationrelevant to the operation it just completed.

RMAN will automatically generate an identifying tag for each backup it creates.A tag acts as the name of the backup, which can be used to find specific backupsin the repository if necessary. By default, RMAN generates backup tags using thefollowing format:

TAGYYYYMMDDTHHMMSS

Lesson 4: Recovery Manager Backups 237

Page 253: Oracle 9i DBA Fund - II

In this format, YYYYMMDD indicates the year, month, and date that the backupwas started. The time the backup was started is indicated by the characters thatfollow the T after the date. For example, a backup that was started on May 15,2003 at 8:15 A.M. exactly will be labelled with the following tag:

TAG20030515T081500

RMAN allows you to optionally specify your own tags for backups when theyare executed. This is done by including the keyword TAG with the BACKUPcommand. Tags are not case sensitive and must be 30 characters or less. A tag fora single backup set will apply to all pieces within that backup set. Additionally,tags can be reused without overwriting previous tags. For example, a backup cre-ated last week may have the tag 'FULL_WEEKLY', while a new backup thisweek can also have the same tag. The following command will create a fullbackup of the database and override the default tag with the labelMONDAY_HOT_BACKUP:

BACKUP DATABASE TAG MONDAY_HOT_BACKUP;

Creating RMAN Image CopiesWhen using RMAN to create image copy backups of datafiles, RMAN uses thesame step-by-step process it uses to create backup sets. Just like backup sets,RMAN can create hot or cold image copies and can use them to automaticallyrestore and recover the database in the event of a failure. The only difference isthat the output files of image copies are not backup sets that consist of backuppieces. Rather, the output files are exact copies, bit-for-bit, of the original targetfiles. RMAN still allocates a channel, backs up the control file if control fileautobackup is enabled, backs up the spfile, and updates the repository.

To create image copy backups, you would use the COPY command instead ofusing the BACKUP command. With a single COPY command, you would list oneor more input files and the respective output paths and file names of the imagecopies to create. You can use this command to create image copies of datafiles,control files, and archive logs, all of which can be included in a single COPYcommand. The syntax for the COPY command can be somewhat complex, but asimplified version is shown here:

COPY FILE_TYPE 'input_file' TO 'output_file' [,...];

In this syntax, FILE_TYPE refers to the type of input file you are copying,which can be DATAFILE, ARCHIVELOG, or CURRENT CONTROLFILE. The'input_file' argument specifies the file that is to be copied. This argumentcan be specified as an absolute path and file name enclosed in single quotes or asa datafile ID number, which can be determined from the data dictionary of thetarget database. If file_type is CURRENT CONTROLFILE, then there is noneed to include the 'input_file' argument. The 'output_file' specifiesthe path and file name of the image copy to be created from the input file. Thefollowing list of commands shows some example COPY commands to createimage copies of files in the target database:

The COPY Command

238 Oracle9i Database: Fundamentals II

Page 254: Oracle 9i DBA Fund - II

COPYDATAFILE 'D:\oracle\oradata\ora92\system01.dbf' TO

'D:\oracle\backup\copies\system01.bak';

COPYDATAFILE 2 TO 'D:\oracle\backup\copies\undo01.bak',DATAFILE 5 TO 'D:\oracle\backup\copies\example01.bak;

COPYCURRENT CONTROLFILE TO 'D:\oracle\backup\copies\control01.bak',DATAFILE 1 TO 'D:\oracle\backup\copies\system01.bak';

COPYARCHIVELOG 'D:\oracle\oradata\ora92\oraarch\ORA92_3833.arc' TO

'D:\oracle\backup\copies\ORA92_3833_arc.bak';

In the first COPY command, an image copy of the SYSTEM01.DBF datafile iscreated in the D:\oracle\backup\copies folder. The input file is specified with anabsolute path and file name of the datafile. In the second example, multipledatafiles are to be copied and are listed by their ID numbers, which can be deter-mined from the data dictionary. In the third example, the COPY commandincludes both the current control file and the SYSTEM01.DBF datafile. In the lastexample, a single archive log is being copied from its original location to the ’D:\oracle\backup\copies folder.

TASK 4C-1Performing Cold Database Backups Using RMAN

Objective: To perform a full, cold backup of the database using RMAN,and to back up the database by creating image copies.

1. To perform a cold database backup using RMAN, the database must be inthe mount stage, but not opened. Also, since your recovery catalog resides inthe database that will be backed up, the recovery catalog will be unavailablefor this operation. Therefore, you will use the control file as the RMANrepository.

Open a command prompt.

At the command prompt, issue the following command:

rman target rman/buprec@ora92 nocatalog

Lesson 4: Recovery Manager Backups 239

Page 255: Oracle 9i DBA Fund - II

The RMAN utility will launch and connect to the target database using thecontrol file as the repository.

2. At the RMAN prompt, type shutdown immediate; and press Enter.

The output will show that the database was closed and dismounted, and thedatabase shut down.

Type startup mount; and press Enter.

The output will show that the Oracle instance was started, and the databasemounted.

3. To see the current settings of the RMAN configuration parameters, typeshow all; and press Enter.

The output will show RMAN’s current configuration for this target database,some of which you had set in an earlier activity. You will see that datafileswill be backed up to the D:\oracle\rman_bup folder. You will also see that

240 Oracle9i Database: Fundamentals II

Page 256: Oracle 9i DBA Fund - II

the control will be automatically backed up, also with the destination ofD:\oracle\rman_bup.

4. Since all the necessary configuration parameters are already set, you simplyneed to issue the backup command to perform a full, cold backup.

At the prompt, type backup database; and press Enter.

You will see RMAN begin the backup process. First RMAN allocates achannel, then generate a list of datafiles to be included in the backup set.Once the datafiles are backed up, RMAN will automatically back up thecontrol file and spfile. The entire backup process may take several minutesto complete.

5. Leaving the RMAN window open, open a window to the D:\oracle\rman_bup folder.

The folder contains two files. The first file is the backup copy of the controlfile, and has a name that begins with the letter C, followed by a string ofnumbers. As indicated by the configuration parameters, the control file willautomatically be backed up for each backup of the database. The other file is

The names of the files yousee on your system may notbe the same as those shownhere.

Lesson 4: Recovery Manager Backups 241

Page 257: Oracle 9i DBA Fund - II

named ORA92_1_1, and is the RMAN backup set containing the coldbackup of the database.

6. Leaving the rman_bup window open, switch back to the RMAN window.

You will now create an image copy of the datafile that makes up the USERStablespace. To determine the name and location of the USERS datafile, typereport schema; and press Enter.

The output will show a list of the datafiles in the target database. Find thedatafile for the USERS tablespace. Make note of the file number of thatdatafile, which is found in the first column of the report. In the exampleshown here, the file number of the USERS datafile is 9.

7. To create an image copy of the USERS datafile, issue the following com-mand, making sure to substitute the file number of your USERS datafilefrom the schema report:

copy datafile 9 to 'D:\oracle\rman_bup\users_img.dbf';

You will see RMAN begin the copy process. First, RMAN allocates a chan-nel, then copies the USERS01.DBF datafile to the D:\oracle\rman_bupfolder, and names the copy USERS_IMG.DBF. Once the file is copied,

The output of the schemareport may be wider than

your window, which causeslonger lines of text to wrap

to the next line.

242 Oracle9i Database: Fundamentals II

Page 258: Oracle 9i DBA Fund - II

RMAN then automatically backs up the control file and spfile.

8. Leaving the RMAN window open, switch back to the D:\oracle\rman_bupwindow.

You will see two new files in the folder. The first new file is USERS_IMG.DBF, which is the image copy of the USERS01.DBF datafile. The other newfile is another backup copy of the control file, which was automatically gen-erated by RMAN.

Close the rman_bup window and switch back to the RMAN prompt.

9. You will now open the database to make it available for general use.

At the RMAN prompt, type alter database open; and press Enter.

RMAN will display the message “database opened.”

10. Exit from both RMAN and the command prompt.

RMAN Hot BackupsThe only real difference between an RMAN cold backup and an RMAN hotbackup is that the database remains open and available during a hot backup.Since RMAN does not have to put tablespaces in backup mode, which is requiredfor a user-managed hot backup, there will be little or no impact on database per-

Lesson 4: Recovery Manager Backups 243

Page 259: Oracle 9i DBA Fund - II

formance while the backup is executing. Like the RMAN cold backup, theRMAN hot backup is initiated with the BACKUP command. If the persistent con-figuration parameters are set appropriately, then the only option that needs to beincluded with this command is the backup target, such as DATAFILE,TABLESPACE, DATABASE, or ARCHIVELOG. When executing the backup,RMAN will allocate a channel, locate the files to backup and add them to thebackup set, backup the control file if control file autobackup is enabled, backupthe spfile, then deallocate the channel. Once the operation is complete, RMANwill update the repository with all pertinent information about the backup set itjust created.

TASK 4C-2Perform a Hot Backup of the Database Using RMAN

Objective: To perform a hot backup of the database using RMAN.

1. In your environment, the recovery catalog is contained in the target database.Since a hot backup is performed while the database is open, the recoverycatalog is available. Therefore, you will connect to the target database andthe recovery catalog simultaneously.

Open a command prompt. At the prompt, issue the following command:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

The output will show that RMAN has connected to both the target databaseand the recovery catalog.

2. Since the RMAN environment is already configured, you simply have toissue the backup command.

At the RMAN prompt, type backup database; and press Enter.

You will see RMAN begin the backup process. With the exception ofexcluded datafiles, all datafiles, the control file, and the spfile were includedin the backup. While this backup is occurring, the database remains openand available to users with very little or no impact to performance. The

The connectionspecifications for the target

database and recoverycatalog can be listed in anyorder at the RMAN prompt.

244 Oracle9i Database: Fundamentals II

Page 260: Oracle 9i DBA Fund - II

backup may take several minutes to complete.

3. Exit from both RMAN and the command prompt.

RMAN Incremental Hot BackupsTo decrease the amount of time it takes to perform a hot backup of a large data-base, RMAN provides the ability to perform incremental backups of the database.When performing a standard full backup of the database, RMAN adds eachdatafile to the backup set and backs up all datablocks within each datafile thathave changed since the datafile was created. This could potentially mean that anentire datafile could be backed up if the datafile was very full at any point in itslifetime.

When performing incremental hot backups, RMAN will only back up datablocksthat have changed since the last incremental backup. For example, let’s say a newtablespace was created that consisted of a single datafile sized at 50 MB, 45 ofwhich have been allocated to tables and indexes during the lifetime of thedatafile. During a standard RMAN hot backup, RMAN will back up all 45 MB,regardless of whether any of those datablocks have actually been modified for along time. During an incremental RMAN hot backup, RMAN will only back upthe datablocks in the file that have changed since the last backup. Let’s say a hotbackup of the datafile was performed two days ago, and since then, only 1 MB ofthose 45 allocated have actually changed. During the next incremental hotbackup, only that one changed megabyte worth of datablocks will be backed up,instead of all 45. This can greatly reduce the amount of time and storage spacerequired to perform a backup of the database.

RMAN can create incremental backups by using backup levels, ranging from 0 to8. The backup increment level is specified with the BACKUP command when thebackup is executed. Each higher backup level backs up less and less data fromthe database. An incremental level 0 backup is identical to a standard full hotbackup of the database. However, you cannot perform an incremental level 1backup of a database that has only been backed up using a standard hot backup.In order to perform incremental backups of a database, you must have performedat least one incremental level 0 backup. This level 0 backup stands as thebaseline for all future incremental backups. If you attempt to perform a level 1incremental backup of a database that does not have a level 0 incrementalbackup, RMAN will automatically perform a level 0 incremental backup instead.

incremental backup:A backup of the databasethat includes only thedatablocks that have changedsince a previous incrementalbackup instead of alldatablocks that contain data.

Lesson 4: Recovery Manager Backups 245

Page 261: Oracle 9i DBA Fund - II

By definition, the default behavior of an incremental backup behaves in this man-ner:

• A level n incremental backup in which n is greater than zero backs up eitherall blocks changed after the most recent backup at level n or lower.

To put this in plain English, consider these examples:

• A level 0 incremental backup backs up all datablocks that contain data orhave ever contained data.

• A level 1 incremental backup backs up all datablocks that have changedsince the last level 1 backup or the last level 0 backup, whichever was morerecent.

• A level 2 incremental backup backs up all datablocks that have changedsince the last level 2 backup, or the last level 1 backup, or the last level 0backup, whichever was more recent.

The same behavior is repeated throughout all eight incremental levels. Figure4-11 illustrates the concept of incremental backups that are performed throughouta single week using various incremental levels.

Figure 4-11: RMAN Incremental Backups

In this figure, incremental backups are performed daily. On Sunday, an incremen-tal level 0 backup is performed, which backs up all datablocks that have evercontained data. On Monday, an incremental level 3 backup is performed, whichbacks up all datablocks that have changed since the last level 3 or lower backupwas performed, as shown by the first arrow from the top. In this case, the lastincremental backup performed at level 3 or lower was the level 0 backup per-formed on Sunday, so the only blocks that were backed up were those thatchanged between Sunday and Monday.

RMAN Incremental Backups

246 Oracle9i Database: Fundamentals II

Page 262: Oracle 9i DBA Fund - II

On Tuesday, another incremental level 3 backup is performed, which again backsup all datablocks that have changed since the last level 3 or lower backup wasperformed. Except in this case, the last level 3 or lower backup was performed onMonday, so only the blocks that were changed between Monday and Tuesday areactually backed up, as indicated by the second arrow from the top.

On Wednesday, an incremental level 2 backup is performed, which backs up alldatablocks that have changed since the last level 2 or lower backup wasperformed. In this case, the last incremental backup performed at level 2 or lowerwas the level 0 backup performed on Sunday. All datablocks that changedbetween Sunday and Wednesday were backed up, as indicated by the third arrowfrom the top. This backup included datablocks that were also included in thebackups performed Monday and Tuesday.

On Thursday, an incremental level 3 backup is performed, which backs up alldatablocks that have changed since the last level 3 or lower backup wasperformed. In this case, the last incremental backup performed at level 3 or lowerwas the incremental level 2 backup performed on Wednesday. Another incremen-tal level 3 backup is performed on Friday, backing up all datablocks that havechanged since the level 3 backup on Thursday.

On Saturday, an incremental level 1 backup is performed, which backs up alldatablocks that have changed since the last level 1 or lower backup. In this case,the last incremental backup performed at level 1 or lower was the level 0 backupperformed on the previous Sunday. All datablocks that have changed since thatSunday are included in this backup, which includes datablocks that have beenbacked up one or more times throughout the week.

Finally, on Sunday, another incremental level 0 backup is performed, backing upall datablocks that have ever contained data. This new level 0 backup will serveas the baseline backup for the following week.

Restoring and Recovering From an Incremental BackupRestoring and recovering a database from an incremental backup is slightly dif-ferent than restoring and recovering from a standard backup. If media failurecauses the loss of a datafile, you would still issue the RESTORE and RECOVERcommands through RMAN, however RMAN takes some different steps. RMANwill first restore the datafile from the last incremental level 0 backup of thatdatafile, regardless of how long ago that was. Then it will apply the latest incre-mental 1 backup to that newly restored datafile, almost in the same fashion thatarchive logs are applied to the database. All datablocks that are found in the level1 backup are written to the restored datafile to replace the older version of theblocks. RMAN will then apply the latest incremental 2 backup to the datafile,then the latest increment level 3, and so on.

For our example in Figure 4-11, if media failure causes the loss of a datafile onFriday after Friday’s backup, the incremental level 0 backup from the first Sun-day is restored. RMAN will then attempt to apply the latest level 1 backup to thatnewly-restored datafile. Since no level 1 backup exists, RMAN will move to thelatest level 2 backup, which was performed on Wednesday. Since this level 2backup contains all the same datablocks that were backed up on Monday andTuesday, there is no need to restore those backups at all. After applying thechanges found in that backup, RMAN will apply the last two level 3 backups that

Lesson 4: Recovery Manager Backups 247

Page 263: Oracle 9i DBA Fund - II

were performed on Thursday and Friday. Once RMAN has applied all incremen-tal backups in order, RMAN will start applying any archive logs that weregenerated after the incremental level 3 backup on Friday. This entire process ismuch faster than trying to restore and apply all the archive logs since the level 0backup was performed.

It’s important to note that incremental backups really only save time during back-ups, but not during recoveries. While restoring incremental backups and applyingthem to the datafiles is faster than applying archive logs, RMAN must still restorethe level 0 backup from the backup set, then restore and apply all incrementalbackups from the last level 1 forward, then restore and apply all the archive logsgenerated since the latest backup. The total time for this operation will take aboutthe same as using standard backups and just using the archive logs for recovery.In reality, the only savings you gain is the amount of time it takes to perform theincremental backups, but incremental backups will not necessarily reduce yourmean time to recovery.

TASK 4C-3Perform Incremental Hot Backups using RMAN

Objective: To perform incremental hot backups using RMAN.

1. Before performing hot backups in true increments, you must first perform alevel 0 incremental hot backup.

Open a command prompt. Launch RMAN and connect with the follow-ing command:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

You will see RMAN launch and connect to both the target database and therecovery catalog.

2. Perform a level 0 incremental backup by issuing the following com-mand:

backup incremental level 0 database;

The output will show RMAN allocate a channel, determine which files toinclude in the backup set, back up the datafiles, then back up the control fileand spfile. A level 0 incremental hot backup is very similar to a basic fullhot backup. All the datafiles, with the exception of any datafiles specified by

248 Oracle9i Database: Fundamentals II

Page 264: Oracle 9i DBA Fund - II

the EXCLUDE parameter, are included in the backup set.

3. In the output, find the line that starts with the words “piece handle”. Thisline tells you the name of the file that was generated from this backup set.Make a note of the name of the file that was generated. In the exampleshown in step 2, the file name is ORA92_13_1.

Open a window to the D:\oracle\rman_bup folder.

In the rman_bup window, if you cannot see the sizes of the individual files,choose View→Details. The contents of the window will change to show thefull details of its files.

Find the file that was just generated from your level 0 backup. The sizeof the file, as shown in the Size column, should be relatively large. Asshown in the example here, the ORA92_13_1 file is 397,000 kilobytes.

4. A level 1 incremental hot backup will back up only the datablocks that havechanged since the last level 1 or level 0 hot backup. To show this, you willcreate a table in the USERS tablespace, which must modify datablocks. Onlymodified datablocks of this tablespace will actually be backed up.

Lesson 4: Recovery Manager Backups 249

Page 265: Oracle 9i DBA Fund - II

Leaving the rman_bup window open, launch SQL*Plus and log in as sys.

Create a table in the USERS tablespace by issuing the following com-mand:

CREATE TABLE test_inc (col1 NUMBER)TABLESPACE users;

Oracle will display the message “Table created.”

Exit from SQL*Plus.

5. Switch back to the RMAN window.

Perform an incremental level 1 hot backup of the database by issuingthe following command:

backup incremental level 1 database;

The output will look almost identical to that of the level 0 hot backup youjust performed. Although it looks as if RMAN is adding all the datafiles tothe backup set, it is really just examining the datafiles to determine if anyblocks have changed. RMAN will back up only those datablocks that have

250 Oracle9i Database: Fundamentals II

Page 266: Oracle 9i DBA Fund - II

changed since the last incremental hot backup at level 1 or below.

6. In the RMAN output, find the line that starts with the words “piecehandle” to determine the name of the file that was just generated. In theexample shown here, that file name is ORA92_15_1.

Switch to the rman_bup window. Find the file that was just generatedby your level 1 incremental backup. The size of this file should be muchsmaller than the file generated by your level 0 incremental backup in step 2.In the example shown here, the level 0 backup piece, file ORA92_13_1, is397,000 KB, while the level 1 backup piece, ORA92_15_1, is only 1,048KB. Only the datablocks that were modified by your CREATE TABLE com-mand in step 4 were included in the backup set, resulting in a much smallerbackup piece.

Incremental hot backups provide a way to drastically reduce the amount ofresources, including time and disk space, required to successfully back up acritical database.

7. Close the rman_bup window.

Lesson 4: Recovery Manager Backups 251

Page 267: Oracle 9i DBA Fund - II

Exit from both the RMAN utility and the command prompt.

Backing Up the Archive LogsRMAN provides the ability to back up the archive logs that are generated by atarget database. To back up archive logs, the BACKUP ARCHIVELOG commandis used, which accepts a filtering condition to choose which archive logs youwant to back up. You can specify a single archive log, a range of archive logs, orall archive logs generated by the database that are still in the file system. Therange of archive logs can specify date and time of generation, log sequence num-bers, SCN, or by file name pattern using the same type of character wildcardsused in the WHERE clause of SQL statements. You can also optionally include theDELETE ALL INPUT clause, which instructs RMAN to delete the backed uparchive logs from the file system after the backup operation is complete. The fol-lowing statements are examples of the BACKUP command to perform variousbackup operations on different sets of archive logs:

BACKUP ARCHIVELOG ALL;

BACKUP ARCHIVELOG ALL DELETE ALL INPUT;

BACKUP ARCHIVELOG FROM TIME 'SYSDATE-30' UNTIL TIME 'SYSDATE-7';

BACKUP ARCHIVELOG FROM SCN = 52456 DELETE ALL INPUT;

BACKUP ARCHIVELOG LIKE 'ARC0003%.001;

In the first example, all archive logs that the target database has generated andthat still reside on the file system are backed up. In the second example, allarchive logs are backed up and then deleted from the file system afterwards. Inthe third example, only archive logs between 30 days ago and 7 days ago arebacked up. In the fourth example, all archive logs that contain the specified SCNor higher are backed up and then deleted afterwards. In the final example, allarchive logs that match the specified pattern are backed up. If a BACKUPARCHIVELOG command executes but finds no logs that meet the specified filtercriteria, RMAN does not return any errors, but instead simply does not create abackup set, does not delete any files, and does not make any entries in therepository.

Archive logs can also be backed up during any other type of backup by includingthe PLUS ARCHIVE log option with the BACKUP command. For example, toback up the entire database along with all archive logs, then delete the archivelogs afterwards, you would issue the following command:

BACKUP DATABASE PLUS ARCHIVELOG DELETE INPUT;

Backing Up Archive Logs

252 Oracle9i Database: Fundamentals II

Page 268: Oracle 9i DBA Fund - II

TASK 4C-4Backing Up the Archive Logs

Objective: To back up the archive logs using RMAN.

1. Open a window to the D:\oracle\ora92\database\archive folder.

You should see a list of archive logs that have been generated by yourdatabase. You will use RMAN to back up these archive logs, and then deletethem from the system after the backup automatically.

2. Leaving the archive folder open, open a command prompt, and thenlaunch RMAN with the following command:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

RMAN will launch and connect to both the target database and the recoverycatalog.

3. At the RMAN prompt, back up and delete the archive logs by issuing thefollowing command:

backup archivelog all delete all input;

The output will show that RMAN archived the current redo log, then allo-cated a channel and generated a list of archive logs to include in the backup

The number of archive logsand their details on yoursystem may be different thanwhat is shown here.

The number of archive logsshown in the D:\oracle\ora92\database\archive folder maynot match the number ofarchive logs added to theRMAN backup set. This isbecause some of the archivelogs were rendered uselesswhen you opened thedatabase with theRESETLOGS option ear-lier in the course. RMANdetects this and excludesthe unneeded archive logsfrom the backup.

Lesson 4: Recovery Manager Backups 253

Page 269: Oracle 9i DBA Fund - II

set. RMAN then added each archive log to the backup set, and deleted thearchive logs from the file system.

4. Exit from RMAN and the command prompt.

In the database window, you will see that the backed up archive logs havebeen deleted from this folder. They were backed up by RMAN to theD:\oracle\rman_bup folder, and then removed from the file system. Anyarchive logs still in this folder are left over from an earlier ALTERDATABASE OPEN RESETLOGS command.

5. Delete all remaining archive logs from the database folder.

Close the database window.

Topic 4DRMAN Catalog Maintenance and ManagementSince the RMAN recovery catalog consists of basic tables within the database,RMAN provides the ability to store frequently used backup and recovery scriptsright in the catalog. Creating, maintaining, and executing stored scripts isextremely easy and can greatly reduce the maintenance overhead of managingthese scripts using other methods, such as in standard text files in the file system.

RMAN scripts are created and managed right from the RMAN prompt. To createa script, you would use the CREATE SCRIPT command, provide a script name,and list the script commands within a set of curly braces. You do not need to adda semicolon after the closing curly brace to terminate the command. The follow-ing example creates a stored script to perform a full hot backup of the targetdatabase:

RMAN> CREATE SCRIPT full_hot_backup2> {3> BACKUP DATABASE PLUS ARCHIVELOG;4> }

Creating an RMAN StoredScript

254 Oracle9i Database: Fundamentals II

Page 270: Oracle 9i DBA Fund - II

A useful feature of managing scripts with RMAN is that RMAN automaticallychecks the scripts for syntax errors at creation time. If RMAN finds a syntaxerror anywhere in the CREATE SCRIPT command, it will immediately return anerror and the script will not be created. Finding an error when the script is cre-ated is better than finding an error at execution time, especially if the script is torun unattended on a schedule.

To view the contents of a stored script from the RMAN prompt, you would usethe PRINT SCRIPT command and specify the script name. Unlike theCREATE SCRIPT command, this command does require the semicolon to indi-cate that the command is complete. The contents of the specified script will bedisplayed right from the RMAN prompt, as shown in this example:

RMAN> PRINT SCRIPT full_hot_backup;

printing stored script: full_hot_backup{BACKUP DATABASE PLUS ARCHIVELOG;}

If you need to change a script that is already stored in the catalog, you would usethe REPLACE SCRIPT command and include the script’s full syntax just as youwould if you were creating a new script, as shown in the following example:

RMAN> REPLACE SCRIPT full_hot_backup2> {3> BACKUP DATABASE PLUS ARCHIVELOG DELETE ALL INPUT;4> }

In this example, the full_hot_backup script that was already stored in the recov-ery catalog was replaced with a new set of commands.

To delete a stored script, you would use the DELETE SCRIPT command andspecify the name of the script you would like to delete, along with a terminatingsemicolon. You must be very careful with this command; once executed, thespecified script is deleted immediately without further prompting from the DBA,and there is no way to roll back the operation. The following example deletes thefull_hot_backup script:

RMAN> DELETE SCRIPT full_hot_backup;

deleted script: full_hot_backup

To execute a script from the RMAN prompt, you would issue the RUN commandwith a set of curly braces, within which you would include the EXECUTESCRIPT command. The following command will execute the full_hot_backupscript:

RMAN> RUN {EXECUTE SCRIPT full_hot_backup;}

The RUN command is extremely flexible. You can include any number of com-mands within its curly braces, such as several backup commands, and evenexecuting several stored scripts in succession.

When managing scripts from the RMAN prompt, RMAN simply adds, modifies,and deletes the scripts within tables in the recovery catalog. As such, RMAN pro-vides two recovery catalog-related views that can be used to view RMAN storedscripts using standard SQL statements. The RC_STORED_SCRIPT view providesthe complete list of scripts that are stored within the catalog, and theRC_STORED_SCRIPT_LINE provides a complete line-by-line listing of each

Displaying an RMANStored Script

Replacing an RMAN StoredScript

Lesson 4: Recovery Manager Backups 255

Page 271: Oracle 9i DBA Fund - II

script. When querying from these views, it’s important to remember that thename of the script is case sensitive and will be stored in the exact case you usedin the CREATE SCRIPT command. The following example shows a query to theRC_STORED_SCRIPT line to bring up a list of all stored scripts in the recoverycatalog:

SQL> SELECT script_name2 FROM rc_stored_script3 ORDER BY script_name;

SCRIPT_NAME------------------------------------------------backup_archive_logsbackup_control_filefull_cold_backupfull_hot_backup

SQL>

The following example shows a query to the RC_STORED_SCRIPT_LINE viewto bring up the contents of the full_hot_backup script:

SQL> SELECT text2 FROM rc_stored_script_line3 WHERE script_name='full_hot_backup';

TEXT-----------------------------------------------------{BACKUP DATABASE PLUS ARCHIVELOG DELETE ALL INPUT;}

SQL>

It’s important to note that a stored script is only valid for the target database youare currently connected to. In other words, if RMAN is connected to the ORA92database as the target, and you execute the CREATE SCRIPT command, thescript you create can only be run against the ORA92 database. However, becauseRMAN scripts are stored in tables within RMAN’s schema, it is very easy to addor reassign RMAN scripts for other databases using basic SQL commands againstthe RC_STORED_SCRIPT and RC_STORED_SCRIPT_LINE views from theSQL*Plus prompt.

TASK 4D-1Creating, Using, and Managing RMAN Scripts

Objective: To create, use, and manage RMAN scripts to simplify databasebackups.

1. You will create an RMAN script to perform a full, hot backup of thedatabase. The script will be stored in the recovery catalog.

Open a command prompt, and launch RMAN with the following com-mand:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

256 Oracle9i Database: Fundamentals II

Page 272: Oracle 9i DBA Fund - II

RMAN will launch and connect to both the target database and the recoverycatalog.

2. Your RMAN script will be named full_hot_backup, and will only back upthe database. Since all the essential configuration parameters are already set,your script only needs to contain the BACKUP DATABASE command.

At the RMAN prompt, create the full_hot_backup script by issuing thefollowing command:

create script full_hot_backup{BACKUP DATABASE;}

RMAN will display the message “created script full_hot_backup.” The scriptis now stored in the recovery catalog and can be viewed through theRC_STORED_SCRIPT and RC_STORED_SCRIPT_LINE views.

3. To see the contents of any RMAN script, you would issue the PRINTSCRIPT command.

At the prompt, type print script full_hot_backup; and press Enter.

The output will show the contents of the full_hot_backup script.

4. After looking at the script, you decide that you want the script to also backup the archive logs, then delete them from the file system afterwards. Youalso want to tag the backup set for easy identification later. To change thescript, you would use the REPLACE SCRIPT command.

Lesson 4: Recovery Manager Backups 257

Page 273: Oracle 9i DBA Fund - II

At the prompt, issue the following command:

replace script full_hot_backup{BACKUP TAG test_scriptDATABASE PLUS ARCHIVELOG DELETE ALL INPUT;}

RMAN will display the message “replaced script full_hot_backup.”

5. To see the changed content of your script, type print script full_hot_backup; and press Enter.

The output will show the new content of your script.

6. To execute a stored RMAN script, you would issue the RUN command, andenclose the EXECUTE SCRIPT command, and the script name, inside a setof brackets.

Execute your full_hot_backup script by issuing the following command:

run {execute script full_hot_backup;}

You will see RMAN execute the full hot backup as specified in the script.The backup will include all datafiles except those specified by the EXCLUDEparameter, the archive logs, the control file, and the spfile. Additionally, allarchive logs will be deleted from the file system after they are backed up.

258 Oracle9i Database: Fundamentals II

Page 274: Oracle 9i DBA Fund - II

7. You have decided that you no longer need the full_hot_backup script. Youwill delete it using the DELETE SCRIPT command.

At the prompt, type delete script full_hot_backup; and press Enter.

RMAN will display the message “deleted script: full_hot_backup.”

8. Exit from RMAN and the command prompt.

RMAN Reports and ListsRMAN provides a powerful reporting and listing capability that can be executedright from the RMAN prompt. All information displayed in RMAN reports andlists come directly from the recovery catalog. The LIST command is used to pro-vide various lists of backups based on the backup history of the target database,while the REPORT command is used to display information on just about every-thing else that RMAN knows about the target database, such as the current layoutof the database, datafiles that need to be backed up, and so on.

The REPORT CommandThere are four main options that can be used with the REPORT command, whichare listed in the following table.

Option DescriptionSCHEMA Reports on the layout of the target database, such as datafile names

and locations and their sizes.UNRECOVERABLE Provides a report on the datafiles that have had unrecoverable

operations perform on their contents, such as tables that have theNOLOGGING attribute set.

NEED BACKUP Provides a report about the datafiles that need to be backed up tomaintain the backup retention or redundancy policy set by the DBA.

OBSOLETE Reports on the database and archive log backups that can be deletedbecause they have passed their retention or redundancy policy set bythe DBA.

The SCHEMA option can be used to report on the current layout of the targetdatabase or the layout of the target at a specified point in time. You can specifyan alternate point in time with the AT clause along with a date and time string, aspecific SCN, or a log sequence number. Consider the following examples:

REPORT SCHEMA;

REPORT SCHEMA AT TIME '15-JAN-2003 08:00:00';

REPORT SCHEMA AT SCN=45614;

REPORT SCHEMA AT SEQUENCE=15 THREAD=1;

The REPORT CommandOptions

Lesson 4: Recovery Manager Backups 259

Page 275: Oracle 9i DBA Fund - II

In the first example, the REPORT SCHEMA command generates a report based onthe current layout of the target database. In the second example, the commandgenerates a report based on how the layout of the database looked on January 15,2003 at 8:00 A.M. The third command generates a report based on how the lay-out of the database looked at change number 45614, while the last commandgenerates a report on how the database looked when redo log sequence 15 wasfirst opened. Specifying an alternate point in time with the REPORT SCHEMAcommand can provide valuable information if you need to determine when thelayout of the target database had changed.

The UNRECOVERABLE option generates a list of datafiles that have had unrecov-erable operations performed against their contents. For example, let’s say theTOOLS tablespace contains a table that has its logging attribute set toNOLOGGING. Since no DML operation against this table will generate redo infor-mation, the datafiles of the TOOLS tablespace will have changes to data thatcannot be recovered using archive logs. The REPORT UNRECOVERABLE com-mand can be used to determine which datafiles are affected. The DBA can eitherdecide to enable logging for objects in those tablespaces or to back up thosedatafiles more frequently.

The NEED BACKUP option is used to generate a report of datafiles that needbacking up to maintain the retention policy set by the DBA. For example, if theDBA has set a backup retention policy of seven days using the CONFIGUREcommand, the REPORT NEED BACKUP command will report on the datafilesthat need to be backed up because they currently require more than seven day’sworth of archive logs if the current backup copy were restored. Creating newbackups of those datafiles will result in fewer archive logs that need to be appliedif the live datafiles were restored from the new backups. The OBSOLETE optionis used to generate a report of datafiles that can be deleted because they are nolonger needed to satisfy the retention or redundancy policy set by the DBA.

The LIST CommandThe LIST command is used to generate lists of backups that have been per-formed for the target database and to list each incarnation of the target database,which indicates each time the RESETLOGS option has been used with theALTER DATABASE OPEN command.

To generate a list of backups that have been performed for the target database,you would simply include the BACKUP option with the LIST command. TheLIST BACKUP command by itself will instruct RMAN to generate a full list ofall known backups for the target database, which will include all datafiles, controlfiles, archive logs, and spfiles. To filter the output, you can specify the type ofbackup you wish to list with the BACKUP option. The following types of backupscan be listed with the LIST BACKUP command:

• TABLESPACE

• DATAFILE

• CONTROLFILE

• SPFILE

• ARCHIVELOG

The TABLESPACE option allows you to specify a single tablespace that youwant to generate your list for. The list will include all backups of any datafilesthat make up the specified tablespace. The following command will list all back-ups of the SYSTEM tablespace:

LIST BACKUP OF TABLESPACE system;

The LIST BACKUPCommand Options

260 Oracle9i Database: Fundamentals II

Page 276: Oracle 9i DBA Fund - II

You can also generate a list of a specific backup by including the TAG clausewith the LIST BACKUP command. This will generate a list of any backups withthe specified tag and will show all files included in each backup. The followingcommand lists all backups with the tag 'full_nightly':

LIST BACKUP TAG 'full_nightly';

When listing all backups of a single datafile, you would specify the current fullpath and file name for that datafile. RMAN will list all backups for that datafile,even if the file had been moved or renamed during its lifetime. The followingcommand will list all backups of the SYSTEM01.DBF datafile, currently found inthe D:\oracle\oradata\ora92 folder:

LIST BACKUP OF DATAFILE 'D:\oracle\oradata\ora92\system01.dbf';

The CONTROLFILE option will display a list of all backups of the control file,regardless if the backup was performed by itself, included with a full databasebackup, or by the control file autobackup feature. The same logic is applied to theSPFILE option. With this option, all backups of the SPFILE will be listed,regardless of whether the backups were performed manually or automatically. Thefollowing two commands will list all control file and spfile backups, respectively:

LIST BACKUP OF CONTROLFILE;

LIST BACKUP OF SPFILE;

The COPY option will generate a list for all image copies that have been createdfor the target database. When used alone, the LIST COPY command will gener-ate a list that includes image copies of all file types, including datafiles, controlfiles, and archive logs. To filter the output, you can specify the file type with theLIST COPY command, as shown in the following examples:

LIST COPY OF DATAFILE 'D:\oracle\oradata\ora92\system01.dbf';

LIST COPY OF ARCHIVELOG ALL;

LIST COPY OF CONTROLFILE;

The LIST ARCHIVELOG command is used to list backups of archive logs andcan include a filter to specify a single archive log, a range of archive logs, a filename pattern, or all archive logs. This option accepts same filtering logic that canbe used for archive log backups. The following command lists backups of archivelogs using different filters:

LIST BACKUP OF ARCHIVELOG ALL;

LIST BACKUP OF ARCHIVELOG LIKE'D:\oracle\oradata\oraarch\ora_0003%.arc';

LIST BACKUP OF ARCHIVELOG FROM SEQUENCE=15;

The LIST INCARNATION command will generate a list of all known incarna-tions of all databases with entries in the recovery catalog. This list will show youthe date, time, the reset SCN for each time a database has been opened with theRESETLOGS option. To filter the output to a single database, you can specify thedatabase name using the OF DATABASE clause, as shown in this example, whichwill list only the incarnations for the ORA92 database:

LIST INCARNATION OF DATABASE 'ora92';

Lesson 4: Recovery Manager Backups 261

Page 277: Oracle 9i DBA Fund - II

TASK 4D-2Generate RMAN Reports and Lists

Objective: To generate RMAN reports and lists to extract backup infor-mation from the recovery catalog.

1. Open a command prompt, then launch RMAN with the following com-mand:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

RMAN will launch and connect to both the target database and recoverycatalog.

2. To see a report of the current layout of the database, type report schema;and press Enter.

The output will show a list of datafiles that currently exist in the ORA92database. This information is very important when designing a backup andrecovery strategy for your database.

3. To generate a list of all backups of all files generated by RMAN for the tar-get database, type list backup; and press Enter.

RMAN will generate a long list of backups that were generated. This listwill include all files that were backed up, including datafiles, control files,The output may be so long

that it will scroll up beyondthe maximum limit of the

command prompt, and youmay not be able to see all of

it. This is normal.

262 Oracle9i Database: Fundamentals II

Page 278: Oracle 9i DBA Fund - II

archive logs, and the spfile. You may have to scroll up to see all of theoutput.

4. Since the LIST BACKUP command alone may generate more informationthan can be easily read, you can filter the output based on the type of filebacked up.

To see a list of backed up datafiles only, type list backup of database; andpress Enter.

The output will show a list of all backup copies of the datafiles, but will notinclude control files, archive logs, or the spfile.

5. To generate a list of backups of just the control file, type list backup ofcontrolfile; and press Enter.

Lesson 4: Recovery Manager Backups 263

Page 279: Oracle 9i DBA Fund - II

The output will show a list of backup copies of the control file only.

6. To generate a list of archive logs that have been backed up, type list backupof archivelog all; and press Enter.

The output will show only information about backup copies of archive logsand which backup sets they belong to.

7. To generate a list of backups created as image copies, type list copy; andpress Enter.

The output will show only information about image copies that were gener-ated by RMAN.

8. Earlier in this lesson, you generated an RMAN script to perform a full, hotbackup of the database. In that script, you specified a tag name for thatbackup set, called test_script. You can generate a list of backup sets by theirtag name.

At the prompt, type list backup tag test_script; and press Enter.

264 Oracle9i Database: Fundamentals II

Page 280: Oracle 9i DBA Fund - II

The output will show all the information about the backup set that was gen-erated from your RMAN script. The backup set was easily identified by thetag test_script.

9. RMAN uses the RETENTION POLICY configuration parameter to deter-mine which datafiles are in need of backing up and which backups are nolonger needed for recovery.

To determine the current retention policy for the target database, type showretention policy; and press Enter.

The output will show that the current retention policy is set to 1, whichmeans that RMAN is configured to maintain exactly one backup copy of allcritical database files. To comply with the retention policy, any backup cop-ies other than the most current one will be considered obsolete. Also, anyfiles that have not been backed up, or files whose last backup is older thanthe current full backup, will be considered in need of a backup.

10. To determine which datafiles are in need of backing up to comply with theretention policy, type report need backup; and press Enter.

The output will show that the EXAMPLE01.DBF datafile is in need ofbackup. This file has been excluded from all backups, as specified by theEXCLUDE parameter. Because of this, the file is in need of backup to com-ply with the retention policy.

11. To determine which backups are obsolete and can be deleted, type reportobsolete; and press Enter.

Lesson 4: Recovery Manager Backups 265

Page 281: Oracle 9i DBA Fund - II

The output will show a list of backup sets and backed up control files thatare no longer necessary to comply with the retention policy. You may haveto scroll up to see all of the output. These files can be deleted and purgedfrom the recovery catalog. You will learn how to do this in the next task.

12. Exit from RMAN and the command prompt.

Crosscheck and Delete Backup SetsOver time, the backup entries in the recovery catalog may differ slightly thanwhat is actually stored on disk or on backup tape. This may be caused by olderbackup files being manually deleted with OS-level commands, backup tapes beingoverwritten by the media manager, or by media failure where the backup filesreside. To help keep the recovery catalog up to date and purge old entries,RMAN provides the CROSSCHECK command to identify backup entries that areno longer valid.

The CROSSCHECK command only executes against backup entries for the currenttarget database, and can be used to validate any type of backup that can be cre-ated with the BACKUP or COPY commands, as shown in the following examples:

CROSSCHECK BACKUP;

CROSSCHECK BACKUP OF CONTROLFILE;

CROSSCHECK BACKUP OF TABLESPACE system;

CROSSCHECK BACKUP OF DATAFILE'D:\oracle\oradata\ora92\tools01.dbf';

CROSSCHECK COPY OF CONTROLFILE;

CROSSCHECK COPY OF DATAFILE'D:\oracle\oradata\ora92\tools01.dbf';

In the first example, all backups of all types for the target database are validatedagainst the actual backup files that exist in their backup locations. The secondexample crosschecks all backups of the control file. The third examplecrosschecks all backups of the system tablespace, while the fourth examplecrosschecks a single datafile. The last two examples crosscheck image copies ofthe control file and a single datafile, respectively.

crosscheck:A process of validating

recovery catalog entriesagainst the backup files that

actually exist in the filesystem.

Crosschecking Backupsand Copies

266 Oracle9i Database: Fundamentals II

Page 282: Oracle 9i DBA Fund - II

You can also specify specific backups with the CROSSCHECK command, such asby tag, by backup set number, or backup piece number. This allows you to iden-tify a single backup entry in the recovery catalog if you need to. Some examplesof these crosschecks are shown here:

CROSSCHECK BACKUP TAG full_weekly;

CROSSCHECK BACKUPSET 433,434,435,436;

CROSSCHECK BACKUPPIECE 887,888,889;

In the first example, RMAN will crosscheck all backups with the tag full_weekly.In the second example, backup sets with the ID numbers listed will becrosschecked. When crosschecking complete backup sets, all backup pieceswithin each set are automatically crosschecked. In the last example, only specificbackup pieces are crosschecked.

When RMAN crosschecks a backup or image copy, it will compare its entries inthe recovery catalog to the list of files that actually exist in the file system. If anyof the files are not found on the file system, the related entries are marked asEXPIRED in the recovery catalog. RMAN will not consider any expired backupsor image copies as valid backups for restore and recovery operations in the eventof a media failure.

After executing the CROSSCHECK command, you can issue the LIST EXPIREDcommand, which will generate a list of all expired backups in the recoverycatalog. The DELETE EXPIRED command can be executed to purge all expiredbackup entries from the recovery catalog. This command does not delete any filesfrom the file system.

Delete Existing and Obsolete BackupsWhile the CROSSCHECK command together with the DELETE EXPIRED com-mand can identify backup entries in the recovery catalog for which the physicalbackup files no longer exist, the DELETE command, with other appropriateoptions, can be used to delete valid backups, including the physical files in thebackup locations and all recovery catalog entries. Any backup that can be createdwith the BACKUP and COPY commands can be deleted with the DELETE com-mand, as shown in the following examples:

DELETE BACKUP;

DELETE BACKUP OF TABLESPACE system;

DELETE BACKUP OF DATAFILE 'D:\oracle\oradata\ora92\system01.dbf';

DELETE BACKUP TAG full_weekly;

DELETE BACKUPSET 364,383,838;

DELETE COPY OF DATAFILE 'D:\oracle\oradata\ora92\example01.dbf';

The first example is actually a very powerful one. All backups for the currenttarget database will be deleted, regardless of the file type of the backup, includingdatafiles, control files, archive logs, and spfiles. The second example deletes allbackups for the SYSTEM tablespace, while the third example deletes all backupsof only a single datafile. The fourth example deletes all backups with the tagfull_weekly, while the fifth example deletes all listed backup sets. The finalexample deletes all image copies of the EXAMPLE01.DBF datafile.

Deleting Backups andCopies

Lesson 4: Recovery Manager Backups 267

Page 283: Oracle 9i DBA Fund - II

When executing the DELETE BACKUP or DELETE COPY commands, RMANwill first list all backups it has found in the recovery catalog that meet the crite-ria, then prompt the DBA for confirmation before actually proceeding with theoperation. When deleting the recovery catalog entries and backup files, if anyrecovery catalog entries are found that do not have corresponding backup files onthe file system, the entries are deleted without error. Any backup files that do nothave a valid entry in the recovery catalog are ignored, because RMAN has noway of knowing what those files are.

If you need to remove the entries about a backup from the recovery catalog, butyou want to retain the backup files, then you have two options. You can move orrename the files then use the DELETE command to purge the catalog entries. Theother option is to use the CHANGE command with the UNCATALOG option. Thiscommand can be used to delete recovery catalog entries while ignoring the corre-sponding files in the backup locations. The following example illustrates the useof this command:

CHANGE BACKUPSET 832 UNCATALOG;

In this example, the recovery catalog entries for backup set 832 will be purgedfrom the catalog. The backup pieces that make up this backup set, however, willbe left untouched where they are stored. This provides the DBA a convenientway of cleaning up the recovery catalog even if the backup files must be kept forany reason.

If the DBA has configured a retention policy for backups with the CONFIGURERETENTION POLICY, then the REPORT OBSOLETE command can be used togenerate a report of all backups that can be deleted because they are no longerneeded to comply with the retention policy. For example, if the retention policy isset to a redundancy of three backups per datafile, the REPORT OBSOLETE com-mand will report on any backup that is no longer needed since three backups forthat datafile already exist that are more recent. The DELETE OBSOLETE com-mand can be used to delete all obsolete backups in the recovery catalog. Thiscommand will purge all recovery catalog entries as well as remove their relatedbackup files from the backup locations.

To make a specific backup exempt from the retention policy, you can use theCHANGE...KEEP command, as shown in the following example:

CHANGE BACKUPSET 243 KEEP;

In this example, the backup set with ID number 243 will be exempt from theretention policy, meaning that the REPORT OBSOLETE and DELETEOBSOLETE will not consider this backup as obsolete, even if its existence defiesthe retention policy. To make a backup comply with the retention policy, youwould use the UNKEEP option with the CHANGE command, as shown in thisexample:

CHANGE BACKUPSET 243 UNKEEP;

268 Oracle9i Database: Fundamentals II

Page 284: Oracle 9i DBA Fund - II

TASK 4D-3Crosschecking and Deleting Backup Sets

Objective: To crosscheck backup sets against the recovery catalog anddelete expired and obsolete backups.

1. You will first delete a backup set from the file system manually, and thenupdate the recovery catalog using the CROSSCHECK and DELETEcommands.

Open a window to the D:\oracle\rman_bup folder.

Find the backup set file with the highest backup set ID. The backup setID is indicated by the number immediately following the database nameORA92. In the example shown here, that file is ORA92_21_1.

Select the backup file with the highest backup set ID and pressShift+Delete. A question box will appear asking if you are sure you want todelete the file. Click Yes.

2. Leaving the rman_bup window open, open a command prompt, and thenlaunch RMAN with the following command:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

RMAN will launch and connect to both the target database and recoverycatalog.

3. To validate the backup entries in the recovery catalog, type crosscheckbackup; and press Enter.

You will see RMAN allocate a channel, then compare each backup entry inthe recovery catalog against what actually exists on disk. Towards the end ofthe output, you will see that the file you deleted could not be found on the

Your results will varydepending on the number ofarchive logs.

Lesson 4: Recovery Manager Backups 269

Page 285: Oracle 9i DBA Fund - II

disk, and was therefore marked as EXPIRED in the recovery catalog.

4. Since the backup set is no longer available on disk, the related entries forthat backup set in the recovery catalog can be purged.

At the prompt, type delete expired backup; and press Enter.

RMAN will allocate a channel, display a list of entries found to be expiredin the recovery catalog, and then ask you if you really want to delete thelisted objects. Type YES and press Enter.

The output will show that the expired backup was deleted, which means thatthe recovery catalog entries related to the expired backup set were purgedfrom the catalog.

5. Obsolete backups are backups that are no longer needed according to theconfigured retention policy.

To see a list of obsolete backups, type report obsolete; and press Enter.

270 Oracle9i Database: Fundamentals II

Page 286: Oracle 9i DBA Fund - II

The output will show a list of all backup copies that are no longer necessaryas determined by the retention policy.

6. The DELETE OBSOLETE command will automatically purge all obsoletebackup entries from the recovery catalog and remove the related files fromdisk, if they exist.

At the prompt, type delete obsolete; and press Enter.

The output will show a list of files that RMAN has determined are obsolete,and asks if you really want to delete the objects. Type YES and pressEnter.

Lesson 4: Recovery Manager Backups 271

Page 287: Oracle 9i DBA Fund - II

You will see RMAN allocate a channel, then delete each obsolete backup.

7. Switch back to the rman_bup window.

You will see that the folder contains only a few files. One of these files isthe current backup of the control file. The other files contain a complete setof backed up datafiles and archive logs that would be required to perform acomplete recovery in the event of a failure. RMAN had deleted all otherbackup sets, which were no longer needed according to the retention policy.

8. Close the rman_bup window.

Exit from both RMAN and the command prompt.

Catalog OS-level Database BackupsIf a user-managed database backup was performed using the ALTERTABLESPACE...BEGIN BACKUP and standard OS-level copy commands,these backups can still be cataloged in RMAN’s recovery catalog. This lets theDBA take advantage of many of RMAN’s capabilities, even if RMAN did not

272 Oracle9i Database: Fundamentals II

Page 288: Oracle 9i DBA Fund - II

create the backup. To generate catalog entries for a user-managed backup, youwould use the CATALOG command and specify the full path and name of the fileto catalog. This command can be used to catalog image copies of datafiles, con-trol files, and archive logs. The CATALOG command accepts three differentoptions, DATAFILECOPY, CONTROLFILECOPY, or ARCHIVELOG. You canspecify multiple files of the same type to catalog within a single command, butyou cannot mix file types within a single command. If you need to catalog differ-ent file types, you must list each type of file with separate CATALOG commands.

Since only RMAN can create its own proprietary backup sets with backup pieces,the CATALOG command can only generate catalog entries for image copies offiles created by OS-level commands. Additionally, you can only catalog backupfiles that were generated by the target database you are currently connected to.This is because RMAN will associate the newly-cataloged backup files with thecurrent target database. If you attempt to catalog a backup file that originatedfrom a different database, RMAN will return an error. The following examplesillustrate the use of the CATALOG command:

CATALOG DATAFILECOPY 'D:\oracle\hot_bup\system01.dbf';

CATALOG CONTROLFILECOPY 'D:\oracle\hot_bup\control.bak';

CATALOG ARCHIVELOG'D:\oracle\oradata\ora92\archive\ARC_0003.ARC';

Once the information about manually created backups have been cataloged in therecovery catalog, RMAN can immediately consider those backup files as candi-dates for restore if necessary.

TASK 4D-4Cataloging OS-level Database Backups

Objective: To catalog database backups that were performed through OScommands with the recovery catalog.

1. Earlier in the course, you had performed a user-managed full cold backup ofthe database and stored the backed up files in the D:\oracle\cold_bup folder.Open a window to the D:\oracle\cold_bup folder.

These files were created through the use of standard operating system com-mands and are not currently listed in the recovery catalog. You will useRMAN to create entries for some of these files in the recovery catalog so thebackup can be restored by RMAN if necessary.

Close the cold_bup window.

2. Open a command prompt, and launch RMAN with the following com-mand:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

RMAN will launch and connect to both the target database and recoverycatalog.

3. To generate a list of image copies currently registered in the recovery cata-log, type list copy of database; and press Enter.

The CATALOG Command

Lesson 4: Recovery Manager Backups 273

Page 289: Oracle 9i DBA Fund - II

No image copies are currently registered in the recovery catalog, thereforeRMAN will not return any output.

4. Register the backup copies of the SYSTEM, USERS, and TOOLSdatafiles with the following commands:

catalog datafilecopy 'D:\oracle\cold_bup\system01.dbf';catalog datafilecopy 'D:\oracle\cold_bup\users01.dbf';catalog datafilecopy 'D:\oracle\cold_bup\tools01.dbf';

After each datafile, RMAN will return the message “cataloged datafile copy”and display the file name, record id, and a stamp ID to uniquely identify thefile in the recovery catalog.

5. To confirm that the backup files have been registered with the recovery cata-log, type list copy of database; and press Enter.

The output will show that you have successfully cataloged the datafiles ofthe SYSTEM, USERS, and TOOLS tablespaces with the recovery catalog. Ifthe need arises, RMAN will be able to locate, restore, and recover thesebackup datafiles in the event of a disk failure or file corruption.

6. Exit from both RMAN and the command prompt.

While in this activity you areonly cataloging some of thefiles of a cold backup, you

must remember that all filesof a cold backup must be

available in order to recoverand restore the database with

that backup, including thedatafiles and the control file.

274 Oracle9i Database: Fundamentals II

Page 290: Oracle 9i DBA Fund - II

Backup and Restore ValidationNo backup and recovery strategy is complete without testing the capabilities andsoundness of its routines. RMAN provides a feature to validate its backup andrestore capabilities. This is done by including the VALIDATE option with thespecific BACKUP or RESTORE command you wish to test. This option can beincluded with any backup or restore operation RMAN can perform, as shown inthe following examples:

BACKUP VALIDATE DATABASE;

RESTORE VALIDATE DATABASE;

When validating a backup or restore operation, RMAN does not actually performthe operation. Instead, RMAN acts out the process, but does not generate backupsets, restore datafiles, nor make entries in the recovery catalog. It simply checksfor file existence and availability of channel resources. For example, let’s say youissued the following command:

BACKUP VALIDATE TABLESPACE system;

RMAN will act out the process of backing up the SYSTEM tablespace, but willnot actually do so. It will simply allocate the channel, ensure that the SYSTEMtablespace exists in the target database, locate its files, then attempt to reach thebackup destination. If RMAN encounters any errors during the process, such asnot being able to reach the backup destination because of an invalid configura-tion, RMAN will report the errors.

During a restore validation, RMAN will attempt to find a valid backup that existsin its backup location and act out the process of restoring the file without actuallydoing so. RMAN will immediately terminate the operation if any part of the vali-dation fails, such as not finding a valid backup for the specified target. Forexample, let’s say you issued the following command:

RESTORE VALIDATE TABLESPACE sales;

If no SALES tablespace exists in the target database, or if the tablespace existsbut has never been backed up, RMAN will return an error. The VALIDATE fea-ture can be extremely useful if you need to determine whether or not your backupand recovery strategy is sound and will work when necessary.

TASK 4D-5Validate Backup and Restore Operations

Objective: To ensure that a specified backup or restore operation can suc-ceed as expected.

1. You will perform validation checks to ensure that the database can bebacked up and restored using the existing RMAN configuration.

Open a command prompt and launch RMAN with the following com-mand:

rman target rman/buprec@ora92 rcvcat rman/buprec@ora92

RMAN will launch and connect to both the target database and the recoverycatalog.

Backup and RestoreValidation

Lesson 4: Recovery Manager Backups 275

Page 291: Oracle 9i DBA Fund - II

2. At the RMAN prompt, type backup validate database; and press Enter.

The output will look very similar to a standard backup, except RMAN doesnot actually perform the backup. RMAN acts out the backup process butdoes not generate a backup set, nor does it record any information to therecovery catalog. If any issues are found during the process, such as a chan-nel configuration for a backup tape that does not exist, messages would beincluded in the output to provide information about the issues.

3. Once the backup validation is complete, type restore validate database; andpress Enter.

The output will show that RMAN starts the validation of the datafile backupset, and acts out a full restore of the database using the latest full backup. Ifany issues are found during the process, messages would be included in theoutput to provide information about the issues. In this case, RMAN hasreported that there is no backup or image copy of datafile 5 found to restore.This is because the EXAMPLE01.DBF datafile has been excluded from alldatabase backups. This information could be critical when determining if thecurrent database backups are sufficient to recover from a major failure.

4. Exit from both RMAN and the command prompt.

Close all open windows.

276 Oracle9i Database: Fundamentals II

Page 292: Oracle 9i DBA Fund - II

Backing Up the Recovery CatalogBecause the RMAN recovery catalog exists in a standard schema within anOracle database, you should take sufficient measures to safeguard the databaseagainst failures. If the database where the recovery catalog is lost, you will not beable to use RMAN or its backups to restore or recover any database that RMANsupports. However, backing up the recovery catalog poses an interestingchallenge.

If you use RMAN with the recovery catalog to back up the recovery catalog data-base, and the recovery catalog database subsequently suffered media failure, youwould not be able to restore the database from the backup you generated. This isbecause RMAN would need to log in to the recovery catalog to restore thebackup, but the recovery catalog would not be available because the database isdown. To avoid this paradox, there are multiple techniques that you could use tocreate a valid backup of the recovery catalog database that you could actuallyrestore from.

Since the recovery catalog database itself is just like any other Oracle database,stored inside an Oracle database, any backup method could be used to back upthis database. However, the key to this scenario is not the backup of the database,but the ability to restore the database using whatever backup you create. Youcould use the Oracle export utility to export the recovery catalog on a regularbasis, or you could use manually scripted hot backups. However, these solutionsultimately defeat the purpose of using RMAN in the first place, which is to sim-plify and improve the backup and recovery process for all Oracle databases in anenvironment.

One technique is to set up two or more RMAN recovery catalogs in differentdatabases. With this configuration, each recovery catalog can share the load ofbacking up the databases in the environment, and also each recovery catalog canbe used to back up the other. Figure 4-12 illustrates this concept.

Figure 4-12: Using multiple RMAN recovery catalogs to perform backups.

Multiple Recovery Catalogsfor Cross-backups

Lesson 4: Recovery Manager Backups 277

Page 293: Oracle 9i DBA Fund - II

In this figure, two RMAN recovery catalogs have been configured. Each recoverycatalog acts as the RMAN repository for half of the databases in the environment.Additionally, each catalog is used to back up the other. If media failure causes theloss of one catalog, the other RMAN configuration can be used to restore andrecover it.

While this configuration may be ideal for larger environments, it may not be aviable solution for smaller environments. There may not be enough target data-bases that need backing up to justify the cost of setting up to independent servers,each with its own RMAN configuration. Another solution is to use the RMANutility to perform the backups, but use the control file of the database where therecovery catalog resides as the RMAN repository for that one database. In addi-tion, you would use RMAN to create image copies of the database’s datafiles,rather than RMAN backup sets. Using this technique, RMAN can still be used toback up the database, but if some sort of failure causes the database to becomeunavailable, you will not be dependent on the recovery catalog to restore it. Addi-tionally, if the recovery catalog database uses its control file, you will be able touse RMAN to perform the recovery since its repository is gone. However, sinceyou backed up the database using image copies, you can simply use OS-levelcommands to restore the control file and any other datafiles that were lost. Figure4-13 illustrates this technique of backing up the recovery catalog database.

Figure 4-13: Using RMAN to back up a single recovery catalog database.

In this figure, a single RMAN configuration is being used to back up all the criti-cal Oracle databases in the environment, using the recovery catalog as therepository. However, for the backup of the recovery catalog database itself, thedatabase’s control file is used as the RMAN repository, and image copies are cre-ated from the database’s datafiles, control file, and archive logs. Using thistechnique, the recovery catalog database can be restored from most mediafailures. If a datafile is lost, RMAN can restore the datafile from the image copywhile using the control file as the repository. If the control file is lost, you cannotuse RMAN to restore it since the repository is also lost, but you can restore thecontrol file manually since it is just an image copy. Once the control file isrestored, you can continue with the recovery manually, or you can optionallyswitch back to RMAN to perform the recovery.

Backing Up a SingleRecovery Catalog

278 Oracle9i Database: Fundamentals II

Page 294: Oracle 9i DBA Fund - II

TASK 4D-6List and Describe Methods to Back Up the RecoveryCatalog

1. You have created a database that will house the RMAN recoverycatalog. This database will also house the repositories for Oracle Enter-prise Manager and several of its add-on components, such as thePerformance Manager, the Change Manager, and Oracle Expert. Discusssome of the ways that this database could be backed up, and identify themethod that you think would work best.

Because the database itself is just like any other Oracle database, anybackup method could be used to back up this database. However, the key tothis scenario is not the backup of the database, but the ability to restore thedatabase using whatever backup you create. You should ensure that a recov-ery of the database does not depend on the recovery catalog that is housedinside the database itself. If the database is unavailable, then so is thisrepository.

Some of the most favored options include:

• Manually scripted hot backups.

• RMAN hot backups creating image copies of all datafiles, using thecontrol file as the repository.

• Multiple RMAN repositories, each one backing up another.

The best solution will be the one that fits the requirements best. In the simplescenario given, with no other information, the best strategy might be to useRMAN to create hot backups consisting of image copies of the database. Toeliminate the dependency on the recovery catalog, you would use the controlfile as the repository. This strategy provides the ease of RMAN’s backupmanagement features, and allows you to restore the datafiles of any of thetablespaces, provided that the database is up and accessible. This will alsoallow you to manually restore the datafiles and/or control file manually inthe event that the current control file is lost.

2. What benefit would you gain by performing logical backups of therecovery catalog using Oracle’s export utility, in addition to standardphysical backups of the recovery catalog database?

If the server where the recovery catalog database is completely lost, you canquickly import the recovery catalog contents to any Oracle database of acompatible version. This may be quicker than rebuilding the lost server andrestoring the database where the recovery catalog originally resided. Whilestoring the recovery catalog on another database that may be a potentialtarget database for backups may not be a preferred long term solution, thismay provide a short term solution to allow backups and recoveries of pro-duction databases until the original RMAN server is rebuilt.

Lesson 4: Recovery Manager Backups 279

Page 295: Oracle 9i DBA Fund - II

SummaryIn this lesson, you learned about the basic features of Recovery Manager(RMAN), and the basic steps RMAN uses to back up and recover an Oracledatabase. You also learned how to configure the RMAN environment, andhow to prepare a database for RMAN backups. You learned how to performdatabase backups with RMAN to create both backup sets and image copiesof critical files. Finally, you learned how to maintain, manage, and back upthe RMAN recovery catalog.

Lesson Review4A Your database has a 30 megabytes datafile that was completely full.

After truncating several tables, the volume in the datablock droppeddown to 12 megabytes. How many megabytes of this datafile will bebacked up by RMAN.

a. 12

b. 26

✓ c. 30

d. The file will not be backed up.

Which of the following can be stored in the repository when using therecovery catalog as a repository, but not with the control file?

a. Target-specific configuration parameter settings.

✓ b. Stored scripts.

c. Information about corruptions in backup files.

d. Complete archive log history.

What is the purpose of the communication channel between RMAN andthe target database?

The communication channel is a dedicated connection to the target databaseand is used to perform the work of copying files to their backup destination,restoring files, and performing recovery of the target database.

4B What command would you use to invoke RMAN and connect to boththe target database and recovery catalog simultaneously?

rman target username/password@db1 catalogusername/password@db2

280 Oracle9i Database: Fundamentals II

Page 296: Oracle 9i DBA Fund - II

From which prompt would you execute the appropriate commands tocreate the recovery catalog?

a. Command prompt

b. Listener control

✓ c. RMAN prompt

d. SQL*Plus prompt

What information about the target database is loaded into the recoverycatalog when the database is first registered with the catalog? Choose allthat apply.

a. Control file layout

✓ b. Database name

✓ c. Incarnation information

✓ d. Oracle version

True or False? Setting the EXCLUDE parameter for the INDX tablespacewill cause the tablespace to be excluded from all backups of all data-bases supported by that repository. Explain your answer.

False. A tablespace exclusion is target database-specific, meaning that atablespace that has been added to the exclusion list will only be excludedfrom future backups of the target database RMAN is currently connected to.Each database will have its own tablespace exclusion list.

4C For an RMAN cold database backup, why does the database have to bein the mount state?

This allows RMAN to log in to the database and read pertinent informationfrom the data dictionary and control file to update the RMAN repository.

True or False? When performing a database backup of a database usingRMAN, RMAN must put each tablespace into backup mode beforebacking up each one.

False. RMAN does not have to put tablespaces in backup mode. It simplyconnects to the target database and starts backing up files, which reducesthe performance impact on the target database.

A level 0 incremental backup was performed on Tuesday, and a level 3incremental backup was performed on Wednesday. If a level 2 incre-mental backup is performed on Thursday, the backup will includedatablocks that have changed since what day?

a. Monday

✓ b. Tuesday

c. Wednesday

d. Since the database was created

Lesson 4: Recovery Manager Backups 281

Page 297: Oracle 9i DBA Fund - II

What command would you use to back up all archive logs that havebeen generated since June 1, 2003?

BACKUP ARCHIVELOG FROM TIME '01-JUN-2003';

4D True or False? RMAN checks the syntax of a stored script at run time.Explain your answer.

False. RMAN checks the syntax of a stored script when the script is created.

The tablespaces in your database all have logging enabled by default.However, a user executed a DDL command with the NOLOGGING option.How could you determine which datafiles were affected by this opera-tion?

a. Issue the LIST UNRECOVERABLE command at the RMANprompt.

✓ b. Issue the REPORT UNRECOVERABLE command at the RMANprompt.

c. Look in the V$RECOVER_FILE data dictionary view.

d. Look in the V$UNRECOVERABLE data dictionary view.

When the CROSSCHECK command is executed, what does RMANdelete? Choose all that apply.

a. Obsolete backup pieces.

b. Redundant backups.

c. Repository entries.

✓ d. None of the above.

True or False? The CATALOG command can be used to recatalog abackup set if the information about the backup set has been purgedfrom the recovery catalog. Explain your answer.

False. The CATALOG command will only generate catalog entries forbackup files created from a user-managed backup, which essentially areimage copies. It cannot be used to catalog a backup set that is in RMAN’sproprietary format.

True or False? When an operation is executed with the VALIDATEoption, RMAN does not need to allocate a communication channel sinceno files are actually backed up or restored. Explain your answer.

False. During a validation operation, RMAN acts out all steps that arerequired to perform the operation, including allocating a channel, but doesnot actually backup or restore any datafiles.

282 Oracle9i Database: Fundamentals II

Page 298: Oracle 9i DBA Fund - II

Your environment has a single RMAN recovery catalog database. Thisdatabase is backed up by RMAN using the control file as the repositoryand by creating image copies of all database files. Give a brief summaryof how you would recover this database in each of the following failurescenarios:

• Loss of a data file

• Loss of the control file

• Loss of a datafile—The image copy of the datafile can be restored auto-matically by RMAN, which can also perform the database recovery.

• Loss of the control file—The image copy of the control file needs to berestored manually. The database recovery can then be handled manuallyor by RMAN.

Lesson 4: Recovery Manager Backups 283

Page 299: Oracle 9i DBA Fund - II

284 Oracle9i Database: Fundamentals II

Page 300: Oracle 9i DBA Fund - II

Recovery ManagerRecoveries

OverviewThe power of RMAN is easily realized when performing a recovery for adatabase that has suffered media failure. RMAN can easily handle restoringfiles and performing complete and incomplete recoveries in various failurescenarios. In this lesson, you will learn how to use RMAN to restore lostfiles from backup and perform complete recoveries. You will also learn howto perform RMAN incomplete recoveries when a complete recovery is notpossible. Finally, you will learn about the mechanisms RMAN provides tosupport RMAN-managed tablespace point-in-time recovery.

ObjectivesTo perform complete and incomplete recoveries of the database using RMAN,you will:

5A Perform a complete recovery of the database with RMAN.

To perform a complete recovery of a database, you would first restoreany lost files and then apply all changes from the archive logs to restoreddatafiles to bring them up to date with the rest of the database. In thistopic, you will learn how to restore a datafile from backup and performcomplete recoveries using RMAN.

5B Perform an incomplete recovery of the database with RMAN.

Performing an incomplete database recovery with RMAN is very similarto performing a user-managed incomplete recovery with only some minordifferences. In this topic, you will learn how to perform incompleterecoveries of the database in various failure scenarios, such as loss of thecontrol file or the current redo log.

Data Fileslogfiles.sql

Lesson Time3 hours

LESSON

5

Lesson 5: Recovery Manager Recoveries 285

Page 301: Oracle 9i DBA Fund - II

Topic 5ARMAN Complete RecoveryBefore attempting to perform recovery on a database that has suffered media fail-ure, you must first restore any lost files from backup. One of the most powerfulfeatures of RMAN is its ability to quickly determine which files need to berestored, locate the backup copies in the backup locations, and restore them totheir original locations. RMAN even provides the ability to restore files to newlocations if the original file locations are no longer available.

The RESTORE command is used to restore files from backup. This commandaccepts a wide range of options and can be used to restore from any set ofbackup files that can be created with the BACKUP command. For example, if youissue the RESTORE DATABASE command, RMAN will automatically scan allcontrol files and datafiles to determine which files need to be restored, then locatethe appropriate backup files and restore them. If you issue the RESTORETABLESPACE command and specify a tablespace name, RMAN will restore anydatafiles that are missing for that tablespace. Any datafiles that do not need to berestored will not be touched, unless you also include the FORCE option. If thisoption is included, all datafiles for the specified recovery target are restored,regardless if the file already exists in the file system. For example, if you issuethe following command, RMAN will restore all datafiles for the EXAMPLEtablespace, even if only one was missing:

RESTORE FORCE TABLESPACE example;

RMAN does not necessarily restore all specified files from the same backup set.When determining which backup to use to restore the specified files, RMAN willimmediately try to extract the files from their last known backup. However, ifthat operation fails for any reason, RMAN will automatically try to extract thefiles from a previous backup. It will keep trying older and older backups until itdetermines that there is no valid backup file that can restore the specified file, atwhich point it will return an error. During a successful restore operation, it iscompletely possible that RMAN will restore one file from one backup set andanother file from a different backup set. You must remember that restoring filesonly replaces lost files with their backup copies. It does not, however, applyarchive logs to roll the database forward to the point of failure.

Restore Files to New Locations with RMANIf the original location of a datafile is no longer available due to media failure,then you must restore the datafile to a new location. To do this with RMAN, youwould follow these steps

• Provide RMAN with the new paths and file names you want to restore thefiles to.

• Restore the lost files to their new locations.

• Rename the files in the target database’s control file to point to their newlocations.

• Recover the files.

• Bring the recovered files or tablespaces online.

286 Oracle9i Database: Fundamentals II

Page 302: Oracle 9i DBA Fund - II

To provide RMAN with the new paths and file names you want to restore the lostfiles to, you would use the SET NEWNAME command. With this command, youwould indicate the file you want restored by specifying either the file ID numberor full path and file name of the file’s original location. You would also includethe full path and file name of its new location. The following example will pro-vide RMAN with the new location and file name where datafile 28 will berestored to:

SET NEWNAME FOR DATAFILE 28 TO'F:\oracle\oradata\newdisk\sales05.dbf';

The SET NEWNAME command only instructs RMAN where to restore the file to,but it does not actually restore the file, nor does it change the target database’sinternal pointers to the file. After issuing the SET NEWNAME command, youwould restore the files to their new locations by issuing the RESTORE command.

Once the datafiles are restored, you must issue the SWITCH command, which isequivalent to the ALTER DATABASE RENAME FILE command for the targetdatabase. The SWITCH command accepts either the file ID number of the file youare restoring, its full path and file name, or the ALL option, which adjusts all ofthe target database’s internal pointers for all datafiles you have specified with theSET NEWNAME command. The following example changes all internal pointersfor the target database to the newly restored datafiles that were specified withSET NEWNAME commands:

SWITCH DATAFILE ALL;

Once all missing files have been restored to their new location and the targetdatabase’s internal pointers have been set to point to the newly-restored files, youcan begin recovery.

All the commands for this entire operation must be executed from within thecurly braces of a RUN block. If you attempt to issue the SET NEWNAME orSWITCH commands directly at the RMAN prompt, you will receive an error. Thefollowing example will perform the entire operation of restoring lost datafiles,renaming them in the target database, recovering the files, then bringing themonline:

RUN{

SQL 'alter tablespace sales offline immediate';SET NEWNAME FOR DATAFILE 28 TO'F:\oracle\oradata\newdisk\sales05.dbf';RESTORE TABLESPACE sales;SWITCH DATAFILE ALL;RECOVER TABLESPACE sales;SQL 'alter tablespace sales online;'

}

In this example, RMAN will first bring the SALES tablespace offline with theIMMEDIATE option. This is because one of the tablespace’s datafiles,SALES05.DBF, has been lost due to media failure. The IMMEDIATE optionbrings the tablespace offline without issuing a checkpoint on its datafiles, whichwould cause an error due to the missing file. The SET NEWNAME command pro-vides RMAN with the new path and file name where the backup datafile will berestored to, and then the RESTORE command actually restores the file. TheSWITCH DATAFILE ALL command changes the target database’s pointers fordatafile 28 to its new path and file name. The RECOVER command performsrecovery for the SALES tablespace, and the final command brings it back online.

Restoring a File to a NewLocation

Lesson 5: Recovery Manager Recoveries 287

Page 303: Oracle 9i DBA Fund - II

TASK 5A-1Restoring Files with RMAN

Objective: To restore lost files from backup using RMAN.

1. Before attempting to restore datafiles, you will ensure that you have onegood, hot backup of the database. You will perform this backup with RMANwhile using the target database control file as the RMAN repository.

Open a command prompt, and launch RMAN with the following com-mand:

rman target rman/buprec@ora92 nocatalog

RMAN will launch and connect to the target database and will use the con-trol file as the RMAN repository.

2. You will perform a backup of all datafiles in the database, including theEXAMPLE datafile. Currently, the EXAMPLE table is excluded from allbackups, as specified by the EXCLUDE parameter.

To change the EXCLUDE parameter to stop excluding the EXAMPLEtablespace from backups, issue the following command:

CONFIGURE EXCLUDE FOR TABLESPACE 'EXAMPLE' CLEAR;

After a moment, RMAN will display the message “tablespace EXAMPLEwill be included in future whole database backups”, and that the old RMANconfiguration parameters were successfully deleted.

3. You will now perform the full, hot backup. The backup will include alldatafiles, the control file, the spfile, and all archive logs. You will also deletethe archive logs from the file system after they have been backed up.

At the RMAN prompt, issue the following command:

BACKUP DATABASE PLUS ARCHIVELOG DELETE INPUT;

You will see RMAN begin the backup process. It will take a few minutes forthe backup to complete.

Your results may varydepending on the number of

archive logs.

288 Oracle9i Database: Fundamentals II

Page 304: Oracle 9i DBA Fund - II

Once the backup is complete, exit from both RMAN and the commandprompt.

4. You will now simulate the loss of all datafiles, then restore them from yourbackup using RMAN.

Launch SQL*Plus and log in as sys.

To shut down the database, type shutdown immediate; and press Enter.

You will see Oracle close and dismount the database, then shut down theinstance.

5. Leaving the SQL*Plus window open, open a window to the D:\oracle\oradata\ora92 folder.

You will delete all Oracle datafiles from this folder. You will not delete thecontrol files, the redo log files, or the TEMP01.DBF file. Select the follow-ing files to delete:

• CWMLITE01.DBF

• DRSYS01.DBF

• INDX01.DBF

• ODM01.DBF

• RMAN01.DBF

• SYSTEM01.DBF

• TOOLS01.DBF

• UNDOTBS01.DBF

• USERS01.DBF

• XDB01.DBF

Delete the selected files, and only these files, from the folder. Be careful

Lesson 5: Recovery Manager Recoveries 289

Page 305: Oracle 9i DBA Fund - II

not to delete any files other than what is listed here.

6. Leaving the ora92 folder open, switch back to the SQL*Plus window.

At the SQL*Plus prompt, type startup and press Enter.

You will see Oracle start the instance and mount the database, but the data-base will not open because it cannot file the SYSTEM01.DBF datafile. Youhave simulated the loss of all datafiles in the database.

Exit from the SQL*Plus window.

7. You will use RMAN to restore all the datafiles from the last backup.

Open a command prompt, and then launch RMAN with the followingcommand:

rman target rman/buprec@ora92 nocatalog

290 Oracle9i Database: Fundamentals II

Page 306: Oracle 9i DBA Fund - II

RMAN will launch and connect to the target database using the control fileas the RMAN repository.

8. To restore the datafiles from the last backup, type restore database; andpress Enter.

RMAN will determine the type of recovery that is required and whichbackup copies of the datafiles should be used to restore the database. RMANwill then extract those files from the appropriate backup set and restore themto their original locations.

9. Once the restore is complete, exit from both RMAN and the commandprompt.

Switch back to the ora92 window.

Lesson 5: Recovery Manager Recoveries 291

Page 307: Oracle 9i DBA Fund - II

You will see that the datafiles you deleted earlier have all been restored byRMAN.

Although the datafiles have been restored, you must remember that restoringdatafiles only involves copying the datafiles from their backup locations totheir original locations. It does not, however, recover the database to rollforward changes contained in the archive logs. The database will remain inan unusable state until the recovery is performed. You will do this in thenext activity.

10. Close the ora92 window.

Performing Complete RecoveryTo perform a recovery with RMAN, you would use the RECOVER command, justas you would during a user-managed recovery. The main difference between anRMAN recovery and a user-managed recovery is that RMAN will automaticallydetermine where the required archive logs are stored, restore them from backup ifnecessary, and apply them to the database. Whereas with user-managed recovery,you would need to perform all those activities manually.

The RECOVER command can be used to perform recoveries on the entire data-base, one or more tablespaces, or one or more datafiles, as shown in thefollowing syntax statements:

RECOVER DATABASE;

RECOVER TABLESPACE tablespace_name [,...];

RECOVER DATAFILE 'path_and_file_name' [,...];

The RECOVER Command

292 Oracle9i Database: Fundamentals II

Page 308: Oracle 9i DBA Fund - II

If you are performing a full database recovery, the database must be mounted butnot open. If you are performing a tablespace or datafile recovery, the databasemay be open, but all datafiles related to the recovery must be taken offline beforestarting the recovery. You can bring the datafiles offline right from the RMANprompt using the SQL command, and including the appropriate ALTERDATABASE DATAFILE command within single quotes, as shown in thisexample:

RMAN> SQL 'alter database datafile 12 offline';

sql statement: alter database datafile 12 offline

As the recovery process proceeds, RMAN will identify which archive logs needto be restored and applied, and then apply them to roll the recovery target for-ward to bring it up to date with the control file. After the recovery is complete,the recovered datafiles will still be offline, but they can be brought back online byspecifying the SQL command with the appropriate ALTER DATABASEDATAFILE or ALTER TABLESPACE command in single quotes. If you areperforming a full database recovery, you can simply open the database right fromthe RMAN prompt by issuing the ALTER DATABASE OPEN command. In thefollowing example, datafile 12 is being brought online after it has been recovered:

RMAN> SQL 'alter database datafile 12 online';

sql statement: alter database datafile 12 online

An additional feature of the RECOVER command is the ability to delete archivelogs immediately after they have been restored and applied to the database. Eacharchive log that needs to be applied is restored from backup, applied to the data-base, and then immediately deleted before the next archive log is restored. Thisfeature is extremely handy if you have a limited amount of disk space to workwith during a recovery operation. The following command will instruct RMAN torecover the entire database and delete all restored archive logs after they areapplied to the database:

RECOVER DATABASE DELETE ARCHIVELOG;

TASK 5A-2Perform a Complete Recovery

Objective: To perform a complete recovery after restoring the databasefrom backup.

1. Launch SQL*Plus and log in as sys.

At the SQL*Plus prompt, type ALTER DATABASE OPEN; and pressEnter.

Lesson 5: Recovery Manager Recoveries 293

Page 309: Oracle 9i DBA Fund - II

Oracle will return an error stating that the SYSTEM01.DBF datafile needsmedia recovery.

2. In the previous task, you simulated the loss of all datafiles in the database,then restored all the datafiles from the last backup. Since the backup copywas valid and all archive logs since the backup was performed are available,you will be able to perform a complete recovery. You will perform thisrecovery using RMAN.

Exit from the SQL*Plus window.

Open a command prompt, and launch RMAN with the following com-mand:

rman target rman/buprec@ora92 nocatalog

RMAN will launch and connect to the target database using the control fileas the RMAN repository.

3. When performing a database recovery with RMAN, the RMAN utility willdetermine the type of recovery required, and will automatically extract anynecessary archive logs from the appropriate backup set, and apply their con-tents to the database.

At the RMAN prompt, type recover database; and press Enter.

RMAN will allocate a channel, and then perform the recovery.

4. Once the recovery is complete, you must open the database to make it avail-able for general use.

294 Oracle9i Database: Fundamentals II

Page 310: Oracle 9i DBA Fund - II

At the RMAN prompt, type ALTER DATABASE OPEN; and press Enter.

After a moment, RMAN will display the message “database opened.”

5. Exit from the RMAN utility and the command prompt.

Block Media RecoveryFrom time to time, datablocks within the datafiles may become corrupted for onereason or another. If you are working with a user-managed backup and recoverystrategy, the only recovery option available would be to restore the entire datafilefrom backup and perform a recovery. This can be very time-consuming if the filerequiring recovery was large, and may be difficult to justify for only a fewdatablocks of corruption. However, RMAN provides the ability to recover indi-vidual data blocks with its Block Media Recovery (BMR) feature. Whenperforming a user-managed recovery on a datafile, the tablespace to which thatdatafile belongs will be unavailable until recovery is complete. With BMR, youcan recover individual data blocks while the affected tablespace remains online.

Block corruption errors are usually written to the alert log. You can also findinformation about corrupted data blocks in the V$BACKUP_CORRUPTION,V$COPY_CORRUPTION, and V$DATABASE_BLOCK_CORRUPTION views.When a block corruption is found, you can execute the BLOCKRECOVER com-mand from the RMAN prompt. The syntax of the BLOCKRECOVER command isas follows:

BLOCKRECOVER DATAFILE d1 BLOCK b1[,b2...][DATAFILE d2 BLOCK b3[,b4...]]...

You can specify as many datafiles and data blocks as necessary to repair thecorruptions. To repair the corruption of block number 3833 in the D:\oracle\oradata\ora92\users01.dbf datafile, you would issue the following command:

BLOCKRECOVER DATAFILE 'D:\oracle\oradata\ora92\users01.dbfBLOCK 3833;

You can optionally specify the CORRUPTION LIST option with theBLOCKRECOVER command. This option will instruct RMAN to perform blockmedia recovery on all datablocks that are listed as corrupt in the V$DATABASE_BLOCK_CORRUPTION view. This can reduce the amount of text the DBA musttype at the RMAN prompt to perform the recovery. The following examplerecovers all known corrupted datablocks in the database:

BLOCKRECOVER CORRUPTION LIST;

BMR:(Block Media Recovery) Afeature that allows RMAN torecover only corrupt blocksin a datafile, rather than theentire datafile.

Block Media Recovery(BMR)

Lesson 5: Recovery Manager Recoveries 295

Page 311: Oracle 9i DBA Fund - II

When the BLOCKRECOVER command is issued, RMAN will locate the last non-incremental backups of the specified datafiles and rebuild only the specifieddatablocks in the live datafiles based on the information found in the backups.RMAN will then restore and apply all necessary archive logs to bring the affecteddatablocks up to date with the rest of the database. The entire operation can beperformed with the database and the affected datafiles online. However, there aresome restrictions to block media recovery, which include:

• BMR can be performed only from RMAN.

• The corrupted blocks are not available until the block has been successfullyrecovered.

• Only a complete recovery of a data block is allowed; incomplete recovery isnot available.

• BMR is available only from a full backup; it is not available from incremen-tal backups.

By taking advantage of block media recovery, the DBA can address datablockcorruptions in the database and take steps to resolve the issue without taking asingle datafile offline.

TASK 5A-3Describe Block Media Recovery

1. True or False? Block media recovery can be performed from both theRMAN utility and the SQL*Plus prompt. Explain your answer.

False. Block media recovery is only available from within the RMAN utility.

2. Which data dictionary views could be queried to determine whichdatablocks were found to be corrupted during a backup operation?Choose all that apply.

✓ a. V$BACKUP_CORRUPTION

b. V$BLOCK_CORRUPTION

✓ c. V$COPY_CORRUPTION

d. V$CORRUPTION

3. You want to recover the corrupted datablock number 107734 in theD:\oracle\oradata\ora92\oem01.dbf datafile. What would be the com-mand to perform this operation?

BLOCKRECOVER DATAFILE'D:\oracle\oradata\ora92\oem01.dbf'BLOCK 107734;

4. True or False? During BMR, if RMAN discovers that a copy of thedatablock in question resides in the last incremental hot backup, RMANwill automatically recover the datablock using that backup copy.Explain your answer.

False. BMR is available only from a full backup; it is not available fromincremental backups.

296 Oracle9i Database: Fundamentals II

Page 312: Oracle 9i DBA Fund - II

Topic 5BRMAN Incomplete RecoveryPerforming an incomplete database recovery with RMAN is very similar to per-forming a user-managed incomplete recovery. Both methods require the followingsteps:

1. Mount the database.

2. Restore the appropriate backup files.

3. Recover the database, but stop the recovery before all changes are applied.

4. Open the database with the RESETLOGS option.

For user-managed recoveries, all of these steps must be handled manually, includ-ing determining which backup files need to be restored, locating and restoringthose files, and applying the appropriate archive logs up to the point in time thatyou want to stop the recovery. RMAN simplifies the process by providing theability to automatically determine which backup files are necessary for the opera-tion, restoring them, and then restoring and applying all appropriate archive logsto recover the database to the specified point in time.

To perform an incomplete recovery with RMAN, you would first determine thepoint in time you wish to recover the database to. For user-managed incompleterecovery, you can specify the point in time as a true date and time or as a spe-cific SCN. You can recover to an arbitrary point in time by issuing the CANCELcommand while applying archive logs to simply stop the recovery at any point.For RMAN incomplete recovery, you can still specify the recovery point in timeas a date and time or a specific SCN, however the CANCEL option is unavailable.As an alternative, you can specify the actual log sequence number you want tostop the recovery at. Once RMAN has recovered the database through all archivelog sequence numbers previous to the specified log sequence number, it will stopthe recovery. RMAN will not recover the changes stored in the specified archivelog sequence number, but all changes previous to it. The command in the follow-ing example illustrates an incomplete recovery to a specified log sequencenumber:

RECOVER DATABASE UNTIL LOG SEQUENCE 291 THREAD 1;

In this example, the database will be recovered up to, but not including, logsequence 291. Specifying the log sequence number is only available for incom-plete recoveries from within RMAN. Conversely, the CANCEL option is onlyavailable for user-managed recoveries, and cannot be used from within RMAN.

In RMAN, there are two options available for specifying the point in time torecover the database to. You can either include the UNTIL clause with theRECOVER database command, or you can issue the stand-alone SET UNTILcommand. The SET UNTIL command uses similar syntax as the UNTIL clause,but it is specified before the RESTORE and RECOVER commands are issued andmust be specified within the curly braces of a RUN block. This is usually moreconvenient, because it allows RMAN to choose the correct backup set to restorefor the recovery operation. Consider this example:

ALTER DATABASE MOUNT;RESTORE DATABASE;RECOVER DATABASE UNTIL TIME '15-AUG-2003 10:15:00';

Lesson 5: Recovery Manager Recoveries 297

Page 313: Oracle 9i DBA Fund - II

In this example, the RESTORE command causes RMAN to restore the last knowngood backup of the database. The RECOVER command then tells RMAN torecover the database to a specific point in time. However, it is possible that thespecified recover time is earlier than the last known good backup. If this is thecase, then RMAN will return an error when attempting to perform the recovery.You can still use the UNTIL clause if you know the exact backup set you wish touse for recovery. You would simply include either a backup set ID number or abackup set tag with the RESTORE command. However, the SET UNTIL clauseallows RMAN to make this decision for you, which can simplify the restore andrecovery process. Consider this example, which makes use of the SET UNTILcommand:

RUN{

ALTER DATABASE MOUNT;SET UNTIL TIME '15-AUG-2003 10:15:00';RESTORE DATABASE;RECOVER DATABASE;

}

In this example, the SET UNTIL command specifies the recovery point in timebefore the RESTORE command is issued. This allows RMAN to select the mostappropriate backup to perform the recover. When the RECOVER command isissued, Oracle can roll the database forward from the time the older backup wastaken to the specified recovery point in time without issue. Once the database isrecovered to the specified point in time, you would open the database with theRESETLOGS option.

There is one other minor difference in syntax to specify the recovery point intime within RMAN rather than for user-managed recovery. In user-managedrecovery, when specifying a specific SCN as the recovery point in time, youwould use the keyword CHANGE, as shown in the following example:

RECOVER DATABASE UNTIL CHANGE 39392;

In RMAN, you would use the keyword SCN instead of CHANGE, as shown in thefollowing two examples:

SET UNTIL SCN 39382;

RECOVER DATABASE UNTIL SCN 39382;

RMAN incomplete recovery can be used to restore and recover a database to aspecific point in time, which may be necessary after certain types of media fail-ure, such as loss of the control file or the current redo log group.

Loss of Control FileAs you learned earlier, if a database loses all copies of its control file, the data-base will immediately crash. If you have a valid backup of the control file, thedatabase can be recovered fairly quickly. If the backup control file was createdmanually, you would need to manually restore the file to its original location andperform an incomplete recovery of the database. However, RMAN can simplifythe process by automating many of the steps that need to be performed for thistype of recovery.

When the RESTORE command is issued, RMAN will restore all necessary filesfor a database, including datafiles and all copies of the control file, and willrestore these files from the most appropriate backup set for the specified recoveryoperation. RMAN will also handle restoring and applying all necessary archivelogs to roll the database forward to the point of failure.

The SET UNTIL Command

298 Oracle9i Database: Fundamentals II

Page 314: Oracle 9i DBA Fund - II

Since you would be recovering the database using backup control file, Oracle willnot know when to stop applying recovery since the control file’s SCN will not bethe most current one. For user-managed recovery, you can easily issue theCANCEL command once Oracle requests an archive log that has not yet beengenerated. However, the CANCEL command is not available within RMAN.Instead, you can specify the last known log sequence number as the recoverypoint in time. Since the target database is down, you will not be able to log in tothe database to determine the sequence number, but you can look in the targetdatabase’s alert log for informational entries about the latest log switch that wasperformed. The following example shows the alert log entry for the latest redolog switch that occurred in the target database prior to the media failure:

Thu Aug 05 11:26:56 2003Thread 1 advanced to log sequence 67Current log# 3 seq# 67 mem# 0:

D:\ORACLE\ORADATA\ORA92\REDO03.LOGThu Aug 05 11:26:56 2003ARC0: Evaluating archive log 2 thread 1 sequence 66ARC0: Beginning to archive log 2 thread 1 sequence 66Creating archive destination LOG_ARCHIVE_DEST_1:'D:\ORACLE\ORADATA\ARCHIVE\LOG_00066.ARC'ARC0: Completed archiving log 2 thread 1 sequence 66

In this example, the last archived log sequence was sequence 66. This means thatthe log group that was the current group when the media failure occurred has asequence number of 67. For an incomplete recovery with RMAN, you couldspecify the recovery point in time to the next higher sequence number, which is68. RMAN will recover the database up to, but not including, the specifiedsequence number. If the last redo log for the recovery has not yet been archived,as in this case where log sequence number 67 is still the current group, RMANwill automatically use the current redo log group to apply the latest changes tothe database after all archive logs have been applied. The following exampleshows the set of commands that can be used to recover the database after loss ofthe control file:

STARTUP NOMOUNT;RESTORE CONTROLFILE;ALTER DATABASE MOUNT;RECOVER DATABASE UNTIL SEQUENCE 68 THREAD 1;ALTER DATABASE OPEN RESETLOGS;

If the recovery catalog is used, and the catalog is stored in a database that isindependent from the target database, then restoring the control file and recover-ing the target database is very simple and can use the commands shown. RMANwill use the information in the recovery catalog to determine which backup con-trol file to restore. However, if the target database’s control file is used as therepository, then the recovery becomes slightly more difficult. The control file islost, which means RMAN has no repository for the target database. However, itis still possible to use RMAN for the recovery.

If you have configured control file autobackups with the CONFIGURE command,and have at least one control file autobackup that was created no more than thenumber of days specified by CONTROL_FILE_RECORD_KEEP_TIME, thenyou can restore the control file from its autobackup. Even without the repository,you would just need to tell RMAN which database you are recovering, andRMAN will scan the backup location specified by the channel configuration forany control file autobackup copies for the specified database. To tell RMAN

Lesson 5: Recovery Manager Recoveries 299

Page 315: Oracle 9i DBA Fund - II

which database you are recovering, you would specify the database ID number(DBID) with the SET DBID command. You can determine the DBID for the tar-get database by looking at the file name of a control file autobackup for the targetdatabase. Consider the following example set of commands:

SET DBID 1808973453STARTUP NOMOUNT;RESTORE CONTROLFILE FROM AUTOBACKUP;ALTER DATABASE MOUNT;RECOVER DATABASE UNTIL SEQUENCE 68 THREAD 1;ALTER DATABASE OPEN RESETLOGS;

In this example, the first command tells RMAN the DBID of the database youare trying to recover. This allows RMAN to search for the correct control file inthe backup location to restore. The database is then started in the nomount state.The RESTORE command tells RMAN to restore the last known good control fileautobackup for the specified DBID. RMAN will scan the backup location for acontrol file autobackup that contains the specified DBID, going back the numberof days specified by the CONTROL_FILE_RECORD_KEEP_TIME parameter,and restore a copy to all locations specified by the target database’s CONTROL_FILES parameter. The database is then mounted and recovered up to, but notincluding, log sequence 68. Once the recovery is complete, the database isopened with the RESETLOGS option. If no valid control file autobackup is foundthat was created within the number of days specified by CONTROL_FILE_RECORD_KEEP_TIME, then RMAN will not restore any files and will return anerror.

TASK 5B-1Describe Recovery with RMAN After Loss of ControlFile

1. Which one of the following statements is true?

a. Cancel-based recovery is unavailable for user-managed recovery,and change-based recovery is unavailable for RMAN recovery.

✓ b. Sequence-based recovery is unavailable for user-managed recovery,and cancel-based recovery is unavailable for RMAN recovery.

c. Cancel-based recovery is unavailable for user-managed recovery,and sequence-based recovery is unavailable for RMAN recovery.

d. Change-based recovery is unavailable for user-managed recovery,and time-based recovery is unavailable for RMAN recovery.

300 Oracle9i Database: Fundamentals II

Page 316: Oracle 9i DBA Fund - II

2. You are performing a restore and recovery of a database that has lostall copies of the current control file. You are using RMAN without arecovery catalog. What command would you issue to tell RMAN whichtarget database is being restored?

a. SET DATABASE

✓ b. SET DBID

c. REGISTER DATABASE

d. RESET DATABASE

3. If the target database is down, how could you determine the correctvalue to specify for the SET DBID command?

a. By looking at the name of the backup sets generated by RMAN.

✓ b. By looking at the name of the control file autobackup.

c. By looking at the name of the spfile autobackup.

d. By opening the backup control file in a text editor.

Loss of the Current Redo Log GroupAs you learned earlier, losing the current redo log due to media failure willimmediately cause the database to crash and you are guaranteed to lose anychanges to the data that were stored in the current log group. However, you canuse RMAN to easily recover the database after this type of failure to get it upand running again. Using RMAN to recover the database after a loss of the cur-rent redo log is almost identical to a user-managed recovery in the same scenario.If you have been using the target database’s control file as the RMAN repository,and if the control file is still intact after the media failure, you can still use it asthe repository for this recovery. Loss of the current redo log group requires thefollowing steps to recover the database:

1. Restore all datafiles from backup.

2. Recover the database up to but not including the lost redo log.

3. Open the database with the RESETLOGS option.

You must restore all datafiles from backup, because you cannot roll the databaseback in time; you can only roll it forward from the last known good backup.When rolling the database forward during recovery, RMAN will automaticallyrestore and apply all required archive logs to perform the recovery, but will nottry to apply the current redo log group. Upon opening the database, RMAN willautomatically re-create any redo log file members that are missing due to themedia failure. The following set of commands can be used to perform the data-base recovery in this scenario:

STARTUP MOUNT;RESTORE DATABASE;RECOVER DATABASE UNTIL SEQUENCE 67 THREAD 1;ALTER DATABASE OPEN RESETLOGS;

Lesson 5: Recovery Manager Recoveries 301

Page 317: Oracle 9i DBA Fund - II

In this example, RMAN will first restore all datafiles from the last known goodbackup. The RECOVER command specifies the log sequence number at which tostop the recovery. In this case, the current redo log group had a log sequencenumber of 67, which can be determined by looking in the alert log for the lastlog switch. By specifying this log sequence number with the RECOVER com-mand, you instruct RMAN to recover the database up to, but not including, thissequence number. Once the recovery is complete, RMAN will open the databasewith the RESETLOGS option and re-create any redo log file members that werelost. You must remember that any changes that were stored in the current redolog group will be lost.

You could optionally use the SET UNTIL clause prior to restoring the datafilesto allow RMAN to search for and restore the most appropriate backup of thedatafiles if the latest backup was created after the point in time you wish torecover to. The following example shows a RUN block that could perform thisoperation:

RUN{

STARTUP MOUNT;SET UNTIL SEQUENCE 67 THREAD 1;RESTORE DATABASE;RECOVER DATABASE;ALTER DATABASE OPEN RESETLOGS;

}

In this example, the database is mounted and the recovery point in time is set bythe sequence number of the current redo log group. The RESTORE commandtells RMAN to restore the most appropriate datafiles to perform the point-in-timerecovery, and the RECOVER command instructs RMAN to restore and apply allnecessary archive logs with the exception of the current redo log group. The data-base is then opened with the RESETLOGS option. Any missing redo log files areautomatically re-created and any changes that were in the current redo log groupat the time of the failure will be lost.

TASK 5B-2Using RMAN to Recover After Loss of the Current RedoLog

Objective: To perform an incomplete recovery using RMAN from theloss of the current online redo log group

1. You will first simulate the loss of the current online redo log.

Launch SQL*Plus and log in as sys.

To force a log switch, type ALTER SYSTEM SWITCH LOGFILE; andpress Enter.

302 Oracle9i Database: Fundamentals II

Page 318: Oracle 9i DBA Fund - II

Oracle will display the message “System altered.”

2. To determine which redo log group is the current group, type @C:\079176\logfiles.sql and press Enter.

The STATUS column in the output will show which log group is the currentgroup, and the SEQ# column will show the log sequence number of eachgroup. In the example shown here, the current log group is log group 3, witha log sequence number of 7.

3. You will now create a small table.

At the prompt, issue the following command:

CREATE TABLE test_rman_redo (col1 VARCHAR2(5));

Oracle will display the message “Table created.”

Insert a row into the table with the following statements:

INSERT INTO test_rman_redo VALUES('A');COMMIT;

Oracle will display the messages “1 row created” and “Commit complete.”The redo information generated from the CREATE TABLE and INSERT

Lesson 5: Recovery Manager Recoveries 303

Page 319: Oracle 9i DBA Fund - II

statements was first stored in redo log buffer, and then written to the currentredo log group.

4. You will now force a log switch. The current online redo log will bearchived, and Oracle will switch to the next log group.

At the prompt, type ALTER SYSTEM SWITCH LOGFILE; and pressEnter.

Oracle will display the message “System altered.”

To see which log group is now current, type @C:\079176\logfiles.sql andpress Enter.

The output will show that Oracle has switched to the next redo log group.The redo log that contains the CREATE TABLE and INSERT statements hasbeen archived. In this example, log group 1 is now the current log group,which also has a log sequence number of 8. Log group 3 has been archived.

5. You will now insert another row into the table.

At the prompt, issue the following statements:

INSERT INTO test_rman_redo VALUES('B');COMMIT;

Oracle will display the messages “1 row created” and “Commit complete.”

6. At the prompt, type @C:\079176\logfiles.sql and press Enter.

The redo information for the CREATE TABLE and the first INSERT state-ments is stored in log group 3, which has been archived. The redoinformation for the last row inserted was stored in the current online loggroup, which is now log group 1. Losing the current online log group willmean that all changes stored in that log group are permanently lost. How-

It is normal for the redo loggroups to sometimes switch

out of sequence from theirlog group numbers.

304 Oracle9i Database: Fundamentals II

Page 320: Oracle 9i DBA Fund - II

ever, all changes in the previous group can be recovered from the archivelog. Make a note of which log group is the current group, along with itslog sequence number from the SEQ# column. In this example, the logsequence number for the current online redo log group is 8.

7. You will now simulate the loss of the current online redo log group.

At the prompt, type shutdown abort and press Enter.

Oracle will display the message “ORACLE instance shut down.”

8. Leaving SQL*Plus open, open a window to the D:\oracle\oradata\ora92folder.

In the ora92 folder, delete the redo log file that corresponds with the cur-rent online redo log group for your database. In the example here, the filewould be REDO01.LOG. Be careful to delete the correct file, and onlythat file.

Close the ora92 window.

9. At the SQL*Plus prompt, type startup and press Enter.

The output will show that the instance was started and the databasemounted, but the database could not be opened because Oracle could notfind the current online redo log group.

10. To recover from this type of loss, you must restore all datafiles from backupand perform an incomplete recovery up to the last archive log that wasgenerated. All changes stored in the current log group will be lost. You willrestore and recover the database using RMAN.

Leaving the SQL*Plus window open, open a command prompt andlaunch RMAN with the following command:

rman target rman/buprec@ora92 nocatalog

Lesson 5: Recovery Manager Recoveries 305

Page 321: Oracle 9i DBA Fund - II

RMAN will launch and connect to the target database using the control filefor the RMAN repository.

11. To perform a full restore of the database, type restore database; and pressEnter.

RMAN will allocate a channel and begin the restore process. All backupcopies of the datafiles will be extracted from the backup set and restored totheir original locations, overwriting the existing datafiles. It will take a fewminutes for the restore to complete.

12. You will now use RMAN to perform an incomplete recovery of thedatabase. Since the failure occurred due to loss of the current online redolog, the most efficient method of recovery is to specify the log sequencenumber of the current online log group as the stopping point during recoveryusing the UNTIL SEQUENCE option of the RECOVER command.

To recover the database until the current log sequence number, issue thefollowing command. For the x, specify the log sequence number of thecurrent online redo log group for your database, which you determinedin step 6. In this example, the log sequence number for the current redo loggroup is 8.

recover database until sequence x thread 1;

RMAN will determine the archive logs and their locations that are needed toperform the specified recovery. RMAN will then extract any archive logsfrom the latest backup set, if necessary, then apply the contents of the logsto roll the database forward. All logs that are available are applied to thedatabase, with the exception of the log that normally would have been gen-erated when the current online log group was archived.

Once the database has been recovered to the specified log sequence number,

306 Oracle9i Database: Fundamentals II

Page 322: Oracle 9i DBA Fund - II

RMAN will display the message “media recovery complete.”

13. The database has been recovered to include all available changes. The cur-rent online redo log group is no longer available, therefore its changes willbe lost.

At the RMAN prompt, type alter database open resetlogs; and press Enter.

After a few moments, RMAN will display the message “database opened.”

Exit from both the RMAN utility and the command prompt.

14. When you opened the database with the RESETLOGS option, you created anew incarnation of the database, and all backups of the previous incarnationof the database are now useless for recovery. You should immediately per-form another full, cold backup of the database in case there is some sort offailure in the near future.

At the RMAN prompt, type shutdown immediate; and press Enter.

At the prompt, type startup mount; and press Enter.

After a moment, RMAN will report that the instance has started and thedatabase was mounted.

To back up the database, type backup database; and press Enter.

A full, cold backup of the database will begin. It will take several minutesfor the backup to complete.

15. Once the cold backup is complete, you will also create an image copy of thecontrol file. This will allow you to recover the database if the recovery cata-log is not available.

At the RMAN prompt, issue the following command:

copy current controlfile to 'D:\oracle\rman_bup\control.bak';

Lesson 5: Recovery Manager Recoveries 307

Page 323: Oracle 9i DBA Fund - II

RMAN will create an image copy of the control file in the D:\oracle\rman_bup folder.

Type alter database open; and press Enter.

After a moment, RMAN will display the message “database opened.”

Exit from both the RMAN utility and the command prompt window.

16. At the SQL*Plus prompt, type Connect sys@ora92 as sysdba and pressEnter. Type ora92 for the password and press Enter.

17. To see which changes were recovered and which were lost, you will nowquery from the TEST_RMAN_REDO table.

At the SQL*Plus prompt, type SELECT * FROM test_rman_redo; andpress Enter.

The output will show that only the first row, containing the value A, wasrecovered. The second row, containing the value B, which was only stored inthe current online redo log group, was lost.

18. You have successfully performed an incomplete recovery of the databaseusing RMAN with the UNTIL SEQUENCE option.

After performing an incomplete recovery and opening the database using theRESETLOGS option, all information about tempfiles belonging to any tem-porary tablespaces are lost. You will add the tempfile back to your temporarytablespace.

At the SQL*Plus prompt, issue the following command:

ALTER TABLESPACE temp ADD TEMPFILE'D:\oracle\oradata\ora92\temp01.dbf' REUSE;

Oracle will display the message “Tablespace altered.”

19. Exit from SQL*Plus.

Tablespace Point-in-Time RecoveryOne of the most involved recovery scenarios is performing a tablespace point-in-time recovery. This type of recovery is performed to recover a single tablespaceto a different point in time than the rest of the database, and cannot be done witha single database. You would need to create a clone of the original database,recover the clone database to the specific point in time, then move the newly

308 Oracle9i Database: Fundamentals II

Page 324: Oracle 9i DBA Fund - II

recovered data back to the original database. Performing this recovery manuallyrequires quite a bit of preparation and configuration ahead of time and involvesmany hands-on steps to complete. RMAN greatly simplifies a tablespace point-in-time recovery by automating a majority of the most tedious and error prone stepsof the process.

To perform a tablespace point-in-time recovery, RMAN takes the followingactions:

• Creates a clone of the target database using a minimal set of files.

• Recovers the clone database to the specified point in time.

• Opens the clone database with the RESETLOGS option.

• Performs a transportable tablespace export of the tablespace that is beingrecovered from the clone database.

• Shuts down the clone database.

• Renames the original datafiles in the target database to point to the newly-recovered clone datafiles.

• Imports the transportable tablespace back into the target database.

The clone database is created by restoring the necessary files from a hot backupof the original database. When creating the clone, RMAN only restores the abso-lute minimum files necessary to get the clone up and running with only thetablespace to be recovered. This minimizes the number of files that need to berestored and can greatly reduce the amount of time and space needed for therecovery, especially if the target database has many large tablespaces. For thepurposes of the recovery process, the files to be restored are grouped into the fol-lowing file sets:

• Auxiliary set—Consists of the minimum set of files to make the clone data-base a fully operational database, which includes the control file and thedatafiles of the SYSTEM and UNDO tablespaces.

• Recovery set—Consists of all datafiles for the tablespace that is to berecovered.

Once restored, RMAN performs a recovery of the clone database to the specifiedpoint in time using the appropriate archive logs, and then it opens the databasewith the RESETLOGS option. RMAN then uses the transportable tablespace fea-ture of Oracle’s export and import utilities to move the tablespace back to thetarget database. You will learn more about transportable tablespaces in detail inthe next lesson. For now, this lesson will focus on the overall steps required toperform the tablespace point-in-time recovery.

While RMAN performs most of the steps required to perform a tablespace point-in-time recovery, there are some minor preparations that need to be donemanually before invoking RMAN. These steps include:

• Create a new directory to store the files of the auxiliary and recovery sets.

• Make a copy of the parameter file from the original database to be used tostart the clone database.

• Set up the operating system environment to support the clone database.

• Configure the Oracle Net environment to accept connection requests for theclone.

Lesson 5: Recovery Manager Recoveries 309

Page 325: Oracle 9i DBA Fund - II

After making a copy of the target database’s parameter file, and renaming itappropriately, there are several parameter additions and changes that need to bemade. The new parameter settings for the clone database allow the clone to resideon the same system as the target database without conflict. The modified cloneparameter file should contain the parameters shown in the following table.

Parameter Descriptionlock_name_space Set to the new name of the clone database.db_file_name_convert Specifies the directory path where the auxiliary file set will be

restored to.log_file_name_convert Specifies the directory path where the redo logs will be re-

created when the clone is opened with the RESETLOGSoption.

control_files Specifies the directory path and file names where the controlfiles will be restored to.

log_archive_start Must be set to FALSE, since the clone must be running inNOARCHIVELOG mode.

The LOCK_NAME_SPACE parameter provides a new name for the cloneinstance to allow it to start up along side the target instance. The value youspecify for the LOCK_NAME_SPACE parameter should be different than theINSTANCE_NAME parameter in the target database. It’s important to note thatwhile the LOCK_NAME_SPACE parameter in the clone should be different thanthe INSTANCE_NAME parameter in the target, the DB_NAME parameter onboth databases must be identical.

The DB_FILE_NAME_CONVERT and LOG_FILE_NAME_CONVERT param-eters should include the original directory path where the files reside for thetarget database along with the new directory path where they will reside for theclone database. You can list any number of directory path conversions as neces-sary for each parameter. For example, if your target database has datafiles of theSYSTEM and UNDO tablespaces and the log file members of the redo logsspread out across five directories, you would list each original directory alongwith a conversion directory so RMAN will know where to restore datafiles and tore-create the redo log files for the clone database to use. The following exampleshows these two parameters with appropriate settings:

db_file_name_convert =('D:\oracle\oradata\ora92\','D:\oracle\oradata\clonedb\')log_file_name_convert =('D:\oracle\oradata\ora92\','D:\oracle\oradata\clonedb\')

Its very important to note that the DB_FILE_NAME_CONVERT parameter onlyspecifies the new directory path where the datafiles of the auxiliary set will berestored to, namely the SYSTEM and UNDO tablespace datafiles. For the recov-ery set, RMAN will attempt to restore the datafiles to their original locations.Therefore, you must first issue the SET NEWNAME command during the RMANsession to restore the files of the recovery to the new clone location. You mustnot however, issue the SWITCH command. Doing so will instruct RMAN tochange the target database’s internal pointer for the original datafiles.

The CONTROL_FILES parameter for the clone database should be changed sothat RMAN will not overwrite the target database’s control files when restoringthe backup control file for the clone. This parameter should be set with full direc-tory path and file names for each control file you want to use for the clone.

310 Oracle9i Database: Fundamentals II

Page 326: Oracle 9i DBA Fund - II

The clone database must be running in NOARCHIVELOG mode. RMAN willhandle setting the clone to NOARCHIVELOG mode before opening it, but theLOG_ARCHIVE_START parameter must set to FALSE before beginning therecovery process.

In addition to the parameters listed here, you may want to consider changingsome other parameter values for resource usage and performance reasons. Sincethe parameter file for the clone database is a copy of the parameter file for theoriginal database, memory allocation parameters such as SHARED_POOL_SIZEand DB_CACHE_SIZE will be the same for both the clone and the target. Sinceyou are not expecting any sort of user load on the clone database, you can shrinkthe values for these parameters to the absolute minimum requirements necessaryto start the instance. This can greatly reduce the memory consumption required tohave both databases up and running on the same server and will hopefully avoidany negative performance impacts if the target database is still in use.

The steps needed to configure the operating system to support the clone databasedepends on the platform the database is running. If you are running on a Win-dows system, for example, you would need to ensure that the appropriateWindows service is created for the new instance. For Unix systems, you wouldneed to set the appropriate environment variables, such as $ORACLE_HOMEand $ORACLE_SID.

To configure the Oracle Net environment to accept connection requests for theclone database, you would need to add connect descriptors to your names resolu-tion method. For example, if you are using local naming, you would need to addan entry to the tnsnames.ora file on the server. You will also need to make anentry in the listener.ora file and reload this listener to ensure that the listener canproperly route connection requests from RMAN to the clone.

Once the environment is configured to support the clone database, you can invokeRMAN and connect to all databases involved in the recovery, which include therecovery catalog, the target database, and the clone database. To connect to therecovery catalog and target database, you would use the standard syntax you haveused throughout this course. Once RMAN is invoked and connected to both therecovery catalog and target database, you would issue another command to con-nect to the clone database. The following is an example of the commands to useto connect to all three databases:

C:\>rman target rman/buprec@ora92 target rman/buprec@ora92

Recovery Manager: Release 9.2.0.1.0 - Production

Copyright (c) 1995, 2002, Oracle Corporation. All rightsreserved.

connected to target database: ORA92 (DBID=1808973453)

RMAN>connect clone rman/buprec@clonedb

Once connected to all three databases, you must first allocate a special clonechannel that is used to restore the datafiles for the clone database, as shown inthis example:

ALLOCATE CLONE CHANNEL C1 TYPE DISK;

Lesson 5: Recovery Manager Recoveries 311

Page 327: Oracle 9i DBA Fund - II

In this example, the clone channel was allocated to restore all files from a disklocation. Even if the datafiles of the recovery and auxiliary sets will be restoredfrom tape, RMAN will replicate the current control file from the original databaseto create the control file for the auxiliary database. Since this control file resideson disk, at least one channel of type DISK must be allocated, even if you mustallocate another channel to restore the datafiles from type. If this is the case, yourchannel allocations may look like this:

ALLOCATE CLONE CHANNEL C1 TYPE DISK;ALLOCATE CLONE CHANNEL C2 TYPE 'SBT_TAPE'

Once the channel is allocated, you only need to provide RMAN with the pathsand file names where you want the datafiles of the recovery set to be restored to.This is done with the SET NEWNAME command, as shown in the followingexample:

SET NEWNAME FOR DATAFILE 5 to'D:\oracle\oradata\clonedb\example01.dbf';

After specifying the new paths and file names, you do not need to issue theRESTORE command. You would simply issue the RECOVER TABLESPACEcommand, which instructs RMAN to first restore all files of the auxiliary set andall datafiles for the specified tablespace. The auxiliary set will be restored to thedirectory specified by the DB_FILE_NAME_CONVERT and CONTROL_FILESparameters on the clone database. The RECOVER command also includes thepoint in time that you want to restore the clone database to. The followingexample shows a complete set of commands to perform the recovery of the clonedatabase:

RUN{

ALLOCATE CLONE CHANNEL C1 TYPE DISK;SET NEWNAME FOR DATAFILE 5 to'D:\oracle\oradata\clonedb\example01.dbf';RECOVER TABLESPACE example UNTIL SEQUENCE 68 THREAD 1;

}

In this example, the clone channel is allocated and the new path and file name forlone datafile in the EXAMPLE tablespace is specified. The RECOVER commandinstructs RMAN to recover the EXAMPLE tablespace up to but not including logsequence 68. Once this RUN block is executed, RMAN will perform the follow-ing steps:

1. Allocate the clone channel.

2. Restore the control files to the clone location.

3. Restore the datafiles of the SYSTEM and UNDO tablespaces to the clonelocation.

4. Restore the datafiles of the tablespace to be recovered to the clone location.

5. Mount the clone database.

6. Recover the clone database to the point in time specified.

7. Open the clone database with the RESETLOGS option.

8. Create a transportable tablespace export of the tablespace to be recovered.

9. Shut down the clone database.

10. Rename the datafiles of the EXAMPLE tablespace in the target database topoint to the newly-recovered clone EXAMPLE datafiles.

11. Import the transportable tablespace into the target database.

RMAN Tablespace Point-in-Time Recovery

312 Oracle9i Database: Fundamentals II

Page 328: Oracle 9i DBA Fund - II

Once the datafiles are imported into the target database, the tablespace is consid-ered to be recovered. However, the datafiles of the recovered tablespace will stillreside in the location where they were restored to, most likely in the clonedirectory. After the recovery operation, RMAN will leave the recoveredtablespace offline in the target database to allow you to copy the datafiles back totheir original locations and rename them within Oracle before bringing themonline. This will help avoid confusion by having live datafiles stored in a strangelocation.

TASK 5B-3Describe Tablespace Point-in-Time Recovery UsingRMAN

1. What is the difference between the recovery set and the auxiliary set?

The recovery set contains all the datafiles of the associated tablespace thatis to be recovered. The auxiliary set contains the minimum number ofdatafiles from the primary database to be restored for the clone database tomake the clone fully operational, which includes the control file, the systemtablespace datafiles, and the undo segment tablespace datafiles. The auxil-iary set does not include any of the datafiles of the associated tablespace tobe recovered.

2. True or False? The DB_FILE_NAME_CONVERT parameter specifiesthe new names and locations to where RMAN will restore the filesincluded in the recovery and auxiliary sets. Explain your answer.

False. The DB_FILE_NAME_CONVERT parameter specifies the new nameand location to where RMAN will restore the files included in the auxiliaryset only. To specify the new names and locations for the files included in therecovery set, you would include the SET NEWNAME FOR DATAFILE com-mand in your RMAN script just prior to beginning the recovery process.

3. All of your backup copies are stored on tape. However, when perform-ing tablespace point-in-time recovery with RMAN, you must stillallocate at least one channel of type DISK. Why?

The datafiles of the recovery and auxiliary sets will be restored from tape,but RMAN will replicate the current control file from the original databaseto create the control file for the auxiliary database. Since this file resides ondisk, a channel of type DISK must be allocated.

Lesson 5: Recovery Manager Recoveries 313

Page 329: Oracle 9i DBA Fund - II

4. Once the clone database has been restored and recovered, what type ofexport will RMAN perform to copy the recovered tablespace back to theoriginal database?

a. Conventional path, full database export

b. Direct path, full database export

c. Direct path, tablespace-level export

✓ d. Transportable tablespaces

5. Once the RMAN tablespace point-in-time recovery is complete, in whatstate will RMAN leave the recovered tablespace in the original data-base?

a. ONLINE

b. RECOVER

✓ c. OFFLINE

d. READ ONLY

SummaryIn this lesson, you learned how to perform both complete and incompleterecoveries with RMAN. You learned how to restore lost files, includingdatafiles, control files, archive logs, and the spfile. You also learned how torecover the database to the point of failure and to alternative points in timeusing the RMAN utility. Finally, you learned how to use RMAN to performa tablespace point-in-time recovery by creating a clone database, recoveringthat clone to a specific point in time, and transferring the recoveredtablespace back to the original database.

Lesson Review5A Which RMAN command is equivalent to the ALTER DATABASE

RENAME FILE command?

a. CREATE DATAFILE...AS

b. RESET DATAFILE

c. SET NEWNAME

✓ d. SWITCH

What command would you use to perform a recovery of the USERStablespace and delete each restored archive log after it is applied?

RECOVER TABLESPACE users DELETE ARCHIVELOG;

314 Oracle9i Database: Fundamentals II

Page 330: Oracle 9i DBA Fund - II

Which clause of the BLOCKRECOVER command can be specified torecover all datablocks shown in the V$DATABASE_BLOCK_CORRUPTION view?

a. ALL

b. ALL KNOWN CORRUPTIONS

c. COMPLETE

✓ d. CORRUPTION_LIST

5B Why is it usually better to issue the SET UNTIL command rather thaninclude the UNTIL command during an RMAN incomplete recovery?

If the UNTIL command is used, RMAN will try to restore the last knowngood backup of the recovery target, which may have been created after thepoint in time specified by the UNTIL clause. If you issue the SET UNTILcommand before the RESTORE command, RMAN will automatically choosethe most appropriate backup of the recovery target and avoid potentialerrors during recovery.

Your database has suffered a loss of all copies of the current control file.By looking in the alert log for the last redo log switch, you have deter-mined that the current log sequence number for the database was 32.When using RMAN to perform an incomplete recovery, what logsequence number should you specify for the UNTIL clause?

a. 31

✓ b. 32

c. 33

d. None, RMAN will automatically determine when to stop the recov-ery

Your database has suffered a loss of the current redo log group. By look-ing in the alert log for the last redo log switch, you have determinedthat the current log sequence number for the database was 32. Whenusing RMAN to perform an incomplete recovery, what log sequencenumber should you specify for the UNTIL clause?

✓ a. 31

b. 32

c. 33

d. None, RMAN will automatically determine when to stop the recov-ery

Lesson 5: Recovery Manager Recoveries 315

Page 331: Oracle 9i DBA Fund - II

Which files make up the auxiliary set for an RMAN tablespace point-in-time recovery? Choose all that apply.

a. Archive logs to perform the recovery.

✓ b. Control file.

✓ c. Datafiles of the SYSTEM tablespace.

d. Datafiles of the tablespace to be recovered.

✓ e. Datafiles of the UNDO tablespace.

316 Oracle9i Database: Fundamentals II

Page 332: Oracle 9i DBA Fund - II

Loading and Moving Data

OverviewOracle provides several utilities to load and unload data in and out of thedatabase. For example, the SQL*Loader utility is used to bulk load datafrom flat ASCII files into the database. The export utility is used to exportdata from the database into a file in binary format, which can then beimported back into the same database or another database. In this lesson,you will learn how to use these utilities to load, unload, and move data inlarge volumes.

ObjectivesTo move data around quickly and easily using Oracle-provided utilities, you will:

6A Quickly bulk-load data into the database.

Occasionally, you may find the need to bulk load data into the database.With Oracle9i, there are multiple methods available, such as theSQL*Loader utility and external tables, to do just that. You will learnhow to use SQL*Loader to quickly load simple files containing data inASCII format into the database. You will also learn how to create exter-nal tables to access data in files outside of the database through table-likestructures from within the database.

6B Import and export data in and out of the database.

The export and import utilities provide the capability to export data fromthe database to a file in binary format, and import it back to the samedatabase or to another database. They also provide the ability to moveentire tablespaces between databases by transporting only the tablespacemetadata from the data dictionary. You will learn how these utilitieswork, and you will perform multiple types of exports and imports.

Data Filesinventory.datlistplan.sqlitem_ext.sqlfinal_setup.pif

Lesson Time4 hours

LESSON

6

Lesson 6: Loading and Moving Data 317

Page 333: Oracle 9i DBA Fund - II

Topic 6ALoad Data into the DatabaseThe SQL*Loader utility is a command line utility that allows you to bulk loaddata stored in simple text files into the database. As simple as the utility is, itcomes with powerful data parsing capabilities that enable the utility to read fromflat files regardless of the format of the data. The utility allows you to load frommultiple datafiles simultaneously or load into multiple tables simultaneously. Youcan load data based on a set of conditions similar to a WHERE clause of aSELECT statement, and you can manipulate the data as it loads using Oracle’sbuilt-in SQL functions.

SQL*Loader also comes with comprehensive error reporting capabilities. Anyrecords that do not meet the certain conditions you specify, or records that violateconstraints, can be extracted to separate files to be dealt with individually. Youcan configure the utility to cease loading if a specified number of errors areencountered, and you can continue a load that had not completed due to a systemor utility failure. Figure 6-1 illustrates how SQL*Loader loads data into thedatabase.

Figure 6-1: The SQL*Loader utility.

As shown in Figure 6-1, SQL*Loader will read the data from the datafiles. Thecontrol file shown here is different from the database’s control file. TheSQL*Loader control file is more or less a configuration file that is created byhand and contains a list of parameters that tell SQL*Loader how to load the data.The control file lists the names and locations of the datafiles that contain the data,the columns of the target table, any SQL functions to use while loading, and anyother SQL*Loader options you would like to use for the load. You can optionallyspecify the name and location of a log file, which records all screen output during

The SQL*Loader Utility

318 Oracle9i Database: Fundamentals II

Page 334: Oracle 9i DBA Fund - II

the loading. You can also specify names and locations of bad and discard fileswhere the utility will place data that cannot or will not be loaded. The bad filewill contain any data that could not be loaded due to some type of error. Theseerrors could be mismatched datatype, a value that is too large for the target col-umn, or any other Oracle-related error. If no errors are encountered, the file is notcreated. The discard file will contain any rows of data that do not meet the condi-tions specified in the control file. This allows conditional loading of data, butextracts the rows that do not meet the specified criteria.

Types of LoadsSQL*Loader supports two methods of loading data: conventional path and directpath. In conventional path loading, SQL*Loader reads the data from the flat fileand generates standard INSERT statements to pass to the database. This methodof loading provides maximum flexibility because Oracle functions, such asUPPER or TO_CHAR, can be applied to the data prior to inserting it into a table.In direct path loading, SQL*Loader reads the data from the flat file, but bypassesthe SQL processing engine of the database and stores the data directly in the tar-get table. Because the SQL processing engine has been bypassed, Oraclefunctions cannot be used against the data while it is loading, but the speed andperformance of direct path loads is often far superior than conventional pathloads. The decision to use one over the other will depend on the requirements ofthe data to be loaded. You will learn how to use both loading methods later inthis topic.

The SQL*Loader Control FileThe SQL*Loader control file is a simple text file that can easily be created byhand. The control file contains the names and locations of the datafiles where thedata is stored and the format the data is stored in within the datafiles. It alsospecifies the name of target table and the columns where the data will be loadedto. Any Oracle functions to apply on the data while loaded would be listed foreach column. The control file also contains any options that are to be used duringloading. Additionally, the control file could also contain the actual data that is tobe loaded. The data must be listed at the end of the file after all other control filecontents. This allows simple maintenance and ease of management when dealingwith multiple datafiles.

Since SQL*Loader is such a powerful utility, the control file syntax allows a longlist of available commands and options. Shown here is the basic syntax for aSQL*Loader control file.

[RECOVERABLE | UNRECOVERABLE][CONTINUE] LOAD DATAINFILE file_name[,...]BADFILE file_nameDISCARDFILE file_nameFIELDSTERMINATED BY [WHITESPACE | 'string']ENCLOSED BY 'string'OPTIONALLY ENCLOSED BY ' string'TRAILING NULLCOLS[INSERT | APPEND | REPLACE | TRUNCATE]INTO TABLE table_nameWHEN (conditions)(column_list)[BEGIN DATA]

conventional path load:A method of loading datainto Oracle using standardSQL calls.

direct path load:A method of loading datainto Oracle that writesdirectly to the datablocks inthe datafiles, bypassing theSQL processing engine.

Refer to the Oracle9i Utilitiesmanual for a complete list ofSQL*Loader control fileoptions and keywords.

Lesson 6: Loading and Moving Data 319

Page 335: Oracle 9i DBA Fund - II

In this syntax, the [RECOVERABLE | UNRECOVERABLE] option specifieswhether or not the SQL*Loader run will generate redo information into the redologs. Disabling redo log information will greatly speed up the loading process,but since no redo information was recorded, the load will not be recoverable inthe case of instance or media failure. If this clause is omitted, the current loadwill default to RECOVERABLE.

The [CONTINUE] LOAD DATA keywords starts the main control file command.The optional keyword CONTINUE can be specified to continue a load that hadnot completed due to some failure, such as instance or media failure. TheINFILE clause lists the names and locations of the source datafiles. SQL*Loaderwill load from the datafiles listed in the INFILE clause in the sequential order.

The BADFILE clause specifies the name and location of the bad file to be gener-ated, if necessary. All rows of data that cause an error during the load will becopied from the datafile into the bad file. As SQL*Loader is running, it will dis-play on the screen, and record in the log file if specified, any errors that occurduring the load. After examining the errors, you can edit the bad file to modifythe data and rerun SQL*Loader to load these rows. If no errors are encounteredduring a load, no bad file is generated. If the BADFILE clause is omitted, no badfile will be generated even if there are errors.

There are two types of text files that can be read by SQL*Loader, fixed-widthand delimited. In a fixed-width datafile, all columns of data are separated evenlyin a fixed-width. In a delimited datafile, all fields are separated by some specificcharacter that is not read as data. The FIELDS clause specifies how the columnsof data are separated in a delimited text file. You will learn more about datafileformats later in this lesson.

The TRAILING NULLCOLS options tell SQL*Loader how to handle any tablecolumns that do not have corresponding data in the datafile. For example, let’ssay the target table contains 12 columns, but your text file contains eight columnsof data. By including the TRAILING NULLCOLS clause, you instructSQL*Loader to load the eight columns of data into the first eight columns of thetable, and leave the last four columns of the table null. This clause is only validif the target columns that are to remain null do not have NOT NULL constraintsdefined on them.

The [INSERT | APPEND | REPLACE | TRUNCATE] clause specifies howto handle the target table during the load. The INSERT option can only be usedto load data into an empty table, and the APPEND option will add the data to thetable without disturbing any existing data. The REPLACE option will execute anunconditional DELETE command on the table, while the TRUNCATE commandtruncates the table prior to loading. While both the REPLACE and TRUNCATEoptions will completely remove all data from the table, the TRUNCATE option isgenerally much faster than REPLACE. The INTO TABLE clause lists the targettable the data will be loaded into.

The conditions to load data are specified in the WHEN clause. The WHEN clausecontains relational comparisons similar to those used in the WHERE clause ofSQL statements. All data that meets the criteria specified in the WHEN clause isloaded, while any data not meeting the criteria is discarded. If a discard file isspecified with the DISCARDFILE clause, all discarded rows are copied into thediscard file.

The columns_list clause lists the columns of the table where the rows are tobe loaded. You can optionally apply Oracle functions to each of the columnslisted in the column list. The data in the datafile will be loaded into the columnsbased on sequential order. For example, the first column of data will be loaded

320 Oracle9i Database: Fundamentals II

Page 336: Oracle 9i DBA Fund - II

into the first column in the column list, the second column of data into the sec-ond column listed, and so on. All columns in the datafile must be tied to aspecific table column. Table columns cannot be skipped in the control file, butyou can leave off any columns at the end of the table that will not receive data.For example, if the datafile has 10 columns of data, you must list the first 10 col-umns of the table. The last two columns can be omitted only if you include theTRAILING NULLCOLS clause.

The BEGIN DATA clause tells SQL*Loader that all contents in the file after thatpoint is data, and is intended to be loaded into the target table. This clause can beoptionally used if you decide to load the data from the control file itself, and canbe very useful if only a relatively small number of rows is to be loaded. If theBEGIN DATA clause is included, you must list the INFILE clause asINFILE *.

The following shows an example of the contents of a SQL*Loader control file.

UNRECOVERABLELOAD DATAINFILE 'd:\sqlldr\employee.txt'BADFILE 'd:\sqlldr\bad\employee.bad'TRUNCATEINTO TABLE employeeFIELDS

TERMINATED BY ","OPTIONALLY ENCLOSED BY '|'TRAILING NULLCOLS

(emp_id,last_name,first_name,ssn,dept_no

)

As shown in this example, the data in the EMPLOYEE.TXT file will be loadedinto the EMPLOYEE table and will not produce redo log information. If anyrows cause errors during loading, they will be copied to the EMPLOYEE.BADfile that will be created in the d:\sqlldr\bad directory. Prior to loading the data, theEMPLOYEE table will be truncated. The fields in the EMPLOYEE.TXT file areseparated by commas and might also be enclosed by a single pipe (|). Any col-umns at the end of the table that are not going to be loaded with data will remainnull.

Datafile FormatsSQL*Loader can read two different types of datafile formats, fixed-width anddelimited. In a fixed-width datafile, the columns of all rows in the file are set at afixed-width, much like a spreadsheet. To load the data, you would include in thecontrol file the starting position and ending position of each column in thedatafile. Figure 6-2 shows a sample datafile in a fixed-width format.

Lesson 6: Loading and Moving Data 321

Page 337: Oracle 9i DBA Fund - II

Figure 6-2: A fixed-width format datafile.

In a delimited datafile, each field is separated by some identifying character,called a delimiter. As SQL*Loader reads the file, it will know where each columnstops and another starts when it encounters the delimiter. The most commondelimiters used are the comma and the pipe (|). When creating datafiles to beloaded with SQL*Loader, it is recommended that you choose a character that caneasily be differentiated from actual data. For example, if the data you are loadingcontains names and address, you should not use a comma-delimited file becausethere is a good chance the data itself may include commas.

Although a fixed-width datafile looks much cleaner, it is actually easier to createa control file for a delimited file; you only need to specify the character used asthe delimiter. When loading data from a fixed-width datafile, you omit theFIELDS clause, and specify start and stop positions for each column instead.Although this sounds simple, your start and stop positions must be exact or theload will fail. If the datafile is extremely large, such as 500 MB or more, youmay not have enough physical memory to open the file and look at the data toconfirm column positions. Shown here are the contents of a control file withspecifications to load a fixed-width datafile.

UNRECOVERABLELOAD DATAINFILE 'd:\sqlldr\employee.txt'BADFILE 'd:\sqlldr\bad\employee.bad'TRUNCATEINTO TABLE employee(

emp_id POSITION(1:6),last_name POSITION(8:28),first_name POSITION(30:50),ssn POSITION(52:61),dept_no POSITION(63:68)

)

322 Oracle9i Database: Fundamentals II

Page 338: Oracle 9i DBA Fund - II

In this example, each column is specified with a position to tell SQL*Loaderwhere in the datafile the column starts and stops. For example, the LAST_NAMEcolumn begins at the 8th position from the left side of the file, and ends at the28th position from the left side of the file.

SQL*Loader CommandsSQL*Loader is a command line utility and, therefore, comes with several argu-ments that can be passed to the utility when executed. The entire SQL*Loadercommand is entered at the command prompt with all arguments on a single line,and each argument is assigned a value. The table shown here provides a list ofvalid arguments with a description of appropriate values for each.

Argument Descriptionuserid The Oracle user name and password to execute the load with. This user must

have INSERT privileges on the target table.control The name of the control file to use for the load, including full path and file

name.bad The path and file name of the bad file where rows that cause errors will be

stored.data The path and file name of the datafile to load from.discard The path and file name of the file to store discarded rows.discardmax The maximum number of rows allowed to be discarded. Once this limit is

reached, the load is terminated. This argument defaults to allow all discards.skip The number of rows in the datafile to skip starting from the first row. This is

useful when you must continue a previous load that failed. The default is 0.load The number of rows to load. The default is all rows.errors The maximum number of errors to allow before terminating the load. The

default is 50.rows The number of rows in a conventional path bind array, or the number of

rows between saves in a direct path load. For conventional path, the defaultis 64, for direct path the default is all rows.

bindsize The size of the conventional path bind array in bytes.silent Suppress all screen-displayed messages during run. Useful for loads run

from a batch file or script.direct Use direct path. Default is FALSE.parfile The path and file name of an option parameter file that contains command

line arguments.parallel Perform parallel load (multiple datafiles into a single table). Default is

FALSE.file The name of the tablespace datafile to first start loading the data. The table

may extend out of this datafile if necessary.readsize Size of the read buffer in bytes.

You may have noticed that several arguments have the same purpose as portionsof the control file syntax. This is the case, and you have a choice of listing thosearguments in the command line, or as clauses in the control file. If the argumentsappear in both the command line and control file, the arguments in the commandline will take precedence. The following example shows a sample SQL*Loadercommand, complete with arguments.

Lesson 6: Loading and Moving Data 323

Page 339: Oracle 9i DBA Fund - II

sqlldr userid=system/ora92 control=d:\sqlldr\sample.ctl ⇒log=d:\sqlldr\sample.log bad=d:\sqlldr\sample.bad ⇒discard=d:\sqlldr\sample.dis discardmax=1000 rows=100 ⇒bindsize=10240

In this example, the load will be run as the user SYSTEM and will use theinstructions found in the SAMPLE.CTL control file. This control file specifies thename of the datafile to load from and the name of the target table to load to. Allscreen output will be recorded in the SAMPLE.LOG log file, and if any rowscause errors, they will be stored in the SAMPLE.BAD bad file. If any rows donot meet the criteria specified by the control file’s WHEN clause, these rows willbe copied to the SAMPLE.DIS discard file, and the maximum number of discardsallowed will 1000. The number of rows to load into the bind array is 100, andthe bind array will be 10240 bytes, or 10 MB.

TASK 6A-1Using SQL*Loader

Objective: To quickly load data into the database using SQL*Loader.

1. The inventory.dat file contains 5000 rows of sample inventory data that youwill load into the a table in the database.

Open a window to the C:\079176 folder. Double-click the inventory.datfile to open it. A caution window will appear to warn you about opening a*.dat file. Click Open With. Select Notepad from the list of applicationsand click OK.

The inventory.dat file will open in a Notepad window. The contents of thisfile are in a delimited format, with each field terminating with a comma. Youwill load the contents of this file into a table in the database. When you are

324 Oracle9i Database: Fundamentals II

Page 340: Oracle 9i DBA Fund - II

done looking at the contents, close the inventory.dat file.

2. You will first create the ITEM table where the data will be stored.

Leaving the C:\079176 window open, launch SQL*Plus and log in as sys.

At the SQL*Plus prompt, issue the following command to create theITEM table:

CREATE TABLE item(item_id NUMBER(12,0),vendor_id NUMBER(12,0),item_name VARCHAR2(64),descr VARCHAR2(1000),unit VARCHAR2(5),retail_price NUMBER(8,2),qty_on_hand NUMBER(8,0))TABLESPACE users;

Lesson 6: Loading and Moving Data 325

Page 341: Oracle 9i DBA Fund - II

Oracle will display the message “Table created.”

3. You will now create the control file for SQL*Loader to load this data.

Leaving SQL*Plus open, choose File→Programs→Accessories→Notepad.This will launch the Notepad application.

4. In this control file, you will specify that the data to be loaded is located inthe file C:\079176\inventory.dat. You will direct the utility to automaticallycreate a bad file called C:\079176\inventory.bad to catch any rows that causeerrors. You will also specify that each field in the datafile is terminated by acomma.

In Notepad, type the following lines:

LOAD DATAINFILE 'C:\079176\inventory.dat'BADFILE 'C:\079176\inventory.bad'INSERTINTO TABLE itemFIELDS TERMINATED BY ','(ITEM_ID,VENDOR_ID,ITEM_NAME,DESCR,UNIT,RETAIL_PRICE,QTY_ON_HAND

)

Once you have completed the contents of the file, save the file to theC:\079176 directory. Change the Save As Type to ALL Files, and namethe file INVENTORY.CTL

326 Oracle9i Database: Fundamentals II

Page 342: Oracle 9i DBA Fund - II

5. Open a command prompt.

At the command prompt, launch SQL*Loader to load theINVENTORY.DAT file into the database. Use the following command:

sqlldr USERID='sys/ora92@ora92 as sysdba' ⇒control=c:\079176\inventory.ctl ⇒log=c:\079176\inventory.log

Once you press Enter, SQL*Loader will execute and load all the data fromthe INVENTORY.DAT file into the ITEM table. You will see the outputfrom the utility scroll by as it loads rows of data. Once you are finishedlooking at the output, exit from the command prompt.

6. Once the load is complete, you should check the SQL*Loader log and badfiles to see if any errors were encountered that caused rows to be rejected.

Switch back to the C:\079176 window. You will see that a bad file was notgenerated, which means that no rows were rejected during the load. Openthe INVENTORY.LOG file.

The log file contains a summary of the activity that took place during theload. Take a moment to look through the file. Once you are done looking at

The double arrow (⇒)indicates that commandshould be typed on a singleline and is not part of thesyntax.

Lesson 6: Loading and Moving Data 327

Page 343: Oracle 9i DBA Fund - II

the file, close the Notepad window and the C:\079176 folder.

7. You will now confirm that all 5000 rows have indeed been loaded into theITEM table.

At the SQL*Plus prompt, issue the following query:

SELECT COUNT(*)FROM item;

The output will show that the ITEM table now contains all 5000 rows fromthe INVENTORY.DAT file.

8. You can query the ITEM table to see some of its contents.

First, format the output of your query with the following commands:

328 Oracle9i Database: Fundamentals II

Page 344: Oracle 9i DBA Fund - II

COLUMN item_name FORMAT a25COLUMN descr FORMAT a30SET LINES 132 PAGES 30

Issue the following query:

SELECT *FROM itemWHERE rownum<=20;

The output will show that the ITEM table now contains the rows of datafrom the INVENTORY.DAT file.

9. Exit from SQL*Plus.

Direct Load InsertsStandard SQL allows you to issue an INSERT statement that can retrieve datafrom a table using a standard query and load the rows into another table. A directload insert provides the capability to perform the same task and bypass the SQLprocessing engine to perform a direct-path mode, much in the same way thatSQL*Loader performs a direct path load. This can greatly reduce the amount ofresources consumed to process the statement, which can significantly increase itsperformance.

To perform a direct load insert, you would simply include the APPEND hintimmediately after the INSERT keyword in the statement. This instructs theOracle optimizer to append the result set of the query directly to the target tablewithout having to pull the target datablocks into the buffer cache first. A directload insert can only be performed on INSERT statements that contain a subquery.If you include the APPEND hint with a standard, single-row insert, the hint willbe ignored and Oracle will perform a standard insert.

While a single insert statement can only insert rows into a single table, the queryyou specify can be any valid SELECT statement, which may include any numberof tables. This provides the capability to combine values from multiple tables,perform calculations, and summarize data as necessary. The hint is specified as a

The list of items shown inthe output may not be listedin the same order that isshown here.

direct load insert:A method of loading datafrom one table to anotherusing a direct path load.

Lesson 6: Loading and Moving Data 329

Page 345: Oracle 9i DBA Fund - II

special comment within the statement itself. The APPEND keyword is enclosedinside a set of comment brackets, namely slashes and asterisks, and must includea plus sign (+) as well. When formed properly, a hint can influence Oracle’soptimizer to generate a slightly different execution plan than it normally wouldwithout the hint. A properly formed hint would look like this:

/*+ APPEND */

If Oracle determines that the action specified by the hint is simply not possible,or is missing the plus sign, it will ignore the hint as a simple comment and makeits own determination of how to execute the statement.

The following is an example INSERT statement that will perform a direct loadinsert.

INSERT /*+ APPEND */ INTO monthly_resultsSELECT TO_CHAR(a.trans_date,'MON'), a.item_name,SUM(b.final_price)FROM transactions a, orders bWHERE a.order_id = b.order_idGROUP BY TO_CHAR(a.trans_date,'MON');

In this example, the APPEND hint is properly included after the INSERTkeyword. The SELECT statement performs a join of the TRANSACTIONS andORDERS tables. The results are appended to the end of the MONTHLY_RESULTS table, without needing to pull the target datablocks into the buffercache first.

TASK 6A-2Loading Data Using Direct Load Inserts

Objective: To load data into a table with a direct load insert.

1. Launch SQL*Plus and log in as sys.

To see the difference between a direct load insert and a conventional insert,you will look at the differences between the execution plans of each type ofstatement. You will first need to create the PLAN_TABLE, which will holdthe execution plan generated by the EXPLAIN PLAN command.

At the SQL*Plus prompt, type @D:\oracle\ora92\rdbms\admin\utlxplan.sqland press Enter.

Oracle will display the message “Table created.” You can now generateexecution plans with the EXPLAIN PLAN command.

2. You will create an empty table, called ITEM_DIRECT, with a structure iden-tical to that of the ITEM table. This table will serve the target of our directload insert.

Direct Load Inserts

330 Oracle9i Database: Fundamentals II

Page 346: Oracle 9i DBA Fund - II

At the prompt, create the ITEM_DIRECT table by issuing the followingcommand:

CREATE TABLE item_directTABLESPACE users ASSELECT *FROM itemWHERE 0=1;

Oracle will display the message “Table created.”

To verify that the ITEM and ITEM_DIRECT tables are identical, issue thefollowing commands:

DESCRIBE itemDESCRIBE item_direct

The output will show that the two tables are indeed identical.

3. You will now generate an execution plan for a conventional INSERT state-ment which reads all the rows from the ITEM table and inserts them into theITEM_DIRECT table.

At the prompt, issue the following command:

EXPLAIN PLAN FORINSERT INTO item_directSELECT *FROM item;

Oracle will display the message “Explained.”

4. To see the execution plan you just created, type @C:\079176\listplan.sqland press Enter.

Lesson 6: Loading and Moving Data 331

Page 347: Oracle 9i DBA Fund - II

The execution plan will show a simple insert statement, and a simple tableaccess of the ITEM table.

5. You will now generate an execution plan for a direct load INSERT state-ment to read all the rows from the ITEM table, and append them to theITEM_DIRECT table.

To clear out the plan table, type TRUNCATE TABLE plan_table; andpress Enter.

Oracle will display the message “Table truncated.”

At the prompt, issue the following command:

EXPLAIN PLAN FORINSERT /*+ APPEND */ INTO item_directSELECT *FROM item;

Oracle will display the message “Explained.”

6. To see the new execution plan you just created, type @C:\079176\listplan.sql and press Enter.

The output will show a different execution plan for this INSERT statementthan the previous statement. This execution plan shows an INSERT state-ment and a table access of the ITEM table, just as before, but this time the

332 Oracle9i Database: Fundamentals II

Page 348: Oracle 9i DBA Fund - II

option LOAD AS SELECT is also included. This indicates a direct loadinsert into the target table.

7. You will now execute the direct load insert into the ITEM_DIRECT table.

At the prompt, issue the following command:

INSERT /*+ APPEND */ INTO item_directSELECT *FROM item;

Oracle will display the message “5000 rows created.” Type COMMIT; andpress Enter.

8. Exit from SQL*Plus.

External TablesOracle9i provides a feature that enables you to access external data using stan-dard SQL as if you were querying a table or a view. You can create externaltables, which are table-like structures that direct Oracle to read the data fromexternal files and return it to the calling user. Creating and using external tableseliminates the need to use a separate process that loads the data into the databasebefore processing it. Oracle provides the clause ORGANIZATION EXTERNALfor the CREATE TABLE command to define external tables.

The definition of an external table looks very much like a combination of thestandard CREATE TABLE syntax and a SQL*Loader controlfile. The CREATETABLE command includes the logical structure of the table, meaning the columnsand their data types. It also includes the location where the external file can befound and the information about how the data is formatted in the file. When theexternal table is accessed, thefile that contains the data is read sequentially tofetch the data into the buffer cache. External tables are read-only tables, and youcannot generate indexes on them. Also, you must take extra care to ensure thesecurity of the data because any user that has sufficient privileges through theoperating system can open and read the datafile.

external table:A table-like structure inOracle that accesses anexternal flat file containingdata.

Lesson 6: Loading and Moving Data 333

Page 349: Oracle 9i DBA Fund - II

Before creating external tables, you must first ensure that the Oracle database hasthe appropriate privileges to read from the directory where the file resides in theoperating system. You must then create a special object called a directory withinthe Oracle database. The directory specifies the path where the external fileresides. The syntax to create a directory is shown here.

CREATE OR REPLACE DIRECTORY dir_name AS 'os_path';

In this syntax, dir_name is the name assigned to the directory from within theOracle database. This name can be any character string up to 30 characters inlength and cannot start with a number or special character. The os_path specifiesthe full directory path in the file system. The following command will create adirectory called ETL_LOAD that references the C:\etl\weekly directory on theserver location within the host file system external to the database.

CREATE OR REPLACE DIRECTORY etl_load AS 'C:\etl\weekly';

You can create as many directories as you like, and any valid directory can con-tain multiple text files for use by external tables. Additionally, just likeSQL*Loader, external tables provide a way to handle invalid data that might befound in the datafile. If a row of data fails validation for any reason, such as acharacter found in a column that is supposed to contain only numbers, the rowwill be rejected. You can direct Oracle to send rejected rows to a bad file, whichcan reside in its own directory or in the same directory as the datafile. You canalso specify a log file that will capture any informational messages generated byOracle when the file is accessed.

Once the required directories are created, the owner of the table and any usersthat need to access the external table will need privileges on the directory. Theowner and all other users will need at least the READ privilege on the directorythat contains the datafile. They will also need at least the WRITE privilege on thedirectories that will contain the bad and log files. To grant these privileges, youwould use the standard GRANT command, which is shown here.

GRANT {READ | WRITE} ON dir_name TO user_name;

The CREATE TABLE command contains many clauses and keywords to supportexternal tables. To illustrate its use effectively, we will look at an exampleCREATE TABLE statement for an external table, which is shown here.

CREATE TABLE DISTRICT.STORES_EXT( STORE_ID NUMBER(12,0),REGION_ID NUMBER(12,0),MGR_NAME VARCHAR2(64),MGR_PHONE VARCHAR2(25),STORE_TYPE VARCHAR2(5)

)ORGANIZATION EXTERNAL( TYPE ORACLE_LOADERDEFAULT DIRECTORY dat_dirACCESS PARAMETERS

( RECORDS DELIMITED BY NEWLINEFIELDS TERMINATED BY ','LOGFILE log_dir:'stores_%p.log'BADFILE bad_dir:'stores_%p.bad'

334 Oracle9i Database: Fundamentals II

Page 350: Oracle 9i DBA Fund - II

( store_id,region_id,mgr_name,mgr_phone,store_type

))LOCATION ('stores.dat'))REJECT LIMIT UNLIMITEDPARALLEL (DEGREE 4);

In this syntax, you can see that the command looks like a hybrid between theCREATE TABLE command and a SQL*Loader control file. The first half pro-vides the column names and their data types. The second half specifies how tohandle the file containing the data.

The clause that tells Oracle that the table is an external table isORGANIZATION EXTERNAL. The TYPE clause specifies the access driver,which is the utility that is to be used to access the external data and pass it to theOracle database. The default for this clause is ORACLE_LOADER. Currently,ORACLE_LOADER is the only value allowed for the TYPE clause. It is expectedthat future versions of Oracle may allow additional types of access drivers toaccess the external files.

The DEFAULT DIRECTORY clause specifies the directory to look in to find thedatafile. This directory must first be created with the CREATE DIRECTORYstatement prior to creating the external table. The ACCESS PARAMETERS clausecontains a list of access driver-specific commands to access the data. For theORACLE_LOADER access driver, you can use a syntax very similar to the columnlisting in a SQL*Loader control file.

Within the ACCESS PARAMETERS clause, you would specify how the data inthe external file is formatted. These parameters are not read by the Oracledatabase. Instead, they are passed to the access driver, which uses them to deter-mine how to read the data in the text file. In our example, the RECORDSDELIMITED BY NEWLINE clause indicates that each record is terminated by acarriage return. Also, the FIELDS TERMINATED BY clause specifies how thefields in a single record are separated. In our example, the fields are separated bycommas.

The LOGFILE and BADFILE clauses specify the directories and file names touse for the output log file and badfile, respectively. As stated earlier, all users thatneed to access an external table must have write privileges on these directories.This holds true even if no errors are encountered, and the bad file remains empty.In the file names for these files, you can optionally specify variables to dynami-cally create file names for each log generated. In our example, the variable %pindicates that the OS process ID for the user will be used as part of thefile name.This will ensure that previously generated files will not be overwritten.

The LOCATION clause lists the name of the external file that contains the data.You can even specify multiple file names if the data spans multiple files. Whenaccessing an external table that is made up of multiple files, the files will be readsequentially in the order specified by the LOCATION clause.

The REJECT LIMIT clause specifies how many data access errors are allowedbefore a query is terminated. For example, if the REJECT LIMIT is set to 100,then 100 data access errors will be allowed. The 101st data access error willreturn an error to the user, and the query will be terminated. The value of

Although the default accessdriver for external tables,ORACLE_DRIVER, behavesvery much like SQL*Loader,it is actually not SQL*Loader.The access driver is acompletely different utilitythat was designed to lookand act like SQL*Loader.

Lesson 6: Loading and Moving Data 335

Page 351: Oracle 9i DBA Fund - II

UNLIMITED states that an unlimited number of errors will be allowed. Accesserrors can occur when there is some sort of conversion error on the data in thefile, such as when a character is found in a piece of data that is mapped to aNUMBER data type, or when a character string from the text is wider than its cor-responding column data type will allow.

It is important to remember that you cannot create indexes on external tables, andbecause the files are read sequentially, every pass through an external table willbe equivalent to a full-table scan. You can, however, specify a PARALLEL clause,which allows you to set the degree of parallelism for an external table just as youwould for a normal table. This will enable parallel execution for all queries thataccess the table. It is recommended that you set the PARALLEL clause to a valuethat is at least equal to the number of text files you have. This will allow you toplace your text files on separate disks and balance the I/O throughput, whileallowing parallel access to the data.

Once an external table is created, you can query the table by using basic SQLstatements and access its data as you would with any normal table; you can evenjoin an external table with other tables or views. You can also use data loadingcommands, such as CREATE TABLE...AS SELECT or a direct-load insert, toquery from the external table and load its data into another location within thedatabase. Such processing provides a powerful feature that can load data from aflat file into the database and easily specify filter conditions to narrow down thedata that will be loaded.

TASK 6A-3Creating and Accessing External Tables

Setup: To create and access external tables to read and load data fromoutside the database.

1. You will first create the directories that will hold the datafile, the log file,and the bad file. The three directories will be called data, log, and bad,respectively.

In the C:\079176 directory, create the data, log, and bad directories.

2. You will use the inventory.dat file as the data source for your external table.

Move or copy the inventory.dat file into the data directory.

3. Launch SQL*Plus and log in as sys.

Before you can access the file, you must first tell Oracle where this file islocated. This is done by creating a directory within the database that pointsto the actual path where the file is located. You must also create directoriesto tell Oracle where to create the log and bad files.

To create these directories, issue the following commands at the prompt:

CREATE OR REPLACE DIRECTORY dat_dir AS 'C:\079176\data';CREATE OR REPLACE DIRECTORY log_dir AS 'C:\079176\log';CREATE OR REPLACE DIRECTORY bad_dir AS 'C:\079176\bad';

336 Oracle9i Database: Fundamentals II

Page 352: Oracle 9i DBA Fund - II

After each command, Oracle will display the message “Directory created.”

4. You will now create the external table. This table will have the followingstructure.

COLUMN DATATYPEitem_id NUMBER(12,0)vendor_id NUMBER(12,0)item_name VARCHAR2(64)descr VARCHAR2(1000)unit VARCHAR2(5)retail_price NUMBER(8,2)qty_on_hand NUMBER(8,0)

The following information will be used to create the external table:

• The external table will be called ITEM_EXT.

• The inventory.dat file is located in the dat_dir directory.

• All records in the inventory.dat file are terminated by a newlinecharacter.

• Each field in the inventory.dat file is delimited by a comma (,).

• Any log information will be directed to the log_dir directory into a filecalled itemext_%p.log.

• Any log information will be directed to the log_dir directory into a filecalled itemext_%p.log.

• In the names of the log and bad files, %p indicates the process ID ofthe user session attempting to access the table.

Lesson 6: Loading and Moving Data 337

Page 353: Oracle 9i DBA Fund - II

Create the ITEM_EXT table by issuing the following command from theprompt:

CREATE TABLE item_ext(item_id NUMBER(12,0),vendor_id NUMBER(12,0),item_name VARCHAR2(64),descr VARCHAR2(1000),unit VARCHAR2(5),retail_price NUMBER(8,2),qty_on_hand NUMBER(8,0)

)ORGANIZATION EXTERNAL(TYPE ORACLE_LOADERDEFAULT DIRECTORY dat_dirACCESS PARAMETERS(RECORDS DELIMITED BY NEWLINELOGFILE log_dir:'itemext_%p.log'BADFILE bad_dir:'itemext_%p.bad'FIELDS TERMINATED BY ','(item_id,vendor_id,item_name,descr,unit,retail_price,qty_on_hand)

)LOCATION ('inventory.dat'))REJECT LIMIT UNLIMITED;

Oracle will return the message “Table created.”

The syntax for this CREATETABLE command is

somewhat lengthy. If youhave problems typing in the

entire command, you canfind the exact command inthe C:\079176\item_ext.sql

file.

338 Oracle9i Database: Fundamentals II

Page 354: Oracle 9i DBA Fund - II

5. To bring up a description of the ITEM_EXT table, type DESCRIBE item_ext and press Enter.

Oracle will display the column layout of the ITEM_EXT table. You will seethat it looks identical to a typical Oracle table.

6. Now that the external table has been created, you can query from it just likeany other table.

To see the total number of rows in the table, issue the following query:

SELECT COUNT(*)FROM item_ext;

The output will show that there are 5000 rows in the ITEM_EXT table.

7. To find how many items were purchased from each vendor, issue the follow-ing query:

SELECT vendor_id, COUNT(item_id)FROM item_extGROUP BY vendor_id;

Lesson 6: Loading and Moving Data 339

Page 355: Oracle 9i DBA Fund - II

Oracle will display the number of items that have been purchased pervendor.

8. Since an external table can be queried just like any other table, this becomesa convenient and powerful method for loading data into the database. Youwill query from the table and direct the data to be loaded into another table.

You will create a new table based on the data from the ITEMS_EXT exter-nal table. This new table will be called HIGHER_ITEMS, and will containonly items that have a retail price that is greater than 40 dollars.

At the prompt, issue the following command:

CREATE TABLE higher_itemsTABLESPACE usersASSELECT *FROM item_extWHERE retail_price > 40;

Oracle will display the message “Table created.”

9. To see how many rows exist in your new table, issue the following query:

SELECT COUNT(*)FROM higher_items;

340 Oracle9i Database: Fundamentals II

Page 356: Oracle 9i DBA Fund - II

The output will show that only 2728 of 5000 rows were loaded into theHIGHER_ITEMS table.

10. To see the lowest retail price of the items in this table, issue the followingquery:

SELECT MIN(retail_price)FROM higher_items;

Oracle will display the lowest retail price that exists in the HIGHER_ITEMStable. Only the items with a retail price greater than 40 dollars wereretrieved from the ITEMS_EXT external table and loaded into the HIGHER_ITEMS table.

External tables provide a very convenient method of accessing data that isexternal to the Oracle database. They can be queried like any other table,and can even be joined with other tables and views. External tables also pro-vide a simple but flexible method of loading data into the Oracle database,which can be invaluable in data warehousing environments.

11. Exit from SQL*Plus and close all open windows.

Topic 6BThe Export and Import UtilitiesThe export and import utilities are command line executables that allow you toquickly reorganize data in a database or to move data from one database toanother. The flat file created by the export utility is in binary format and can onlybe read by Oracle’s import utility, but it can be imported into another database,even if the target database resides on another operating system. This comes inespecially useful if you need to quickly move an entire database from one plat-form to another.

Lesson 6: Loading and Moving Data 341

Page 357: Oracle 9i DBA Fund - II

The Export UtilityThere are five levels of exports, which are table, user, tablespace, transportabletablespace, and full. The privileges granted to a user dictate which export the useris allowed to perform. For example, any user can perform a table-level export ofa single table in their own schema, while a full export requires the user to at leasthave the EXP_FULL_DATABASE role. This role provides the user with enoughpermissions to read from all objects in the database.

A table-level export is an export of one or more tables. This type of export canbe used to quickly move large tables from one database to another, or from oneschema to another. When doing a table-level export, you can specify any tablefrom any user’s schema that you have the privileges to access. Additionally, youcan export a combination of tables from different schemas at the same time. Theexport utility even provides a table name pattern-matching feature, by using thepercent sign (%) with the TABLES argument, similar to the pattern matching thatcan be used in the WHERE clause of a SQL statement. For example, if you wishto export all the tables in the database that have names beginning with the string‘FACT’, you could use the following export command:

exp userid=system/oracle@ora92 file=d:\oracle\testexp.dmp ⇒tables=fact%

Unlike the WHERE clause of a SQL statement, the only wildcard supported for theTABLES argument is the percent sign; the underscore (_) is not supported. How-ever, you can include any number of percent signs in any position of the tablename. All accessible tables that have a name matching the pattern are exported tothe file. The import utility supports the same pattern matching functionality withthe TABLES argument. All the tables that have a name matching the specifiedpattern will be imported into the target database.

The export utility also provides the capability of exporting only subsets of dataduring a table-level export. This is done by including a set of conditions with theQUERY argument of the export command. Only the data that satisfies the querywill be exported. If you are exporting multiple tables simultaneously, the sameconditions will apply to all tables.

A user-level export is an export of an entire user’s schema. All objects owned bythe user, such as tables, indexes, constraints, and sequences, will be exported tothe export file. In a user-level export, you can export more than one user at atime by specifying each source user in the export command. However, you can-not mix export modes. For example, you cannot export a single table from oneuser’s schema and another user’s schema in its entirety. A single export must bedone in one mode only. You can, however, export a single table from oneschema, and all the tables from another schema. The disadvantage in doing this isthat you will be missing all other objects and privileges from both users.

A tablespace-level export will export all objects stored in one or moretablespaces, as specified by the TABLESPACES argument. As long as you havesufficient privileges on the objects, the contents of the specified tablespaces areexported to the export file. Additionally, any indexes that belong to the tables inthe exported tablespaces are exported as well, regardless of which tablespaces theindexes are stored in. This type of export is slightly different than a transportabletablespace export, in which no data from the source tablespace is actuallyexported. The export utility exports only the required information from data dic-tionary relevant to the source tablespaces. The datafiles that make up thetablespace are then copied to the target database, and the data dictionary informa-tion is imported back in. You will learn more about transportable tablespace laterin this lesson.

Types of Exports

342 Oracle9i Database: Fundamentals II

Page 358: Oracle 9i DBA Fund - II

A full database export will export everything in the database, with the exceptionof the SYS schema. All users, including their privileges and objects, are exportedinto the export file. This requires the EXP_FULL_DATABASE role or an equiva-lent set of privileges. When exporting the entire database, you cannot selectivelychoose tables or users; it’s all or nothing.

Like SQL*Loader, the export utility also provides both conventional and directpath exports. During a conventional-path export, the export utility generates stan-dard SELECT commands to read data from the source objects, which areprocessed by the SQL processing engine in the database. A direct-path export willbypass the SQL processing engine and write directly to the export file, which cangreatly improve the speed of the export.

The export command comes with a list of available arguments that can be passedat the command line. These arguments dictate the type of export and import per-formed, and specify other options while executing. The following table shows alist of some of the available export arguments and valid values for each.

Argument Valueuserid User name and password of the user executing the utility. Must be the first

argument passed at the command line.buffer Size of the data buffer in bytes.file Path and file name of the export file to create.compress Indicates that each object to be exported will later be imported into a single

extent. The default is Y, to indicate that objects will be compressed.grants Indicates whether user privileges will be included in the export. The default

is Y.indexes Indicates whether indexes will be included in the export. The default is Y.rows Indicates whether rows of data will be included in the export. The default is

Y. If set to N, then only the structure of the objects will be exported.contraints Indicates whether constraints will be included in the export. The default is

Y.log Path and file name of the log file to record screen output.direct Indicates whether the export should be done in direct mode.feedback Sets the number of rows to use for feedback. For every row exported, the

utility will display a dot (.) to the screen to show its progress. The defaultis 0.

filesize Sets the maximum size of the export file. When the size of the first filegrows to this size, and if multiple files are listed by the file argument,the export utility will automatically begin writing to the next file. If multiplefiles are not listed, the export will halt with an error.

query Lists the conditions to filter the data prior to exporting.full Indicates whether to perform a full database export. The default is N. Can-

not be used in conjunction with owner, tables, ortablespaces.

owner Lists the users to export for a user-level export. Cannot be used inconjunction with full, tables, or tablespaces.

tables Lists the tables to export for a table-level export. Cannot be used inconjunction with full or owner.

recordlength Specifies the length of the file record in bytes. The default is operatingsystem dependent.

parfile Path and file name of optional parameter file to hold export parameters.

Lesson 6: Loading and Moving Data 343

Page 359: Oracle 9i DBA Fund - II

Argument Valueconsistent Indicates whether constraint-checking should occur during export to keep

the tables in the export file consistent. The default is Y.triggers Indicates whether triggers should be included in the export. The default is

Y.

The export utility also provides a help screen that can be accessed by runningexport utility with only the help=y argument. The help screen will display a listof all available arguments with their descriptions. The following shows a sampleexport command to take a user-level export of the user Scott.

exp userid=sys/oracle file=d:\export\scott.dmp ⇒log=d:\export\scott.log direct=y feedback=1000 owner=scott

In this example, Scott’s entire schema will be exported into the SCOTT.DMPexport file. The export will be performed in direct mode and will display a dotfor every 1000 rows exported. An export file should never be opened or edited.Doing so could corrupt the file, which will render it useless. The only recoursefor dealing with a corrupted export file is to take another export.

TASK 6B-1Exporting the Database

Objective: To export the contents of the database using the export utility.

1. You will first perform a full database export. You will perform the export indirect mode, and the export file will be named exp_ora92_full.dmp.

Open a command prompt. At the prompt, issue the following commandas if it was a single line of input:

exp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\exp_ora92_full.dmp ⇒log=C:\079176\exp_ora92_full.log full=y direct=y

Once you press Enter, the export will begin. You will see the window fillwith informational messages as the utility processes each step of the export.All objects in the database, except for those owned by SYS, will be exported

344 Oracle9i Database: Fundamentals II

Page 360: Oracle 9i DBA Fund - II

to the exp_ora92_full.dmp file. It will take a few minutes for the export tocomplete.

2. You will now perform an export of just a single schema. The schema youwill use for this export is OE, which is the user for the order entry exampleschema.

At the prompt, issue the following command as if it was a single line ofinput:

exp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\exp_ora92_oe_schema.dmp ⇒log=C:\079176\exp_ora92_oe_schema.log owner=oe direct=y

Once you press Enter, the export will begin. This time, only the objectsowned by the OE user will be exported to the exp_ora92_oe_schema.dmpfile. It will take a few minutes for the export to complete.

3. You will perform an export of only those objects that reside in theEXAMPLE tablespace. All objects in this tablespace, regardless of whichuser owns them, will be exported to the exp_ora92_example_ts.dmp file. Theexport will also include any indexes on the tables in the EXAMPLEtablespace, even if those indexes are stored in a different tablespace.

Lesson 6: Loading and Moving Data 345

Page 361: Oracle 9i DBA Fund - II

At the prompt, issue the following command as if it was a single line ofinput:

exp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\exp_ora92_example_ts.dmp ⇒log=C:\079176\exp_ora92_example_ts.log ⇒tablespaces=example direct=y

Once you press Enter, the export will begin. All objects in the EXAMPLEtablespace will be exported. It will take a few minutes for the export tocomplete.

4. You will now perform an export of only a single table. The table you willuse is the SCOTT.EMP table.

At the prompt, issue the following command as if it was a single line ofinput:

exp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\exp_ora92_scott_emp.dmp ⇒log=C:\079176\exp_ora92_scott_emp.log ⇒tables=scott.emp direct=y

346 Oracle9i Database: Fundamentals II

Page 362: Oracle 9i DBA Fund - II

Once you press Enter, the Scott’s EMP table will be exported to the file. Theexport should complete fairly quickly.

5. You will now perform an export of several tables owned by the SH user, allof which have names that begin with the letter C.

At the prompt, issue the following command as if it was a single line ofinput:

exp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\exp_ora92_wildcard.dmp ⇒log=C:\079176\exp_ora92_wildcard.log tables=SH.C% direct=y

Once you press Enter, all the tables owned by SH that begin with the letterC will be exported.

The export utility provides a wide variety of features to allow DBAs andusers a powerful method of extracting data from an Oracle database. Theutility can export the entire database, one or more users’ schemas, the con-tents of a tablespace, one or more specific tables, or even a list of tables thatmatch a certain naming pattern.

6. Exit from the command prompt.

Lesson 6: Loading and Moving Data 347

Page 363: Oracle 9i DBA Fund - II

The Import UtilityLike the export utility, the import utility also provides five modes of import.Depending on his or her privileges, a user can perform a table-level, user-level,tablespace-level, transportable tablespace, or full import. However, any mode ofimport can be performed on an export file created from any mode of export, withthe exception of the tablespace-level export.

For example, an export file created from a full database export can be used toimport only a single user’s schema or even a single table. Only a subset of thedata contained in the export file will be imported. An export file created from atable-level export can be used for a full import. A full import on any export fileresults in the entire contents of the file being imported. If a table-level export isused for a full import, only the tables owned by the specified user will beimported. Figure 6-3 represents an export file that contains a full database export,and is used for a table level import. A tablespace-level export can only beimported with a tablespace-level import. The import utility does not provide adirect-path import.

Figure 6-3: A full export used for a table-level import.

The import utility provides many of the same arguments as the export utility. Thefollowing table shows a list of available arguments for the import utility.

Argument Valueuserid User name and password of the user executing the utility. Must be the

first argument passed at the command line.buffer Size of the data buffer in bytes.file Path and file name of the file to import from.show Instructs the import utility to only show the contents of the source file.

No data will be imported. The default is N.ignore Specifies whether to ignore create errors during import due to the

object already existing. The default is N.grants Indicates whether user privileges will be imported. The default is Y.indexes Indicates whether indexes will be imported. The default is Y.rows Indicates whether rows of data will be imported. The default is Y. If set

to N, then only the structure of the objects will be imported.contraints Indicates whether constraints will be imported. The default is Y.log Path and file name of the log file to record screen output.commit Specifies whether to send a COMMIT command each time all the data

in the import buffer has been written to the datafiles. The default is N.

A Full Export Used for aTable-level Import

348 Oracle9i Database: Fundamentals II

Page 364: Oracle 9i DBA Fund - II

Argument Valuefeedback Sets the number of rows to use for feedback. For every row imported,

the utility will display a dot (.) to the screen to show its progress. Thedefault is 0.

destroy Clear the contents of the target datafiles prior to importing the data. Thedefault is N.

full Indicates whether to import all the contents of the entire file. The defaultis N. Cannot be used in junction with fromuser, touser, ortables.

fromuser Specifies the name of the schema to import. Can be used inconjunction with touser and tables to transfer objects from oneschema to another. Cannot be used in conjunction with full.

touser Specifies the name of the target schema that will receive the importedobjects. Can be used in conjunction with fromuser and tablesto transfer objects from one schema to another. Cannot be used inconjunction with full.

tables Lists the tables to import for a table-level import. Cannot be used inconjunction with full, but can be used with fromuser andtouser.

recordlength Specifies the length of the file record in bytes. The default is operatingsystem dependent.

parfile Path and file name of optional parameter file to hold import parameters.statistics Specifies how to handle object statistics while importing. Possible

values include ALWAYS, RECALCULATE, NONE, and SAFE. Thedefault is ALWAYS.

indexfile Path and file name of a script file that can be generated to contain theCREATE commands to create all tables and indexes in the importfile. No data will be imported when this argument is specified.

Like the export utility, the import utility also provides a help screen that can beaccessed by passing the argument help=y at the command line. The followingshows a sample import command to perform a full import.

imp userid=sys/oracle file=d:\import\scott.dmp ⇒log=d:\import\scott.log feedback=1000 full=y

In this example, the entire contents of the SCOTT.DMP file will be imported intothe database. All screen output will be recorded in the SCOTT.LOG file, and theutility will generate a dot for every 1000 rows imported to show its progress.Once the tables are imported, the utility will pass the appropriate commands toOracle to enable any referential integrity constraints on the tables. If any con-straints cannot be enabled for any reason, such as a foreign key that references atable that does not exist, the import utility will display a warning to the screen,but will continue with the import. Additionally, any PL/SQL packages, proce-dures, and functions that are included in an export file, namely a full or user-levelexport, will be automatically created and compiled at the end of the importprocess. If compiling these objects are subject to any errors, the objects are stillcreated, but are left in an invalid state. The import utility will display a warningmessage about the error and continue its process.

Lesson 6: Loading and Moving Data 349

Page 365: Oracle 9i DBA Fund - II

TASK 6B-2Importing Data into the Database

Objective: To import data from an export file into the database.

1. In the previous task, you performed several exports from the database, oneof which was a full database export. From that full export, you will performa table level import to import a single table from the HR schema into theSCOTT schema. The table you will import is called JOB_HISTORY.

First, you will confirm that Scott does not currently own a table called JOB_HISTORY.

Launch SQL*Plus and log in as sys.

At the SQL*Plus prompt, issue the following query:

SELECT table_nameFROM dba_tablesWHERE owner='SCOTT';

The output will show that Scott owns four tables, but none of them arenamed JOB_HISTORY.

2. Leaving the SQL*Plus window open, open a command prompt.

350 Oracle9i Database: Fundamentals II

Page 366: Oracle 9i DBA Fund - II

At the prompt, issue the following command as if it was a single line ofinput:

imp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\exp_ora92_full.dmp ⇒log=C:\079176\imp_ora92_job_hist.log ⇒fromuser=hr touser=scott tables=job_history

Once you press Enter, the import will begin. The import utility will find theJOB_HISTORY table almost immediately and import it from the HR schemainto the SCOTT schema.

After a few moments however, the utility will display several error messages

Lesson 6: Loading and Moving Data 351

Page 367: Oracle 9i DBA Fund - II

when attempting to enable constraints on the table.

The JOB_HISTORY table was imported into Scott’s schema, but severalforeign key constraints could not be enabled because they reference tablesthat Scott does not currently own. However, the final message in the output,which states “Import terminated successfully with warnings,” indicates thatthe table was imported even though some warnings were raised during theprocess.

Exit from the command prompt.

3. You will now confirm that the JOB_HISTORY table does indeed exist inScott’s schema.

At the SQL*Plus prompt, type / and press Enter.

Your previous query will execute again. This time, the output will show thatScott now owns a table called JOB_HISTORY.

4. Exit from SQL*Plus.

352 Oracle9i Database: Fundamentals II

Page 368: Oracle 9i DBA Fund - II

Transportable TablespacesIn the previous topic, you learned how to export data from the database andimport it back in again. You learned about full, table, user, tablespace-levelexports and imports. A transportable tablespace export is a special kind of exportthat does not actually export any data. The metadata in the data dictionary that isrelevant to the tablespaces you are transporting are exported into a dictionary file.The datafiles that make up the tablespaces are then copied over to the target data-base and the dictionary file is imported. This feature can only be used betweentwo databases that reside on compatible operating systems.

Transportable tablespaces provide several advantages over other methods of mov-ing data, including other types of exports and imports. Generally, usingtransportable tablespaces is much faster than a standard export and import. This isbecause only the tablespace metadata must be exported, instead of the tablespacecontents. The tablespace metadata is usually very small in size, while thetablespace itself could be gigabytes in size.

There are some limitations to consider when moving data with transportabletablespaces. Both the source and target databases must have identical block sizesand must be of the same character set. You cannot transport a tablespace into adatabase where a tablespace of the same name already exists. Also, tablespacesbeing transported cannot contain replication objects or function-based indexes.The owners of the objects in a tablespace to be transported must already exist inthe target database. Only the tablespace metadata will be moved over and not theuser metadata.

The steps to transport tablespaces from one database to another are fairly simple.They are:

1. Select a set of tablespaces that are self-contained (for example, have nodependencies on objects in tablespaces not included in the set).

2. Create the dictionary file using the export utility.

3. Copy the datafiles and export file to the server where the target databaseresides.

4. Import the dictionary file into the target database.

In step 1, you must choose a set of tablespaces that are self-contained. Thismeans that objects within the tablespaces to be transported have no dependencieson other objects that do not reside in a tablespace included in the set. Forexample, let’s say you wanted to transport the INVENTORY_DATA andINVENTORY_INDEXES tablespaces together. The INVENTORY_INDEXEStablespace contains an index on the EMPLOYEE table that resides in theEMPLOYEE tablespace. In this scenario, the INVENTORY_DATA andINVENTORY_INDEXES tablespaces could not be transported together. Thisstands to reason, since once the tablespaces are moved over, you would have anindex without an associated table.

The issue of integrity constraints can play a role in determining if a tablespace setis self-contained. If you decide to transport the tablespaces with constraintsenabled, and one or more tables have referential constraints to tables outside thetablespace set, then the transport will not be allowed. If you decide you want totransport the tablespaces anyway, you can do so with the constraints disabled.However, be very careful when doing this, as this could lead to an inconsistentset of data in the tablespaces being transported.

transportabletablespace:An Oracle feature that allowsyou to copy an entiretablespace from onedatabase to another bysimply exporting thetablespace metadata from thedata dictionary.

The COMPATIBLEinitialization parameter onboth the source and targetdatabases must be set to 8.1or higher.

Lesson 6: Loading and Moving Data 353

Page 369: Oracle 9i DBA Fund - II

To determine if a tablespace set is self contained, you would use the DBMS_TTSpackage. This package contains the TRANSPORT_SET_CHECK procedure,which is passed the list of tablespace names. You would also specify whether ornot you want to transport the tablespaces with constraints enabled or disabled.Once this procedure is executed, you can query the TRANSPORT_SET_ VIOLA-TIONS view to see if there are any dependency violations. If this view returns norows, then the tablespace set is self-contained. If there are violations, this viewwill show detailed descriptive information about which objects caused theviolations. The following shows a sample statement to execute theTRANSPORT_SET_CHECK procedure to determine if the INVENTORY_DATAand INVENTORY_INDEXES tablespaces are self-contained.

EXECUTEdbms_tts.transport_set_check('inventory_data,inventory_indexes',TRUE)

In this example, the names of the tablespaces are passed together as a singleargument enclosed in single quotes. The value TRUE is also passed to specifythat the tablespaces are to be transported with constrains enabled.

After the TRANSPORT_SET_CHECK procedure is complete, querying theTRANSPORT_SET_VIOLATIONS view will show dependency violations if any.The following shows a sample output from this view.

VIOLATIONS----------------------------------------Constraint SYS.FK_ITEM_VENDOR_ID betweentable SYS.ITEM in tablespaceINVENTORY_DATA and table SYS.VENDOR intablespace VENDOR

This output shows that the ITEM table in INVENTORY_DATA has a foreign keyconstraint to a table that resides in a tablespace not included in the tablespace set.If you leave the constraints enabled, you will not be allowed to transport this setof tablespaces.

Once you have determined that a set of tablespaces are self-contained, you mustset the tablespaces to read-only with the ALTER TABLESPACE command. Thisis to ensure that the tablespace remains self-contained during the transportingprocess. The syntax to set a tablespace in read-only mode is shown here.

ALTER TABLESPACE tablespace_name READ ONLY;

Once the tablespaces are set to read-only, you can use the export utility to createthe dictionary file that contains the required tablespace metadata. The followingshows an example export command to transport the INVENTORY_DATA andINVENTORY_INDEXES tablespaces.

exp transport_tablespace=y tablespaces=(inventory_data,⇒inventory_indexes) constraints=n file=d:\export\inv_tts.dmp

Notice in this example that the command includes the argumentconstraints=n. This specifies that the tablespace will be transported withoutreferential integrity constraints. This is because we found a dependency violationbetween the ITEM and VENDOR tables. Once this command is issued, theexport utility will prompt for a user name and password. A tablespace-levelexport can only be done by a user with the SYSDBA role. Once logged in, theexport utility will export the metadata and generate the dictionary file. After thedictionary file is created, the tablespaces can be set back to read-write. While thisis not required to transport tablespaces, the data will not be modifiable by userswhile the tablespace is read-only.

354 Oracle9i Database: Fundamentals II

Page 370: Oracle 9i DBA Fund - II

The datafiles and dictionary file can now be transported over to the target system.You can place the datafiles in any directory you like; you will specify their newlocations as part of the import process. Once copied over, the import utility isused to import the dictionary file into the target database. The following shows asample import command to “plug-in” our inventory tablespaces.

imp transport_tablespace=y datafiles=þ'd:\oracle\oradata\ora92\inv_data01.dbf',⇒'d:\oracle\oradata\ora92\inv_indx01.dbf' ⇒tablespaces=inventory_data,inventory_indexes ⇒file=d:\import\inv_tts.dmp

As shown in this example, the datafiles are stored in the d:\oracle\oradata\ora92directory on the target server. The file argument lists the path and file name of thedictionary file that contains the tablespace metadata. Once the metadata isimported, the tablespaces are now part of the new database. The tablespaces areinitially imported as read-only, and can be set to read-write if necessary.

TASK 6B-3Transporting a Tablespace

Objective: To transport a tablespace using the export and import utilities.

1. The transportable tablespace feature was designed to provide a way to movea tablespace between two databases fairly quickly. Since you only have asingle database on your system, you will simulate this behavior by generat-ing a transportable tablespace set for the RMAN tablespace, dropping thetablespace, then importing it back in.

Launch SQL*Plus and log in as sys.

To determine the current status of the RMAN tablespace, issue the follow-ing query:

SELECT tablespace_name, statusFROM dba_tablespacesWHERE tablespace_name='RMAN';

Lesson 6: Loading and Moving Data 355

Page 371: Oracle 9i DBA Fund - II

The output will show that the RMAN tablespace is currently online andavailable for general use.

2. Before transporting a set of tablespaces, you must ensure that the tablespaceset is self-contained. This is done with the TRANSPORT_SET_CHECK pro-cedure of the DBMS_TTS package.

At the prompt, issue the following command:

EXECUTE DBMS_TTS.TRANSPORT_SET_CHECK('RMAN')

Oracle will display the message “PL/SQL procedure successfullycompleted.”

3. If the TRANSPORT_SET_CHECK procedure finds any issues with the listof tablespaces specified that would prevent you from transporting thetablespaces together, it populates the TRANSPORT_SET_VIOLATIONSview with pertinent information about those issues.

To determine if any issues were discovered, issue the following query:

SELECT *FROM transport_set_violations;

Oracle will display the message “no rows selected.” This indicates that thereare no dependencies between the objects in the RMAN tablespace and

356 Oracle9i Database: Fundamentals II

Page 372: Oracle 9i DBA Fund - II

objects in other tablespaces, so the RMAN tablespace can be transported.

4. Before transporting a tablespace, the tablespace must be in read-only mode.

At the prompt, type ALTER TABLESPACE rman READ ONLY; and pressEnter.

Oracle will display the message “Tablespace altered.”

To confirm that the tablespace is in read-only mode, issue the followingquery again:

SELECT tablespace_name, statusFROM dba_tablespacesWHERE tablespace_name='RMAN';

The output will show that the RMAN tablespace is indeed in read-onlymode. The tablespace is now ready for transport.

5. Leaving the SQL*Plus window open, open a command prompt.

At the prompt, generate a transportable tablespace export file by issuing

Lesson 6: Loading and Moving Data 357

Page 373: Oracle 9i DBA Fund - II

the following command as if it was a single input line:

exp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\tts_ora92_rman.dmp ⇒log=C:\079176\tts_ora92_rman.log ⇒transport_tablespace=y tablespaces=rman

Once you press Enter, the export utility will begin to extract the metadatainformation for the RMAN tablespace and it’s contents. However, no datafrom the tables in the RMAN tablespace will be exported.

Once the export is complete, the tts_ora92_rman.dmp file contains all theinformation necessary to import the RMAN tablespace into another database.The export file and all datafiles for the tablespace can be copied to anotherserver, and the tablespace can be imported.

6. Because your system has only one database, you will assume that thedatafile and export file have both been copied to another system, and you areabout to import the tablespace into another database. However, beforeimporting the tablespace, you must first drop the existing RMAN tablespacefrom the database.

Leaving the command prompt open, switch back to the SQL*Plus window.

At the SQL*Plus prompt, type DROP TABLESPACE rman INCLUDINGCONTENTS; and press Enter.

358 Oracle9i Database: Fundamentals II

Page 374: Oracle 9i DBA Fund - II

Oracle will display the message “Tablespace dropped.”

To confirm that the RMAN tablespace has been dropped, issue the followingquery again:

SELECT tablespace_name, statusFROM dba_tablespacesWHERE tablespace_name='RMAN';

Oracle will display the message “no rows selected.” The RMAN tablespaceno longer exists in the database.

7. You will now use the export file you just created to import the RMANtablespace into the database.

Switch back to the command prompt.

At the command prompt, issue the following command as if it were asingle input line:

imp userid='sys/ora92@ora92 as sysdba' ⇒file=C:\079176\tts_ora92_rman.dmp ⇒log=C:\079176\ts_ora92_rman_imp.log ⇒transport_tablespace=y tablespaces=rman ⇒datafiles=D:\oracle\oradata\ora92\rman01.dbf

Once you press Enter, the import process will begin. The output may look asif individual tables were being imported, however only the metadata con-

Lesson 6: Loading and Moving Data 359

Page 375: Oracle 9i DBA Fund - II

cerning those tables are imported into the data dictionary.

Once the import is done, the last line of the output will state “Import termi-nated successfully without warnings.” Close the command prompt.

8. You will now confirm that the RMAN tablespace has been imported asexpected.

At the SQL*Plus prompt, issue the following query again:

SELECT tablespace_name, statusFROM dba_tablespacesWHERE tablespace_name='RMAN';

The output will show that the RMAN tablespace has been imported and iscurrently still set to read-only.

9. To set the tablespace back into read-write mode, type ALTERTABLESPACE rman READ WRITE; and press Enter.

Oracle will display the message “Tablespace altered.”

10. You have successfully transported a tablespace from one database to another.

Exit from SQL*Plus.

360 Oracle9i Database: Fundamentals II

Page 376: Oracle 9i DBA Fund - II

Apply Your Knowledge 6-1

LAB: Table Recovery After User ErrorObjective: To recover a table after a user accidentally deletes all the rows

in a table.

Setup: Open a window to the C:\079176 folder. Double-click the filenamed final_setup. A blank command prompt window willappear for several moments, then disappear. Close theC:\079176 window.

You are the DBA for a database that currently supports an application thathas been in development for several weeks, and the application is scheduledto go live tomorrow. However, a developer calls you to say that he has acci-dentally deleted all 50,000 rows from the SH.CUSTOMERS table, andcommitted the transaction. He states that the contents of the table are abso-lutely critical for the application and must be recovered at all costs.

Your task is to recover the contents of SH.CUSTOMERS table. You may useany skills and techniques you have learned throughout this course, as well asany resources available on your system. The recovery of theSH.CUSTOMER table contents is of the highest priority; the content of anyother user tables in the database is irrelevant. Your first steps should includemaking a list of possible recovery methods, and identifying which method isbest for this scenario.

While attempting to recover the table, you may encounter other issues withthe system. These issues may involve any aspect of the system, including theoperating system, disk media, Oracle installation, datafiles, and/or client andserver configurations. If you do encounter any other issues, you shouldresearch, identify, and resolve those issues as quickly as possible so you canmove towards your immediate goal of recovering the table.

Once you believe that you have successfully recovered theSH.CUSTOMERS table, be sure to issue a query to ensure that all 50,000rows have indeed been recovered. If your recovery was not successful, or ifyou lose the database completely, consult your instructor for furtherdirection.

SummaryIn this lesson, you learned how to move large volumes of data quickly byusing Oracle-provided utilities. You learned how to use SQL*Loader to bulkload data from flat ASCII files into the database. You also learned how toperform direct-load inserts from one table to another, and you learned howto create external tables to access data outside of the database through atable-like structure inside the database. You learned to use the export utilityto export data from the database into a binary file, and then import it backin using the import utility. Finally, you learned how to move entiretablespaces by using Oracle’s transportable tablespace feature.

Suggested Time:2 hours

See Additional InstructorNotes.

Lesson 6: Loading and Moving Data 361

Page 377: Oracle 9i DBA Fund - II

Lesson Review6A While loading data with SQL*Loader, if a row causes an error, which

file is the row copied to?

a. Discard file

✓ b. Bad file

c. Recycle bin

d. Exceptions file

True or False? SQL functions can be applied to data while it is beingloaded with a conventional path using SQL*Loader. Explain youranswer.

True. During conventional path loading, SQL*Loader will generate a stan-dard INSERT statement to pass to the database to load each row, which caninclude SQL functions. During a direct path mode, the SQL processingengine is bypassed, and the data is inserted directly into the target table.Therefore, SQL functions are not allowed during a direct path load.

When loading data with SQL*Loader, which control file option can beused to load data in to an empty table? Choose all that apply.

✓ a. INSERT

✓ b. APPEND

✓ c. REPLACE

✓ d. TRUNCATE

If the data to be loaded resides in the same file as the control file syntax,how should the INFILE clause be specified?

a. INFILE=true

✓ b. INFILE *

c. INFILE

d. It should be omitted

Your SQL*Loader control file contains the BADFILE clause, and thecommand you are using at the command prompt contains the BADargument. Which one will be used to determine the name and locationof the bad file?

✓ a. The command line

b. The control file

c. Both will be ignored

d. An error will be returned

362 Oracle9i Database: Fundamentals II

Page 378: Oracle 9i DBA Fund - II

True or False? To improve the performance of a query that executesagainst an external table, you can add an index that supports the WHEREclause of the query. Explain your answer.

False. You cannot create an index on an external table. If performancebecomes a factor, you can execute the query in parallel.

6B True or False? You can export tables from multiple schemassimultaneously. Explain your answer.

True. By performing a table-level export, you can export a combination oftables from different schemas at the same time.

True or False? A transportable tablespace export will export all objectsthat exist in a single tablespace.

False. For a transportable tablespace export, no data from the sourcetablespace is actually exported. The export utility exports only the requiredinformation from the data dictionary relevant to the tablespace.

The following export command results in an error. Why?

exp userid=sys/oracle file=d:\oracle\sample.exp ⇒direct=y owner=james tables=order,item,billing ⇒recordlength=10240

The owner argument is used for a user-level export, while the tablesargument is used for a table-level export. These two arguments cannot beused together.

Which procedure of the DBMS_TTS package is used to determine if aset of tablespaces is self-contained?

a. TRANSPORTABLE_TABLESPACE

b. IS_SELF_CONTAINED

✓ c. TRANSPORT_SET_CHECK

d. TRANSPORT_SET_VALID

True or False? The datafiles of a tablespace that are being transporteddo not need to reside in the same directory structure on the targetserver as on the source server. Explain your answer.

True. The datafiles can be stored anywhere on the target server. The newlocations of the datafiles are specified as part of the import process.

Lesson 6: Loading and Moving Data 363

Page 379: Oracle 9i DBA Fund - II

364 Oracle9i Database: Fundamentals II

Page 380: Oracle 9i DBA Fund - II

LESSON 6

Topic 6BThe final_setup file launches the go.exe executable. This executable makes changes to the state of the systemwhich will cause the students to encounter several issues while attempting to recover the SH.CUSTOMERS table.The go.exe executable makes the following changes:• All rows in the SH.CUSTOMERS table are deleted, and commit is issued.• The instance is aborted with the SHUTDOWN ABORT command.• All copies of the current control file are deleted.• The EXAMPLE01.DBF datafile is deleted.• The primary listener is stopped.In order to bring the database to a state where the SH.CUSTOMERS table can be recovered, the students must:1. Restart the listener.2. Manually restore all copies of the control file from the control file image copy created in Task 5B-2, step 15.3. Use RMAN to restore the EXAMPLE01.DBF datafile from the backup set created in Task 5B-2, step 14. This

must be done while RMAN is connected to the control file as the repository.Once the students have reached this point, the best course of action is to perform a tablespace point-in-timerecovery of the database to the SCN just prior to the DELETE statement that was issued to delete all the rowsfrom the SH.CUSTOMERS table. That would ensure that all data, including the most recent transactions, havebeen recovered with the exception of the DELETE statement. In the current environment, the furthest the studentsare expected to get is to restore the database to the last log sequence number prior to the current redo log. Thestudents would get extra kudos if they mention using the LogMiner utility to extract the last transactions fromthe current redo log, although they are not expected to perform this task.After restoring the datafiles, if the students perform an incomplete recovery using all redo logs, and open thedatabase with the RESETLOGS option, they will notice that the SH.CUSTOMERS table is still empty. This isbecause the redo information related to the DELETE statement is included in the current redo log file.If some students seem to have difficulty performing a tablespace point-in-time recovery, it is acceptable to applyall redo information, including the current redo log, open the database with the RESETLOGS option, then importthe SH.CUSTOMERS table from either the exp_ora92_full.dmp or exp_ora92_wildcard.dmp export files created inTask 6B-2. Although this will not guarantee that the latest transactions are included in the restored table, thetable can be restored to its last known good state, and any outstanding transactions can either be manuallyapplied, or extracted from the redo and archive logs using LogMiner and then applied. To reiterate, it is notexpected that the students use LogMiner to extract and apply redo information, but if it is at least mentioned,this is considered a bonus.

ADDITIONAL INSTRUCTOR NOTES

Additional Instructor Notes 365

Page 381: Oracle 9i DBA Fund - II

366 Oracle9i Database: Fundamentals II

Page 382: Oracle 9i DBA Fund - II

application program interfaceAn interface provided by a software venderthat accepts procedural calls from a customapplication to the vendor’s software.

archive logA copy of a redo log that has been filledand switched out as the current log group.Archive logs are used to apply changes toa backup to bring it up to date duringrecovery.

backup modeA special mode for tablespaces that allowsthem to be copied while the database is upand running.

backup setA logical object created by RMAN thatcontains multiple backup pieces. Eachbackup piece contains one or more originalfiles from the target database.

before imageThe original version of data before it waschanged by a transaction.

bequeath connectionA single-task database connection wherethe client and server reside on the samemachine.

BMR(Block Media Recovery) A feature thatallows RMAN to recover only corruptblocks in a datafile, rather than the entiredatafile.

centralized namingA names resolution method that stores allthe connect descriptors in a centrally-located repository. All clients needing toresolve connect descriptors contact the cen-tral repository.

checksumA hash value generated by reading a singlepiece of data.

client-server architectureA configuration where multiple clients con-nect to a single server.

clone databaseA database created by restoring and recov-ering the hot backup of another database toanother location.

cold backupA full backup of the database while thedatabase is shut down.

communication channelA dedicated connection between RMANand the target database

complete recoveryA database recovery where all changes tothe database are recovered right up to thepoint of failure.

connect descriptorThe full connection definition for a net ser-vice name.

connection poolingThe technique of pooling multiple clientconnections into a group of fewer databaseconnections.

conventional path loadA method of loading data into Oracle usingstandard SQL calls.

CORBA(Common Object Request Broker Architec-ture) Architecture that provides an industry-wide standard of accessing various types ofdata sources through a network

crosscheckA process of validating recovery catalogentries against the backup files that actuallyexist in the file system.

dead connection detectionA feature of Oracle Net that automaticallydetects terminated client sessions andhandles the release of database resources.

GLOSSARY

Glossary 367

Page 383: Oracle 9i DBA Fund - II

direct load insertA method of loading data from one table toanother using a direct path load.

direct path loadA method of loading data into Oracle thatwrites directly to the datablocks in thedatafiles, bypassing the SQL processingengine.

dispatcherA background process in a shared serverconfiguration that accepts database requestsfrom user processes and passes them toshared server processes.

DNS(Domain Names System) A server that isused to resolve matching host names totheir respective IP addresses.

external namingA names resolution method similar toexternal naming, except the central reposi-tory is a non-Oracle, third-party product.

external tableA table-like structure in Oracle thataccesses an external flat file containingdata.

global database nameA database identifier to uniquely identify asingle database on a network.

heterogeneous connectivityA feature that allows an Oracle client touse standard Oracle SQL and procedurecalls to seamlessly access non-Oracle datasources.

host namingA names resolution method that uses theclient’s HOSTS file to locate the targetdatabase on the network.

hot backupA backup of the database, either full orpartial, performed while the databaseremains up and running.

IIOP(Internet Inter-ORB Protocol) A presenta-tion protocol designed to implementCORBA technologies across the Internet.

image copyA type of backup file created by RMANwhich is a bit-for-bit image of the originalfile.

incarnationA new version of a database created whenthe database is opened with theRESETLOGS option.

incomplete recoveryA database recovery where not all changesto the database are recovered.

incremental backupA backup of the database that includes onlythe datablocks that have changed since aprevious incremental backup instead of alldatablocks that contain data.

Java Database ConnectivityAn industry standard connectivity interfacefor applications that make use of Java pro-gramming on the client to connect to adatabase source, also known as JDBC.

listenerA constantly running process that listens onthe network for incoming connectionrequests.

local namingA names resolution method that is used toresolve net service names by looking uptheir connect descriptors in a definition filestored locally on the client’s machine.

GLOSSARY

368 Oracle9i Database: Fundamentals II

Page 384: Oracle 9i DBA Fund - II

MML(Media-management layer) Third-partybackup utilities that can integrate withRMAN to help perform backup and recov-eries of the database.

MTBF(Mean time between failures) The averageamount of time that passes between failuresof a system.

MTTR(Mean time to recovery) The averageamount of time it takes to recover a systemafter a failure.

multi-protocol connectivityA configuration that supports several differ-ent client protocols to connect to a singledatabase.

N-tier configurationA multi-level configuration where eachcomponent of a system, such as client,application, and database, resides at its owntier.

names resolution methodA configured method that is used to trans-late a net service name to the networkaddress where the intended databaseresides.

net service nameAn alias for a destination database a clientwishes to connect to.

network stackA series of layers that a network connec-tion between a client and server must passthrough.

Oracle Net loggingA feature that, when enabled, allows Oracleto log all informational entries to a speci-fied log file for troubleshooting purposes.

Oracle Net tracingA feature that, when enabled, allows Oracleto write out to a trace file every internalstep taken to establish a database connec-tion, usually generates much more detailedoutput than standard logging.

PGA(Program Global Area) The memory area atthe OS level on the server that stores auser’s session data while the user is con-nected to the database.

recovery catalogA database schema that can act as thebackup and recovery information repositoryfor RMAN.

retention policyThe policy used by RMAN to determinewhich database backups in its recoverycatalog are still valid.

SCN(System Change Number) A sequentialnumbering system Oracle uses to trackevery change in the database.

shared server processA single server process that can supportdatabase requests from multiple clientssimultaneously.

single-task connectionA connection where the client user andserver process are one in the same.

system identifierThe identifying name for a database.

tnsping utilityA utility that is used to time the round tripof a network packet from the client to thelistener and back.

GLOSSARY

Glossary 369

Page 385: Oracle 9i DBA Fund - II

transportable tablespaceAn Oracle feature that allows you to copyan entire tablespace from one database toanother by simply exporting the tablespacemetadata from the data dictionary.

trial recoveryA test recovery of the database that is usedto determine whether or not a real recoverywill be successful.

UGA(User Global Area) The memory area at theOS level on the server that exists only in ashared server configuration.

undo segmentsDatabase segments that temporarily holdthe original versions of changed data froma transaction in case the transaction needsto be rolled back and the original versionreplaced.

GLOSSARY

370 Oracle9i Database: Fundamentals II

Page 386: Oracle 9i DBA Fund - II

3DES encryption

See: Advanced Security Option

AAdvanced Security Option

3DES encryption, 20-22

DES encryption, 20-22

RC4 algorithm, 20-22

archive logs

backing up with RMAN, 252-254

ARCHIVELOG mode

configuring, 127-135

archiver (ARCH) process, 109

Bbackup

cold, 114-120

cold, RMAN, 236-243

control file, 148-153

hot, 127-135

hot, RMAN, 243-245

read-only tablespaces, 153-154

resolving failed hot backup, 154-158

RMAN, 236-243

user-managed, 142-147

backup sets

See: RMAN

bequeath connection

See: user connection process

block corruption, 168-171

Also see: block media recovery

Block Media Recovery

See: BMR

block media recovery (BMR), 295-296

Also see: RMAN

BMR, 295-296

Ccentralized naming

See: names resolution methods

checkpoint (CKPT) process, 110

client-server architecture, 3-6

cold backup

definition, 101-103

complete recovery

See: recovery

connect descriptor, 9, 10

Connection Manager

connection pooling, 18-20

multi-protocol connectivity, 18-20

connection pooling

See: Connection Manager

connection process

See: user connection process

control file, 111, 210-212, 298-300, 209-213

Also see: RMAN

loss of, 180-188

CORBA, 87-90

Ddatabase writer (DBWR) process, 110-111

DES encryption

See: Advanced Security Option

direct load inserts, 329-333

dispatcher process, 76-77, 81-82

Eexport

types, 342-344

external naming

See: names resolution methods

external tables, 333-341

Ffailures

instance failure, 98

media failure, 98

session failure, 97

statement, 96

transaction failure, 96-97

GGIOP, 87-90

Hheterogeneous connectivity, 22-23

INDEX

Index 371

Page 387: Oracle 9i DBA Fund - II

host naming

See: names resolution methods

hot backup

definition, 101-103

HTTP/FTP presentations

See: layered architecture

IIIOP, 87-90

image copies

See: RMAN

import

types, 348-352

incomplete recovery

See: recovery

incremental backups

See: RMAN

inserts

direct load, 329-333

instance failure

See: failures

instance recovery

See: recovery

JJava client communication stack

See: layered architecture

Java thin client, 15-16

JDBC, 15-16

Llayered architecture

Java client communication stack, 15-16

OCI layer, 13-15

OPI layer, 13-15

Oracle communication stack, 13-15

Oracle communications stack, 12-18

Web client communication stack, 16-17

Listener Control utility (lsnrctl), 35-41

listener process, 11

configuring for Web clients, 87-90

Also see: layered architecture

creating, 25-27

creating manually, 42-46

Also see: Listener Control utility (lsnrctl)

Listener Control utility (lsnrctl), 35-41

local naming

See: names resolution methods

log writer (LGWR) process, 109

logging

Oracle Net, 66-68

lsnrctl

See: Listener Control utility (lsnrctl)

Mmedia failure

See: failures

media recovery

See: recovery

MTBF, 100-105

MTS

See: Oracle Shared Server

MTTR, 100-105

multi-protocol connectivity

See: Connection Manager

Multi-threaded Server

See: Oracle Shared Server

NN-tier architecture, 3-6

names resolution methods

centralized naming, 46-49

external naming, 46-49

host naming, 46-49

local naming, 46-49, 55-64

net service name, 9, 10

networking

client-side configuration, 46-49

server-side configuration, 25-35

troubleshooting, 64-74

Also see: tnsping utility

Web client configuration, 87-90

Also see: layered architecture

INDEX

372 Oracle9i Database: Fundamentals II

Page 388: Oracle 9i DBA Fund - II

OOracle communications stack

See: layered architecture

Oracle Net

components, 5-6

logging, 66-68

tracing, 66-68

Oracle Shared Server, 74-80

configuring, 80-83

monitoring and tuning, 83-87

OSS

See: Oracle Shared Server

RRC4 algorithm

See: Advanced Security Option

read-only tablespaces, 196-199

recovery

cold, 114-120, 127-135

complete, 104

complete, RMAN, 286-292

hot, 135-138

incomplete, 104, 177-178

incomplete, repercussions, 178-179

incomplete, RMAN, 297-301

loss of control file, 180-188, 298-300

loss of current log group, 189-196, 301-308

no backup, 172

read-only tablespaces, 196-199

structures, 105-114

trial recovery, 168-171

user-managed, 142-147

user-managed, complete, 159-168

user-managed, incomplete, 176-180

recovery catalog

See: RMAN

backing up, 277-279

stored scripts, 254-259

redo log, 301-308

loss of current group, 189-196

redo log buffer, 107

redo log files, 107-108

restoring datafiles

, 171-176

RMAN

architecture, 207-209

archive logs, 252-254

backup sets, 217-219

backup validation, 275-276

backups, 236-243

block media recovery (BMR), 295-296

cataloging OS-level backups, 272-274

complete recovery, 286-292

configuration parameters, 229-235

configuring, 219-222

crosscheck, 266-272

deleting backup sets, 266-272

hot backups, 243-245

image copies, 217-219, 238-239

incomplete recovery, 297-301

incremental backups, 245-252

lists, 259-266

loss of control file, 298-300

loss of current log group, 301-308

process flow, 213-217

recovery catalog, 212, 222-226, 254-259, 277-279

registering a database, 227-229

reports, 259-266

repository, 209-213

restore, 286-287

restore validation, 275-276

tablespace point-in-time recovery, 308-314

Ssession failure

See: failures

shared server process, 76-77, 82

single-task connection

See: user connection process

SQL*Loader, 318-329

commands, 323-324

control file, 319-321

datafile formats, 321-323

statement failure

See: failures

system monitor (SMON) process, 109

INDEX

Index 373

Page 389: Oracle 9i DBA Fund - II

Ttablespace point-in-time recovery

RMAN, 308-314

user-managed, 200-201

tnsping utility, 50

tracing

Oracle Net, 66-68

transaction failure

See: failures

transparent gateway, 22-23

transportable tablespaces, 353-361

Also see: export

Also see: import

trial recovery, 168-171

Also see: block media recovery

TSPITR

See: tablespace point-in-time recovery

two-task connection

See: user connection process

Uundo segments, 106-107

user connection process, 7-12

bequeath connection, 7-12

Oracle Shared Server, 76-77

WWeb client communication stack

See: layered architecture

Web client configuration, 87-90

INDEX

374 Oracle9i Database: Fundamentals II

Page 390: Oracle 9i DBA Fund - II