R030 – Oracle Database Notes Version 1.

0

Page 1/135 Date: 29.08.2007

Oracle Database Notes - Oracle 10g Administration
1 ROLE OF THE DATABASE ADMINISTRATOR - DBA ............................................................................. 6 1.1 1.2 2 INTRODUCTION ............................................................................................................................................. 6 RESPONSIBILITIES OF THE DBA..................................................................................................................... 6

ORACLE ARCHITECTURE ............................................................................................................................ 7 2.1 PHYSICAL STRUCTURE .................................................................................................................................. 7 2.1.1 Data Files ................................................................................................................................................ 7 2.1.2 Redo-log Files.......................................................................................................................................... 7 2.1.3 Control Files............................................................................................................................................ 7 2.2 LOGICAL STRUCTURE.................................................................................................................................... 7 2.2.1 Tablespace ............................................................................................................................................... 7 2.2.2 Schema Objects........................................................................................................................................ 7

3

INSTANCE.......................................................................................................................................................... 8 3.1 SYSTEM GLOBAL AREA (SGA) ..................................................................................................................... 8 3.1.1 Automatic Shared Memory Management................................................................................................. 8 3.1.2 SGA_TARGET Initialization Parameter.................................................................................................. 8 3.1.3 Buffer cache ............................................................................................................................................. 8 3.1.4 Redolog Buffers ....................................................................................................................................... 8 3.1.5 Shared Pool ............................................................................................................................................. 9 3.1.6 Library Cache.......................................................................................................................................... 9 3.1.7 Data Dictionary ....................................................................................................................................... 9 3.1.8 Streams Pool............................................................................................................................................ 9 3.2 PGA - PROGRAM GLOBAL AREA................................................................................................................... 9 3.2.1 Background Processes............................................................................................................................. 9

4 4.1

DATABASE CREATION ................................................................................................................................ 12 SYSAUX TABLESPACE............................................................................................................................. 12

4.2 DEFAULT PERMANENT TABLESPACE ........................................................................................................... 12 4.2.1 Pre-requisites for creating a database .................................................................................................. 12 4.2.2 Steps to create a database ..................................................................................................................... 12 4.3 DATA DICTIONARY VIEWS YOU CAN QUERY.............................................................................................. 14 5 TABLESPACE MANAGEMENT ................................................................................................................... 15 5.1 ADDITIONAL TABLESPACES......................................................................................................................... 15 5.2 ADVANTAGES OF HAVING DIFFERENT TABLESPACES ................................................................................... 15 5.3 TYPES OF TABLESPACES ............................................................................................................................. 15 5.4 BIGFILE TABLESPACE ............................................................................................................................... 15 5.5 TEMPORARY TABLESPACE GROUPS ............................................................................................................ 16 5.5.1 Examples................................................................................................................................................ 16 5.6 DATA DICTIONARY VIEWS YOU CAN QUERY.............................................................................................. 19 6 STORAGE PARAMETERS ............................................................................................................................ 20 6.1 6.2 7 AUTOMATIC SEGMENT SPACE MANAGEMENT............................................................................................. 21 DATA DICTIONARY VIEWS .......................................................................................................................... 22

MANAGING ROLLBACK SEGMENTS....................................................................................................... 23 7.1 7.2 DATA DICTIONARY VIEWS .......................................................................................................................... 24 PENDING OFFLINE ....................................................................................................................................... 24

R030 – Oracle Database Notes Version 1.0

Page 2/135 Date: 29.08.2007

8

UNDO MANAGEMENT.................................................................................................................................. 25 8.1 8.2 8.3 8.4 8.5 OVERVIEW OF UNDO MANAGEMENT .......................................................................................................... 25 UNDO RETENTION ....................................................................................................................................... 25 STEPS TO CREATE AND MAINTAIN UNDO TABLESPACE ............................................................................... 26 RETENTION GUARANTEE ............................................................................................................................. 27 DATA DICTIONARY VIEWS .......................................................................................................................... 27

9

MANAGING REDOLOG FILES.................................................................................................................... 28 9.1 9.2 9.3 9.4 INTRODUCTION ........................................................................................................................................... 28 MIRRORED REDO LOGS ............................................................................................................................. 28 LOG SWITCHES............................................................................................................................................ 28 DATA DICTIONARY VIEWS .......................................................................................................................... 29 MANAGING REDOLOG FILES ............................................................................................................... 30 10.1 10.2 10.3 INTRODUCTION ........................................................................................................................................... 30 MANAGING THE SIZE OF THE CONTROL FILE ................................................................................................ 30 DATA DICTIONARY VIEWS .......................................................................................................................... 32 ARCHIVED REDO LOG FILES................................................................................................................ 33 11.1 11.2 11.3 INTRODUCTION ........................................................................................................................................... 33 TO CONVERT THE DATABASE INTO ARCHIVELOG MODE ......................................................................... 33 DATA DICTIONARY VIEWS .......................................................................................................................... 33 ORACLE MANAGED FILES..................................................................................................................... 34 12.1 INTRODUCTION ........................................................................................................................................... 34 12.2 MAIN BENEFITS OF THE ORACLE MANAGED FILES ...................................................................................... 34 12.2.1 Scenario 1: Add Oracle Managed Files to an Existing Database..................................................... 35 12.2.2 Scenario 2: CREATE DATABASE: Using Oracle Managed Files.................................................... 35

10

11

12

13

MANAGING USERS AND RESOURCES................................................................................................. 36 13.1 MANAGING DATABASE USERS .................................................................................................................... 36 13.2 CREATING USERS ........................................................................................................................................ 36 13.3 MANAGING RESOURCES WITH PROFILES ..................................................................................................... 37 13.3.1 To Enable the Resource Limit ........................................................................................................... 38 13.3.2 To Create and Alter a Profile............................................................................................................ 38 13.3.3 To Drop a Profile .............................................................................................................................. 38 13.4 SESSION AND USER LICENSING ................................................................................................................... 39 13.5 USER AUTHENTICATION .............................................................................................................................. 39 13.5.1 Password File Authentication ........................................................................................................... 39 13.6 VIEWING INFORMATION ABOUT DATABASE USERS AND PROFILES .............................................................. 40

14

MANAGING USER PRIVILEGES AND ROLES .................................................................................... 42 14.1 IDENTIFYING USER PRIVILEGES................................................................................................................... 42 14.2 CATEGORIES OF PRIVILEGES ........................................................................................................................ 42 14.2.1 System Privileges............................................................................................................................... 42 14.2.2 Object Privileges ............................................................................................................................... 42 14.3 MANAGING USER ROLES ............................................................................................................................. 43 14.3.1 System defined roles .......................................................................................................................... 43 14.3.2 Creating, Altering, Dropping, Granting and Revoking Roles ........................................................... 43 14.3.3 Creating a Profile.............................................................................................................................. 44 14.3.4 Listing Privilege and Role Information ............................................................................................. 46

15

AUDITING.................................................................................................................................................... 47 15.1 INTRODUCTION ........................................................................................................................................... 47 15.2 INITIALIZATION PARAMETERS FOR AUDITING .............................................................................................. 47 15.2.1 Creating and Deleting Database Trail Views ................................................................................... 47 15.3 TYPES OF AUDITING .................................................................................................................................... 47 15.3.1 Auditing Successful and Unsuccessful Statement Execution ............................................................. 48

R030 – Oracle Database Notes Version 1.0

Page 3/135 Date: 29.08.2007

15.3.2 Auditing BY SESSION versus BY ACCESS ....................................................................................... 48 15.4 PRIVILEGE LEVEL OF AUDITING ............................................................................................................... 48 15.5 OBJECT LEVEL AUDITING ........................................................................................................................... 48 15.6 STATEMENT AUDITING ................................................................................................................................ 49 15.7 DATA DICTIONARY VIEWS TO QUERY ......................................................................................................... 50 16 16.1 16.2 16.3 16.4 16.5 17 MANAGING ORACLE NETWORKING USER “NET MANAGER” ................................................... 51 INTRODUCTION ........................................................................................................................................... 51 CONFIGURING LISTENER.ORA AND TNSNAMES.ORA ..................................................................................... 51 DATABASE LINKS ........................................................................................................................................ 51 GLOBAL NAMES .......................................................................................................................................... 52 MATERIALIZED VIEWS ................................................................................................................................ 53 MANAGING EXPORTS AND IMPORTS ................................................................................................ 55 17.1 TYPES OF BACKUPS..................................................................................................................................... 55 17.1.1 Export and Import ............................................................................................................................. 55 17.2 MAIN TASKS OF EXPORT AND IMPORT ........................................................................................................ 55 17.3 INCREMENTAL, CUMULATIVE AND COMPLETE EXPORTS ............................................................................ 57 17.4 IMPORT PARAMETERS ................................................................................................................................. 58 17.5 IMPORTING INCREMENTAL, CUMULATIVE AND COMPLETE EXPORT FILES ................................................... 59 17.6 POINTS TO REMEMBER BEFORE DOING EXPORT OR IMPORT ......................................................................... 59 17.7 SELECTING DETAILED INFO ABOUT INCTYPE EXPORTS ............................................................................ 61 18 ORACLE DATA PUMP .............................................................................................................................. 62 18.1 INTRODUCTION ........................................................................................................................................... 62 18.2 BENEFITS OF DATA PUMP EXPORT AND IMPORT ......................................................................................... 62 18.3 DATA PUMP EXPORT MODES ...................................................................................................................... 62 18.4 DATA PUMP IMPORT MODES....................................................................................................................... 63 18.5 TRANSPORT OF TABLESPACES ACROSS DIFFERENT PLATFORMS ................................................................. 63 18.5.1 Initiate a Job During Data Pump Export operations and Restarting the Jobs ................................. 64 18.6 DATA DICTIONARY VIEWS TO QUERY ......................................................................................................... 64 19 TUNING – ENHANCING THE PERFORMANCE OF DATABASE..................................................... 65 19.1 INTRODUCTION ........................................................................................................................................... 65 19.2 GOALS FOR TUNING .................................................................................................................................... 65 19.3 TURING PROCESS STEPS.............................................................................................................................. 65 19.3.1 Tuning memory allocation................................................................................................................. 65 19.3.2 Tuning I/O ......................................................................................................................................... 65 19.3.3 Tuning Contention............................................................................................................................. 65 19.3.4 Memory Tuning ................................................................................................................................. 66 19.3.5 Stripping ............................................................................................................................................ 67 19.3.6 Parallel Query Option....................................................................................................................... 68 19.3.7 Table Cache....................................................................................................................................... 68 19.4 ONLINE SEGMENT SHRINKING ..................................................................................................................... 69 20 20.1 20.2 20.3 21 MEMORY MANAGEMENT...................................................................................................................... 70 INTRODUCTION ........................................................................................................................................... 70 DYNAMIC SYSTEM GLOBAL AREA (SGA)................................................................................................... 70 BUFFER CACHE ADVISORY ......................................................................................................................... 70 OPTIMIZATION ......................................................................................................................................... 71 21.1 INTRODUCTION ........................................................................................................................................... 71 21.2 EXECUTION PLAN STEPS ............................................................................................................................. 72 21.3 TYPES OF OPERATIONS ............................................................................................................................... 72 21.4 THE TRCSESS UTILITY ................................................................................................................................. 75 21.4.1 Sample output of trcsess .................................................................................................................... 75 21.5 ACTIVE SESSION HISTORY REPORTS ........................................................................................................... 76 21.5.1 Running the ashrpt.sql Report........................................................................................................... 76 21.6 AUTOMATIC WORKLOAD REPOSITORY REPORTS ........................................................................................ 77

....................................................................................1.............. 111 25.................................................10 Propagating Information from the Control File.................................................. 101 25........................... 79 22........4 TYPES OF RECOVERY MANAGER BACKUPS............ 77 MANAGING SHARED SERVERS .......................... 80 22.................................................................. 97 25......................4...................................................................................................................0 Page 4/135 Date: 29..........................................................4 Delete Script ... 105 25...................................................................3 Media Recovery........................ 92 24.......4..................................................................................................................................................................................................................................... 85 23.........................................................1 INTRODUCTION ................................................1................5 RESTORE ..................2 ADVANTAGES OF PARTITIONING TABLES ..... 112 ............................................. 94 24........2 RMAN COMMANDS................ 105 25.............1 21.7 Release Channel . 92 24..........3....................................................................................................3 TYPES OF PARTITIONS ......... 92 24...............................................................1 Enabling and Disabling Change Tracking...........................1 Types of Indexes .........................................................2......5 COMPRESSED BACKUPS .............................................................................................................. 107 25.........................................2......... 79 22............. 88 23........ 91 24........................................................................ 82 23....................................2...............................................................................6............................................ 81 23 PARTITIONED TABLES AND INDEXES .......................................3 ONLINE BACKUP MODE OR ENTIRE DATABASE BACKUP .................... 82 23..............................................................................................................08...........2.......................................................................................................................................2.......................................................5 DATA DICTIONARY VIEWS .........................................3....1 To Check Whether Shared Server Is Working ..............................................2 Server Process..2.....................9 Determining Datafile Backup Status ...6............................................................... 94 24............................................................................................................. 94 24......................................................2 Incremental...........................6 RECOVER ........................................................2 BACKUP ... 111 25...................... 80 22...4..................2..........................................................................................................................4..1 Allocate Channel .....................................................................................................................1 INTRODUCTION ...................................................................................................................... 82 23.................................................................1 Whole Database Backup ................. 77 Running the awrrpti........................................................ 93 24...........2 Thread Recovery...........................................................sql Report .....................2 USING DEDICATED SERVER PROCESSES . 97 25............................................................... 109 25...........................1 MANAGING PARTITIONED TABLES ................................................................................................................................................................... 82 23...............................................................2 Hot Backup at Tablespace Level ................................................................3 List Partitioning ..................................................4 Composite Range-Hash Partitioning Tables...............................................4.................................................................... 94 25 RECOVERY MANAGER ........................................................4. 110 25..................................................................................................................................................................................1 COLD BACKUP ...............................................4 MANAGING PARTITIONED INDEXES ..............................................2.............. 79 22................................................................................ 84 23...............................................................................................................................2 Setting Up the Recovery Catalog Schema ..................................................................2.......1 Block Level ....3 Create Script.............................................................................................................. 112 25........................................... 97 25..4 RECOVERY ............................................... 84 23.....................2..................... 97 25.............................................................................................................................................................3 Incremental Backup Sets .................................................3..........................................................................................................................................2 Hash Partitioning ................................................4 SIMPLIFIED SHARED SERVER CONFIGURATION..1 Costs and Benefits When Using a Recovery Catalog ........................3 IMPROVING INCREMENTAL BACKUP PERFORMANCE: CHANGE TRACKING.......... 105 25....... 110 25.......................................................................................2 22 Running the awrrpt.......................................2................ 100 25................................................ 82 23.... 109 25....................................4...................... 110 25...........1........................................3 USING SHARED SERVER PROCESS ......................................................1 Range Partitioning ........................................3..3........................................................................8 Show .............................................................1........................ 89 23.............3...4.......................................... 111 25...... 86 23................................................................ 110 25...................... 100 25...............................................................................................................2................................R030 – Oracle Database Notes Version 1........... 90 24 MANAGING BACKUPS AND RECOVERY........... 91 24.....................................................................................................5 Composite Range-List Partitioned Tables...............1 Client Process....... 79 22................................................................ 79 22.......................................................................................................2 HOT BACKUP ...........6 CONFIGURING COMPRESSED BACKUP SETS AS DEFAULT FOR TAPE OR DISK ...1 Full ..........................2007 21................sql Report .................... 111 25....................................

.................... 130 30 31 32 INSTALLATION OF ORACLE10G ON RED HAT ENTERPRISE LINUX 4 ................. 127 29......... 131 INSTALLATION OF ORACLE10G ON SUN SPARC (SOLARIS 9) .... 119 WORKING WITH RAW DEVICES .........................................................................................4.......................................................................................................................... 125 28......................4 DBMS_JOBS PACKAGE ......................................................... 135 .............. 127 29................................5........ 112 25....................... 124 28................ 114 26.......................................3 ORACLE FLASHBACK TABLE ... 113 25................................................................................... 129 29........................................................................................7 IMAGE COPIES ...................................................................................... 126 29.................................................................................................... 126 29..............2 DISADVANTAGES .................................................................3 Converting a Lock ..............1 Files that can be stored in the Flash Recovery Area.........2 DBMS_PIPE ..0 Page 5/135 Date: 29..................................................................1 THE FLASH RECOVERY AREA .....9 INCREMENTALLY UPDATED BACKUPS: ROLLING FORWARD IMAGE COPY BACKUPS ............1 BACKUP ..................................................................... 114 26......................................................................................................................................3 To Disable Flashback Database .......... 112 25....................................................................................1................... 124 28............................................................ 113 26..3 Purging Objects from the Recycle Bin ............................2 To perform the FLASHBACK DATABASE.............................................................................................................. 117 26...............................................................2 ORACLE FLASHBACK QUERY ................... 113 26.......................... 125 29 DBMS PACKAGES ......................4 BACKUP AND RECOVERY................................1.................................................1..........................................5.....................2 Requesting a Lock .................................................................................................2 Performing Flashback Drop on Tables in the Recycle Bin ..........................................5 FLASHBACK DATABASE ......................8..1 ADVANTAGES ..................................................... 126 29... 115 26.................................................................... 117 26..... 113 26 FLASHBACK TECHNOLOGY ................................................ 124 28............................................................................................................................. 113 26....................1........................3 DBMS_ALERT PACKAGE ........................CREATING ALERTS .........................................08.................5....4...................1 Recycle Bin ......................2 RECOVERY ......................................................10 RMAN RECOVERY CATALOG VIEWS ............. 117 26..........................1 To Enable Flashback Database ..... 115 26........................................................................................2 Initialization parameters for the Flash Recovery Area ..........................................................................................................................1 Naming Locks...................................................3 CREATING A DATABASE USING RAW DEVICES ............................ 125 28.......................................................................................................................................................................................8 DROP DATABASE IN RMAN..................................................................................................................................................................R030 – Oracle Database Notes Version 1.................. 118 27 28 WORKING WITH SQL*LOADER .....................................................................................4 ORACLE FLASHBACK DROP – UNDO A DROP TABLE OPERATION .............................................................................................................................................4.................................................................................... 124 28........................ 112 25.................................1 Restrictions............ 113 26.................................. 116 26.............................1 DBMS_LOCK PACKAGE .......................................................... 126 29........................... 116 26............4................................................................................................................................................................................................................................. 133 INDEX .....2007 25..1........................................................................................4......................................................

He is concerned with the safety and security of the database. adhere and cooperate the policies and procedures pertaining to the database. 1.2007 1 ROLE OF THE DATABASE ADMINISTRATOR . • Must monitor the database performance. He must establish base lines and compare the database performance against them to ensure adequate performance. • Must have political skills. and Oracle security features • Create new users and manage privileges • Ensure compliance with Oracle license agreement • Control and monitor user access to the database • Monitor and optimize the performance of the database • Tune and troubleshoot the database • Plan and implement appropriate backup and recovery strategies for the database • Minimize the database down time (in case of a crash) • Contact Oracle Corporation for technical support .0 Page 6/135 Date: 29. • Must tend to the daily administration of the database. • Allocate system storage and plan for future storage requirements for the database system • Manage Logical and Physical database structures • Control access to the database using operating system network • Manage the Operating system. The DBA also measures the performance of the database and takes corrective action to ensure the adequate response time. • Must ensure that appropriate backup and recovery procedures are in place to meet the business requirements. • Must be available 24x7. probably a month or more of the project teamwork would be lost. • Install and upgrade the Oracle Server and application tools. If the project is not backed up and the database is lost.R030 – Oracle Database Notes Version 1. This is a critical function of a DBA.DBA 1. • Must monitor the growth of the database to ensure the smooth functioning of daily activities. • Must be able to tackle issues as soon as they spring up. A DBA’s position os one of the most technically challenging roles that exists within all the teams. He established the appropriate measures and procedures to make sure that the database is backed up and secured. • Must work closely with the system administrator to install all software and patches. A DBA might not want to upgrade the system on the busiest day of the year.1 Introduction The DBA is the guardian of the database.08. • Must work closely with the technical team to ensure. This includes development of policies to control the movement of the applications on to a production database.2 Responsibilities of the DBA The DBA: • Must be responsible for putting up security in place to make certain that only the right people can access the right data. eg. Common sense is required. • Configure or aid in the configuration of the computer network. A DBA works closely with the data architects to implement the database design.

Indexes. Database links.1 Data Files An Oracle database has one or more physical ‘Data’ files that hold the actual data of all logical structures like tables. Procedures. • Datafile: Their size. It is divided into five parts. • Information about each log group and current log group that LGWR is writing.08. Tablespace and Datafile can be stated as: • Each database is logically divided into one or more Tablespaces. They are used to maintain internal consistency and play a vital role in recovery operations. • Log history of database. • The combined storage capacity of a database Tablespace is the total storage capacity of the database. . The relationship between a Database. 2.1 Physical Structure Physical structure of a database comprises of the following files: • Data files • Redo-log files • Control files • Archive log files • Parameter file or Server parameter file • Alert log and Trace files 2. Packages. Functions. status. 2.2007 2 ORACLE ARCHITECTURE 2. etc. Views. indexes. Schema objects like tables. the path. • The combined size of a Tablespace datafiles is the total storage capacity of the Tablespace.R030 – Oracle Database Notes Version 1. full name. A data file can be associated with only one database and only one Tablespace. redo-logs and threads that are enabled (in parallel server).3 Control Files The Control files record control information of all files within the database. etc. name.0 Page 7/135 Date: 29.2. Synonyms.1. 2.1. These files can be mirrored and are used in performing recovery operations. Sequences. Database Triggers. etc. Example: Tables. path. • Redo-logs: Each member of the log group.2 Schema Objects Schema is a logical collection of database objects of a user. etc. 2. • Information about the database.1. total number of datafiles. indexes. the size. Clusters. log sequence no.2 Logical Structure Logical structure comprises of Tablespaces.1 Tablespace Logical area of storage in a database that directly corresponds to one or more physical data files.. Oracle automatically modifies the control files.2.2 Redo-log Files The primary function of Redo-logs is to record all the changes made to the database before they are written to the data files. 2. etc. These files can also be mirrored. • One or more datafiles are explicitly created for each Tablespace to physically store the data of all logical structures in a Tablespace. which users cannot edit. views. They are used to maintain internal consistency and guide during Database recovery.

hence modifying the data block in the server memory. When automatic SGA memory management is enabled. . Set the value of SGA_TARGET.2 SGA_TARGET Initialization Parameter The SGA_TARGET initialization parameter reflects the total size of the SGA and includes memory for the following components: 1. 3.1. It can also have modified data that has not yet been permanently written to disk. the sizes of the different SGA components are flexible and can adapt to the needs of a workload without requiring any additional configuration. the foreground server processes reads the datafile information on the disk into the buffer caches. allowing the target system to maximize the use of all available SGA memory.2007 3 INSTANCE A System Global Area (SGA) and Oracle background processes constitute an instance. 5. 3. then the latter is bumped up to accommodate SGA_TARGET. If SGA_TARGET is set to a value greater than SGA_MAX_SIZE at startup. in contrast to earlier releases.1. 3. a log of changes made to a database. If other Users request new data from the disk and if no data block is freely available in the buffer cache. either by editing the text initialization parameter file and restarting the database or by issuing the following statements: SQL> ALTER SYSTEM SET SGA_TARGET = <value>. 7. 2.4 Redolog Buffers Stores redo log entries. Thus.R030 – Oracle Database Notes Version 1. Fixed SGA The Log Buffer The Buffer Cache The Shared Pool The Large Pool (optional) The Java Pool (optional) The Streams Pool (optional) It is significant that SGA_TARGET includes the entire memory for the SGA. 3. 4. 6.1. 3.1 Automatic Shared Memory Management DBA can simply specify the total amount of SGA memory available to an instance using the SGA_TARGET initialization parameter and the Oracle Database will automatically distribute this memory among various sub-components to ensure most effective memory utilization. in which memory for the internal and fixed SGA was added to the sum of the configured SGA memory parameters.1 System Global Area (SGA) It is a shared memory region allocated by Oracle that contains data and control information for an Oracle instance. The database automatically distributes the available memory among the various components as required. SGA_TARGET can be decreased or increased dynamically.1. Redo-log buffers and Shared pool area. An SGA comprises of Buffer cache.08.0 Page 8/135 Date: 29. DBWR writes the blocks from the buffer cache to the datafile using the LRU (Last Recently Used) mechanism. However. it cannot exceed the value of SGA_MAX_SIZE that was computed at startup. SGA_TARGET gives you precise control over the size of the shared memory region allocated by the database. After start-up. When a row in a table is updated.3 Buffer cache Buffer cache stores the most recently used blocks of data. 3.

and sharing the events with other databases and applications. you can share data and events in a stream.2 LGWR Writes redo-log entries generated in the redo log buffer to an on-line redo-log file.1. . The stream routes specified information to specified destinations.0 Page 9/135 Date: 29.1 DBWR It writes blocks from the buffer cache to the appropriate data files. Streams provide the capabilities needed to build and operate distributed enterprises and applications. Oracle does not consider a transaction as committed until LGWR successfully writes the transaction redo entries and a commit record to the transaction log. The redo log buffer is a small memory area that temporarily caches transactions and redo entries for all system transactions. Oracle then caches the statement in the Shared pool and if another user issues the same statement.1. Oracle temporarily stores your transaction redo entries in the server’s redo log buffer. To maximize the performance of the system’s internal operation.1.7 Data Dictionary Oracle continuously requests and updates the information in the data dictionary of the database. 3.1. and high availability solutions.2. 3. Using Oracle Streams.1 DBWR CKPT PMON Dnnn Snnn QMNn MMON RBAL Background Processes Database writer Check point Process monitor Dispatcher Shared Server Process Queue monitor process Manageability Monitor Process Rebalance activity process LGWR SMON RECO CJQ ARCn MMNL MMAN Log writer System monitor Recoverer Coordinator Job Queue Process Archiver Manageability Monitor Light Process Memory Manager Process 3. 3.5 Shared Pool Shared pool comprises of library cache and dictionary cache. Oracle creates a small record called redo entries that contains just enough information necessary to regenerate the changes made by the transaction. 3.1. It writes a block in memory back to disk only when a time-out occurs or when a foreground Server process doesn’t have enough free buffers in the memory or if Oracles performs a checkpoint. data warehouses.2.8 Streams Pool Oracle Streams enables information sharing. The stream can propagate information within a database or from one database to another.08.2.1. 3.2 PGA .R030 – Oracle Database Notes Version 1. Oracle shares the statement already in memory rather than repeating the same steps. data dictionary cache holds the dictionary information. As and when a transaction is carried out.2007 3. To configure streams pool. Library cache stores and shares SQL statements and PL/SQL procedures in memory. 3.6 Library Cache Oracle Parses the statement and determines the most efficient Execution plan for the statement when a SQL statement is issued.Program Global Area Memory buffer that contains data and holds control information for the Server Process. specify the size of the pool in bytes using the STREAMS_POOL_SIZE initialization parameter. The result is a feature that provides greater functionality and flexibility than traditional solutions for capturing and managing events.

6 ARCn The process copy filled On-line Redolog files to the specified destination. and.1. Its duty can be performed by LGWR.R030 – Oracle Database Notes Version 1. control files of the database.2.1. 3. The sequential set of archived transaction log files that ARCH creates. are different from other Oracle background processes in that processes failure does not cause the instance to fail. the local RECO attempts to connect to a remote database and automatically complete the commit or rollback a local portion of any pending distributed transactions.3 CKPT Responsible for signaling the DBWR at checkpoints and updating all the data files.7 RECO This process is used to resolve distributed transactions that are pending due to a network or a system failure in distributed database.2. 3. 3. It is active only when database is running in ‘Archive log mode’.1. it checks on Dispatcher and Server Processes. is called as Archived transaction log. Checkpoint indicates how much of the transaction log’s redo entries Oracle must apply if a server crash occurs and a database recovery is necessary. You can configure up to 10 queue monitor processes.9 CJQ This is the coordinator of job queue processes for an instance. restarts them in times of failure. • When the buffer is 1/3 full 3.2.2. In the MTS environment. freeing resources used by the processes.1.1. .5 PMON This process performs Process Recovery when a User process fails. At time intervals.1. The purpose of a Checkpoint is to establish mileposts of transaction consistency on disk. 3.2.1. to make free space contiguous and easy to allocate 3. It monitors the JOB$ table.4 SMON Performs: • Instance recovery at instance startup in a multiple instances • Recovery of instances that have failed in Cluster Environment (RAC) • Cleans up temporary segments that are no longer in use • Recovers dead transactions skipped during crash and instance recovery • Coalesce the free extents within the database.2.2007 LGWR writes: • When log buffer is full • When a transaction is committed • For every three seconds.08. It is responsible for cleaning up the cache. These processes.10 QMNn The queue monitor process is an optional background process for Oracle Streams Advanced Queuing.8 Dnnn It is responsible for routing requests from connected user processes to available shared server processes and returning responses back to the appropriate user processes.2. which monitors the message queues.2. 3.1. like the job queue processes.0 Page 10/135 Date: 29. 3.

When a distributed transaction is committed.1. The new redo log file is marked as low SCN. ORB1. 3.1. the highest SCN of all database instances involved is given to the distributed transaction. The next transaction B that commits five minutes later will receive an SCN value of 31 or greater.1. 3.2. 3. it will be assigned an SCN value. there will never be a problem with read consistency at the time of high transactions. and so fort.15 ORBn ORBN performs the actual rebalance data extent movement in an Automatic Storage Management instance. If B receives a value say 37. multiple transactions may commit at a time then the LGWR process may write multiple commit records to online redo log files.2. 30. This is known as group commits.2.1.17 Low and High SCN When a redo log file is filled up.13 MMAN MMAN is used for internal database tasks.2. which have been recently modified 3.2.12 MMNL MMNL performs frequent and lightweight manageability-related tasks. SCN need not be sequential.08. when the log file is closed. called ORB0. When a transaction commits.16 SCN System change number defines a committed version of a database at a precise moment of time.2007 3.14 RBAL Coordinates rebalance activity for disk groups in an Automatic Storage Management instance. Similarly. it is assigned an SCN that uniquely identifies the transaction. There can be many of these at a time.1.0 Page 11/135 Date: 29.1.2. The low SCN represents the lowest value of the change number that is stored in that log file. which is one greater than the high SCN of previous log. Primarily used for recovery operations. Thus. For example: • • • • If transaction A does updates and commits.2. . It performs a global open on Automatic Storage Management disks. It plays an important role in distributed databases.1. for example: • Issuing alerts whenever a given metrics violates its threshold value • Taking snapshot by spawning additional process (MMON slaves) • Capturing statistics value for SQL objects.R030 – Oracle Database Notes Version 1. such as session history capture and metrics computation. the high SCN mark is set to the highest SCN recorded in the log file.11 MMON MMON performs various manageability-related background tasks. 3. it switches to next the redo log file. that means Oracle has assigned the SCN numbers of 30 and 37 to two transactions A and B. 3. You can get more information from V$LOG_HISTORY.

bash_profile "init<Oracle_SID>. then the SYSTEM Tablespace is the default permanent Tablespace for non-SYSTEM users. Oracle strongly recommends that you create a default permanent tablespace. The space requirements of the SYSAUX Tablespace will increase after the database is fully deployed.ora". regardless of how many data files it has or how many instances access it.2. 4. Create the initialization (parameter) by copying from the sample "init. The size of the SYSAUX Tablespace is determined by the size of the database components that occupy SYSAUX.08. Oracle Database assigns to this Tablespace any non-SYSTEM users for whom you do not explicitly specify a different permanent Tablespace. You cannot drop or rename the SYSAUX Tablespace. Because it is the default Tablespace for many Oracle Database features and products that previously required their own Tablespaces.R030 – Oracle Database Notes Version 1. depending on the nature of its use and workload. You cannot alter these attributes with an ALTER TABLESPACE statement. it reduces the number of Tablespaces required by the database and that you. 4.bash_profile export ORACLE_SID=DEMO (or another database name) export ORACLE_HOME=/oraeng/app/oracle/product/10. The SYSAUX Tablespace serves as an auxiliary Tablespace to the SYSTEM Tablespace. 4.bash_profile #execute .2.ora (same as your ORACLE_SID=DEMO) . must maintain.1 • • 4.ora initDEMO. as a DBA.2 Default Permanent Tablespace The DEFAULT TABLESPACE clause of the CREATE DATABASE statement specifies a default permanent Tablespace for the database.2. thus reducing the load on the SYSTEM Tablespace. $ cd $ORACLE_HOME/dbs $ cp init. A database needs to be created once.0 Page 12/135 Date: 29.1 SYSAUX Tablespace The SYSAUX Tablespace is always created at database creation. If you do not specify this clause. Other functionality or features that previously used by the SYSTEM Tablespace can now use the SYSAUX Tablespace.2 Pre-requisites for creating a database Sufficient Primary memory should be available to start the Oracle instance Sufficient Disk space must be available on the computer Steps to create a database $ vi .ora" to The name of the file can be anything but the name has to be specified explicitly at the time of the database startup.0 export PATH=$ORACLE_HOME/bin:$PATH :wq $ .2007 4 DATABASE CREATION Database creation prepares many operating system files so that they work together as an oracle database.

script written in a file 'cr8demo.ora" file. .log’. “REUSE” is used only if the respective file is already existing with the same size.dbf’ SIZE 170M SYSAUX DATAFILE ‘/disk1/oradata/DEMO/sysaux01. :wq Note: Defining the CONTROLFILE clause is optional.log’. which is defined in the following lines (i. /disk2/oradata/DEMO/cont2. $ $ $ $ $ $ $ cd /disk1/oradata mkdir DEMO cd DEMO mkdir bdump cdump udump # Create directories as specified in init<Oracle_SID>. redolog files.R030 – Oracle Database Notes Version 1.ora db_name=DEMO instance_name=DEMO db_cache-size=16m control_files=(/disk1/oradata/DEMO/contl.ctl) background_dump_dest=/disk1/oradata/DEMO/bdump user_dump_dest=/disk1/oradata/DEMO/udump core_dump_dest=/disk1/oradata/DEMO/cdump #Parameters to be passed for automatic undo management (optional) undo_management=auto undo_Tablespace=UNDOTBS undo_retention=900 :wq Create the necessary directories to place database files.e. example:.sql CREATE DATABASE demo DATAFILE ‘/disk1/oradata/DEMO/system01. GROUP 2 (‘/disk1/oradata/DEMO/redolog2a. because we will be specifying it in init.dbf’ SIZE 10M DEFAULT TABLESPACE user_data DATAFILE ‘/disk1/oradata/DEMO/user_data1. Moreover. ‘/disk2/oradata/DEMO/redolog2b. control files and the dump_dest directories.2007 Make the necessary changes in your "init<Oracle_SID>. ‘/disk2/oradata/DEMO/redolog1b. $ vi initDEMO.0 Page 13/135 Date: 29. Now to create the database.dbf’ SIZE 20M DEFAULT TEMPORARY TABLESPACE temp TEMPFILE ‘/disk1/oradata/DEMO/temp01.ctl. if db_name=DEFAULT change it to db_name=DEMO.ora file.log’) SIZE 4M CONTROLFILE REUSE.ora cd /disk2/oradata mkdir DEMO cd Execute the CREATE DATABASE command.log’) SIZE 4M. $ vi cr8demo.sql' – create with vi and execute the script).dbf’ SIZE AUTOEXTEND ON UNDO TABLESPACE undotbs DATAFILE ‘/disk1/oradata/DEMO/undotbs01.dbf’ SIZE 20M LOGFILE GROUP 1 (‘/disk1/oradata/DEMO/redolog1a.08.

$ sqlplus /nolog SQL> CONNECT / AS SYSDBA SQL> STARTUP NOMOUNT SQL> @cr8demo. the CATPROC and CATALOG scripts are to be executed.R030 – Oracle Database Notes Version 1.sql #as user SYS SQL> @ORACLE_HOME/rdbms/admin/catproc. The command is: SQL> @$ORACLE_HOME/rdbms/admin/pupbld. The commands are as follows: SQL> @ORACLE_HOME/rdbms/admin/catalog. Oracle performs the following operations: • Creates the control file(s) for the database • Creates the redolog files for the database • Creates the SYSTEM Tablespace and the system rollback segment • Creates the SYSAUX Tablespace • Creates Default Permanent Tablespace USER_DATA • Creates UNDO Tablespace and default temporary Tablespace TEMP • Creates the data dictionary • Creates user SYS and SYSTEM • Mounts and Opens the database for use After the above statement is processed.sql #as user SYS Then.sql".sql When you execute this statement. which are present in "$ORACLE_HOME/rdbms/admin" directory. connect as "system/manager" and execute "pupbld.0 Page 14/135 Date: 29.sql #as user SYS 4. as user “SYS”.3 • • • • • Data Dictionary Views You Can Query V$SGA V$INSTANCE V$DATABASE V$PROCESS V$SYSAUX_OCCUPANTS .2007 Use SQLPLUS to execute the commands.08.

UNDO Segments and Temporary Segments in different Tablespaces on different Hard-Drives. 1.0 Page 15/135 Date: 29. To resize the BIGFILE Tablespace. 5. • Control availability of data by taking individual Tablespace online or offline. 2.3 Advantages of having different Tablespaces Separation of user data from data dictionary data (which is in System Tablespace). SQL> CREATE TABLESPACE user2_demo DATAFILE ‘/disk1/oradata/DEMO/user2_demo01.2 • • • • • • • 5. A database administrator can use the Tablespace to do the following: • To control the user access by making it read only or read write.4 BIGFILE Tablespace A BIGFILE Tablespace is a Tablespace with a single. but very large (up to 4G blocks) datafile. Rollback Segments. • Control database size by adding/dropping Tablespaces. SQL> ALTER TABLESPACE bigtbs RESIZE 20M.1 Additional Tablespaces A database is divided into one or more logical storage units called Tablespaces. They can be created as follows: SQL> CREATE TABLESPACE user1_demo DATAFILE ‘/disk1/oradata/DEMO/user1_demo01.2007 5 TABLESPACE MANAGEMENT 5. • Perform online database backup or recovery operations. To create a BIGFILE Tablespace.08. the above types can be specified (Default is Permanent).R030 – Oracle Database Notes Version 1. 5. • Assign specific space quota for database users. Indexes. read only activity or temporary storage segments Backup individual Tablespaces leaving the rest for user access Types of Tablespaces • Read/Write • Read Only • Temporary • Undo While or after the Tablespace creation. for best performance. SQL> CREATE TABLESPACE index_demo DATAFILE ‘/disk1/oradata/DEMO/index_demo01.dbf’ SIZE 10M EXTENT MANAGEMENT DICTIONARY. Separation of one application data to another.dbf’ REUSE.dbf’ SIZE 10M EXTENT MANAGEMENT LOCAL UNIFORM SIZE 20K ONLINE. it is recommended to place the Tables. A database DEMO [created earlier] requires four (4) Tablespaces.dbf’ SIZE 10M. Remember. • Allocate data storage across devices to improve performance. SQL> CREATE BIGFILE TABLESPACE bigtbs DATAFILE ‘/disk1/oradata/DEMO/bigtbs01. . Store different Tablespaces datafiles on separate disk drives to reduce I/O contention Separate rollback segment data from user data or Undo Tablespace Take individual Tablespaces offline while others remain online Reserve a Tablespace for a particular type of a database use such as high update activity.

Assigning a Tablespace Group as the Default Temporary Tablespace SQL> ALTER DATABASE DEFAULT TEMPORARY Tablespace ts_grp1. To add a datafile to a Tablespace SQL> ALTER TABLESPACE user1_demo ADD DATAFILE ‘/disk1/oradata/DEMO/user1_demo02.1 Examples 1. .0 Page 16/135 Date: 29. To make Read-only Tablespace to Read/Write SQL> ALTER TABLESPACE user1_demo READ WRITE.08. 2. 5.R030 – Oracle Database Notes Version 1. To change the Default storage parameters SQL> ALTER TABLESPACE user1_demo DEFAULT STORAGE (INITIAL 40K NEXT 40K MINEXTENTS 2 MAXEXTENTS 20 PCTINCREASE 50).2007 3. 3. To enable autoextend on for the bigfile Tablespace.dbf’ SIZE 50M TABLESPACE GROUP ts_grp1. To make a Tablespace offline SQL> ALTER TABLESPACE user1_demo OFFLINE [NORMAL|IMMEDIATE|TEMPORARY].dbf’ SIZE 10M. 5. 4. 3. 2. You can remove a Tablespace from a group as shown in the following statements: SQL> ALTER TABLESPACE temp3 TABLESPACE GROUP ‘’. SQL> ALTER TABLESPACE bigtbs AUTOEXTEND ON. You can add a Tablespace to a group as shown in the following statement: SQL> ALTER TABLESPACE temp2 TABLESPACE GROUP ts_grp1. To make a Tablespace Read-only SQL> ALTER TABLESPACE user1_demo READ ONLY. 5.5 Temporary Tablespace Groups 1. 4.5.. 6. To create a temporary Tablespace group SQL> CREATE TEMPORARY TABLESPACE temp1 TEMPFILE ‘/disk1/oradata/DEMO/1mtemp201. To make a Tablespace online SQL> ALTER TABLESPACE user1_demo ONLINE.

dbf \ (press Enter) /disk2/oradata/DEMO/user1_demo.dbf’ TO ‘/disk2/oradata/DEMO/user1_demo01. Issue the ALTER DATABASE command SQL> ALTER TABLESPACE user1_demo RENAME DATAFILE ‘/disk1/oradata/DEMO/user1_demo01. Second method a. Finally open the database SQL> SHUTDOWN SQL> STARTUP 8.dbf’.R030 – Oracle Database Notes Version 1. d.dbf c. use ALTER TABLESPACE command: SQL> ALTER TABLESPACE user1_demo RENAME TO user2_demo. 9. b. Make the desired Tablespace offline SQL> ALTER TABLESPACE user1_demo OFFLINE. Copy or move the desired datafile to a new location at OS level $cp /disk1/oradata/DEMO/user1_demo.dbf’ TO ‘/disk2/oradata/DEMO/user1_demo01. To drop a tablespace SQL> DROP TABLESPACE user1_demo INCLUDING CONTENTS.dbf \ (press Enter) /disk2/oradata/DEMO/user1_demo. Copy or Move the desired datafile to new location at OS level $cp /disk1/oradata/DEMO/user1_demo. To change the name of a datafile in a Tablespace This can be done in two methods: First method a.08. To rename a tablespace. Bring the table to mount state SQL> CONNECT / as sysdba SQL> STARTUP MOUNT b. d. Bring the tablespace to online mode SQL> ALTER TABLESPACE user1_demo ONLINE.2007 7. Note: You cannot rename SYSTEM or SYSAUX tablespaces and tablespaces on OFFLINE mode.0 Page 17/135 Date: 29.dbf’. . Issue the ALTER TABLESPACE command SQL> ALTER TABLESPACE user1_demo RENAME DATAFILE ‘/disk1/oradata/DEMO/user1_demo01.dbf c.

R030 – Oracle Database Notes Version 1.dbf’).dbf’ AUTOEXTEND ON NEXT 1M MAXSIZE 20M. SMON process coalesces the free extents of tablespaces in background. To assign table to a specific data file: SQL> ALTER TABLE junk ALLOCATE EXTENT (DATAFILE ‘/disk1/oradata/DEMO/user1_demo01. To extend the size of a datafile automatically: SQL> ALTER DATABASE DATAFILE ‘/disk1/oradata/DEMO/user1_demo02.ora file with the following parameters: $ vi initDEMO. but the DB_nk_CACHE_SIZE parameters default it to 0 and no additional block size caches are configured.dbf’. 14. 11. when you create any tablespace other than SYSTEM. Datafile should be empty. To coalesce a tablespace .2007 10. 13.Smaller contiguous free extents can be coalesced into one larger free extent. Note: You cannot drop a datafile containing data.ora DB_2K_CACHE_SIZE=4M DB_4K_CACHE_SIZE=4M Note: By default. edit the INIT<SID>. SQL> CREATE TABLESPACE user4k_demo DATAFILE ‘/disk1/oradata/DEMO/user4k_demo01. By default.dbf’ SIZE 10M EXTENT MANAGEMENT LOCAL UNIFORM SIZE 20K BLOCKSIZE 4K ONLINE. 15.dbf’ RESIZE 10M. In order to configure multiple block sizes. To change the size of the a datafile: SQL> ALTER DATABASE DATAFILE ‘/disk1/oradata/DEMO/user1_demo01. 12. If you intend to use multiple block sizes in your database you must have DB_CACHE_SIZE and at least one DB_nk_CACHE_SIZE parameter set.dbf’ SIZE 10M EXTENT MANAGEMENT DICTIONARY BLOCKSIZE 2K. Oracle assigns an appropriate default value to the DB_CACHE_SIZE value to the DB_CACHE_SIZE parameter.0 Page 18/135 Date: 29.08. A new option is added to DROP TABLESPACE command to delete the OS files associated with the tablespace: SQL> DROP TABLESPACE user2_demo INCLUDING CONTENTS AND DATAFILES. To drop a datafile SQL> ALTER DATABASE DROP DATAFILE ‘/disk1/oradata/user1_demo01. SQL> CREATE TABLESPACE user8k_demo DATAFILE ‘/disk1/oradata/DEMO/user8k_demo01. the extent management is LOCAL AUTOALLOCATE. . SQL> ALTER TABLESPACE user1_demo COALESCE.

d. To get the details of Default Temporary Tablespace and Default Permanent Tablespace SQL> SELECT property_name.08. status FROM DBA_TABLESPACES.2007 5. file_id. block_size. b. extent_management. To list all the datafiles information with their size. SUM(bytes) FROM DBA_FREE_SPACE GROUP BY tablespace_name. property_value FROM DATABASE_PROPERTIEIS WHERE property_name LIKE ‘%DEFAULT%’.R030 – Oracle Database Notes Version 1.0 Page 19/135 Date: 29. To see the information about tablespaces: SQL> SELECT tablespace_name. bytes FROM DBA_DATA_FILES. To query the free space available in the tablespace SQL> SELECT tablespace_name. . SQL> SELECT file_name.6 • • • • • • • Data Dictionary Views You Can Query DBA_TABLESPACES DBA_TABLESPACE_GROUPS DBA_DATAFILES DBA_FREE_SPACE V$TABLESPACE V$DATAFILE DATABASE_PROPERTIES a. contents. c. tablespace_name.

You can also user K or M as above. It is specified in percentage.08. can ever be allocated for the segment. It cannot be negative. a user can specify the parameters while creating the objects. If pctincrease is 0.2007 6 STORAGE PARAMETERS Every tablespace has default storage parameters. 50% 0% OS specific Default: Minimum: Maximum: Note: Pctincrease for Rollback Segment is always 0. Though default system values are given data blocks. 5 datablocks 1 datablock OS specific The total number of extents.R030 – Oracle Database Notes Version 1. pctincrease. user bytes to set a value for this Parameter. next. This allows for a large allocation of space at creation time. You can also use the abbreviations K and M to indicate kilobytes and megabytes. 1 (extent) 1 (extent) OS specific Default: Minimum: Maximum: NEXT Default: Minimum: Maximum: MAXEXTENTS Default: Minimum: Maximum: MINEXTENTS Default: Minimum: Maximum: If minextents are more than 1. The following are the parameters: INITIAL The size in bytes of the first extent allocated when a segment is created. it grows by pctincrease. The second extent is equal to the original setting for the next. To override the system defaults in that Tablespace. If pctincrease is greater than 0. . then all incremental extents are the same size. including the first. From third extent onwards ‘Next’ is set to the previous size of Next multiplied by (1+Pctincrease/100). PCTINCREASE The percent by which each incremental extent grows over the last incremental extent allocated for a segment. Dependent on the data block size and OS 1 (extent) OS specific The total number of extents to be allocated when the segment is created. then the specified number of incremental extents is allocated at creation time using initial. even if contiguous space is not available. then each time the next is calculated.0 Page 20/135 Date: 29. 5 datablocks 2 datablocks OS specific The size of the next extent to be allocated for a segment. Pctincrease cannot be specified for Rollback segments.

They provide better space utilization and completely eliminate any need to specify and tune the PCTUSED. this space effectively becomes a permanent part of the block header. If such attributes should be specified. however. Once allocated. Insert some rows and check in USER_SEGMENTS SQL> DELETE FROM junk. SQL> CREATE TABLESPACE ts_auto DATAFILE ‘/disk1/oradata/DEMO/ts_auto01. Using the SEGMENT SPACE MANAGEMENT clause of CREATE TABLESPACE you can specify AUTO or MANUAL to specify the type of segment space management Oracle will use. which will not reset the high water mark. they are ignored. SQL> ALTER TABLE junk DEALLOCATE UNUSED KEEP 40K. the block is considered to be full and it is not available to insert new rows. It is used to allow a block to be reconsidered for the insertion of new rows. of transaction entries that can concurrently use data in a data block.08.R030 – Oracle Database Notes Version 1. Free lists have been the traditional method of managing free space within segments. The maxtrans parameter is used to limit the no. SELECT * FROM USER_SEGMENTS WHERE segment_name = ‘JUNK’. PCT USED INITTRANS MAXTRANS 6. SQL> SELECT * FROM USER_SEGMENTS WHERE segment_name = ‘JUNK’. The default value is 1 for tables and 2 for clusters. do: SQL> TRUNCATE TABLE junk. . ALTER TABLE JUNK DEALLOCATE UNUSED KEEP 40K. Oracle 9i allows free and used space within segments stored in locally managed tablespaces to also be managed automatically. if available. Bitmaps. The keyword AUTO tells Oracle that you want to use bitmaps to manage the free space within segments. you will see that the initial is not decreased because you have used delete command.0 Page 21/135 Date: 29. It reserves pre-allocated amount of space for initial number of transaction entries to access rows in the data block concurrently. Space is reserved in the header of all data blocks of all associated data or index segment. SELECT * FROM USER_SEGMENTS WHERE segment_name = ‘JUNK’. provide a simpler and more efficient way of managing segment space.2007 PCT FREE It is used to set percentage of a block to be reserved (kept free) for future updates. But. the block is again available for insertion of new rows.dbf’ SIZE 10M EXTENT MANAGEMENT LOCAL UNIFORM SIZE 20K SEGMENT SPACE MANAGEMENT AUTO. if you still want to decrease further then. When the percentage of a block being used falls below PCTUSED either through row deletion or updates reducing column storage. SQL> ALTER TABLE junk DEALLOCATE UNUSED KEEP 40K. Note: Check in user_segments. As multiple transactions concurrently access the rows of the same data block. To change the initial extent of a Table: SQL> SQL> SQL> SQL> CREATE TABLE junk (a NUMBER) STORAGE (INITIAL 40K).1 Automatic Segment Space Management Locally managed tablespaces allow extents to be managed automatically by Oracle. FREELISTS and FREELISTS GROUPS attributes for segments created in the database. Once the space reserved by inittrans is depleted. space is allocated for each transaction’s entry in the block. After this parameter is met. space for additional transaction entries is allocated out of the free space in a block.

PIECES shows the amount of fragmentation in the datafiles of the tablespace. Listing the Segment Storage Parameters SQL> SELECT segment_name. next_extent “NEXT_EXT”. initial_extent. AVG(blocks) “AVERAGE”. Listing of free space (extents) of each Tablespace: SQL> SELECT tablespace_name. max_extents FROM DBA_SEGMENTS WHERE segment_name=’EMP'.dba_free_space WHERE tablespace_name = ‘SYSTEM’ GROUP BY tablespace_name. Listing tablespaces and default storage parameters: SQL> SELECT tablespace_name “TABLESPACE”. and. and you want to make sure that there is enough spaces in the containing tablespace. tablespace_name. tablespace_name FROM dba_data_files.2007 6. file_id. min_extents. MAX(blocks) “MAXIMUM”. c. bytes. pct_increase FROM dba_tablespaces. MIN(blocks) “MINIMUM”. d. This query is useful when you are going to create a new object or you know that a segment is about to extend. max_extents “MAX_EXT”. SUM(blocks) “TOTAL” FROM sys. Listing the datafiles and associated Tablespaces of a database: SQL> SELECT file_name. next_extent. b. COUNT(*) “PIECES”.0 Page 22/135 Date: 29. .08. initial_extent “INITIAL_EXT”. • • • SUM shows the amount of free space in each tablespace. min_extents “MIN_EXT”.2 • • • • • • • Data Dictionary Views DBA_SEGMENTS DBA_EXTENTS DBA_TABLES DBA_INDEXES DBA_TABLESPACES DBA_DATA_FILES DBA_FREE_SPACE a. file_id.R030 – Oracle Database Notes Version 1. MAXIMUM shows the largest contiguous area of space.

System Tablespace and System Rollback Segment is created. When you create database. To convert a locally managed tablespace to dictionary managed. You cannot drop this segment. To create a rollback segment. To bring rollback segments online automatically.TABLESPACE_MIGRATE_FROM_LOCAL (‘RBSDATA’).08. There are two types of Rollback Segments. 4.2007 7 MANAGING ROLLBACK SEGMENTS Rollback segments stores undo information and are used for the following purposes: • To undo the previous command • For read consistency and • For crash recovery Each rollback segment: • Consists of several rollback entries from multiple transactions • Stores block information such as file and blocked. Note: Rollback segment cannot be created in a locally managed tablespaces. as well as data as it existed before being modified • Must be created under special circumstances and brought online before being used • May increase due to large transactions • Will automatically shrink to optimal if extended • Transactions can be assigned automatically or explicitly Rollback segment maintains a table for every transaction. 3. To make it offline or online. If you want to either make it online or want to change storage parameters you have to use alter command as follows: SQL> ALTER ROLLBACK SEGMENT <segment> [ONLINE|OFFLINE]. segment_name FROM DBA_SEGMENTS WHERE segment_type – ‘DEFFERED ROLLBACK’. 1. • PUBLIC and • PRIVATE SQL> SELECT segment_type. Depending on the number of transactions you have to decide how many Rollback Segments are needed. try the following: SQL> EXEC DBMS_SPACE_ADMIN.ora parameter file.0 Page 23/135 Date: 29. the tablespace must be a dictionary-managed tablespace. 2.R030 – Oracle Database Notes Version 1. . To change storage parameters: SQL> ALTER ROLLBACK SEGMENT rbs1 STORAGE (MAXEXTENTS 15). set ROLLBACK SEGMENTS parameter in init<ORACLE_SID>. To create a temporary Tablespace group SQL> CREATE ROLLBACK SEGMENT rbs1 TABLESPACE rbs_demo STORAGE (INITIAL 40K NEXT 40K OPTIMAL 120K MINEXTENTS 2 MAXEXTENTS 10). which is identified by SMON during recovery. SQL> ALTER ROLLBACK SEGMENT rbs1 [ONLINE|OFFLINE].

To shrink rollback segment manually: SQL> ALTER ROLLBACK SEGMENT rbs1 SHRINK TO 100K. extents FROM DBA_SEGMENTS WHERE segment_type = ‘ROLLBACK’. Oracle now offers another method of storing undo that eliminates the complexities of managing rollback segment space. SQL> DROP ROLLBACK SEGMENT rbs1. blocks. use the following query: SQL> SELECT name. and drop the segment SQL> ALTER ROLLBACK SEGMENT rbs1 OFFLINE. bytes.1 • • • • • Data Dictionary Views DBA_SEGMENTS USER_SEGMENTS DBA_ROLLBACK_SEGS V$ROLLSTAT V$ROLLNAME Examples: a. xacts ‘Active Transactions’. status FROM V$ROLLNAME. but it is not used for new transactions. To display Rollback Segment information: SQL> SELECT segment_name. optsize. Make it offline first. status FROM DBA_ROLLBACK_SEGS. This method uses an UNDO TABLESPACE.USN = V$ROLLSTAT. Oracle has used rollback segments to store undo.USN. hwmsize. Note: You cannot use both methods in the same database instance . Historically. To determine whether any Rollback Segment for an instance are in this state. Space management for these rollback segments have proven to be quite complex. 7. To check the name. tablespace and its size: SQL> SELECT segment_name.08. b. it does not actually go offline until all active transactions in it have completed.2007 5. 6. wraps resize. tablespace_name. V$ROLLSTAT WHERE V$ROLLNAME. its status in DBA_ROLLBACK_SEGS remain ONLINE. extents. To explicitly assign a Rollback Segment to a transaction SQL> SET TRANSACTION USE ROLLBACK SEGMENT rbs1.0 Page 24/135 Date: 29. 7.R030 – Oracle Database Notes Version 1. Between the time when you attempt to take offline and where it is actually offline. and enables DBA’s to exert control over how long the undo is retained before being overwritten. tablespace_name.2 Pending Offline When you take a Rollback Segment offline. 7. To drop a rollback segment.

you only have to allocate enough disk for the workload in that instance in an undo tablespace. DROP. you cannot CREATE.0 Page 25/135 Date: 29. For each Oracle instance.08. • Undo segments have the same structure as normal rollback segments but they: o Support automatic creation o Use a modified allocation policy compared to Oracle8i o Support dynamic extents transfer • SMON shrinks undo segments when needed If you use the rollback segment method of managing undo space. the default is 900 seconds. That is. the instance starts. but uses the SYSTEM rollback segment. is retained until its retention time has expired even across restarting the instance.2007 8 UNDO MANAGEMENT 8. and are called undo segments. You no longer need to decide on the number and sizes of rollback segments to create. . Oracle automatically selects for use the first available undo tablespace. which is not recommended. You determine the mode at instance startup using UNDO_MANAGEMENT initialization parameter. • Rollback segments are still used but are internally created and maintained. The UNDO_RETENTION parameter can be set in the initialization parameter file or can be changed dynamically at any time using the ALTER SYSTEM command: SQL> ALTER SYSTEM SET UNDO_RETENTION = 900. you are operating in the automatic undo management mode. If there is no undo tablespace available.1 Overview of Undo Management An undo tablespace is organized as a uniform bitmapped tablespace. It is persistent and can survive system crashes. Oracle Flashback features depend upon the availability of older undo information. you are said to be operating in the manual undo management mode. undo generated before an instance crash. or ALTER undo segments. • With automatic undo management. If the UNDO_RETENTION initialization parameter is specified. If you use the undo tablespace method. It is composed of one or more files containing undo segments. and on how to assign transactions (of different sizes) strategically to individual rollback segments.2 Undo Retention Retention is specified in units of seconds. UNDO_MANAGEMENT = AUTO UNDO_TABLESPACE = UNDOTBS UNDO_RETENTION = 900 8. When the instance starts up.R030 – Oracle Database Notes Version 1.

R030 – Oracle Database Notes Version 1.0

Page 26/135 Date: 29.08.2007

8.3 Steps to Create and Maintain Undo Tablespace 1. CREATE an Undo Tablespace There are two methods of creating an undo tablespace. The first method creates the undo tablespace when the CREATE DATABASE statement is issued. The second method is used with an existing database. It uses CREATE UNDO TABLESPACE statement. You cannot create database objects in an undo tablespace. It is reserved for system-managed undo data.
SQL> CREATE UNDO TABLESPACE undotbs_02 DATAFILE ‘/disk1/oradata/DEMO/undo_01.dbf’ SIZE 10M;

An undo tablespace is permanent, locally managed tablespace, read-write and in logging mode with default block size. Values for MINIMUM EXTENT and DEFAULT STORAGE are system generated. 2. Altering an Undo Tablespace However, because most aspects of undo tablespaces are system managed, you need only be concerned with the following actions: a. Adding or resizing a datafile b. Renaming a data file c. Bringing a datafile online or taking it offline d. Beginning or ending an open backup
SQL> ALTER TABLESPACE undotbs_02 ADD DATAFILE ‘/disk3/oradata/DEMO/undo_02.dbf’ SIZE 10M AUTOEXTEND ON;

3. Switching Undo Tablespace You can switch from using one undo tablespace to another. Because the UNDO_TABLESPACE initialization parameter is a dynamic parameter, the ALTER SYSTEM SET statement can be used to assign a new undo tablespace.
SQL> ALTER SYSTEM SET UNDO_TABLESPACE=undotbs_02;

Note: The switch operation does not wait for transactions in the old undo tablespace to commit. If there are any pending transactions in the old undo tablespace, undo tablespace enters into a PENDING OFFLINE mode (status). If the parameter value for UNDO_TABLESPACE is set to '' (single quotes), the current undo tablespace will be switch out without switching in any other undo tablespace. For example, to un-assign an undo tablespace in the event that you want to revert to ROLLBACK SEGMENT UNDO MODE.
SQL> ALTER SYSTEM SET UNDO_TABLESPACE = '';

4. Dropping an Undo Tablespace Use the DROP TABLESPACE statement to drop an undo tablespace. An undo tablespace can only be dropped if it not currently used by any instance. If the undo tablespace contains any outstanding; e.g. a transaction died but has not yet been fully recovered), the DROP TABLESPACE statement fails.
SQL> DROP TABLESPACE undotbs_02 INCLUDING CONTENTS AND DATAFILES;

Note: We cannot drop an UNDO tablespace that is ONLINE.

R030 – Oracle Database Notes Version 1.0

Page 27/135 Date: 29.08.2007

8.4 Retention Guarantee If retention guarantee is enabled, the specified minimum undo retention is guaranteed. When you enable this option, the database never overwrites unexpired undo data – that is, undo data whose age is less than the undo retention period. By enabling the guarantee option, you instruct the database not to overwrite unexpired undo data even if it means risking failure of currently active DML operations. A typical use of the guarantee option is when you want to ensure deterministic and predictable behavior of Flashback Recovery by guaranteeing the availability of the required undo data.
SQL> CREATE UNDO TABLESPACE undo_tbs1 DATAFILE ‘/disk1/oradata/DEMO/undo_tbs1_01.dbf’ SIZE 10M RETENTION GUARANTEE;

Existing undo tablespaces can also be made to comply with the guarantee by ALTERing them, as in:
SQL> ALTER TABLESPACE undo_tbs2 RETENTION GUARANTEE;

In case we don’t want guarantee retention, then:
SQL> ALTER TABLESPACE undo_tbs2 RETENTION NOGUARANTEE;

You can verify that the tablespace has guaranteed undo retention with:
SQL> SELECT RETENTION FROM DBA_TABLESPACES WHERE TABLESPACE_NAME=’UNDO_TBS1’;

8.5 • • • • •

Data Dictionary Views DBA_UNDO_EXTENTS DBA_SEGMENTS USER_SEGMENTS V$UNDOSTAT V$TRANSACTION

Examples: a. To query overall undo segments statistics:
SQL> SELECT begin_time, end_time, undotsn, undoblks, txncount, maxcoconcurrency as “MAXCON” FROM V$UNDOSTAT;

b. To check the commit time for each extent in the undo tablespaces:
SQL> SELECT segment_name, tablespace_name, extent_id, file_id, block_id, blocks, commit_jtime, commit_wtime, status FROM DBA_UNDO_EXTENTS;

R030 – Oracle Database Notes Version 1.0

Page 28/135 Date: 29.08.2007

9 MANAGING REDOLOG FILES
9.1 Introduction Redologs record all the block level updating made to the database. Every database must have at least two redo-log groups and one file per group. These files can be mirrored to avoid single point of failure. These are used by Oracle during instance recovery and for media recovery. These files are written in circular fashion to save disk space. The filled redo log files will be archived if the database is running in archivelog mode. It is strongly recommended that database should run in Archive log mode. For e.g., if power fails abruptly and data in memory can not be written on datafiles, however Oracle recovers the unrecorded data in datafile by applying redologs. The process of applying the redolog during recovery operation is called rolling forward. Note: The minimum Redo log file size is 4MB. 9.2 Mirrored REDO Logs The recommended redolog file configuration is, at least two redolog per members per group. • All members of a group of log files contain the same information • Group members are updated simultaneously • Each group may or may not contain the same number of members as other groups. 9.3 Log Switches • A log switch occurs when Oracle switches from one redo log to another • A log switch occurs LGWR has filled one log file group • A log switch can be forced by a DBA when the current redo log needs to be archived At a log switch the current redo log is assigned a log sequence number that identifies the information stored in that redolog and also used for synchronization. A checkpoint automatically occurs at log switch. 1. To add a new group to existing database
SQL> ALTER DATABASE ADD LOGFILE group 3 (‘/disk1/oradata/DEMO/redolog3a.log’, (‘/disk2/oradata/DEMO/redolog3b.log’) SIZE 4M;

2. To add a new member to the existing groups
SQL> ALTER DATABASE ADD LOGIFILE MEMBER ‘/disk/oradata/demo/redolog2b’ TO GROUP 2;

3. To rename a log file a. Using sqlplus, bring database to mount state
SQL> ALTER DATABASE CLOSE;

b. Use the console, copy data files to new destination
$> cp /disk3/oradata/demo/redolog2a.log \ /disk2/oradata/demo/redolog2a.log

c. Back to sqlplus, rename the redo-log
SQL> ALTER DATABASE RENAME FILE ‘/disk3/oradata/DEMO/redolog2a.log’ TO ‘/disk2/oradata/DEMO/redolog2a.log’;

d. Finally, open the database
SQL> STARTUP

However. and there by eliminate the single point of failure of online redolog.2007 4.4 • • • • • • Data Dictionary Views V$LOG V$LOGFILE V$LOG_HISTORY V$LOGHIST V$RECOVERY_LOG V$ARCHIVED_LOG . first force a log switch to occur. ORA-7360 Unable to obtain information about log group. If you need to drop the active group.log’. first force a log switch to occur. If you need to drop the active member. Note: If the redolog files are lost. Make sure an online redolog is archived before dropping it. even though all other groups have two members each.08. you should rectify this situation immediately. To drop a member. If you drop a member from the online group. To drop the log group and members If you drop online group then you will get the following error. b. b. /*(to drop a group)*/ SQL> ALTER DATABASE DROP LOGFILE MEMBER ‘/disk3/oradata/demo/redolog2a. the above command (which command? -. all groups have at least two members. so that. You can drop an online redo log group only if it is not the active member.. regardless of the number of members in the groups. 5.Domingo) will recreate those logfiles. then you get the following error. for e. 9. ORA-313 – Open failed for member of member of log group. You can drop an online redolog group only if it is not the active group. It is OK to drop online redolog files. SQL> ALTER SYSTEM SWITCH LOGFILE. SQL> ALTER DATABASE DROP LOGFILE GROUP 3. An instance requires at least two groups of online redolog files. so that. consider the following points: a.R030 – Oracle Database Notes Version 1. consider the following points: a.0 Page 29/135 Date: 29. a mirrored online redolog becomes temporarily unsymmetrical.g. if you are using duplexed groups of online redolog files. you can drop one member of one group. To clear online redo logs SQL> ALTER DATABASE CLEAR UNARCHIVED LOGFILE GROUP 2. To drop online redolog group.

dbf’ SIZE 10M. $ vi bkup. MAXLOGMEMBERS. If a control file is damaged due to disk failure the associated instance must be shutdown. 10. and the other in /disk2/oradata/Demo/control2.ctl’ is in unrecoverable state. Assume that one control file is located in path /disk1/oradata/DEMO/control1. $ cd /disk1/oradata/DEMO/udump $ cp ora_2065. MAXINSTANCES of the CREATE DATABASE statement that created the associated database.ctl \ /disk2/oradata/DEMO/control2. issuing the command: SQL> ALTER TABLESPACE user_demo ADD DATAFILE ‘/disk1/oradata/DEMO/user03.1 Introduction Control files are created by Oracle.sql If the MAXDATAFILES parameter is set to 5 and if you try to add 6th datafile. SQL> ALTER DATABASE BACKUP CONTROL FILE TO TRACE.2 Managing the size of the control file Typical control files are small.sql SQL> ALTER TABLESPACE user_demo ADD DATAFILE ‘/disk1/oradata/DEMO/user03. the damaged control file can be restored using an intact copy of the control file and the instance can be restarted. Every Oracle database should have at least two control files (recommended).0 Page 30/135 Date: 29. ORA-1503 create control file failed ORA-116 file number 3 larger than MAXDATAFILES (5) To increase the number of maximum data files supported by your DB. . MAXLOGFILES.sql MAXDATAFILES 10 :wq SQL> CONNECT / AS SYSDBA SQL> @bkup.sql $ cat bkup.ctl. MAXLOGHISTORY.2007 10 MANAGING REDOLOG FILES 10.dbf’ SIZE 10M. By using mirrored control files. edit your trace file. The major portion of a control file size depends on the values set for the parameters: MAXDATAFILES.ORA.ctl SQL> STARTUP No media recovery is required. The path of a control file is specified in INIT. you avoid unnecessary problems if a disk failure occurs on the database server.trc bkup. then issue the following command. $cp /disk1/oradata/DEMO/control1. The maximum control file size is operating system specific.R030 – Oracle Database Notes Version 1.08. If one control file ‘control1. each stored on each different disk.ctl. To check the number of files specified in control files. Once the disk drive is repaired.

Edit the parameter control_files in INIT.08. Trace the control file SQL> ALTER DATABASE BACKUP CONTROLFILE TO TRACE. To drop excessive control files a. To create an additional copy of controlfile. SQL> SHUTDOWN IMMEDIATE $ cat initDEMO. $ cd /disk2/oradata/DEMO $ cp control1. Finally execute the traced control file to create new control file .trc STARTUP NOMOUNT CREATE CONTROLFILE REUSE DATABASE “DEMO” RESETLOGS NOARCHIVELOG LOGFILE GROUP 1 (‘/disk1/oradata/DEMO/redolog1.dbf’ SQL> ALTER DATABASE OPEN RESETLOGS. To rename (change the name of) a database a. 1. To trace the control file to udump destination and generate the create control file syntax: SQL> ALTER DATABASE BACKUP CONTROLFILE TO TRACE.trc STARTUP NOMOUNT CREATE CONTROLFILE SET DATABASE “ACCT” RESETLOGS NOARCHIVELOG LOGFILE GROUP 1 (‘/disk1/oradata/DEMO/redolog1. Shutdown the database b. ‘/disk2/oradata/DEMO/redolog2.log’.2007 Follow the same steps to increase the parameter values for LOGFILES and LOGMEMBERS.ctl) SQL> STARTUP 3.sql SHUTDOWN ABORT @orabkup. Edit trace file. replace the keyword REUSE to SET $ vi ora_2065. leaving at least one control file to start the database c. c.ora d. GROUP 2 (‘/disk1/oradata/DEMO/redolog1.log’. Include the complete path of the new file in 'control_files' parameter in INIT.log) SIZE 4M.log’. GROUP 2 (‘/disk1/oradata/DEMO/redolog1. Remove the existing control files from their destination e.trc orabkup.ctl control2. b.ctl SQL> STARTUP 2. ‘/disk2/oradata/DEMO/redolog2.0 Page 31/135 Date: 29. $ cd /disk2/oradata/DEMO/udump $ vi ora_2065.ORA and remove one of the control file entries.R030 – Oracle Database Notes Version 1.log) SIZE 4M DATAFILE ‘/disk1/oradata/DEMO/system01.log) SIZE 4M.ORA.ORA # here we are only observing line 1 which reads control files CONTROL_FILES = (/disk2/oradata/DEMO/control2. Restart the database The above steps do not delete the file physically from the disk. ‘/disk2/oradata/DEMO/redolog2. ‘/disk2/oradata/DEMO/redolog2. Set the parameter db_name to the new line in the init.dbf’ SQL> $ cp SQL> SQL> ALTER DATABASE OPEN. issue the following statements. ora_2065.log) SIZE 4M DATAFILE ‘/disk1/oradata/DEMO/system01.sql 4.log’.

R030 – Oracle Database Notes Version 1.08.3 Data Dictionary Views • V$CONTROLFILE • V$CONTROLFILE_RECORD_SECTION .0 Page 32/135 Date: 29.2007 10.

shutdown the database with normal.08.1 Introduction It is the DBA’s choice whether to run the database in ARCHIVELOG mode or in NOARCHIVELOG mode. online backups and database recovery will not be possible.3 Data Dictionary Views • V$ARCHIVED_LOG • V$ARCHIVE_DEST • V$ARCHIVE_PROCESSES . Note: To enable archive log mode.R030 – Oracle Database Notes Version 1. this parameter is obsolete in 10g and automatic archiving is enabled in 10g. If database is chosen to operate in NOARCHIVELOG mode. The redo log files (online and archived) are essential for database recovery since they contain information on all changes made to the database. After passing the above parameters in init<SID>. These files are sometimes referred to as the offline redolog files since they are not open during normal operation of the database and are required only during recovery. immediate option. automatic archival will be started but the database will still be in NOARCHIVELOG mode.ora LOG_ARCHIVE_DEST=/disk2/oradata/DEMO/ARCH :wq $ mkdir /disk2/oradata/DEMO/ARCH $ sqlplus “/ as sysdba” SQL> STARTUP MOUNT SQL> ARCHIVE LOG LIST The above command will show whether automatic archival is started or not and also whether the database is running in archive log mode or not. $ cd $ORACLE_HOME/dbs $ vi initDEMO. 11. These archive files are known as the archived redolog files.0 Page 33/135 Date: 29. The following command will convert the database in ARCHIVELOG mode: SQL> ALTER DATABASE ARCHIVELOG. archived redologs. If the database is running in archivelog mode. contents of the online redolog files are copied to an archive area by an Oracle background processes Achiver (ARCn).ora SQL> SHUTDOWN IMMEDIATE.ora.2 To Convert the database into ARCHIVELOG mode Enter the following parameters in the init<SID>. Note: LOG_ARCHIVE_START=TRUE.2007 11 ARCHIVED REDO LOG FILES 11. SQL> ALTER DATABASE OPEN. or simply archived redo. 11.

This feature does not affect the creation or naming of administrative files such as trace files. the DBA. Oracle managed files eliminate the need for you. online redo logs and control files. 12. alert files and core files. all the files (datafiles. where n is any integer between 1 and 5.R030 – Oracle Database Notes Version 1. You specify operations in terms of database objects rather than filenames. Oracle Managed datafiles. Oracle internally uses standard file system interfaces to create and delete files as needed for the following database structures: • Tablespaces • Online redo log files • Control files Through initialization parameters. control files and online logs) will be created at the destination specified by the DB_CREATE_FILE_DEST parameter. you specify the file system directory to be used for a particular type of file. It also makes development of portable third party applications easier since it eliminates the need to put OS specific filenames in SQL scripts. While the parameter DB_CREATE_FILE_DEST specifies the default location of datafiles. reduce disk space wasted in obsolete files. created by default. If neither of the last two parameters are set. audit files. Oracle then ensures creation of a file with a unique name and deletes it when the corresponding object is dropped. .08.2007 12 ORACLE MANAGED FILES 12. This feature allows for specifying operations in terms of database objects. decides the default location for copies of online logs and control files. OMF reduces errors caused by administrators specifying incorrect file names. is created and deleted when no longer needed.0 Page 34/135 Date: 29.2 Main benefits of the Oracle Managed Files • Ease of Oracle file management • Reduction of Oracle file management errors • Disk space management improvements • Easier third-party application integration The new OMF feature simplifies database administration by eliminating the need for administrators to directly manage the files of an Oracle database. Oracle uses the standard operating system (OS) file system interfaces internally to create and delete files as needed for tablespaces. and simplifies creation of test and development databases. DBAs only need to specify the location of these files using new initialization parameters.1 Introduction Using the Oracle managed files simplifies the administration of an Oracle database. to directly manage the operating system files comprising an Oracle database. the parameter DB_CREATE_ONLINE_LOG_DEST_<n>. an Oracle-managed file. The default size of Oracle Managed online logs will also be 100MB. Oracle then ensures that a unique file. will be 100MB in size and will be auto extensible with unlimited maximum size.

one each in directories /disk1/oradata/demo3 and /disk2/oradata/DEMO The control file in /disk1/oradata/DEMO is the primary control file. Creating tablespaces Once DB_CREATE_FILE_DEST is set. Try to check the datafile in the path specified in DB_CREATE_FILE_DEST. The datafile is created in the location specified by DB_CREATE_FILE_DEST by default. a 10 MB datafile in directory /disk1/oradata/DEMO • • If no CONTROL_FILES initialization parameter was specified. 12. • A 200 megabyte SYSTEM tablespace datafile in directory /disk1/oradata/DEMO • Two online redo log groups with two members of 100 MB each.2 Scenario 2: CREATE DATABASE: Using Oracle Managed Files 1. then two control files.R030 – Oracle Database Notes Version 1. When tablespace tbs_2 is dropped. set the DB_CREATE_FILE_DEST initialization parameter to the file system directory in which to create the data files.08. For example: SQL> CREATE TABLESPACE tbs_2.2. but the DBA would like to create new tablespaces with Oracle-managed files and locate them in directory ‘/disk1/oradata/demo2. • For the undo tablespace named undo_ts.1 Scenario 1: Add Oracle Managed Files to an Existing Database Assume in this case that an existing database does not have any Oracle-managed files. one each in directories /disk1/oradata/DEMO and /disk2/oradata/DEMO. A database with the following characteristics is created. Setting the initialization parameters To allow automatic datafile creation. Included in the initialization parameter file: DB_CREATE_FILE_DEST = ‘/disk1/oradata/DEMO’ DB_CREATE_ONLINE_LOG_DEST_1 = ‘/disk1/oradata/DEMO’ DB_CREATE_ONLINE_LOG_DEST_2 = ‘/disk2/oradata/DEMO’ 2.2007 12. the file sizes for Oracle managed files for the default temporary tablespace and undo tablespace are specified. 2. . the datafiles associated with this tablespace will also be removed from the operating system. This can be done dynamically as follows: SQL> ALTER SYSTEM SET DB_CREATE_FILE_DEST = ‘/disk1/oradata/DEMO’. 1.2.0 Page 35/135 Date: 29. Create the database statement SQL> CREATE DATABASE db1 DATAFILE SIZE 200M SYSAUX DATAFILE SIZE 100M DEFAULT TEMPORARY TABLESPACE dflt_ts TEMPFILE SIZE 10M UNDO TABLESPACE undo_ts DATAFILE SIZE 10M. SQL> DROP TABLESPACE tbs_2. the DATAFILE clause can be omitted from a CREATE TABLESPACE statement. In this example.

Always make sure that the default tablespace option is given while creating a user. . you can make sure that your facility complies with the license agreement. you have a license that states how many concurrent users are allowed to connect to the database. Note: Profile clerk must be created prior to creating a user. and additional quotas for other tablespaces which they can create objects. SQL> ALTER USER user_01 PROFILE clerk. the user’s temporary tablespace contains the temporary segment. giving user name and password is mandatory. Through the management of users and their access. 2. When a user executes a SQL statement that requires the creation of a temporary segment. a user has no quota on any tablespace in the database. If the user has the privilege to create a schema object.0 Page 36/135 Date: 29. Whereas. you should specifically assign the user a default tablespace. • Default tablespace • Temporary tablespace • Tablespace quotas • Profile Default Tablespace Each user is associated with a default tablespace.R030 – Oracle Database Notes Version 1. The default setting for every user’s default tablespace is the SYSTEM tablespace.08. Once this policy is defined. the appropriate levels of database access for different types of users. 13. If the user is already created. a user must run a database application and connect to the database instance using a valid user name defined in the database. assign users a quota for the default tablespace. An organization must establish a database security policy that defines. Temporary Tablespace Each user is associated with a temporary tablespace. In general. 1.2007 13 MANAGING USERS AND RESOURCES 13. When you create a new user. you must assign a quota to allow the user to create objects.2 Creating Users You can create a new database user by using the create user dialog box in SQL*DBA or the SQL command creates user. you can then manage the database users easily. among other things. Using a tablespace other than SYSTEM reduces contention between data dictionary objects and user objects for the same data files. Tablespace Quotas By default. If a user creates any type of object. it is not advisable for user data to be stored in the SYSTEM tablespace.1 Managing Database Users To access a database. use ALTER USER command to assign profile. To change the profile of an existing user. The following command creates the new database user "user_01". Minimally. the following will take the default values if not provided. SQL> CREATE USER user_01 IDENTIFIED BY demo DEFAULT TABLESPACE user_demo QUOTA 5m ON user_demo QUOTA 3m ON system PROFILE clerk. For you Oracle Server. Another area that comes under managing database users is licensing.

. issue the ALTER USER command. LOGICAL_READS_PER_SESSION and PRIVATE_SGA. SESSIONS_PER_USER CPU_PER_SESSION CPU_PER_CALL CONNECT_TIME FAILED_LOGIN_ATTEMPTS PASSWORD_LIFE_TIME PASSWORD_REUSE_MAX PASSWORD_VERIFY_FUNCTION PASSWORD_LOCK_TIME PASSWORD_GRACE_TIME IDLE_TIME LOGICAL_READS_PER_SESSION LOGICAL_READS_PER_CALL PRIVATE_SGA COMPOSITE_LIMIT Limits the number of concurrent sessions for user. A session is created every time a database user connects to the database. Limits the total resource cost per session.0 Page 37/135 Date: 29.08. A profile is a named set of resource limits that can be assigned to a user. SQL> ALTER USER user_01 IDENTIFIED BY <new_password>. The following resource limits can be set during profile creation. 13. 5. This is expressed in hundredths of seconds. Limits CPU time for a call.3 Managing Resources with Profiles System resource limits are managed with the user profiles. Limits the CPU time for session. To change a user’s password. This is expressed in hundredths of seconds. the current statement is rolled back and error message is returned to the user.2007 3. this is a composite of the resources such as CPU_PER_SESSION.R030 – Oracle Database Notes Version 1. The database administrator has option to globally enable or disable profiles. The identified by clause is used to give the user a password. SQL> ALTER USER user_01 QUOTA 10M ON user_data02 QUOTA 0M ON system. Limits the elapsed connect time of a session. Use cascade option if user has any objects already existing in the schema. To create a profile issue the “CREATE PROFILE” command. These resources can generally be established at the session and statement levels. CONNECT_TIME. If a session level resource limit is reached. That is the DBA has a capability to make specific resource limits apply to all users. The following statement assign quotas on more tablespaces and revokes quota from SYSTEM tablespace. No of failed attempts after which account is going to be locked No of days the password is valid No of times password can be changed Function with which it is going to verify the password No of days password is going to be locked No of days it is going to prompt for password expiry Defines the maximum amount of continuous inactive time span Limits the number of data blocks read in a session Limits the number of data blocks read for a call to Proces a SQL statement Limits the amount of private space a session can reserve in the system global area. To drop a user SQL> DROP USER user_01 CASCADE. This limit applies only if you are using a multi-threaded server. 4.

0 Page 38/135 Date: 29. 13. • List of users in the database • Each user’s default tablespace for tables.ora). you have to include. The following information is available in the data dictionary for every user and profile.R030 – Oracle Database Notes Version 1.3 To Drop a Profile SQL> DROP PROFILE clerk CASCADE. clusters and indexes • Memory usage for each current session • Space quotas for each user • Each user’s assigned profile and resource limits • The cost assigned to each applicable resource 13. or SQL> ALTER SYSTEM SET RESOURCE_LIMIT=TRUE. Use CASCADE option if you assign profile to any user.3. All others assume their resource limits as defined by the default profile.2 To Create and Alter a Profile SQL> CREATE PROFILE <profile_name> LIMIT SESIONS_PER_USER [integer|unlimited|default] CPU_PER_SESSION [integer|unlimited|default] CPU_PER_CALL [integer|unlimited|default] CONNECT_TIME [integer|unlimited|default] PASSWORD_LIFE_TIME [integer|unlimited|default] PASSWORD_GRACE_TIME [integer|unlimited|default] FAILED_LOGIN_ATTEMPT [integer|unlimited|default] IDLE_TIME [integer|unlimited|default] LOCAL_READS_PER_SESSION [integer|unlimited|default] LOCAL_READS_PER_CALL [integer|unlimited|default] COMPOSITE_LIMIT [integer|unlimited|default] PRIVATE_SGA [integer|unlimited|default]. RESOURCE_LIMIT=true (in init.3.2007 13. SQL> ALTER PROFILE clerk LIMIT LOGICAL_READS_PER_SESSION 20000 CPU_PER_CALL DEFAULT LOGICAL_READS_PER_CALL 100. This statement defines only four resources.08.1 To Enable the Resource Limit The following statement creates profile named “clerk”. To enable profile. . Note: One can not drop the DEFAULT profile.3. Example: SQL> CREATE PROFILE clerk LIMIT SESSIONS_PER_USER 1 CONNECT_TIME 560 CPU_PER_CALL 6000 FAILED_LOGIN_ATTEMPTS 3 PASSWORD_LIFE_TIME 60 PASSWORD_LOCK_TIME 1 PASSWORD_GRACE_TIME 10 IDLE_TIME 15.

13. To set both the warning limit and maximum limit: SQL> ALTER SYSTEM SET LICENSE_MAX_SESSIONS = 64 LICENSE_SESSIONS_WARNING = 54. 13.. Set the initialization parameter REMOTE_LOGIN_PASSWORDFILE = EXCLUSIVE 3. To set the maximum sessions for an instance: SQL> ALTER SYSTEM SET LICENSE_MAX_SESSIONS = 100. SQL> SHUTDOWN V$PWFILE_USERS view gives the information regarding the password file . • You can define users such that authentication is performed by the operating system or network service. The user Scott can connect to the database without connect to internal SQL> CONNECT scott/oracle AS SYSDBA.4 Session and User Licensing If your site is licensed by concurrent usage. one can connect to the database through other user by following steps. b. c. This is called database authentication.1 Password File Authentication Instead of connecting to sys.5 User Authentication Oracle provides several means for users to be authenticated before they are allowed to create a database session. This is called external authentication.0 Page 39/135 Date: 29.R030 – Oracle Database Notes Version 1.5. you can track and limit the number of sessions concurrently connected to a database. (or) SQL> GRANT SYSOPER to scott. Create the password file using the ORAPWD utility $ cd $ORACLE_HOME/dbs $ orapwd file=<filename> password=<password> entries=<max_users> Example: $ orapwd file=orapwDEMO password=oracle entries=3 2. you can limit the number of named users created in a database. Grant sysdba or sysoper to users SQL> connect / as SYSDBA SQL> GRANT SYSDBA TO scott. To set the user limit: SQL> ALTER SYSTEM SET LICENSE_MAX_USERS = 30. 4. you control the licensing facilities. • You can define users such that the database performs both identification and authentication of users. If your site is licensed by named users.2007 13.08. and must enable the facilities and set the appropriate limits by setting these initialization parameters: • LICENSE_MAX_SESSIONS • LICENSE_SESSION_WARNING • LICENSE_MAX_USERS a. 1. In either case.

Listing all tablespace quotas: SQL> SELECT username.6 Viewing Information about Database Users and Profiles • DBA_USERS • ALL_USERS • USER_USERS • DBA_TS_QUOTAS • USER_TS_QUOTAS • USER_PASSWORD_LIMITS • USER_RESOURCE_LIMITS • DBA_PROFILES • RESOURCE_COST • V$SESSION • V$SESSTAT • V$STATNAME Examples: SQL> CREATE PROFILE prof_clerk1 LIMIT SESSIONS_PER_USER 1 IDLE_TIME 30 CONNECT_TIME 600.5. profile FROM DBA_USERS. bytes. maxbytes. a. created. tablespace_name. Create a user exactly as OS account (Example: devadm is an OS account) SQL> CREATE USER devadm IDENTIFIED EXTERNALLY. SQL> CREATE USER user_jone IDENTIFIED BY jone DEFAULT TABLESPACE user_data QUOTA UNLIMITED ON user_data. Connect to the database via “sqlplus” as follows: $ sqlplus / 13.R030 – Oracle Database Notes Version 1.1.1 Connecting to the database directly through OS login account 1. Include OS_AUTHENT_PREFIX=" " parameter in init<sid>. Grant privileges to devadm SQL> GRANT DBA TO devadm. account_status. 3. default_tablespace.08. temporary_tablespace. And restart the database in order to read the initialization parameter file.ora parameter file. . SQL> CREATE USER user_lee IDENTIFIED BY lee DEFAULT TABLESPACE user_data TEMPORARY TABLESPACE temp_data QUOTA 50M ON user_data PROFILE prof_clerk1. b. Listing all users and associated information: SQL> SELECT username. SQL> CREATE USER user_mary IDENTIFIED BY mary.2007 13. 2. blocks FROM DBA_TS_QUOTAS. 4.0 Page 40/135 Date: 29.

the exact number is indicated by the MAX_BYTES columns. Viewing memory use for each user session: SQL> SELECT username. value || ‘BYTES’ “Current UGA Memory” FROM V$SESSION sess.R030 – Oracle Database Notes Version 1. V$STATNAME name WHERE sess.SID AND Stat. sessions_highwater s_high. .SID=stat. d.2007 c. sessions_current s_current.STATISTIC# AND name.STATISTIC# = name. Listing all profiles and assigned limits: SQL> SELECT * FROM DBA_PROFILES ORDER BY profile.08.0 Page 41/135 Date: 29. V$SESSTAT stat. Unlimited quotas are indicated by “-1”. users_max FROM V$LICENSE. To see the current licensing limits: SQL> SELECT sessions_max s_max.NAME = ‘session uga memory’. sessions_warning s_warning. Note: When specific quotas are assigned. e.

finance. the right to create Tablespace is a system privilege. The following statement grants ‘system privileges’ to user Tom and to the role finance. Because system privilege are powerful they should be granted to trusted users with discretion. 14.1. Views.2 Object Privileges An object privilege is permission to perform an action on a specific object. SQL> GRANT CREATE USER.2.Tables.2. finance. The user must have the admin option for a system privilege being revoked.Tables • Insert .08.1 Granting system privileges System privileges can be granted to users and roles using the GRANT command. Views . SQL> GRANT CREATE SESSION TO Tom. 14. Views • Reference . Following are the available object privileges and their associated objects: • Alter .2.2 Categories of privileges • System privileges • Object privileges System privileges enable the user to perform an action on a type of object. Sequences • Update .2.Tables. such as a table.Tables • Select . ALTER TABLE TO Tom.Tables. whereas object privileges give the user permission to perform the action on a specific object.Tables.2007 14 MANAGING USER PRIVILEGES AND ROLES 14. The following are few examples of privileges: • The right to access the database • The right to Select data from another user’s tables • The right to execute another user’s stored procedures • The right to create new users 14. For example.1. Views • Execute . Sequences • Delete .2 Revoking system privileges System privileges can be revoked using REVOKE command.0 Page 42/135 Date: 29. Note: System privileges cannot be granted along with object privileges and roles in the same grant command.Tables. 14. SQL> REVOKE CREATE TABLE FROM Robert.Procedures • Index . 14. Some database objects don’t have an associated object privilege. package or view.R030 – Oracle Database Notes Version 1.1 System Privileges A system privilege is the right or permission to execute a particular database action on a particular type of object.1 Identifying User Privileges A privilege is a permission to execute an action or to access another user’s object.

R030 – Oracle Database Notes Version 1. backup_any_table. 2.1 System defined roles Oracle provides five predefined roles with the Oracle Server. sys. 14. When a role is crated it has no privileges associated with it. To grant object privilege: You must own the object specified or have been granted the object privileges with the grant option. Revoking the object privileges: Object privileges can be revoked using the REVOKE command. The following command creates the role named clerk: SQL> CREATE ROLE clerk IDENTIFIED BY demo.2007 1. Altering roles You can alter roles using the ALTER ROLE command: SQL> ALTER ROLE clerk IDENTIFIED BY <password>. create table. Roles have a certain set of properties that promote an easier management of database privileges. The GRANT command is used to assign privileges and roles to the new role. create procedure. Dropping.3. IMP_FULL_DATAASE Become user. This option enables users to do the following: • Grant or revoke the role to or from any user or role in the database • Grant the role with admin option to other users and roles • Alter or drop the role • The creator of a role is automatically granted the role with admin option. create sequence. SQL> GRANT INSERT. SQL> REVOKE UPDATE ON temp FROM Tom. The properties are as follows: • Simplistic privilege management • Individual dynamic privilege management • Application specific security 14. Roles are created to manage the privileges for a database or to manage the privileges for a user group. DBA All system privilege with admin option EXP_FULL_DATABASE Select any table. delete and update on the tables sync.3 Managing User Roles Roles are named groups of related privileges that are granted to individual users and other roles.2 Creating. A system role can be granted with the admin option. 2.3. The following is a list of the Oracle predefined roles and their granted privileges: CONNECT Create session RESOURCE Create cluster. insert. create trigger. Roles are not contained in the schema of the user. UPDATE ON temp TO Tom. create type etc. Creating a role The name you provide for the role must be unique among the user names and roles in the database. write down DELETE_CATALOG_ROLE Delete privileges on all dictionary packages for this role.0 Page 43/135 Date: 29.08. one must have the CREATE ROLE system privilege. Altering. EXECUTE_CATALOG_ROLE Execute privileges on all catalog views and views for this role.incvid. SELECT_CATALOG_ROLE Select privilege on all catalog tables and views for this role. To create a role. 14. . You cannot grant and revoke privileges and roles to these predefined roles just as you can to any role you define. Granting and Revoking Roles 1.incexp.incfil and sys. You must grant privileges or other roles to a new role.

14.3.3.sql). Public represents all users of the system. Note: Prior to using the PASSWORD_VERIFY_FUNCTION. . 14.3. To create a user with the same password as the username with the Prof: SQL> CREATE USER Scott IDENTIFIED BY scott PROFILE Prof. 4. Use the SQL GRANT command or the grant system privilege.0 Page 44/135 Date: 29. Password_parameter IN VARCHAR(30). SQL> GRANT manager TO user_01 WITH ADMIN OPTION.R030 – Oracle Database Notes Version 1. which sets the default profile parameters. You can not selective revoke the admin option of a role. and to public. ORA-28003: Password verification for the specified password failed ORA-20001: Password same as user 3. To lock a user’s account: SQL> ALTER USER scott ACCOUNT LOCK. 2. The format of the PL/SQL is: routine_name ( userid_parameter IN VARCHAR(30). Granting roles Roles can be granted to users. The next statement grants role manager the user user_01 with the admin option. to other roles.2007 3. Revoking roles Roles can be revoked using the REVOKE command: SQL> REVOKE clerk FROM tom. Dropping roles To drop a role from a database. use the DROP ROLE command: SQL> DROP ROLE clerk.08. you must revoke the role and then again grant the role without the admin option. 5. SQL> CREATE PROFILE prof LIMIT FAILED_LOGIN_ATTEMPTS 5 PASSWORD_LIFE_TIME 60 PASSWORD_REUSE_MAX 60 PASSWORD_REUSE_TIME UNLIMITED PASSWORD_VERIFY_FUNCTION verify_function PASSWORD_LOCK_TIME 1 PASSWORD_GRACE_TIME 10. ORA-28007: The password can not be reused 4. To change the user’s password to scott again and returns and error SQL> ALTER USER scott IDENTIFIED BY scott. you need to create the function.3 Creating a Profile Examples: The following statement creates the profile prof.1 Password Complexity Verification 1. To remove the admin option. Oracle password complexity verification routine can be specified using a PL/SQL script (utlpwdmg. Old_password_parameter IN VARCHAR(30)).

account_status. To list roles of the database: SQL> SELECT * FROM dba_roles. expiry_date FROM dba_users WHERE username = ‘SCOTT’. To check the account status: SQL> SELECT username. 16. admin_option FROM role_role_privs WHERE role = ‘SYSTEM_ADMIN’. 10. To check a user’s account status: SQL> SELECT username.0 Page 45/135 Date: 29. grantable FROM dba_tab_privs WHERE grantee = ‘jward’. user_id. To expire a user’s password: SQL> ALTER USER scott PASSWORD EXPIRE.R030 – Oracle Database Notes Version 1. To list information about the privilege domains of roles: SQL> SELECT granted_role. 11. 6. lock_data FROM dba_users WHERE username=’SCOTT’. account_status. 13. user_id.2007 5. column_name. privilege FROM dba_col_privs. account_status. To list all the column specific privileges that have been granted: SQL> SELECT grantee. both from explicit privilege grants and from enabled roles: SQL> SELECT * FROM session_privs. To list all role grants SQL> SELECT * FROM DBA_ROLE_PRIVS.08. To list all system privileges currently available in the issuer’s Security domain. 8. To unlock a user’s account: SQL> ALTER USER scott ACCOUNT UNLOCK. 7. expiry_date FROM DBA_USERS WHERE username=’SCOTT’. 14. 12. To list object privileges granted to a user SQL> SELECT table_name. 15. privilege. To check the user account status for the lock mode: SQL> SELECT username. user_id. To list all system privilege grants SQL> SELECT * FROM DBA_SYS_PRIVS. 9. table_name. .

privilege FROM dba_role_privs a. To check the granted SYSTEM PRIVILEGES to user TOM SQL> SELECT * FROM dba_sys_privs WHERE grantee = ‘TOM’.grantee and a.grantee.granted_role = b.0 Page 46/135 Date: 29. To check the granted ROLES and their PRIVILEGES to TOM user: SQL> SELECT a.4 • • • • • • • • • • • • • • • • • • • • Listing Privilege and Role Information ALL_COLS_PRIVS ALL_TABS_PRIVS ALL_TAB_PRIVS_MADE ALL_TAB_PRIVS_RECD DBA_ROLES USER_ROLES_PRIVS USER_SYS_PRIVS COLUMN_PRIVILIGES ROLE_ROLE_PRIVS SESSION_PRIVS USER_COL_PRIVS USER_TAB_PRIVS USER_TAB_PRIVS_MADE USER_TAB_PRIVS_RECD DBA_COL_PRIVS DBA_ROLE_PRIVS DBA_SYS_PRIVS DBA_TAB_PRIVS ROLE_SYS_PRIVS SESSION_ROLES . 18.08.3. dba_sys_privs b WHERE a. 14.granted_role.grantee = ‘TOM’. b. a.2007 17.R030 – Oracle Database Notes Version 1.

ORA AUDIT_TRAIL = [TRUE or DB | OS | FALSE or NONE] AUDIT_FILE_DEST = /disk1/oradata/DEMO/audit Audit trail can be set to three parameters: • TRUE or DB Stores the audit information in the database only • OS Stores the audit information in physical files • FALSE or NONE Auditing is disabled AUDIT_TRAIL enables or disables the writing of rows to the audit trail. 15. privilege and object auditing in three areas: • Successful and unsuccessful executions of the audited SQL statement • By SESSION and by ACCESS auditing • For specific users or for all users in the database (statement and privilege auditing only).2007 15 AUDITING 15. • Protect the audit trail: when auditing for suspicious database activity. Auditing can be done on all types of commands. To help you view meaningful auditing information in this table. then specifically: When starting to audit for suspicious database activity.Oracle allows you to focus statement. • Archive audit records and purge audit trail: Once you have collected the required information. protect the audit trail so that audit information can not be added.2 Initialization Parameters for Auditing In order to invoke auditing you have to set these parameters in INIT. You have to run cataudit. When your auditing purpose is to monitor for suspicious database activity.sql (automatically run when you run catalog. consider the following guidelines: • Audit generally.R030 – Oracle Database Notes Version 1. consider the following guidelines: • Audit pertinent actions: To avoid cluttering meaningful information with useless audit records and reduce the amount of audit trail administration.sql) as sys to create audit trail views.AUD$ table). audit options must be set more generally at first.1 Creating and Deleting Database Trail Views The database audit trail (SYS. only audit the targeted database activities. and FALSE is equivalent to NONE. The values TRUE and FALSE are also supported for backward compatibility TRUE is equivalent to DB. Audited records are written if the value is NONE or if the parameter is not present. Therefore. The OS option enables system wide auditing and causes audited records to be written to the operating system’s audit trail (the SYS.AUD$) is a single table in each Oracle’s Data Dictionary. 15. 15. archive the audit records of interest and purge audit trail of this information. .2. it is common that not much information is available to target specific users or schema objects.0 Page 47/135 Date: 29. the general audit options should be turned off and more specific audit options enabled. When auditing a normal database activity.3 Types of Auditing • Privileges level of auditing • Object level of auditing • Statement level of auditing Focusing Statement. Once preliminary audit information is recorded and analyzed. several predefined views are provided. changed or deleted without being audited.08.1 Introduction Auditing is done to check regular and suspicious activity on the database. Privilege and Object Auditing: .

Using either form of the AUDIT command. To audit sessions of STEEVE and LORI SQL> AUDIT CREATE SESSION BY steeve. unsuccessful attempts to execute or both. SQL> SELECT * FROM dba_priv_audit_opts If any of the users who are under auditing has performed the audited operation then he can be queried from DBA_AUDIT_TRAIL: SQL> SELECT username. SQL> AUDIT SELECT. 3. 15. 15. you can include: • The WHENEVER SUCCESSFUL option. BY SESSION inserts only one audit record in the audit trail. lori. To audit insert by all only when they are successful SQL> AUDIT INSERT ON scott. returncode FROM dba_audit_trail. privilege.R030 – Oracle Database Notes Version 1. to audit both successful and unsuccessful executions of the audited statement. To audit create tables by Scott: SQL> AUDIT CREATE TABLE BY scott. BY SESSION For any type of audit. to audit only unsuccessful executions of the audited statement • Neither of the previous option.1 Auditing Successful and Unsuccessful Statement Execution For a statement.3.4 Privilege level of AUDITING Monitoring on suspicious activities done at the system privileges granted to any user. per user and schema object. 15. To see the specifications that were there we need to query DBA_PRIV_AUDIT_OPTS.3. action_name. 2. Auditing on select by ALL SQL> AUDIT SELECT ON emp.emp BY ACCESS.2007 15.emp WHENEVER SUCCESSFUL. . Object auditing audits the operations permitted by schema object privileges. DELETE ON scott. 1.0 Page 48/135 Date: 29. 1.2 Auditing BY SESSION versus BY ACCESS Most auditing options can be set to indicate how audit records should be generated if the audited statements is issued multiple times in a single user session. 2.08. • The WHENEVER NOT SUCCESSFUL option. To audit select and delete only whenever any user access the object.5 Object Level Auditing Object auditing is the selective auditing of specific DML statements. BY ACCESS Setting audit BY ACCESS inserts one audit record into the audit trail for each execution of an auditable operation. during the session that includes the audited action. Example: the single audit trail contains 4 records for four selected statements if the audit on select. to audit only successful executions of the audited statement. such as SELECT or DELETE statements on a given table. or object. auditing oracle allows the selected auditing of successful executions of statements.

we need to query DBA_STMT_AUDIT_OPTS SQL> SELECT * FROM dba_stmt_audit_opts. action_name. regarding a particular type of database structure or schema object. Auditing on all types of DML statements by all users SQL> AUDIT INSERT. To see the specifications that were there. but not a specifically named structure or schema object (for example.0 Page 49/135 Date: 29.emp To see the specifications that were there. To audit on an statement which has table key word in it SQL> AUDIT TABLE BY scott. 3. regardless of the table or view). audit select table audits all select from TABLE/VIEW statements. To audit at statement by all users when ever not successful SQL> AUDIT SELECT TABLE WHENEVER NOT SUCCESSFUL.R030 – Oracle Database Notes Version 1. SQL> SELECT username. If any of the users who are under auditing has performed the audited operation then he can be queried from DBA_AUDIT_TRAIL. 15. returncode FROM dba_audit_trail. which work with statement level of auditing: 1.6 Statement Auditing Statement auditing is the selective auditing of related groups of statements that fall into two categories: • DDL statements. To audit all users by session SQL> AUDIT SESSION. regarding a particular type of database structure or schema object. 2. To audit Scott by access SQL: AUDIT VIEW BY scott BY ACCESS. . action_name. then he can be queried from DBA_AUDIT_TRAIL SQL> SELECT username. returncode FROM dba_audit_trail. audit table audits all create and drop table statements) • DML statements. Queries.08. UPDATE. we need to query DBA_OBJ_AUDIT_OPTS SQL> SELECT * FROM dba_obj_audit_opts WHERE object_name=’EMP’. If any users who are under auditing has performed the audited operation.2007 4. but not a specifically named structure or schema object (for example. 4. DELETE ON scott.

SQL> DELETE sys. To disable audit: SQL> NOAUDIT.aud$. To audit all unsuccessful select. f. action_name. e. INSERT TABLE. DELETE ON scott. SQL> SELECT username.0 Page 50/135 Date: 29. 15.emp. INSERT ANY TABLE. c. logoff_time. EXECUTE ANY PROCEDURE BY ACCESS WHENEVER NOT SUCCESSFUL. DBA_AUDIT_STATEMENT • USER_AUDIT_OBJECT. DELETE ANY TABLE. DBA_AUDIT_SESSION • USER_TAB_AUDIT_OPTS . by access: SQL> AUDIT SELECT ANY TABLE. Delete on EMP table of SCOTT: SQL> AUDIT INSERT. UPDATE. d.7 Data Dictionary Views to Query • STMT_AUDIT_OPTION_MAP • AUDIT_ACTIONS • ALL_DEF_AUDIT_OPTS • DBA_STMT_AUDIT_OPTS • USER_OBJ_AUDIT_OPTS. To view the information of auditing you have to query: SQL> SELECT * FROM all_def_audit_opts. and delete statements on all tables and unsuccessful uses of the execute any procedure system privilege. Update. obj_name. SQL> SELECT username.08. DELETE TABLE. by all database users. ses_actions FRO sys. To audit Insert.2007 Exercises: a. DELETE TABLE: SQL> NOAUDIT INSERT TABLE. DBA_AUDIT_OBJECT • DBA_AUDIT_EXISTS • USER_AUDIT_SESSIONS. b. insert. To disable audit for a session: SQL> NOAUDIT SESSION. DBA_OBJ_AUDIT_OPTS • USER_AUDIT_TRAIL. SELECT TABLE. logoff_dlock FROM dba_audit_sessions. To disable SELECT TABLE. logoff_pread. logoff_lread.R030 – Oracle Database Notes Version 1. logoff_lwrite. DBA_AUDIT_TRAIL • USER_AUDIT_SESSION.dba_audit_object.

168.1 Introduction ORACLE NET facilitates the sharing of data between databases.0 Page 51/135 Date: 29. 16.ora If you are connected to a database DEMO on a machine named ‘LOCAL_HOST’ and would like to get the information from ORCL database on a machine named ‘REMOTE_HOST’ having the user SYSTEM/MANAGER.at machine remote host (server side machine) $ vi listener.2. Database links are used to access schema objects at remote database from the local database SQL> CREATE DATABASE LINK <linkname> CONNECT TO <username> IDENTIFIED BY <password> USING ‘<aliasname>’.ad the machine local host (client side machine) $ vi tnsnames.0.0) ) ) :wq /*save the file and start the listener.15) (PORT = 1521)) ) ) ) SID_LIST_LISTENER = (SID_LIST = (SID_DESC = (SID_NAME = ORCL) (ORACLE_HOME = /oraeng/app/oracle/product/10. SQL> CONNECT scott/tiger. .0.3 Database Links 1.2 Configuring listener. SQL> CREATE DATABASE LINK lnk1 CONNECT TO system IDENTIFIED BY manager USING ‘myalias’.08.ora MYALIAS = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL=TCP) (HOST = 192.*/ $ lsnrctl start listener /* issue the command to start the listener */ $ cd $ORACLE_HOME/network/admin #-.R030 – Oracle Database Notes Version 1. even if those databases do not reside on the same server. Each database server in the distributed database environment cooperates to maintain the consistency of the global database.2007 16 MANAGING ORACLE NETWORKING USER “NET MANAGER” 16.ora and tnsnames. To create database link at the local database which connects to the remote database user.168.ora LISTENER = (DESCRIPTION_LIST = (DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL=IPC) (KEY=ORCL) (ADDRESS = (PROTOCOL=TCP) (HOST=192. then steps to be taken for establishing a connection through SQL*NET are as follows: $ cd $ORACLE_HOME/network/admin #-.15) (PORT = 1521)) ) (CONNECT_DATA = (SERVICE_NAME = ORCL) ) ) $ sqlplus system/manager@myalias /* at local host */ 16. issue: SQL> GRANT CREATE DATABASE LINK TO scott. but on different servers running different operating systems and communications protocols.

DB_DOMAIN”.08. Database Links do not support DDL (CREATE. where the domain_name for the machine is always unique. and there are two or more databases with the same name. ALTER. 16. etc) operations.R030 – Oracle Database Notes Version 1. DB_DOMAIN”. To drop a database link issue the command: SQL> DROP DATABASE LINK <link_name>.com GLOBAL_NAMES = TRUE Start the database and rename the global_name for the database by issuing the following statement: SQL> ALTER DATABASE RENAME global_name TO orcl. and DELETE using database links. 3.mydot. then it becomes difficult to address each of the databases differently. Oracle offers a solution to this problem. DROP. Also Oracle imposes you to create database links pointing to remote databases in the similar pattern “DB_NAME. .ora) to enable GLOBAL NAMES: DB_NAME = ORCL DB_DOMAIN = mydot.0 Page 52/135 Date: 29. You can use DML operations such as INSERT. Gives the Table information of a user system SQL> SELECT * FROM tab@lnk1. Set the following parameters in the initialization file (init<ORACLE_SID>.com. UPDATE.4 Global Names If database participates in a global network with more number of databases. The Global Name for a database in Oracle follows the pattern “DB_NAME.2007 2. by enabling the GLOBAL NAMING concept.

SQL> DROP MATERIALIZED VIEW snap1. You need CREATE MATERIALZED VIEW. usually on one or more tables. If you create a MATERIALZED VIEW with refresh fast option. on which I want to create the MATERIALIZED VIEW then. COMPLETE Entire data is regenerated every time the MATERIALIZED VIEW is refreshed. SQL> CREATE MATERIALIZED VIEW LOG ON <table_name>. Example. send the master database only those rows that have changed for the MATERIALIZED VIEW. To create a MATERIALZED VIEW. If LNK1 has order table. CREATE TABLE. . These objects should not be altered. When MATERIALIZED VIEWs are used. SQL> ALTER MATERIALIZED VIEW snap1 REFRESH FAST. then you need to create a MATERIALIZED VIEW log on the table at the remote site (i. SQL> CREATE MATERIALIZED VIEW snap1 REFRESH COMPLETE WITH ROWID START WITH SYSDATE NEXT SYSDATE + 1 / (24*60*60) AS SELECT * FROM _ HYPERLINK "mailto:jones. When a MATERIALIZED VIEW is created. If you want to make your snap1 to refresh fast then. join conditions or set operations. CREATE VIEW and CREATE INDEX privileges. the steps are as follows: Syntax: SQL> CREATE MATERIALIZED VIEW <materialized view name> REFRESH [COMPLETE | FAST] WITH [PRIMARY KEY | ROWID] START WITH SYSDATE NEXT SYSDATE+1(24*60*60) # (for every second) AS SELECT * FROM <username.5 Materialized Views MATERIALIZED VIEWs can be thought of as a table that holds the results of a query. If you want to drop the MATERIALIZED VIEW then.08. it is referred to as a Complex MATERIALIZED VIEW.. FAST Only the rows that are modified are regenerated every time the MATERIALIZED VIEW is refreshed using the MATERIALIZED VIEW log.order@link1" __jones. Oracle uses MATERIALIZED VIEW log to track the rows that have been updated on the master table. MATERIALIZED VIEW log is a table in the master database that is associated with the master table.R030 – Oracle Database Notes Version 1. available for some type of MATERIALIZED VIEWs. Simple and Complex MATERIALIZED VIEWs: Simple MATERIALIZED VIEW’s queries should not have a GROUP BY.e.table_name@linkname>. called master tables. If a MATERIALIZED VIEW’s query has any of these clauses or operations. a refresh interval is established to schedule refreshes of replicated data. several internal objects are created in schema of the MATERIALZED VIEW.order@link1_. The queries that form the basis of MATERIALIZED VIEWs are grouped into two categories. in a remote database.2007 16.0 Page 53/135 Date: 29. Change information is stored in the MATERIALIZED VIEW log. Local updated can be prevented and transaction based refreshes can be used. CONNECT BY clause. a sub-query. at the server side).

if all participants cannot prepare. All transactions are automatically resolved by RECO and automatically removed from the pending transaction. the initiating node asks all nodes to commit the transaction.0 Page 54/135 Date: 29.2007 However without setting the following parameters in the init<ORACLE_SID>. which starts the necessary background processes (snp0). The Option parameter is to indicated whether MATERIALIZED VIEW has been created with COMPLETE or FAST option. even if there is failure). the MATERIALIZED VIEWs will not get refreshed automatically. it asks to rollback the transaction.08. Commit Phase If all participants respond to the initiating node that they are prepared. If there is failure of transaction due to any reason. the status of transaction is recorded in commit point site. thereby maintaining the integrity.ora. Note: The MATERIALIZED VIEW can be manually refreshed using the DBMS package: SQL> EXECUTE DBMS_MVIEW. ‘refresh_option’). JOB_QUE_PROCESSES=3 Two Phase Commit Oracle automatically controls and monitors the commit or rollback of a distributed transaction and maintains the integrity of the global database using a mechanism called two phase commit. It has two phases: Prepare phase The initiating node asks all the participants to prepare (either to commit or rollback. Commit point decides the commit point strength at the beginning. . This mechanism guarantees that the nodes participating in a distributed transaction either commit or rollback the transaction.R030 – Oracle Database Notes Version 1.REFRESH (‘materialized view name’.

17. These files can be later used to write back into Oracle database via Import. which will be dealt in the next chapter.0 Page 55/135 Date: 29. Import is used to retrieve Oracle database data found in export format files into an Oracle database.1 Types of Backups There are two types of backups: • Physical • Logical Logical backup can be done with export utility where as physical backup is again divided into COLD backup and HOT backup.1 Export and Import Export is an Oracle utility used to store ORACLE database data in export format (.R030 – Oracle Database Notes Version 1.dmp) files for later retrieval. There are three levels of export: • Table level • Schema level • Database level • Tablespace level • Transportable tablespaces across platforms . from Oracle database and store them in Oracle binary format.2007 17 MANAGING EXPORTS AND IMPORTS 17. 17.08.1.2 Main Tasks of Export and Import • Data archival • Upgrading to new releases • Backing up Oracle database • Platform Migration • Database Re-organization • Moving objects from schema to another Export’s basic function is to extract the object definition and table data.

Used to get the SCN closest to the specified time 1.Export indexes (Default “Y”) .dmp) . If you want to export your database.List of tablespaces to transport . If you want to export full database $ exp system/manager FILE=exp.R030 – Oracle Database Notes Version 1.Select clause used to export a subset of a table .List of owner names . If you want to export a table emp which is owned by steeve $ exp steeve/steeve file=steeve.SCN used to set session snapshot back to time .0 Page 56/135 Date: 29.dmp log=scott.Import data to one extent (Default “Y”) .Logfile of screen output .dmp log=inc.Text string used to identify resumable statement .Export transportable tablespace metadata (N) .log owner=scott 3.Entire file (Default “N”) .dmp log=steeve.Suspend when a space related error is encountered (N) .log full=y 2.Export triggers (Y) .Export data rows (Default “Y”) .2007 Syntax: $ exp <username/password> parameters.Incremental export type (INCREMENTAL. Export parameters: BUFFER FILE COMPRESS GRANTS INDEXES ROWS CONSTRAINTS LOG FULL OWNER TABLES INCTYPE PARFILE FEEDBACK TRANSPORT_TABLESPACE TABLESPACES VOLSIZE FILESIZE QUERY TRIGGERS RESUMABLE RESUMABLE_NAME RESUMABLE_TIMEOUT FLASHBACK_SCN FLASHBACK_TIME Examples: .dmp log=exp.Number of bytes tow rite to each tape volume . CUMULATIVE & COMPLETE) .Output file (default expdat.08.List of table names .Wait time for RESUMABLE .Display progress every x rows (default ‘0’) . If you want to export Scott’s object $ exp system/manager FILE=scott.Export constraints (Default “Y”) .Size of a data buffer .log tables=emp 4.Maximum size of each dump file .Export grants (Default “Y”) .log inctype=incremental .Parameter file . with only those tables that are changed after the previous complete backup: $ exp system/manager file=inc.

Then you import the data from: 1. 17.0 Page 57/135 Date: 29. Complete exports Establishes a base for incremental and cumulative exports.dmp log=emp. An incremental export (I) every night Your export schedule is as follows: Day 1 X S 2 I M 3 I T 4 I W 5 I T 6 I F 7 I S 8 C S 9 I M 10 I T 11 I W 12 I T 13 I F 14 I S 15 CI S 16 I M 17 I T 18 I W To restore through day 18.dmp log=scott1. 7.3 Incremental. $ exp scott/tiger file=scott1. use Oracle 8i’s new export option “QUERY” $ exp scott/tiger file=emp.log tables=emp query=\’where deptno=10\’. It exports only partition M from table emp $ exp scott/tiger tables=emp:m rows=y 17.log tables=emp.e. A cumulative export includes all the incremental exports done from last cumulative or complete into a single cumulative export file. If you want to export only a portion of a table’s data. If you want to export tables emp. A cumulative export (C) every Sunday 3. An incremental export exports the table definition and all it’s data not just changed rows (i. you do the following tasks: 1.R030 – Oracle Database Notes Version 1. cumulative or complete export. A complete export (X) of every three weeks 2.dmp log=scott1. The cumulated export taken on day 15 4.2007 5.dept constraints=n $ exp scott/tiger parfile=demo.par 6. first you import the system information from the incremental export taken on day 18. entire table). If you want to export partitions. Cumulative and Complete Exports Incremental exports Backs up only tables that have changed since the last incremental. Three incremental exports taken on days 16. dept which are own by scott. Assume that as manager of a data center. 18 . If emp table is having two partitions M and Z. with no constraints.par – creating an export parameter file file=scott1. Cumulative exports Backs up tables that have changed since the last cumulative or complete export.log tables=emp.08. The cumulative export taken on day 8 3. The complete export taken on day 1 2.dept constraints=n or $ cat demo. It is also similar to full database export except it updates the tables that track incremental and cumulative exports.

08.log ignore=y 5.dmp tables=(e:qc.dmp tables=emp.0 Page 58/135 Date: 29.R030 – Oracle Database Notes Version 1. Migrating data across partitions and tables $ imp scott/tiger file=export. RESTORE) Parameter file Lists file content (Default “N”) Ignore create errors (Default “N”) Overwrite tablespace datafile (Default “N”) Write table/index into specified file From which user To which user you want to import Commit array insert (Default “N”) Whether or not import recovers one or more tablespaces Whether or not import skips building indexes that were set to the index unusable state TRANSPORT_TABLESPACE Import transportable tablespace metadata (N) TABLESPACES List of tablespaces to be transported into the database DATAFILES Datafiles to be transported into the database TTS_OWNERS Users that own data in the transportable tablespace set RESUMABLE Suspend when a space related error is encountered (N) RESUMABLE_NAME Text string used to identify resumable statement RESUMABLE_TIMEOUT Wait time for RESUMABLE Examples: 1.dept fromuser=scott touser=steeve 4.dmp log=imp.dmp) Export grants (Default “Y”) Export indexes (Default “Y”) Export data rows (Default “Y”) Logfile of screen output Entire file (Default “N”) List of table names Incremental export type (SYSTEM. If you want to import only the data of emp and ignore errors $ imp system/manager file=steeve. If you want to import full database $ imp system/manager file=exp.dmp log=scott_imp.e:qd) ignore=y . If you want to import only emp and dept into steeve $ imp system/manager file=scott1.4 Import parameters BUFFER FILE GRANTS INDEXES ROWS LOG FULL TABLES INCTYPE PARFILE SHOW IGNORE DESTROY INDEXFILE FROMUSER TOUSER COMMIT POINT_IN_TIME_RECOVER SKIP_UNUSABLE_INDEXES Size of a data buffer Output file (default expdat.log fromuser=scott touser=john 2.2007 17. If you want to import all Scott’s object to john $ imp system/manager file=scott.dmp log=steeve_ign.log 3.

instead write the command in a file and execute as a SHELL program. the command will still run as a background process. 5. Always specify ‘FILE=<filename>’. it tries to write that data do Export File. 4. Moving Database objects from one database to another Moving Database objects from one User account to another User account When we are upgrading from Oracle version When migrating from one platform to another platform It is an alternative to the regular COLD or HOT Backup (Physical). One complete export X1 2. . Upon using the EXPORT file. The only way to get rid of so many extents is by • Taking a FULL database Export • Re-creating the database • Importing the FULL database By doing so. This will ensure that though there are problems with your terminal or modem. Three incremental exports I16. Whenever you are doing EXP or IMP don’t try to do at the prompt. try to Compress it. For database REORG: If the database has been growing for a while. Always specify ‘LOG=<logfile>’ parameter when you do an EXPORT. Always specify ‘BUFFER=2000000’ so that. Although we probably never see any problems with the data. These kinds of intricacies would be avoided by doing REORG at least every four (4) months. there could be little chance that Oracle gets some bad data because of Disk-Block corruption. all the segments will be created with INITIAL extent as big as the Table’s space (basically it adds all extents space and makes an INITIAL extent). 2. Cumulative and Complete export files To import the data you have the following export file: 1. Another importing that that REORG ensures is INTEGRITY of Oracle Data.DMP. that too not directly. it needs to manage too many extents (since the Segments keep on growing). I17 and i18 You should import in the following order: $ $ $ $ $ $ $ imp imp imp imp imp imp imp system/manager system/manager system/manager system/manager system/manager system/manager system/manager inctype=system full=y file=I18 inctype=restore full=y file=X1 inctype=restore full=y file=C8 inctype=restore full=y file=C15 inctype=restore full=y file=I16 inctype=restore full=y file=I17 inctype=restore full=y file=I18 We do logical Backups for: 1. to know what exactly happened when you are away from the machine.R030 – Oracle Database Notes Version 1. but using NOHUP or AT (UNIX commands). Always perform EXP by giving the complete syntax (command line) rather than the performing by INTERACTIVE method. otherwise Oracle starts writing to a default file called EXPDAT. 4.0 Page 59/135 Date: 29. by which you may overwrite an earlier version of EXP which might be one that is needed. 3. so that it won’t occupy much space. 5. Two cumulative exports C8 and C15 3. 17. 2. 3.5 Importing Incremental. It will also be helpful at the time of IMPORT so that we can compare the LOG files and make sure all tables are rightly being imported with all the rows.6 Points to remember before doing export or import 1.08. If the tape doesn’t work at least we can recover from the Logical Backup 6. which would hide in the dark until you try to Select the data from that Table. it overrides system default BUFFER parameter which is only 64K.2007 17. 6. which means whenever EXP writes 64K worth of data to MEMORY (not SGA).

There is a disadvantage in specifying ‘COMMIT=Y’ which is if the IMPORT fails midway (for any reason). we can go into the LOG file and by removing the Error messages. . CREATE INDEX … CONNECT STEVE. and if the database size is relatively larger.sql 9.dmp log=scott_DDL.08. 8.$s/CONNECT/ALTER SESSION SET CURRENT SCHEMA = SCOTT.dmp indexfile=cr8_indexes. This can be altered by issuing the following command: SQL> ALTER SESSION SET CURRENT_SCHEMA = SCOTT. 11. As we know.dmp log=expscott. EXP & IMP are the only way to get all the SCHEMA definitions. we discussed that INDEXES should be created after IMP.log $ imp scott/tiger file=expscott.sql (At this point we didn’t create any objects. then don’t create indexes as part of the IMP. In point 7. which won’t fill-up Rollback Segments.sql" since it has info like these: CONNECT SCOTT. Hence the entire file would have incomplete statements. Solution: In the above scenario it is best to just drop the last table and start the same command again. But we don’t have any SQL script to generate indexes.dmp log=expfull. 10. Issue these commands immediately one after the other without dropping any tables or deleting any data or objects. the last imported table might contain PARTIAL number of rows this would cause some more failures when this table acts as Master table for other tables. rather IMP with ‘INDEXES=N’ and try to create indexes manually after the IMP is done. that’s why we are logging as that user in-directly. except Oracle writes all the INDEXES information to this file) Now re-create the database and issue the following command: $ imp sys/sys full=y file=expfull_Mar08. So IMP process will generate all errors and will dump into LOG file./ This would be very helpful since we don’t really know all the passwords.2007 7.0 Page 60/135 Date: 29. this would fail because there is no password associated with the UserID.dmp log=impfull. If you have large tables and if the RBS are not big enough to store the entire table’s information. Once the IMP finishes. you use COMMIT=Y at the time of IMPORT whenever the BUFFER is full.log buffer=2000000 indexes=n commit=y Edit the "cr8_indexes. If you are doing an EXP specifying ‘FULL=Y’. You can get the SCHEMA definitions by giving the following command: $ exp scott/tiger file=expscott. This statements fails since we are trying to create all SCOTT’s objects once again which are already there.R030 – Oracle Database Notes Version 1. Please the code: $ exp sys/sys full=y file=expfull_Mar08. we can get the entire SCHEMA definition (undocumented).log buffer=2000000 $ imp sys/sys full=y file=expfull_Mar08. from SYS or SYSTEM as that user. This can be done via ‘vi’ editor :1.

b_exp_type FROM dba_exp_objects a. incremental.0 Page 61/135 Date: 29.2007 17. 3. object_type. To select Detailed info about INCTYPE Exports SQL> SELECT owner.exp_version AND Owner=’SCOTT’ ORDER BY 6.export_version. a.7 Selecting Detailed Info about INCTYPE Exports 1. dba_exp_files b WHERE a. object_name. .export_version = b.08.R030 – Oracle Database Notes Version 1. To observe the details about Logical BACKUP using INCTYPE in the database: SQL> SELECT * FROM dba_exp_version. cumulative. 2. To select info about exported files SQL> SELECT * FROM dba_exp_files ORDER BY 1.

dmp EXCLUDE=view. To perform a full database export $ expdp system/manager DIRECTORY=dpump_dir1 DUMPFILE=expfull. function JOB_NAME=exclude_job . Create a directory to store the dump files: SQL> CREATE DIRECTORY dpump_dir1 AS ‘/usr/apps/datafiles’. SQL> GRANT READ.dmp FULL=y LOGFILE=expfull.dmp SCHEMAS=scott JOB_NAME=scott_job 4. files generated by the original Export (exp) utility cannot be imported with the Data Pump Import (impdp) utility. 2. If you want to export Scott’s objects $ expdp system/manager DIRECTORY=dpump_dir1 DUMPFILE=expdat.1 Introduction The Data Pump facility runs on the server side. Dump files generated by the new Data Pump Export utility are not compatible with the dump files generated by the original Export utility.log JOB_NAME=full_job 3.dept 5. The available modes are as follows: • Full Export Mode • Schema Mode • Table Mode • Tablespace Mode • Transportable Tablespace Mode Examples: 1. To filter metadata info during export operation $ expdp system/manager DIRECTORY=dpump_dir1 DUMPFILE=hr_exclude.steve.2 Benefits of Data Pump Export and Import • The ability to restart Data Pump jobs • The ability to detach from and reattach to long running jobs without affecting the job itself. 18. package. based upon objects and object types.dmp TABLES=emp. • Support for filtering the metadata is exported and imported. If you want to export table emp owned by Scott $ expdp scott/tiger DIRECTORY=dpump_dir1 DUMPFILE=tables. WRITE ON DIRECTORY dpump_dir1 TO scott.3 Data Pump Export Modes The Data Pump Export utility is invoked using the expdp command. Oracle Data Pump technology enables very high-speed movement of data and metadata from one database to another.2007 18 ORACLE DATA PUMP 18. • Data archival • Upgrading to new releases • Backing up Oracle database • Moving between Tablespace Mode 18.R030 – Oracle Database Notes Version 1. Therefore.08.0 Page 62/135 Date: 29.

dept JOB_NAME=scott_job2 4. packages and functions from scott schema. To import only specific tables from scott schema $ impdp scott/tiger DIRECTORY=dpump_dir1 DUMPFILE=expfull.dmp TABLES=emp. the following command is issued $ impdp scott/tiger DIRECTORY=dpump_dir1 DUMPFILE=scott_exclude. The available modes are as follows: • Full import mode • Schema mode • Table mode • Tablespace mode • Transportable tablespace mode Examples: 1. $ expdp SYSTEM/password SCHEMAS=scott DIRECTORY=dpump_dir1 DUMPFILE=scott.08. The following Export and Import commands are executed to remap the scott’s schema into the Steve’s schema. PACKAGE.dmp FULL=y LOGFILE=dpump_dir2:full_imp.5 Transport of Tablespaces Across Different Platforms This functionality can be used to • Allow a database to be migrated from one platform to another • Provide an easier and more efficient means for content providers to publish structured data and distribute it to customers running Oracle Database on different platforms.dmp EXCLUDE=VIEW. To import all the objects owned by scott schema $ impdp system/manager SCHEMAS=scott DIRECTOY=dpump_dir1 LOGFILE=schemas.dmp REMAP_SCHEMA=scott:steve 5.dmp $ impdp SYSTEM/password DIRECTORY=dpump_dir1 DUMPFILE=scott. FUNCTION 18.dmp 3. To perform the full database import $ impdp system/manager DUMPFILE=dpump_dir1:expfull.R030 – Oracle Database Notes Version 1. Make the tablespace READ ONLY. Determine if the platforms use the same Endian format by querying the V$TRANSPORTABLE_PLATFORM SQL> SELECT * FROM V$TRANSPORTABLE_PLATFORM. using the appropriate parameter.log JOB_NAME=full_job1 2.log DUMPFILE=expdat. To exclude the metadata information like views. 2. SQL> ALTER TABLESPACE users READ ONLY. Steps for transporting tablespace from Unix to Windows: 1.4 Data Pump Import Modes Data Pump Import is a utility for loading and export dump file set into a target system.2007 18. The mode is specified on the command line. .0 Page 63/135 Date: 29. • Simplify the distribution of data from a data warehouse environment to data marts which are often running on smaller platforms.

Plug the tablespace into the target database. and worker process to perform the work and keep track of progress.6 Data Dictionary Views to Query • DBA_DATAPUMP_JOBS • USER_DATAPUMP_JOBS • DBA_DIRECTORIES . For every Data Pump Export job and Data Pump Import jobs. such as when the ATTACH parameter is used to attach to a job. SQL> ALTER TABLESPACE users READ WRITE. The job name becomes the name of the master table in the current user’s schema.1 Initiate a Job During Data Pump Export operations and Restarting the Jobs Data Pump uses a master table. logging to the terminal stops and the Export prompt is displayed. 1.R030 – Oracle Database Notes Version 1.2007 3. a master process is created.5. Use the operating system utility to copy the datafiles of USERS tablespace to the target server. The interactive interface. Export the tablespace.08. Export> CONTINUE_CLIENT. At OS prompt. a master process. The master process controls the entire job. To export the scott schema objects and assigning a job name for it. issue: $ expdp dumpfile=users_tts. 18. While the export is running. Enter the following command to reattach to the job you just stopped: $ expdp scott/tiger ATTACH=exp_job 4. From the OS command.dmp transport_datafiles=’c:\oracle\oradata\ORCL\users_01.dbf’ 6.dmp logfile=users_tts. The job name is used to identify the export job in subsequent actions. including communicating with clients. Issue the following command to stop the job Export> STOP_JOB=IMMEDIATE Are you sure you wish to stop this job (y/n) : y 3. After the job status is displayed.log directory=dump_dir1 transport_tablespaces=users 4. Make the new tablespaces read-write in the target database. you can issue the CONTINUE_CLIENT command to resume logging mode and restart the expfull job. $ expdp scott/tiger DIRECTORY=dpump_dir1 DUMPFILE=exp_job. issue: C:> impdp directory=dump_dir dumpfile=users_tts.0 Page 64/135 Date: 29.dmp JOB_NAME=exp_job NOLOGFILE=y 2. creating and controlling a pool of worker processes and performing logging operations. The master table is used to control the export job. 18. This will start the interactive command interface of the Data Pump Export. 5. press Ctrl+C.

3 Tuning Contention Contention may cause Processes to wait until resources are available.R030 – Oracle Database Notes Version 1.3. Oracle memory structures can have large impact non performance.1 Tuning memory allocation Appropriate allocation of memory resources is very essential. By tuning Oracle database.0 Page 65/135 Date: 29.3 Turing Process Steps 19.3. determining the cause of the problem and taking corrective action.2 Goals for Tuning Consider the performance issues when designing the system Tuning at Hardware level and at operating system level.2007 19 TUNING – ENHANCING THE PERFORMANCE OF DATABASE 19. 19.3. • SQL and PL/SQL shared areas • The data dictionary cache • The buffer cache 19. you can tailor its performance to best meet your needs. Identifying performance bottlenecks. • Rollback segments • Processes of the multi-threaded Server architecture • Redolog buffer latches .1 Introduction Tuning is studying the configuration of a system Everyone involved with the system has the same role in the tuning process.08.2 Tuning I/O Disk I/O tends to reduce the performance of many software applications • Distributing I/O to avoid disk contention • Creating extents large enough for your data 19. 19.

R030 – Oracle Database Notes Version 1.0

Page 66/135 Date: 29.08.2007

19.3.4 Memory Tuning 19.3.4.1 Tuning Buffer Cache Buffer cache is the cache structure in the SGA and holds copies in memory of the Most Recently Used Oracle data blocks. First find out the ration between ‘Misses’ and ‘Hits’ i.e., the ‘MISS RATION”. If the ratio is less than 85% then, increase the buffer allocated, using the parameter ‘db_cache_size=<size>.’ In INIT.ORA. The query to find the ratio is as follows:
SQL> SELECT 1-(P.VALUE/D.VALUE+C.VALUE)) “HIT RATIO” FROM V$SYSSTAT P, V$SYSSTAT C, V$SYSSTAT D WHERE P.NAME=’physical reads’ AND D.NAME=’db_block gets’ AND C.NAME=’consistent gets’;

In the above query: Physical reads Consistent gets DB Block gets The value of this column indicates the number of reads made to each database file Statistics reflects the number of accesses made to the block buffer to retrieve the data in a consistent mode Statistics reflects the number of blocks accessed via single block gets.

Note: One physical read can read multiple blocks by changing the following parameters: • DB_FILE_MULTIBLOCK_READ_COUNT = <The number of blocks to read> 19.3.4.2 Tuning Redolog Buffer Cache To tune the Redolog buffer one has to reduce the waiting for the latches. You have to find the ratio between Redolog space wait times and redo writes. If the ratio is more than 1% then we need to tune. The information of this can be obtained from V$LATCH and V$SYSSTAT. The query is as follows:
SQL> SELECT name, value FROM V$SYSSTAT WHERE name=’redo log space requests’;

The value should be nearer to 0. If not increase LOG_BUFFER by 5% until it reaches 0.
SQL> SELECT b.NAME, a.GETS, a.MISSES, a.IMMEDIATE_GETS, a.IMMEDIATE_MISSES FROM V$LATCH A, V$LATCHNAME B WHERE B.NAME IN (‘redo allocation, ‘redo copy’) AND A.LATCH#=B.LATCH#

If misses/gets > 1 and immediate_misses/ (immediate_gets + immediate_misses) > 1 you need to look into LOG_BUFFERS i.e., increase the parameter “log_buffers” in the init.ora In the above query: Gets Misses Immediate_misses Immediate_writes

This column shows the total no of requests for information on the corresponding item. This column shows the no of data requests resulting in cache misses This column shows the number of unsuccessful immediate request for each latch. This column shows the number of successful immediate request for each latch

R030 – Oracle Database Notes Version 1.0

Page 67/135 Date: 29.08.2007

19.3.4.3 Tuning Library cache It is present in data dictionary, which has shared SQL and PL/SQL area. This section tells you how to tune the library cache by: • Examining library cache activity • Reducing library cache misses • Speeding access to shared SQL and PL/SQL areas in the library cache The query is as follows:
SQL> SELECT SUM(pins), SUM(reloads) SUM(reloads)/SUM(pins) * SUM(reloads)*100 “MISS RATIO” FROM V$LIBRARYCACHE;

Pins Reloads

This column shows the number of times an item in the library cache was executed The column shows the number of library cache misses on execution steps

If the miss_ratio is less than 85%, you should reduce this library cache misses (by increasing the ‘shared_pool_size=<bytes>’ parameter in INIT.ORA. 19.3.5 Stripping Stripping is the practice of dividing a large table’s data into small portions and storing these portions in separate data files on separate disks. This permits multiple processes to access different portions of the table concurrently without disk contention. “STRIPPING” is particularly helpful in optimizing random access to tables with many rows. Stripping can either be done manually as below:
SQL> CREATE TABLESPACE test DATAFILE ‘/disk1/oradata/DEMO/u1.dbf’ size 5M, ‘/disk2/oradata/DEMO/u2.dbf’ size 5M, ‘/disk3/oradata/DEMO/u3.dbf’ size 5M STORAGE (MINEXTENTS 3); SQL> CREATE TABLE junk (a NUMBER) STORAGE (MINEXTENTS 3) TABLESPACE test;

Then insert few thousand rows into the table. While the insertion is going on observe the status of the files in V$FILESTAT;
SQL> SELECT file_id FROM dba_data_files; SQL> SELECT * from V$FILESTAT;

If you have more data files and if you have only one DBWR the performance may decrease, so you increase DBWRs.
SQL> SHUTDOWN $ vi init.ora #look for the following parameter DISK_ASYNCH_IO=FALSE DBWR_IO_SLAVES=3 :wq SQL> STARTUP $ ps ux|grep ora_ # observed that there are extra slave processes

R030 – Oracle Database Notes Version 1.0

Page 68/135 Date: 29.08.2007

19.3.6 Parallel Query Option Oracle will process the SQL statement by a single server process with the parallel query option, multiple processes can work together simultaneously to process a single SQL statement. This capability is called parallel query option. The Oracle server can process statement more quickly than if only a single server process processed it, query processing can be effectively split among many CPUs on a single system.
$vi init.ora PARALLEL_MIN_SERVERS=1 PARALLEL_MAX_SERVERS=10 PARALLEL_SERVER_IDLE_TIME=4 (default in minutes) :wq SQL> SHUTDOWN SQL> STARTUP SQL> CREATE TABLE junk (a NUMBER) PARALLEL 5; SQL> SELECT table_name, degree FROM USER_TABLES; SQL> Insert many rows SQL> SELECT * FROM junk;

From any other terminal using the OS command, you can see the ora_pxxx_DEMO processes:
$ ps ux|grep ora_

19.3.6.1 Data Dictionary Views to Query • V$PX_PROCESS • V$PX_SESSION • V$PX_PROCESS_SYSSTAT 19.3.7 Table Cache To cache a table, specify the cache clause either in CREATE TABLE or ALTER TABLE command. If a table is marked as a cached that table’s block will be considered as the most recently used blocks in the data block buffer cache. Even if they read via a full table scan, thus you can avoid having your small tables blocks frequently removed from the data block buffer cache. The example below shows the TEST table is marked as a cache table. The first time its blocks are read into the data block buffer cache, they will be marked as the most recently used blocks in the cache.
SQL> CREATE TABLE test (a NUMBER) CACHE; /* Table is created up-front with Cache option */ SQL> CREATE TABLE test (a NUMBER); /* An e.g. for later decision to implement Cache */ SQL> ALTER TABLE test CACHE;

To deactivate the cache status of the table use the NOCACHE clause:
SQL> ALTER TABLE test NOCACHE;

0 Page 69/135 Date: 29.4 Online Segment Shrinking The online SHRINK command is a feature for reclaiming fragmented free space below the high water mark in an Oracle Database segment. SPACE COMPACT. .R030 – Oracle Database Notes Version 1. Shrink a table and all its dependent segment SQL> SQL> SQL> SQL> ALTER ALTER ALTER ALTER TABLE TABLE TABLE TABLE emp emp emp emp ENABLE SHRINK SHRINK SHRINK ROW MOVEMENT. You use online segment shrink to reclaim Shrink operations can be performed only on segments in locally managed tablespaces with automatic segment space management (ASSM).2007 19. SPACE. SPACE CASCADE.08.

which automate memory management.2007 20 MEMORY MANAGEMENT 20. Continuing its quest to make the management of Oracle databases simple. . The contents of this view are cleared when the advisory is turned off by setting the DB_CACHE_ADVICE=OFF. and facilitates better integration with operating system resource managers. EST_PHYSICAL_READ_FACTOR FROM V$DB_CACHE_ADVICE. closely monitor system memory utilization to ensure its most optimal use. which has a significant impact on the overall performance of the Oracle database. The SGA configuration of a running instance can be altered by changing the values of the parameters governing sizes of the buffer cache (DB_CACHE_SIZE) and the shared pool (SHARED_POOL_SIZE). By allowing such change to be made online. This view can be used to determine if the current size of the buffer cache should be increased or decreased to ensure optimal performance for the present workload. ensures the most efficient utilization of available memory.08.1 Introduction Memory is a critical system resource. provide optimal out-of-box performance and allow dynamic reconfiguration. These predictions are published through a new view V$DB_CACHE_ADVISE. It also makes it possible to dynamically change the memory available to an Oracle instance resulting in either from changes in system hardware or changes to OS resource manager allocations. Database administrators can change the size of the buffer cache and the shared pool without having to restart the instance. BUFFERS_FOR_ESTIMATE. It can be turned by setting the parameter DB_CACHE_ADVICE=ON. therefore. This advisory relies on an internal simulation based on the current workload to predict the cache ‘miss’ rates for various sizes of the buffer cache raging from 10% to 200% of the current cache size.2 Dynamic System Global Area (SGA) Oracle 9i makes it simple to add to and remove memory from an instance. By providing a deterministic way to size the buffer cache. BLOCK_SIZE. the dynamic SGA feature helps administrators increase database availability.R030 – Oracle Database Notes Version 1.0 Page 70/135 Date: 29. Both these parameters have been made dynamic in Oracle 9i and their values can be modified using the ALTER SYSTEM command. The buffer cache advisory is turned off by default since there is a minor performance overhead associated with the data collection and cache simulation. Oracle 9i takes the guesswork out of database memory configuration thereby eliminating wastage caused by memory over-allocation.3 Buffer Cache Advisory Oracle 9i also include an advisory to help DBAs size the buffer cache optimally. 20. Oracle 9i includes a number of features. Oracle 9i’s enhanced memory management enables faster query execution. Changing the value of this parameter to READY stops further data collection but preserves the advisory results in the V$DB_CACHE_ADVICE VIEW. 20. Database administrators. SQL> SELECT NAME.

Using this approach. the Optimizer considers available access paths and factors in information based on the statistics in the data dictionary objects (tables.0 Page 71/135 Date: 29. This is an important step in the processing of any data manipulation language statement (select. There are two types of optimizers like: • Rule based (is obsolete) • Cost based Rule based Cost based Using this approach the Optimizer chooses an execution plan based on the access paths available and the ranks of these paths. To analyze the table EMP the following command can be used: SQL> ANALYZE TABLE emp COMPUTE STATISTICS. ALL_ROWS and FIRST_ROWS.R030 – Oracle Database Notes Version 1.08. update or delete) which is done by the Optimizer.2007 21 OPTIMIZATION 21.1 Introduction Optimization is the process of choosing the most efficient way to execute a SQL statement. insert. clusters or indexes) accessed by the statement to determine which execution plan is most efficient. They are: • Single row by rowed • Single row by cluster join • Single row by hash cluster key with unique key or primary key • Single row by unique or primary key • Cluster join • Hash cluster key • Indexed cluster key • Composite key • Single column indexes • Bounded range search on indexed columns • Unbounded range search on indexed columns • Sort merge join • Max or Min of indexed column • Order by on indexed columns • Full table scans . There are 15 access paths. The ANALYZE command generates these statistics. This can be enabled by using the following command: SQL> ALTER SESSION SET OPTIMIZER_MODE=ALL_ROWS SQL> ALTER SESSION SET OPTIMIZER_MODE=FIRST_ROWS. The cost based approach also considers hints. The Optimizer formulates execution plans and chooses the most efficient plan before executing a statement. Cost based approach has three options: CHOOSE. Cost based with be effective only on the tables which are analyzed.

city. foreign key to company_id) NUMBER (primary key) NUMBER (foreign key to company_id of company) NUMBER (primary key) NUMBER SQL> @ORACLE_HOME/rdbms/admin/utlxplan This command generate a plan_table 21. state FROM company WHERE city=’roanoke’ AND state=’VA’.2 Execution Plan Steps This section deals with the following tables: COMPANY table: company_id name address city state parent_company_id COMPETITOR: company_id product_id SALES: company_id period_id sales_total NUMBER (primary key) VARCHAR2 VARCHAR2 VARCHAR2 (index) VARCHAR2 (index) NUMBER (index) NUMBER (primary key.0 Page 72/135 Date: 29.R030 – Oracle Database Notes Version 1. 2.3 Types of Operations 1. 2 * level)||operation||' '||options||' '||object_name FROM plan_table WHERE statement_id=’ test1’ CONNECT BY prior_id=parent_id AND statement_id = ‘ test1’ START WITH id=1. SQL> SELECT LPAD(‘ ‘.08.2007 21. SQL> EXPLAIN PLAN SET STATEMENT_ID = ‘test2’ FOR SELECT name. ‘Austin’. state FROM company WHERE state=’TX’ AND city IN (‘Houston’. ‘Dallas’). . AND-EQUAL: It merges sorted list of values returned by indexes SQL> EXPLAIN PLAN SET STATEMENT_ID = ‘test1’ FOR SELECT name. Note: For every plan operation issue the above command with different statement id. city. CONCATENATION: It does a union all of results sets.

sales_total > 1000.08. 5. the only difference is the addition of the “+” sign to indicate the start of the hint. You can use hints to specify: • The optimization approach for a SQL statement • The goal of a cost based approach for a SQL statement • The access path for the a table accessed by the statement • The join order for a join statement • A join operation in a join statement Note: The syntax for hints is similar to SQL statement. USING HINTS: Hints are suggestions that give the optimizer for optimizing a SQL statement. ALL_ROWS: It is used to minimize the time it takes for all rows to be returned by the query. city. FILTER: It performs where a clause condition when no index can be used to assist in the evaluation. SQL> EXPLAIN PLAN SET STATEMENT_ID = ‘test6’ FOR SELECT company. SQL> EXPLAIN PLAN SET STATEMENT_ID = ‘test4’ FOR SELECT company.2007 3.period_id = 3 AND sales.sales_total > 1000 7. 8.R030 – Oracle Database Notes Version 1.company_id = sales. state FROM company WHERE company_id=12345. HASH JOIN: It joins tables by creating an in-memory bitmap of one of the tables and then using a hashing function to locate the join rows in the second table. INDEX UNIQUE SCAN: It selects a unique value from a unique index SQL> EXPLAIN PLAN SET STATEMENT_ID = ‘test5’ FOR SELECT name. 6.company_id AND sales. NESTED LOOPS: Nested loops joins tables access operations where at least one of the join columns is indexed. sales WHERE company.name FROM company.sales_total>1000.company_id AND sales.company_id = sales. name FROM company WHERE state=’VA’ CONNECT BY parent_company_id=prior company_id START WITH company_id=1. sales WHERE company. sales WHERE company.period_id = 3 AND sales. 4.company_id AND sales. SQL> EXPLAIN PLAN SET STATEMENT_ID = ‘test3’ FOR SELECT company_id.company_id = sales. . The “+” cannot be preceded by a space.0 Page 73/135 Date: 29.period_id=3 AND sales. SQL> SELECT /*+ ALL_ROWS */ Company.name FROM company.name From company.

instead of quickly removing them from SGA.company_id = sales. FULL: The full hints tells the optimizer to perform a table access full operation the specified table.08.e. You can query the plan table: SQL> SELECT LPAD(‘ ‘. when used for a table in query tells Oracle to treat the table as a cached table. options. sales WHERE company. It ban be used in three different ways: • If a single index is listed.name FROM company. 12.. city. SQL> SELECT /*+ RULE */ company.period_id = 3 AND sales. 10.company_id AND sales. operations.company_id = sales.sales_total > 1000. city.0 Page 74/135 Date: 29. bytes. that index will b used • If multiple indexes are listed. 13. cardinality FROM plan_table.name FROM company. RULE: The rule hint tells the optimizer to use rule-based optimization for a query. i. . SQL> SELECT /*+ FULL (competitor) CACHE (competitor) */ FROM competitor WHERE company_id > 5.period_id = 3 AND sales. the optimizer will choose which indexes to use.company_id AND sales. FIRST_ROWS: It tells the operator to optimize the query with the goal of the shortest response time for the return of the first row from the query. SQL> SELECT /*+ FULL (competitor) NOCACHE (competitor) */ FROM competitor WHERE company_id > 5. SQL> SELECT /*+ FULL (COMPANY) */ name. cache tells Oracle to keep the blocks from the full table scan of a table in the SGA’s data block buffer cache area. the optimizer will choose an index or indexes to use for that table. state FROM company WHERE city = ‘ROANOKE’ AND state = ‘VA’. CACHE: The cache hint.sales_total > 1000. SQL> SELECT /*+ FIRST_ROWS */ company. SQL> SELECT /*+ INDEX (company) */ Name. SQL> SELECT id. 2 * level)||operation||’ ‘||options||’ ‘||object_name FROM plan_table WHERE statement_id = ‘ test1’ CONNECT BY prior_id = parent_id AND statement_id = ‘ test1’ START WITH id = 1. 11. sales WHERE company.R030 – Oracle Database Notes Version 1. • If a table is listed but no indexes are listed.2007 9. state FROM company WHERE city = ‘roanoke’ AND state = ‘VA’.

21. Consolidates the trace information for the given service name. clientid. Syntax: The syntax for the trcsess utility is: Trcsess [output=output_file_name] [session=session_id] [clientid=client_id] [service=service_name] [action=action_name] [module=module_name] [trace_files] where: output session Client id Service Action Module Trace_files Specifies the file where the output is generated. If more than one of the session. If this option is not specified. such as 21.4. the output file could be processed by TKPROF. service.4 The trcsess Utility The trcsess utility consolidates trace output from selected trace files based on several criteria: • Session id • Client id • Service name • Action name • Module name After trcsess merges the trace information into a single output file. In the following case. In this example. The wild character * can be used to specify the trace file names. several trace files are specified: $ trcsess session=21. If trace files are not specified. action. all the files in the current directory are taken as input to trcsess. the session index and serial number is equal to 21. then standard output is used for the output Consolidates the trace information for the session specified.0 Page 75/135 Date: 29.2007 21. You can locate these values in the V$SESSION view. clientid. service.trc main_12995. all files in current directory are taken as input: $ trcsess session=21.08.1 Sample output of trcsess This sample output of trcsess shows the consolidation of traces for a particular session.R030 – Oracle Database Notes Version 1.trc . Consolidates the trace information for given client id. then the trace files which satisfies all the criteria specified are consolidated into the output file. Trcsess can be invoked with various options. One of the session. Consolidates the trace information for the given action name Consolidates the trace information for the given module name Is a list of all the trace file names. The session identifier is a combination of session index and session serial number.2371 In this case.2371. in which trcsess should look for trace information.2371. or module options must be specified. separated by spaces.2371 main_12359. action or module options is specified.

5. Enter value for begin_time: -10 3. The session history report is generated. you need to specify whether you want an HTML or a text report. action or SQL_ID You can view ASH reports using Enterprise Manager or by running the following SQL scripts: • The ashrpt. The HTML report includes links that can be used to navigate quickly between sections. run the ashrpt.sql SQL script generates an HTML or text report that shows ASH information for a specified duration.5 Active Session History Reports Use Active Session History (ASH) reports to perform analysis of: • Transient performance problems that typically last for a few minutes • Scoped or targeted performance analysis by various dimensions or their combinations. Specify the time frame to collect ASH information by asking the begin time in minutes prior to the system date. The default name is accepted in the following example: Enter value for report name: Using the report name ashrpt_1_0310_0131. The reports are divided into multiple sections. • The ashrpti.sql 1. such as time. enter the duration in minutes that report for which you want to capture ASH information from the begin time.2007 21. accept the default report name or enter a report name. session. Enter value for report_type: text 2. The content of the report contains ASH information used to identify blocker and waiter identities and their associated transaction identifiers and SQL for a specified duration.1 Running the ashrpt.0 Page 76/135 Date: 29.R030 – Oracle Database Notes Version 1.sql SQL script generates an HTML or text report that displays ASH information for a specified duration for a specified database instance. The report in this example will gather information beginning from 10 minutes before the current time and ending at the current time.08. module. Next.sql script at the SQL prompt: @$ORACLE_HOME/rdbms/admin/ashrpt.sql Report To generate a text report of ASH information. 21. . The default duration of system date minus begin time is accepted in the following example: Enter value for duration: 4. Next.txt 5. First.

6.sql SQL script generates an HTML or text report that displays statistics for a range of snapshot Ids. a list of the database identifiers and instance number displays. The default name is accepted in the following example: Enter value for report_name: Using the report name awrrpt_1_150_160 5.sql 1. Specify the number of days for which you want to list snapshot Ids. To run an AWR report. • The awrrpti. 21.08.sql script at the SQL prompt: @$ORACLE_HOME/rdbms/admin/awrrpt.sql Report To specify a database and instance before entering a range of snapshot IDs. run awrrpti. Next. The content of the report contains the workload profile of the system for the selected range of snapshots.2 Running the awrrpti. accept the default report name or enter a report name. you need to specify whether you want an HTML or text report. First.sql script at the SQL prompt to generate an HTML or text report: @$ORACLE_HOME/rdbms/admin/awrrpti. you are prompted for the beginning and ending snapshot Id for the workload repository report. The reports are divided into multiple sections.----------. The workload repository report is generated. Enter value for num_days: 2 3. Enter value for begin_snap: 150 Enter value for end_snap: 160 4.6 Automatic Workload Repository Reports You can view the AWR reports with Oracle Enterprise Manager or by running SQL scripts. specify whether you want an HTML or a text report.1 Running the awrrpt.sql 1.---------------3309173529 1 MAIN main DLSUN1690 3309173529 1 TINT251 tint251 stint251 . run the awrrpt. First. The HTML report includes links that can be used to navigate quickly between sections. a user must be granted the DBA role.sql SQL script generates an HTML or text report that displays the statistics for arrange of snapshot Ids on a specified database instance. After that.R030 – Oracle Database Notes Version 1.0 Page 77/135 Date: 29.----.6. • The awrrpt.2007 21. similar to the following: Instance in this Workload Repository Schema ---------------------------------------------------DB Id Inst Num DB Name Instance Host -----. 21. After the list displays. Running Workload Repository Reports using SQL Scripts You can view AWR reports by running the following SQL scripts. Enter value for report_type: text 2.----.sql Report To generate an HTML or text report for a range of snapshot Ids.

sql script. similar to the awrrpt.2007 2. before the text report is generated. Enter values for the database identified (dbid) and instance number (inst_num) at the prompts: Enter value for dbid: 3309173529 Using 3309173529 for database Id Enter value for inst_num: 1 3. Note: Rule Base Optimizer is deprecated in 10g.0 Page 78/135 Date: 29. Next.R030 – Oracle Database Notes Version 1. . you are prompted for the number of days and shapshot IDs.08.

A client-server system splits Processing between two different components. . • The background Process retrieves data block from the actual data file.2 Server Process • Foreground Server Processes: Directly handles the request from the client Process. The listener Process on the Database Server detects the connection request from the client. the listener Process creates a dedicated process and connects the user Process to it.2007 22 MANAGING SHARED SERVERS 22. If so. At this point.g. The advantage of a multithreaded Process is that it can do the work of many single-threaded Processes but requires far less system overhead. It is permanently written to disk when DBWR Process determines it is most efficient to do so. Data is first changed in the SGA. or uses the data blocks already stored in the buffer cache in the SGA of the instance.1 Client Process Responsible for executing a client application on a workstation. If a database uses multi-threaded Server Processes. E. Instead. A single Process can have multiple threads of execution. if necessary. 22. The goals of a Process structure are: • To stimulate a private environment for multiple Processes to work simultaneously • To allow multiple Processes to share computer resources The Process architecture is designed to maximize performance. • If the shared pool contains a shared SQL area for an identical SQL statement. The user executes a single SQL statement. a shared Server Process serves any client request in a Multi-Threaded Server Configuration. • One or more Dispatcher Processes • One or more Shared Server Processes.08. Processes involved in the Shared Server are: • A network Listener Process that connects user Processes to Dispatchers or to a dedicated Server Process. the user inserts a row into a table • The dedicated Server Process receives the statement.1.1 Introduction A Process is a “thread of control” or a mechanism in an operating system that can execute a series of steps. two paths can be followed to continue processing the SQL statement. it can support large numbers of clients with minimal system overhead. • A client workstation runs a database application as SQL*Plus. Shared Server Processes and dedicated Server Processes provide the same functionality. • If the shared pool does not contain a shared SQL area for an identical SQL statement. The database Server is currently running the proper ORACLE NET driver. 22.0 Page 79/135 Date: 29. the listener Process gives the user Process the address of a Dispatcher Process.2 Using Dedicated Server Processes • A database Server machine is currently running Oracle using multiple background Processes. It attempts to establish a connection to the Server using the SQL*Net driver. a new shared SQL area is allocated for the statement in the shared pool. • The Server Process executes the SQL statements stored in the shared SQL area.1. except shared Server Processes are not associated with a specific user Process. the Server Process can use the existing shared SQL area to execute the clients SQL statement. This simply means that a single multithreaded Process can do the work of multiple single-threaded Processes. The network listener Process waits for incoming connection requests and determines if each user Process can use a shared Process.R030 – Oracle Database Notes Version 1. • Background Server Processes: Handles other specific jobs of the database Server. 22. If the user Process request for a dedicated Server.

0 Page 80/135 Date: 29. • The User issues a SQL statement. • A client workstation runs a database application such as Oracle Forms. Once the Shared Server Process finishes processing the SQL statement. • To implement Shared Server you have to set these parameters in init. The SHARED_SERVER parameter is dynamic and hence can be enabled or disabled. 22. • It attempts to establish a connection to the server using ORALE Net driver.0. the other background Processes are running and watching for any conditions that require intervention. In addition. • An available shared Server Process checks the common Dispatcher request and picks up the next SQL statement on the queue. which is in the SGA and shared by all Dispatcher Processes.ora DISPATCHERS = “(PROTOCOL=TCP)(DISP=2)” # minimum dispatchers for TCP to be started MAX_DISPATCHERS = 5 # maximum number of dispatchers you want to start SHARED_SERVERS = 2 # minimum number of server process you want to start MAX_SHARED_SERVERS = 5 # maximum number of server processes LOCAL_LISTENER = (ADDRESS=(PROTOCOL=TCP)(HOST=192. • The Dispatcher Process checks its response queue and sends completed request back to the user Process that made the request.168. Throughout this entire procedure.3 Using Shared Server Process • A database Server is currently running Oracle using multi-threaded Server configuration.2007 • • • The LGWR process records the transaction in the online redo file only on a subsequent commit request from the user. Oracle is managing other transactions and preventing contention between different transactions that request the same data. • The Listener Process on the database Server detects the connection request from the client application and determines how the User Process should be connected to the available Dispatcher. • The Dispatcher Process places the User Process’s request on the request queue.12)(PORT=1521)) $ lsnrctl start $ sqlplus /nolog SQL> CONNECT / as sysdba SQL> SHUTDOWN SQL> STARTUP SQL> EXIT $ sqlplus system/manager@alias #alias name in tnsnames. Note: In Oracle 10g we need not explicitly configure Dispatcher by default one Dispatcher is started. It then Processes the SQL statement as described in previous example. the user updates a row in a table. the Process places the result on the response queue of the Dispatcher Process that sent the request.R030 – Oracle Database Notes Version 1. • The Database Server is currently running the proper ORACLE Net driver. the Server sends a message across the network to the user.4 Simplified Shared Server Configuration Oracle 10g is shared server aware by default and a value greater than zero for SHARED_SERVERS parameter will enable the feature. else appropriate error message is transmitted. If the request is successful. .08. SQL> ALTER SYSTEM SET SHARED_SERVERS=4 SCOPE=BOTH. For example.ora 22.

SQL> SELECT * FROM V$DISPATCHER. listener FROM V$DISPATCHER_CONFIG. 3.08.2007 22.1 To Check Whether Shared Server Is Working 1. connections. SQL> SELECT SERVER FROM V$SHARED_SERVER. SQL> SELECT username. pool.R030 – Oracle Database Notes Version 1. The view V$DISPATCHER_CONFIG gives the information on the existing dispatchers.0 Page 81/135 Date: 29.4. # To see whether the users are connected using shared server or dedicated server process. # Check to see any changes in shared servers busy time after some operations SQL> SELECT * FROM V$QUEUE. . At the database level we can query from the following: SQL> SELECT * FROM V$MTS. It should not appear 2. From the operating system you can give this command to see whether SHARED SERVER is working: $ ps x|grep ora_ #check for (LOCAL=YES) or (LOCAL=NO). # Check to see any changes in dispatcher busy time after some operations. SQL> SELECT dispatchers. server FROM V$SESSION.

23. SQL> ALTER TABLE parts MOVE PARTITION dept2 TABLESPACE ts_2000 NOLOGGING.2 Advantages of Partitioning Tables • Reduce the possibility of data corruption in multiple partitions • Make it possible to back up and recover each partition independently • Make it possible to control the mapping of partitions to disk drives (important for balancing I/O load) 23.2007 23 PARTITIONED TABLES AND INDEXES 23. 01) TABLESPACE tsb. To move table partitions: You can use the MOVE PARTITION clause to move a partition.3 Types of Partitions • Range Partitions • Hash Partitions • List Partitions • Composite Partitions • Composite Range-Hash Partitioning • Composite Range-List Partitioning 23. PARTITION sales_q3 VALUES LESS THAN (2000.R030 – Oracle Database Notes Version 1. 1-3. which have the same local attributes. # This statement always drops the partition’s old segment and creates a new segment. The partition key can be a composite key of up to 16 columns.1 Managing Partitioned Tables A Partitioned table or Partitioned index has been divided into a number of pieces. 07. In each partition. 01) TABLESPACE tsc.0 Page 82/135 Date: 29. 01) TABLESPACE tsd). 8-10 is not allowed. Range partitioning is defined by: • The partitioning specifications for a table or index • Partitioning specifications for each partition Range partitions maps rows to partitions based on ranges of column values. 1. all rows have partition keys that compare less than the partition bound for that partion. 3. . 02. sale_year INT NOT NULL.1 Range Partitioning Range partitioning partitions the data in the tale or index according to a range of values. 2. 10. You cannot have gaps in the ranges. 01.3. sale_day) (PARTITION sales_q1 VALUES LESS THAN (2000. sale_day INT NOT NULL) PARTITION BY RANGE (sale_year. PARTITION sales_q2 VALUES LESS THAN (2000.08. SQL> CREATE TABLE sales (invoice_no NUMBER. To create range partitions: Creating partitions is very similar to creating a table or index. sale_month. or partitions. sale_month INT NOT NULL. Partition by range is also referred to as a partition key. 5-6. To add table partitions SQL> ALTER TABLE sales ADD PARTITION jan2001 VALUES LESS THAN (‘2002. for example. 04. PARTITION sales_q4 VALUES LESS THAN (2001. even if you don’t specify a new tablespace. 01’) TABLESPACE tse. 01) TABLESPACE tsa.

(OR) 5. To merge partition OSU1 into partition OSU2: a. a. Disable the constraints before dropping the partition. 7. SQL> SQL> SQL> SQL> SQL> SQL> ALTER TABLE ALTER TABLE ALTER TABLE ALTER TABLE DELETE FROM ALTER TABLE sales sales sales sales sales sales TRUNCATE PARTITION dec2000.0 Page 83/135 Date: 29. (OR) WHERE TRANSID < 10000. To drop table partitions: Delete the rows from the partition before dropping the partition. SQL> ALTER TABLE sales ENABLE CONSTRAINT dname_sales1. Export the data from OSU1 b.2007 4. SQL> DELETE FROM sales WHERE transid < 10000. 6. PARTITION sales_q5). ENABLE CONSTRAINT dname_sales1. 8. Another way to merge partition OSU1 into partition OSU2. Exchange partition OSU1 of table OH with “dummy” table COLS b. TRUNCATE PARTITION dec2000. SQL> ALTER TABLE sales DROP PARTITION dec2000. to move the data from OSU1 back into OSU2.R030 – Oracle Database Notes Version 1. To truncate partition tables: You can use the ALTER TABLE TRUNCATE PARTITION statement to remove all rows from a table partition with or without reclaiming space. SQL> ALTER TABLE sales SPLIT PARTITION sales_q4 at (2000. SQL> ALTER TABLE sales DISABLE CONSTRAINT dname_sales1. (OR) DISABLE CONSTRAINT dname_sales1. To split table partitions: You can split a table partition by issuing the ALTER TABLE SPLIT PARTITION statement. 12. Import the data from Step 1 into partition OSU2. To merge table partitions: You can use either of the following strategies to merge table partitions. Insert as SELECT from the ‘dummy’ table. c. . 01) INTO (PARTITION sales_q4.08. c. Issue the following statement: SQL> ALTER TABLE OH DROP PARTITION OSU1. TRUNCATE PARTITION dec2000. SQL> ALTER TABLE sales DROP PARTION dec2000. Issue the following statement SQL> ALTER TABLE oh DROP PARTION osu1.

day NUMBER. year) (PARITION h1 TABLESPACE ts1. To create a hash partition SQL> CREATE TABLE purchases(inv_no NUMBER. Range partitioning is useful for segmenting a table along a continuous domain.2 Hash Partitioning Hash partitioning partitions the data according to a hash value. such as time.2007 23.’TN’. 2. 2.0 Page 84/135 Date: 29. 1. except for PCTFREE and MAXEXTENTS which are specified in the statement: SQL> ALTER TABLE sales_by-region MERGE PARTITIONS region_east. North America. The data warehouse administrator could choose to list-partition a large table by the regions Europe.3. Each partition in a list-partitioned table contains data matching a list of discrete partition-key values.3. dropping.’MP’. state_code VARCHAR(4).’NGL’) TABLESPACE ts1. To add a partition to the existing table: SQL> ALTER TABLE purchases ADD PARTITION h4 TABLESPACE ts4. suppose that a data warehouse for a large corporation contains data for many different countries.’AP’. 3. 1. PARTITION h3 TABLESPACE ts3).08. South America. PARTITION h2 TABLESPACE ts2. which is often used in data warehouses. 23. and Asia.’HP’. list partitioning is useful for segmenting a table along a discrete domain. Tables in data warehouses are often range-partitioned by time. month.’MZ’. . sale-date DATE) PARTITION BY LIST (state_code) (PARTITION region_east VALUES (‘WB’. year NUMBER) PARTITION BY HASH(day. It controls the physical placement of data across a fixed number of partitions and gives you a highly tunable method of data placement. store_name VARCHAR(30).’AM’. For example.’UP’.’RT’) TABLESPACE ts2. merging the existing partitions is not possible with Hash Partitioned tables. Month NUMBER. ‘MH’.3 List Partitioning List partitioning complements the functionality of range partitioning. Note: Splitting. PARTITION region_west VALUES (‘GT’. This example MERGEs two partitions into a partition that will inherit all of its attributes from the table-level attributes. so that each range partitions contains the data for a given range of time values such as one partition per month or per week. region_west INTO PARTITION region_east_west PCTFREE 50 STORAGE (MAXEXTENTS 20). In contrast. CREATE A LIST partitioned table: SQL> CREATE TABLE sales_by_region (item# NUMBER. such as products.’KRT’) TABLESPACE ts4).’ND’. qty NUMBER. SQL> ALTER TABLE sales_by_region ADD PARTITION region_south VALUES(‘KRL’. Add a new partition to SALES_BY_REGION table partitioned by the LIST method.’PJB’) TABLESPACE ts3)). PARTITION region note VALUES (‘JM’.R030 – Oracle Database Notes Version 1.

and you can specify a STORE IN clause at the partition level if the list of tablespaces across which the sub-partitions of that partition should be spread is different from those of other partitions. empname VARCHAR(32).08. ‘KRT’) INTO (PARTITION region_south1 TABLESPACE ts4.R030 – Oracle Database Notes Version 1. ‘AP’. All of this is illustrated in the following example. PARTITION p3 VALUES LESS THAN (MAXVALUE) (SUBPARTITION p3_s1 TABLESPACE ts4. 5. SUBPARTITION p3_s2 TABLESPACE ts5)). 23. This example SPLITs the partition REGION_SOUTH into two partitions: SQL> ALTER TABLE sales_by_region SPLIT PARTITION region_south VALUES (‘KRL’. ts7) (PARTITION p1 VALUES LESS THAN (1000). ts3. grade NUMBER) PARTITION BY RANGE (deptno) SUBPARTITION BY HASH (empname) SUBPARITIONS 8 STORE IN (ts1.0 Page 85/135 Date: 29. SQL> CREATE TABLE emp (deptno NUMBER.3. ts6. 6.4 Composite Range-Hash Partitioning Tables Attributes specified for a range partition apply to all sub-partitions of that partition. ts4.2007 4. PARTITION p2 ALUES LESS THAN (2000) STORE IN (ts2. ‘TN’. ts8). This statement DROPs a set of state codes from the existing REGION_EAST partition value-list. ts5. This is a new statement which can be used to extend the partition value list of an existing partition to contain additional literal values: SQL> ALTER TABLE sales_by_region MODIFY PARTITION region_east ADD VALUES (‘BIH’). . PARTITION region_south2 STORAGE (NEXT 100K)). SQL> DELETE sales_by_region WHERE state_code IN (‘MZ’). You can specify different attributes for each range partition. SQL> ALTER TABLE sales_by_region MODIFY PARTITION region_east DROP VALUES (‘MZ’).

‘NJ’). SUBPARTITION q2_1999_southeast VALUES (‘FL’. ‘GA’). of the SALES table by moving the data from FEB95 partition into the MAR95 partition. ‘GA’). ‘WA’). PARTITION q3_1999 VALUES LESS THAN ( TO_DATE(‘1-OCT-1999’. Suppose you have to merge two partitions FEB95 and MAR95. you can include a SUBPARTITION BY LIST clause that follows similar syntax and rules as the PARTITION BY LIST clause. ‘UT’.5. ‘DD-MON-YYYY’)) ‘DD-MON-YYYY’)) ‘DD-MON-YYYY’)) ‘DD-MON-YYYY’)) Exercises: 1.08. SUBPARTITION q3_1999_southwest VALUES (‘AZ’. PARTITION q2_1999 VALUES LESS THAN ( TO_DATE(‘1-JUL-1999’. item_no VARCHAR(20). ‘NJ’). txn_amount number. TABLESPACE tbs_2 (SUBPARTITION q2_1999_nortwest VALUES (‘OR’. TABLESPACE tbs_1 (SUBPARTITION q1_1999_nortwest VALUES (‘OR’. and a table into a partition of a partitioned table by exchanging their data (and index) segments. SUBPARTITION q2_1999_southcentral VALUES (‘OK’. PARTITION q4_1999 VALUES LESS THAN ( TO_DATE(‘1-JAN-2000’. Merging Adjacent Table Partitions: This following scenario describes how to merge two adjacent table partitions.3.1 To MERGE the two Table Partitions 1. SQL> CREATE TABLE sales_feb95 (…. txn_date date. ‘NM’). ‘NM’).5 Composite Range-List Partitioned Tables The concept of range-list partitioning is similar to that of the other composite partitioning method. SUBPARTITION q1_others VALUES (DEFAULT) TABLESPACE tbs_4 ).R030 – Oracle Database Notes Version 1. after the CREATE TABLE… PARTITION BY RANGE clause. SQL> CREATE TABLE sample_regional_sales (deptno number. WI’). ‘WA’). TABLESPACE tbs_3 (SUBPARTITION q3_1999_nortwest VALUES (‘OR’. and optionally a SUBPARTITION TEMPLATE clause. SUBPARTITION q1_1999_southwest VALUES (‘AZ’. SUBPARTITION q2_1999_northeast VALUES (‘NY’. follow. The individual PARTITION and SUBPARTITION clauses. TABLESPACE tbs_4 ). but this time you can specify that the sub-partitions are to be list rather than hash.) TABLESPACE ts_temp STORAGE (INITIAL 2). ‘UT’. Create a temporary table to hold the FEB95 partition data. SUBPARTITION q2_1999_northcental VALUES (‘SD. ‘TX’) ). SUBPARTITION q3_others VALUES (DEFAULT) TABLESPACE tbs_4 ). 23.0 Page 86/135 Date: 29. SUBPARTITION q1_1999_northeast VALUES (‘NY’. 2. ‘VM’. SUBPARTITION q1_1999_southeast VALUES (‘FL’.2007 23. SUBPARTITION q2_1999_southwest VALUES (‘AZ’. Specifically. Exchanging Table Partitions You can convert a partition into a non-partitioned table. . state varchar2(2)) PARTITION BY RANGE (txn_date) SUBPARTITION BY LIST (state) (PARTITION q1_1999 VALUES LESS THAN (TO_DATE(‘1-APR-1999’. ‘WA’).3. ‘VM’. rangehash. ‘UT’. ‘NM’).

SQL> ALTER TABLE sales EXCHANGE PARTITION feb95 WITH TABLE sales_feb95 WITHOUT VALIDATION.2 Creating a View from Partitioned table 1. 6.R030 – Oracle Database Notes Version 1. .5. Instead of attempting to compute the partition to which a row belongs. . Oracle verifies that it belongs to the specified partition. SQL> CREATE TABLE accounts_new (….5.2007 2. SQL> INSERT INTO sales PARTITION (mar95) SELECT * FROM sales_feb95. Now the SALES_FEB95 table placeholder segment is attached to the FEB95 partition.. Exchange the FEB95 partition segment into the table SALES_FEB95. Drop the SALES_FEB95 table to free the segment originally associated with the FEB95 partition. At a time we can’t select data from the two partitions of a table for this we have to create a partition view based on two partitions of a table: SQL> CREATE VIEW account AS SELECT * FROM accounts_jan95 UNION ALL SELECT * FROM accounts_feb95. this frees the segment originally owned by the SALES_FEB95 table. 4. 23.0 Page 87/135 Date: 29.08. Move the data from the SALES_FEB95 table into the MAR95 partition via an INSERT statement. Initially. PARTITION dec95 VALUES LESS THAN (‘960101’)). Note: Using the extended table name here is more efficient. 5. ACCOUNTS_NOV95 and ACCOUTNS_95 will be migrated from the view to the table by creating the partition table. (Optional) Rename the MAR95 partition SQL> ALTER TABLE sales RENAME PARTITION mar95 TO feb)mar95. only the two most recent partitions. 23. Each partition gets a temporary segment of 2 blocks (as a placeholder).3. Drop the FEB95 partition. SQL> DROP TABLE sales_feb95.) TABLESPACE ts_temp STORAGE (INITIAL 2) PARTITION BY RANGE (opening_date) (PARTITION jan95 VALUES LESS THAN (‘950201’). SQL> ALTER TABLE sales DROP PARTITION feb95.3 To Incrementally Migrate the Partition View to a Partition Table 1.. 3.3.

. UNION ALL SELECT * FROM accounts_new PARTITION (nov95) UNION ALL SELECT * FROM accounts_new PARTITION (dec95). Redefine the ACCOUNTS view. 4. SQL> CREATE OR REPLACE VIEW accounts SELECT * FROM accounts_JAN95 UNION ALL SELECT * FROM accounts_FEB95 UNION ALL . SQL> WITH SQL> WITH ALTER TABLE ALTER TABLE TABLE accounts_new EXCHANGE PARTITION nov95 accounts_NOV95 WITH VALIDATION. SQL> DROP VIEW accounts. SQL> RENAME accounts_new TO accounts. 5. .08. the placeholder data segments associated with the NOV95 and DEC95 partitions have been exchanged with the data segments associated with the ACCOUNTS_NOV95 and ACCOUNTS_DEC95 tables. • Type of access to data through applications • Performance in accessing data • Availability in case of disk failure • Are parallel operation possible? All of these issues will influence your choice of an indexing strategy. After all the tables in the UNION ALL views are converted into partitions. So now. drop the view and the partitioned table that was renamed as the view. Drop the ACCOUNTS_NOV95 and ACCOUNTS_DEC95 tables. 3.R030 – Oracle Database Notes Version 1. Use the EXCHANGE command to migrate the tables to the corresponding partitions. TABLE accounts_new EXCHANGE PARTITION dec95 accounts_DEC95 WITH VALIDATION.. 23. Database administrators and application developers need to analyze their indexing needs for their application.4 Managing Partitioned Indexes Indexes can be either partitioned or non-partitioned.0 Page 88/135 Date: 29. which own the placeholder segments that were originally attached to the NOV95 and DEC95 partitions.2007 2.

acct_no) GLOBAL PARTITION BY RANGE (week_no) (PARTITION pi1 VALUES LESS THAN (32). PARTITION I_P2 TABLESPACE IDX2.08. person) GLOBAL PARTITION BY RANGE (acct_no) (PARTITION pi1 VALUES LESS THAN (32). 2. person VARCHAR2 (30).1 Types of Indexes Oracle supports four types of indexes that you can use according to your specified needs: • Non-partitioned indexes • Global prefixed indexes • Local prefixed indexes • Local non-prefixed indexes Examples: 1. but can be defined on any type of partitioned tables. week_no NUMBER (2) NOT NULL) PARTITION BY RANGE (week_no) (PARTITION BY p1 VALUES LESS THAN (16).4. PARTITION pi2 VALUES LESS THAN (MAXVALUES)). the partition name would be the same as the partition name for the corresponding table partition. . PARTITION BY p3 VALUES LESS THAN (53)). Create GLOBAL indexes: SQL> CREATE INDEX sales_idx ON sales (week_no. PARTITION BY p2 VALUES LESS THAN (36). 3. 4. In that case.0 Page 89/135 Date: 29. PARTITION pi2 VALUES LESS THAN (MAXVALUE)).2007 23. one index partition may refer to more than one underlying table partition. you could leave out the partition name and tablespace name. In a global index. PARTITION I_P3 TABLESPACE IDX3). Create table SALES partitioned by RANGE SQL> CREATE TABLE sales (acct_no NUMBER (5) NOT NULL.R030 – Oracle Database Notes Version 1. acct_no) LOCAL (PARTITION I_P1 TABLESPACE IDX1. A global index can only be range partitioned. Create LOCAL indexes: SQL> CREATE INDEX sales_idex ON sales (week_no. sales_amount NUMBER (8) NOT NULL. and the partition would be placed in the same tablespace as the table partition the index is associated with. Note: Note: An index is prefixed if the LEFTMOST columns of the index are based on exactly the same columns as the partition key of the index. Create PREFIXED indexes: SQL> CREATE INDEX sales_idx ON sales (acct_no. Note: In the example.

5 Data Dictionary Views • DBA_PART_INDEXES • DBA_TAB_PARTITIONS • DBA_IND_PARTITIONS • DBA_INDEXES • DBA_OBJECTS • DBA_SEGMENTS SQL> SELECT a. user_part_tables b WHERE a. An index is non-prefixed if the LEFTMOST columns of the index are not based on the same columns as the partition key of the index. SQL> ALTER INDEX quon1 REBUILD PARTITION canada2. new partitions are added to local indexes only when you add a partition to the underlying table.locality FROM user_ind_partitions a. a. Note: 8. PARTITION CANADA2 TABLESPACE TS12). a. 23. To add Index partition: You cannot explicitly add a partition to a local index.index_name=b.tablespace_name. SQL> ALTER INDEX quon1 SPLIT PARTITION Canada AT VALUES LESS THAN (100) INTO (PARTITION CANADA1 TABLESPACE TS11.table_name ORDER BY a. 6.high_value. To Drop Index Partitions: You cannot explicitly drop a partition from a local index.INDEX UNUSABLE.index_name. You cannot add a partition to a global index because the highest partition always has a partition bound of MAXVALUE. To split Index Partitions: You cannot explicitly split a partition in a local index.tablespace_name.partition_name. SQL> ALTER INDEX quon1 REBUILD PARTITION canada1.table_name.high_value FROM user_tab_partitions a. You can use the ALTER INDEX SPLIT PARTITION statement to split a partition in a global index if the partition is empty.partition_name. b.table_name. b. a. a.table_name=b.08. Note: If partition name contains data. 7.0 Page 90/135 Date: 29.index_name. then SPLIT PARTITION marks both split-partion-1 and split-partition2.index_name ORDER BY a.2007 5.partitioning_type. a. . You must ALTER INDEX REBUILD PARTITION to rebuild the partitions before using them. a. b.partition_name. SQL> SELECT a. Instead.partitioning_type. SQL> ALTER INDEX npr REBUILD PARTITION P2. a. Create NON-PREFIXED indexes SQL> CREATE INDEX sales_idx ON sales (acct_no) LOCAL. user_part_indexes b WHERE a.R030 – Oracle Database Notes Version 1. a.partition_name.

sql SQL> CONNECT / AS SYSDBA SQL> SHUTDOWN $ file=’cat cold. SELECT ‘cp ‘||name\ /disk3/oradata/DEMO/BKUP’ FROM V$TEMPFILE. 1. SELECT ‘cp ‘||name\ /disk3/oradata/DEMO/BKUP’ FROM V$CONTROLFILE. SELECT ‘cp ‘||name\ /disk3/oradata/DEMO/BKUP’ FROM V$LOGFILE. unless a hot backup is performed.sql SET ECHO OFF SET PAUSE OFF SET FEED OFF SET HEAD OFF SPOOL cold_backup.sh’ /* stores the file names in a variable */ $ echo “tar Pcvf /disk5/oradata/DEMO/cold. SELECT name FROM V$CONTROLFILE. It is not valid to perform a file system backup of the database while it is open. The steps involved in taking a cold backup of a database are as follows: $ mkdir –p /disk3/oradata/DEMO/BKUP $ vi getfiles.sql SQL> SHUTDOWN SQL> EXIT $ sh cold_backup.tar” $file>tar.sh SELECT ‘cp ‘||name\ /disk3/oradata/DEMO/BKUP’ FROM V$DATAFILE.sh SELECT name FROM V$DATAFILE.cmd . Having all of these files backed up while database is closed provides a complete image of the database as it existed at the time it was closed. Taking cold backup using ‘tar’ command: $ vi getfiles. The full set of these files could be retrieved from the backups at a later date and the database would be able to function. SELECT name FROM V$LOGFILE.sh /* Taking backup to BKUP directory */ $ cd BKUP /* Changing to BKUP directory */ $ ls /* Checking the contents */ 2. SPOOL OFF :wq $ sqlplus /nolog SQL> CONNECT / AS SYSDBA SQL> STARTUP SQL> @getfiles.R030 – Oracle Database Notes Version 1. SELECT name FROM V$TEMPFILE. • All datafiles • All control files • All online redo logs • The init.0 Page 91/135 Date: 29.sql SET ECHO OFF SET HEAD OFF SET FEED OFF SPOOL cold.2007 24 MANAGING BACKUPS AND RECOVERY 24.comd $ sh tar.ora (optional) It is easy to take a backup of datafiles if the database files architecture uses a consistent directory structure. SPOOL OFF EXIT :wq SQL> @getfiles.08.1 Cold Backup Cold backup is taken when database is shutdown normal. The following files should be backed up.

SELECT ‘alter system switch logfile.’ FROM dual.sql SELECT ‘spool hot. SPOOL off @hot_backup.’ ||chr(10)||’!cp ‘||file_name||’ /disk5/oradata/DEMO/HOTBKUP’ ||chr(10)||’alter tablespace ‘||tablespace_name||’ end backup.sql SELECT ‘spool hot.new’’’||’. $ mkdir –p /disk5/oradata/DEMO/HOTBKUP $ vi hot. you must set it to END BACKUP mode. SELECT ‘ alter tablespace ‘||tablespace_name||’ begin backup.’ FROM dual.2. Hot backup can be taken on tablespace by tablespace mechanism. SELECT ‘alter system switch logfile.sql /* execute the SQL file just generated */ EXIT :wq $ cd /disk5/oradata/DEMO/HOTBKUP $ ls –l 24.net’’’||’.2007 3.08.1 Whole Database Backup Whole database backup can be performed while database is up and running in Archive log mode. SELECT ‘alter database ‘||database_name||’ begin_backup.sql /* execute the SQL file just generated */ EXIT :wq $ cd /disk5/oradata/DEMO/HOTBKUP $ ls –l .2 Hot Backup at Tablespace Level Hot backup is taken when the database is up and running in archive log mode. SELECT ‘alter database backup controlfile to ‘|| ‘’’/disk5/oradata/demo/HOTBKUP/control.’ FROM dual.sql SET ECHO OFF SET FEEDBACK OFF SET HEADING OFF SPOOL hot_backup.0 Page 92/135 Date: 29. SPOOL OFF @hot_backup.’ FROM dual.R030 – Oracle Database Notes Version 1. It is worth to note that hot backup will generate lot of redo entries.’ ||chr(10)||’!cp ‘||file_name||’ /disk5/oradata/DEMO/HOTBKUP’ ||chr(10)||’alter database ‘||database_name||’ end backup.2 Hot Backup 24.’ FROM dual. SELECT ‘alter database backup controlfile to ‘|| ‘’’/disk5/oradata/demo/HOTBKUP/control. You must put the tablespace in BEGIN BACKUP mode (using ALTER TABLESPACE command) and after finishing backup.log’ FROM dual. $ mkdir –p /disk5/oradata/DEMO/HOTBKUP $ vi hot.log’ FROM dual.tar 24.2. To restore the database issue $ tar Pxvf cold.’ FROM dba_data_files.sql SET ECHO OFF SET FEEDBACK OFF SET HEADING OFF SPOOL hot_backup.

END LOOP. For example.file_name%type. 4. EXIT WHEN t_tab%notfound. LOOP FETCH t_tab into t_rec.2007 Taking a hot backup using cursors: $ vi hot.put_line (‘alter tablespace ‘||t_rec||’ end backup.sql SET SERVEROUTPUT ON SET ECHO OFF SET HAD OFF SET FEED OFF SPOOL hotbkup.’ FROM dual.dbf /disk2/backup/ 3. ‘ FROM dual. You no longer have the need to place each tablespace into backup mode individually unless you want to backup only one tablespace at a time. SELECT ‘alter system switch logfile.put_line(‘!cp ‘||d_rec||’/disk5/oradata/DEMO/HOTBKUP’).new’’’||’. For example. To end the backup of the database: SQL> ALTER DATABASE END BACKUP.R030 – Oracle Database Notes Version 1. END LOOP. enter: SQL> ALTER SYSTEM ARCHIVE LOG CURRENT. BEGIN OPEN t_tab. Dbms_output.put_line(‘alter tablespace ‘||t_rec||’begin backup.new /disk5/ordata/DEMO/HOTBKUP/control. dbms_output.dbf suffix as follows: $ cp $ORACLE_HOME/oradata/trgt/*. SELECT ‘ ‘||’!mv /disk5/oradata/DEMO/HOTBKUP/control. CLOSE t_tab. t_rec dba_data_files.08.’).sql DECLARE CURSOR t_tab IS SELECT DISTINCT (tablespace_name) FROM dba_data_files. Back up all files of the online tablespaces. d_rec dba_data_files.tablespace_name%type. CURSOR f_tab (fs VARCHAR) IS SELECT file_name FROM dba_data_files WHERE tablespace_name = fs. the command is: SQL> ALTER DATABASE BEGIN BACKUP. END. EXIT WHEN f_tab%NOTFOUND. OPEN f_tab (t_rec). a UNIX user might backup datafiles with the *. LOOP FETCH f_tab INTO d_rec.old’||’ ‘ FROM dual. Dbms_output. SELECT ‘alter database backup controlfile to ‘||’’’/disk5/oradata/DEMO/HOTBKUP/control.0 Page 93/135 Date: 29. If you are backing up all tablespaces datafiles at once in online backup mode. CLOSE f_tab.3 Online Backup Mode or Entire Database Backup 1. 2. SPOOL OFF :wq $ @hotbkup. Archive the online redo logs so that the redo logs required to recover the tablespace backups will be available for later media recovery.’). You can not take individual tablespaces offline or in begin backup when whole database is in BEGIN BACKUP mode.sql 24. .

thread recovery and media recovery. It is used to make backup datafiles current. or to restore changes that were lost when a datafile went offline without checkpoint.3 Media Recovery Media recovery is done in response to a recovery command issued by the DBA.2007 24. the algorithm that applies the redo records against an individual block is the same. Media recovery can apply archived log files.2 Thread Recovery If an instance crashes while it has a database open. The checkpoint SCN stored in the control file for the thread instance dad will have the lost changes applied. When a process dies while changing a buffer. then Oracle will do crash recovery.4. For example.08. If the PMON process is performing the block recovery.1 Block Level It is automatically performed by Oracle during normal operation of the database and is transparent to the user and does not involve any action from the DBA.1 Online and Offline Recovery Recovery command Recover database Recover tablespace Recovery datafile Syntax: SQL> RECOVER [AUTOMATIC] [FROM ‘LOCATION’] [DATABASE] |UNTIL TIME/DATE |UNTIL CANCEL |UNTIL CHANGE USING BACKUP CONTROLFILE. Oracle does not allow it to spend large amount of time working on the recovery of one buffer. as well as online log files.4.4 Recovery Recovery is of three types. Instance recovery is done while the database is open and once instance detects that another instance as dead. This is possible only if you are running multiple instances instance. In all the three cases.0 Page 94/135 Date: 29. Thread recovery is done either as a part of instance recovery or crash recovery. Oracle reconstructs the buffer using the online redo log files for the current thread and writes it to the disk. 24.3. the data files will go offline without a checkpoint being performed by Oracle. This involves applying the database on the redo changes in the thread that have occurred since the last time the thread was check pointed.4. The buffer header contains the information regarding the range of redo records that needs to be applied to it. if you take a tablespace offline.4. If you restart a dead instance before recovery is done. They are online block recovery. the first instance to open the database after an abnormal termination (shutdown abort or database crash) does crash recovery. 24. it is necessary to do thread recovery. 24. using the immediate option. using parallel query option. 24. In general. | Database online | No | Yes | Yes | Database offline | Yes | No | Yes .R030 – Oracle Database Notes Version 1.

0 Page 95/135 Date: 29. Complete recovery should be implemented when all the redolog files. Now try to open the database. Steps: Case 3. which came from last night. The scenario can be simulated as follows: 1. because the database will be in inconsistent state. Now shutdown the database and restore the previous night’s backup and open the database. Cancel the media recovery immediately after applying the last archived file. you will get an Error stating that particular data file is missing. Now abort the instance. you have archived log files but not online redolog files. open database with resetlogs option. Case 2. and a current valid control file are available.2 Complete vs Incomplete Recovery Recovering the database from a media failure without losing any data is known as complete recovery. Here you restore the lost file from the previous nights backup. Take a cold backup of the database. you have lost no data hence it is complete recovery. .R030 – Oracle Database Notes Version 1. In this case. Otherwise it is known as incomplete recovery. so you can restore up to the last available archived log file only by issuing the RECOVER DATABASE UNTIL CANCEL. So it will fail. Note: You just cannot restore the lost datafile from previous backup and start up the database. Startup the database and perform some transactions.08. It may appear to you that it is incomplete. This will invalidate the previous log files. How you’ll recover the database. Everything is same except that it is running in ARCHIVE mode. Case 1. So you lost today’s transactions. but it is still complete recovery for that time. The database is running in NOARCHIVE mode and you lost a data file because of media failure and you take cold backup every night. Here. Everything is as above except that you lost the online redolog files only. 2.4.2007 24. backup data files (for all the lost or damaged data files). Now using HOST command. remove one datafile at the operating system level. it did not loose anything. Mount the database and issue the command RECOVER DATAFILE AUTOMATIC. This is complete recovery though you lost today’s actions because as far as the database is concerned. This is an incomplete recovery. Oracle will apply the relevant archived log files and online redo log files and when it will open the database.3.

R030 – Oracle Database Notes Version 1.2007 Case 4. which the programmer has dropped Shutdown the database Restore the new backup Startup the database Now import the table. ‘/disk2/oradata/DEMO/redolog2.ctl Steps:. 11. We used to take cold backup every night. ‘/disk2/oradata/DEMO/redolog2. Case 5. use CREATE CONTROLFILE command. Open the database by resetting the logs Export the table.ctl SQL> !rm /disk2/oradata/DEMO/control2. GROUP 2 (‘/disk1/ordata/DEMO/redolog1.m. You realized this at 2:00 p.sql SQL> ALTER DATABASE OPEN RESETLOGS. 6.). # Note: Using backup control file if you have restored the control file otherwise use current control file only].m. 10. 9. SQL> STARTUP NOMOUNT.sql CREATE CONTROLFILE REUSE DATABASE DEMO ARCHIVELOG LOGFILE GROUP 1 (‘/disk1/ordata/DEMO/redolog1.0 Page 96/135 Date: 29. 7. . A DBA has lost both the control files of a database. To recovery the database.log’) SIZE 4M. SQL> @cr8ctl. which was exported in step 5. 4. Mount the database and issue the command: SQL> ALTER DATABASE RECOVERY AUTOMATIC USING BACKUP CONTROLFILE UNTIL TIME ‘2005-08-07:11:29:00’.log’) SIZE 4M DATAFILE ‘/disk1/oradata/DEMO/system01. Database is running in Archive log mode. $ vi cr8ctl. 3. On one day.log’. 8.dbf’ RESETLOGS RECOVER DATABASE. Note: Do not forget to take a fresh backup now. Steps: 1. 2. As this is a critical database without losing others data you have to recover the lost table. Switch the log file Shutdown the database Take the cold backup of the current database (New backup) Restore only the datafiles from previous night’s backup provided there are no structural changes to the database. a programmer accidentally dropped one importable table (assume that at 11:29:45 a.08.log’. The scenario can be simulated as follows: SQL> !rm /disk1/oradata/DEMO/control1. 5. which is in archive log mode.

Note: You must install the recovery catalog schema in a different database from the target database you will be backing up. . The size of the recovery catalog schema: • Is dependent of the number of databases monitored by the catalog • Is dependent on the number and size of Recovery Manager scripts stored in the catalog • Will grow as the number of activated logs and backups for each database grow If you use Recovery Manager to backup many databases. If you have more than one database to backup. you may wish to create a separate recovery catalog database. and any associated space used by that schema. Recovery Manager can perform a variety of automated backup and recovery functions. You should also decide whether or not to operate this database in ARCHIVELOG mode.1. SQL> CONNECT rman/rman $ rman catalog rman/rman RMAN> CREATE CATALOG TABLESPACE rman_ts.08. Create a tablespace RCVCAT that will be the default tablespace of a catalog schema placing the read data.1. SQL> GRANT RECOVERY_CATALOG_OWNER TO rman. The only way to restore and recover when you have lost all control files and need to restore and recovery datafiles after creating the control file manually. It is difficult to restore and recover if you lose your control files and do not use a recovery catalog. and also how you will back this database up. To Set Up the Recovery Catalog Schema 1. If you use a recovery catalog.log SQL> CONNECT / AS SYSDBA SQL> CREATE USER rman IDENTIFIED BY rman TEMPORARY TABLESPACE temp DEFAULT TABLESPACE rman_ts QUOTA UNLIMITED ON rman_ts. however. one called “ACCT” and a second called “PAY”. 3. you need to setup the schema.1 INTRODUCTION 25. you must decide which database you will use to install the recovery catalog schema.2 Setting Up the Recovery Catalog Schema When you use a recovery catalog. it could be put in the system tablespace. Oracle suggests you put the recovery catalog schema in its own tablespace. For example. However.2007 25 RECOVERY MANAGER 25. the benefits of using a recovery catalog are lost if you lose the database and need to restore.R030 – Oracle Database Notes Version 1. you can install the recovery catalog for “ACCT” in the “PAY” database. If you don’t. if necessary.1 Costs and Benefits When Using a Recovery Catalog When you use a recovery catalog. 2. This enables you to avoid the extra space requirements and memory overhead of maintaining a separate recovery catalog database. and the recovery catalog for the “PAY” database in “ACCT”. and create the Recovery Manager in that database. assume there are two production databases. however. Issue the following commands: SQL> SPOOL cr8rman. Note: 25. you can create more than one recovery catalog and have each database serve as the other’s recovery catalog. Using Server Manager (Line Mode) connect SYS (as SYSDBA) to the database containing the recovery catalog.0 Page 97/135 Date: 29. Recovery Manager requires that you maintain a recovery catalog schema. this solution is not practical if the recovery catalog databases for both reside in tablespaces residing on the same physical disk.

. RMAN connects in default NOCATALOG mode when the first command requiring a repository connection is run: $ rman RMAN> CONNECT TARGET SYS/sys_pwd@prod1 RMAN> BACKUP DATABASE. CONFIGURE ENCRYPTION ALGORITHM ‘AES128’. 7. CONFIGURE DATAFILE BACKUP COPIES FOR DEVICE TYPE DISK TO 1. CONFIGURE CONTROLFILE AUTOBACKUP FORMAT FOR DEVICE TYPE DISK TO ‘%F’. 2. CONFIGURE ARCHIVELOG DELETION POLICY TO NONE. Because CONNECT CATALOG is not run at the RMAN prompt. This example connects to the target database prod1 without specifying catalog options. CONFIGURE ARCHIVELOG BACKUP COPIES FOR DEVICE TYPE DISK TO 1.rmbk’. CONFIGURE BACKUP OPTIMIZATION OFF. Registering the target database in the recovery catalog from RMAN prompt.R030 – Oracle Database Notes Version 1. CONFIGURE SNAPSHOT CONTROLFILE NAME TO ‘/oraeng/app/oracle/product/10. CONFIGURE DEFAULT DEVICE TYPE TO DISK. To set parameter for automatic backup format for the data files RMAN> CONFIGURE CHANNEL 1 DEVICE TYPE DISK FORMAT ‘/disk2/oradata/DEMO/RMAN/%U. Example to make a connection to the target database and recovery catalog database: $ rman target sys/sys_pwd@prod1 catalog rman/rman ‘prod1’ is the alias name for the target database. 6. RMAN> SHOW ALL. RMAN configuration parameters are: CONFIGURE RETENTION POLICY TO REDUNDANCY 1. RMAN> REGISTER DATABASE.f’.0 Page 98/135 Date: 29.08. This example connects to the target database prod1 without a recovery catalog: $ rman TARGET SYS/sys_pwd@prod1 NOCATALOG. CONFIGURE ENCRYPTION FOR DATABASE ON. CONFIGURE CONTROLFILE AUTOBACKUP OFF. (shows all the configuration parameters) 5.2. RMAN> LIST INCARNATION OF DATABASE. CONFIGURE MAXSETSIZE TO UNLIMITED. 3.2007 Example: 1. CONFIGURE DEVIDE TYPE DISK PARALLELISM 1.0/dbs/snapof_ftde. Catalog maintenance commands are executed outside of a run command as follows: $ rman target sys/sys_pwd@prod1 catalog rman/rman RMAN> RESYNC CATALOG. 4.

rcv: $ rman TARGET SYS/sys_pwd@prod1 CATALOG rman/rman@rcat [@’/oracle/dbs/b_whole_10. This example connects to the target database prod1 and the recovery database rcat.rcv’ (or) cmdfile=/oracle/dbs/b_whole_10.08.dbf’. 9. RESTORE and ALLOCATE can be executed within a run command 11. Note: Here ‘2’.rcv] The contents in b_whole_10.dbf’. Using RMAN perform a copy for a datafile: $ rman target sys/<password>@acct catalog rman/rman RMAN> COPY DATAFILE 2 TO ‘/disk6/oradata/ACCT/RMAN/user1.f APPEND 10. is the file_id from the dba_data_files # Commands such as BACKUP.2007 8. .R030 – Oracle Database Notes Version 1. This example connects to the target database prod1 without a recovery catalog and then specifies that RMAN should append messages to the message log: $ rman TARGET sys/sys_pwd@prod1 NOCATALOG LOG=$ORACLE_HOME/dbs/log/msglog.0 Page 99/135 Date: 29. This example deletes all archived redo logs older than two weeks RMAN> DELETE ARCHIVELOG ALL UNTIL TIME ‘SYSDATE-14’. and then runs the command file b_whole_10.rcv file are: # backup database to ‘/disk6/oradata/ACCT/RMAN/user1.

SET BACKUP COPES = 4. Each connection initiates an Oracle server session on the target or auxiliary instance: this server session performs the work of backing up.1 Allocate Channel To manually allocate a channel. ‘/disk3/bp/%U’. you can specify the SET BACKUP COPIES command. } Example 2 When creating multiple copies of a backup set. ‘/disk2/sv/%U’. which is a connection between RMAN and a database instance. or recovering backup sets and copies. BACKUP DATAFILE 1 FORMAT ‘/disk1/bp/%U’.2. RESTORE. or RECOVER) or one image copy at a time (for COPY).08. RMAN automatically releases the channel at the end of the job. The following example generates a single backup of the database. Each channel operates on one backup set at a time (for BACKUP. Example 1 This command allocates a tape channel for a whole database backup: RMAN> RUN { ALLOCATE CHANNEL dev1 DEVICE TYPE sbt. } .2007 25. and then creates four identical backups of datafile 1 to four file systems: RMAN> RUN { ALLOCATE CHANNEL dev1 DEVICE TYPE DISK MAXPIECESIZE 2M.2 RMAN Commands 25.0 Page 100/135 Date: 29. ‘/dsk3/sv/%U’. restoring. BACKUP DATABASE. BACKUP DATABASE.R030 – Oracle Database Notes Version 1.

DATAFILECOPY ‘filename’ Specifies the file names of one or more datafile image copies. or DATABASE. The server session does not skip blocks when backing up archived redo logs or control files. you must set one of following parameters: DATAFILE.2007 25.R030 – Oracle Database Notes Version 1. level 1 or level 0 backup. FULL Copies all blocks into the backup set. BACKUPSET Backs up either ALL backup sets or backup sets specified by primary_key or completion time. For example. The backup set is the smallest unit of a backup. Each backup set contains at lest one backup piece. skipping only datafile blocks that have never been used. CUMULATIVE Copies the data blocks used since the most recent backup at level n-1 or lower. . in which is a physical file containing the backed up data. or backup set. specify MAXSETSIZE = 3M. CHANNEL channel_id Specifies the case-sensitive name of a channel to use when creating backup sets. You cannot backup from tape to tape or from tape to disk: only from disk to disk or disk to tape. in a level 2 backup RMAN backs up all blocks used since the most recent level 2. For example. TABLESPACE tablespace_name Specifies the names of one ore more tablespaces. RMAN backs up all datafiles that are currently part of the tablespaces. RMAN does not support incremental backups of control files.2. datafile (current or copy). DATABASE Specifies datafiles in the current database. When performing a backup. INCREMENTAL LEVEL = integer Copies only those data blocks that have changed since the last incremental integer backup. A full backup has no effect on subsequent incremental backups. in a cumulative level 2 backup RMAN backs up all blocks used since the most recent level 1 or level 0 backup. specify the files that you want to backup. where n is an integer from 1 to 4. RMAN makes full backups by default if neither FULL nor INCREMENTAL is specified. then in the backup Spec clause.2 BACKUP To backup a database. archived log. Use any name that is meaningful. for example ch1 or dev1. DATAFILECOPY. which are RMAN-specific logical structures. megabytes (M). control file (current or copy). tablespace. kilobytes (K). CURRENT CONTROLFILE Specifies the current controlfile. You can backup a target or standby database. RMAN puts the input files into one or more backup sets. TABLESPACE. archived redo logs. where integer is any integer from 1 to 4. This type of incremental backup is called a differential backup to distinguish it from a cumulative backup.0 Page 101/135 Date: 29. and gigabytes (G). MAXSETSIZE = integer Specifies a maximum size for a backup set in bytes (default). specify the INCLUDE CURRENT CONTROLFILE clause. Use this parameter in conjunction with the DEVICE TYPE sbt clause to backup all backups on disk to tape. DATAFILE Specifies a list of one or more datafiles. or backup sets.08. If you specify INCREMENTAL. so it is not considered a part of the incremental backup strategy. To include the current controlfile in the backup set. Thus. to limit a backup set to 3 MB. RMAN only records backup sets in the repository that Complete successfully.

. If SINCE TIME is not specified. INCLUDE CURRENT CONTROLFILE DELETE INPUT FORMAT Create a snapshot of the current control file and places it into each backup set produced by this clause.R030 – Oracle Database Notes Version 1. and day in this format: YYYYMMDD Specifies an 8-character name constituted by compressed representations of the backup set number and the time the backup set was created Specifies a convenient shorthand for %u_%p_%c that guarantees uniqueness in generated backup filenames Specifies the year in this format: YYYY Specifies the ‘%’ character.2007 FILESPERSET = integer NOT BACKED UP DEVICE TYPE Specifies the maximum number of input files in each backup set. RMAN stores the backup pieces in a port-specific directory ($ORACLE_HOME/dbs on Unix). Specify this option only when backing up archived logs. If you do not Specify the FORMAT parameter. which is a 4-byte value derived as the number of seconds elapsed since a fixed reference time Specifies the year. If you set FILEPERSET = n. SINCE TIME = ‘ date_string’ Specifies the date after which RMAN should backup files that have no backups. Backs up only those files (of the files specified on the command) that RMAN has not backed up since the specified time. Allocates automatic channels for the specified device type only. year and sequence into a unique and repeatable generated name Specifies the month in the Gregorian calendar in format MM Specifies the name of the database. datafile copies. or a SQL date expression such as ‘SYSDATE-1’. The date_string is either a data in the current NLS_DATE_FORMAT.0 Page 102/135 Date: 29. BACKUP DEVICE TYPE DISK DATABASE. month. day. month. %c %d %D %F %M %n %p %s %t %T %u %U %Y %% Specifies the copy number of the backup piece within a set of duplexed backup pieces Specifies the name of the database Specifies the current day of the month from the Gregorian calendar in format DD Combines the DBID. then only those files that have never been backed up will be backed up. Specifies a filename to use for the backup piece. then RMAN never includes more than n files in a backup set. or backup sets.08. Deletes the input files upon successful creation of the backup set. For example %%Y translates to string %Y. padded on the right with x characters to a total length of eight characters Specifies the piece number within the backup set Specifies the backup set number Specifies the backup set time stamp.

0 Page 103/135 Date: 29. ALLOCATE CHANNEL dev2 DEVICE TYPE DISK FORMAT ‘/FS2/%U’. Performing a Cumulative Incremental Backup This example backs up all blocks changes in the database since the most recent level 0 or level 1 backup: BACKUP INCREMENTAL LEVEL 2 CUMULATIVE SKIP INACCESSIBLE DATABASE. you execute this command to backup older backups created more than two weeks ago to tape and then delete the input backup pieces: BACKUP DEVICE TYPE sbt BACKUPSET CRATE BEFORE ‘SYSDATE-14’ DELETE INPUT. BACKUP DATABASE. 4.2007 Examples: 1. Specifying DEVICE TYPE on the BACKUP command This example configures DISK as the default device type. then backs up archived logs to tape: CONFIGURE DEFAULT DEVICE TYPE TO DISK. 6. Backing up backup sets to tape In this example. sales1. You do not want backup sets to exist on disk and tape simultaneously. 2. sales2. BACKUP DEVICE TYPE sbt ARCHIVELOG ALL. BACKUP (TABLESPACE SYSTEM.15). BACKUP CURRENT CONTROLFILE.14. 5.R030 – Oracle Database Notes Version 1. } 3. Hence. . sales3 FILEPERSET 20) (DATAFILE 12.08. you want to keep recent backup sets on disk and older backup sets on tape. Backing up tablespaces and data files This command uses two backup Spec clauses to backup tablespaces and datafiles and let RMAN perform automatic parallelization of the backup: RUN { ALLOCATE CHANNEL dev1 DEVICE TYPE DISK FORMAT ‘/fs1/%U’. Backing up multiples copies of archived logs and deleting the input BACKUP ARCHIVELOG LIKE ‘/arch/dest%’ DELETE ALL INPUT. Backing up a database This command backups the database to the tape and then backs up the control file that contains the record of the database backup.

To restore the control file to its default location enter the following: STARTUP NOMOUNT. } . BACKUP ARCHIVELOG SEQUENCE BETWEEN 288 AND 301 THREAD 1 # Delete original archived redo logs after backup completes DELETE INPUT. RUN { ALLOCATE CHANNEL dev1 DEVICE TYPE sbt. takes a whole database backup. then opens the database. BACKUP DATABASE UNTIL ‘SYSDATE+365’ NOLOGS. This example backups only archived logs 1372 of thread 1 and then deletes it. This examples restores backup archived redo log files from tape to the fall within a range of SCNs: RESTORE ARCHIVELOG SCN BETWEEN 500 AND 700. RESTORE CONTROLFILE. At the RMAN prompt enter STARTUP MOUNT. 9. } 8.08. open the database ALTER DATABASE OPEN. the logs are not deleted. Creating a long-term backup This example creates a consistent backup of the database that is exempt from the retention policy and tells RMAN to keep the backup for the next year. 14.2007 7. Backing up files with no recent backups This example backs up all the database files and archived logs that have not been backup in the last month: BACKUP DATABASE. # Now that the backup is complete. 10. BACKUP CHECK LOGICAL DATAFILE 3. This example mounts the database. BACKUP DATABASE.R030 – Oracle Database Notes Version 1. 13. This example backs up all archived logs from sequence 288 to sequence 301 on thread 1 and deletes the archived logs after the backup is complete. BACKUP ARCHIVELOG SEQUENCE 1372 DELETE INPUT.0 Page 104/135 Date: 29. If the backup fails. 12. STARTUP MOUNT. ALTER DATABASE MOUNT. RUN { SET MAXCORRUPT FOR DATAFILE 3 TO 2. 11. Checking for Corruption This example backups datafile 3 and specifies that no more than two blocks with corruption should be tolerated. but not to keep the archived logs necessary to recover it: SHUTDOWN. ARCHIVELOG ALL NOT BACKED UP SINCE TIME ‘SYSDATE-31’.

RESTORE DATABASE does not automatically include the control file. control files. Store scripts provide a common repository for frequently execute collections of RMAN commands. Note: In Oracle 9i.2. CONTROLFILE Restores the current control file to the default location and automatically replicates it to all CONTROL_FILES locations in the initialization parameter file. The RESTORE commands restores full backups. you restore when a media failure has damaged a current datafile. control file.2. Creating a script example This creates a script called b_whole_10 that backs up the database and archived redo logs. } RUN { EXECUTE script b_whole_10}. incremental backups (level 0 only). RMAN restores files to their default location. Unlike BACKUP DATABAE. run the script with @. or archived log or prior to performing a point-in-time recovery.4 Delete Script To delete a stored script from the recovery catalog Deleting a script – this deletes the script b_whole_10: DELETE SCRIPT b_whole_10. unlike in previous RMAN releases. Any command that is legal within a RUN command is permitted in the stored script. By default. 25. then executes it: CREATE script b_whole_10 { ALLOCATE CHANNEL d1 DEVICE TYPE sbt. 25. and archived redo logs. The default location is first filename specified in the CONTROL_FILES parameter. The script is not executed immediately. Because the RECOVER command automatically restores archived logs as needed. RMAN by default does not restore a datafile if the file is in the correct place and its header contains the expected data (RMAN does not scan the datafile body for corrupt blocks). BACKUP INCREMENTAL LEVEL 0 TAG b_whole_10 DATABASE PLUS ARCHIVELOG. TABLESPACE ‘tablespace_name’ Restores all data files in the specified tablespaces. When you perform a restore operation by using a backup control file and use a recovery catalog. RMAN automatically adjusts the control file to reflect the structure of the restored database.2007 25. .3 Create Script To create a script and store it in the recovery catalog for future reference.0 Page 105/135 Date: 29.R030 – Oracle Database Notes Version 1.08. DATAFILE datafileSpec Restores the datafiles specified by filename or absolute datafile number. Examples: 1. you must issue an additional RESTORE command to perform this operation.5 RESTORE To restore files from backups or image copies. you should seldom need to restore logs manually. or copies of datafiles. DATABASE Restores all data files in the database except those that are offline or read-only.2. Typically.

Restoring archived redo logs to new location This restores all archived redo logs to the /oracle/temp_restore directory: RUN { SET ARCHIVELOG DESTINATION TO ‘/oracle/temp_restore’. replicates it to all multiplexed locations. RUN { STARTUP FORCE NOMOUNT. RUN { ALLOCATE CHANNEL c1 DEVICE TYPE sbt. RESTORE ARCHIVELOG ALL. Restoring a tablespace This takes a tablespace offline.08. ALTER DATABASE MOUNT. } 3. Enter the following: STARTUP NOMOUNT. and mounts the database. This example restores archived redo log files from tape that fall within a range of SCNs: RESTORE ARCHIVELOG SCN BETWEEN 500 AND 700.R030 – Oracle Database Notes Version 1. Restoring the database using a backup control file This example restores the control file.2007 Examples: 1. . and then mounts the control file in order to restore the database.0 Page 106/135 Date: 29. To restore the controlfile to its default location. RESTORE TABLESPACE tbs_1. SQL> “ALTER TABLESPACE TBS_1 ONLINE”. STARTUP NOMOUNT. restores it. } 4. ALTER DATABASE MOUNT. RESTORE CONTROLFILE. 2: Restoring the control file This restores the control file to its default location. and then performs media recovery: SQL> “ALTER DATABASE TBS_1 OFFLINE IMMEDIATE”. ALTER DATABASE MOUNT. } 5. 6. RECOVER TABLESPACE tbs_1. replicates it to all control file locations specified in the parameter file. RESTORE DATABASE. RESTORE CONTROLFILE. RESTORE CONTROLFILE.

} . RMAN first looks for the original archived logs or image copies. and brings it back online. DEVICE TYPE deviceSpecifier Allocates automatic channels for the specified device type only. Recovering a Tablespace in an Open Database The following example takes tbs_1 offline. RECOVER TABLESPACE tbs_1 DELETE ARCHIVELOG. if you configure automatic disk and tape channels. Specifies that the entire database is to be recovered. SQL “ALTER TABLESPACE tbs_1 ONLINE”. and issue REVOER… DEVICETYPE DISK. SCN.08. Recovering datafiles restored to new locations The following example uses the pre-configured disk channel and manually allocates one media management channel to use datafile copies on disk and backups on tape. SQL “ALTER TABLESPACE tbs_1 OFFLINE IMMEDIATE”. SQL “ALTER TABLESPACE tbs_1 OFFLINE IMMEDIATE”.6 RECOVER To apply redo logs or incremental backups to one ore more restored datafiles in order to update them to a specified time. 2. DATABASE TABLESPACE ‘tablespace_name’ DATAFILE datafileSpec Examples: 1. RECOVER TABLESPACE tbs_1.0 Page 107/135 Date: 29. and if none are available. then RMAN allocates only disk channels. it recovers changes to objects created with the NOLOGGING option. RESTORE TABLESPACE_1. or log sequence number for termination of the RECOVER command. RMAN uses online redo records and restores backup sets of archived redo logs as needed to perform he media recovery. then RMAN automatically chooses the one covering the longest period of time. and restores one of the tablespace tbs_1 to a different location: RUN { ALLOCATE CHANNEL dev2 DEVICE TYPE sbt. then it always chooses the incremental backup. SQL “ALTER TABLESPACE tbs_1 ONLINE”. If RMAN has a choice between applying an incremental backup or applying redo.f’ TO ‘disk9/oracle/tbs11. Note: When RMAN applies incremental backups. Note that RMAN can apply incremental backups to restored files that were not created as part of an incremental backup. You must open the database with the RESETLOGS option after incomplete recovery. RMAN performs complete recovery. For example. If overlapping levels of incremental backup are available. Until Clause specifies a non-current time. Applying archived redo logs to datafiles does not recover these changes.2007 25. uses automatic channels to restore and recover it (deleting the logs that it restored from tape). RESTORE TABLESPACE tbs_1. Specifies tablespaces by tablespace name. then it restores backups. Specify datafiles by either filename (by using a quoted string) or absolute datafile number (by using an integer). Specifies a list of one or more datafiles to recover. SET NEWNAME FOR DATAFILE ‘disk7/oracle/tbs11.2. Unless you specify an Until clause.R030 – Oracle Database Notes Version 1. SWITCH DATAFILE ALL.f’.

you need to recover the database using available archived redo logs. ALTER DATABASE MOUNT.f’. } . RESTORE CONTROLFILE TO ‘/tmp/cf.08.f’. RUN { SET UNTIL TIME ‘Jun 18 2004 16:32:36’. REPLICATE CONTROLFILE FROM ‘/tmp/cf.f’’. Because you do not have incremental backups. } 4.tmp’. RUN { SET UNTIL SEQUENCE 1234 THREAD 1. RESTORE CONTROLFILE TO ‘$ORACLE_HOME/dbs/cf1. } 5.f’ SIZE 10M TEMPORARY”. RESTORE DATABASE. manually replicate the control file # RMAN replicates automatically when no destination is specified REPLICATE CONTROL FILE FROM ‘/vobs/oracle/dbs/cf1.2007 3. RECOVER DATABASE SKIP FOREVER TABLESPACE temp1.tmp’. readonly1. ALSTER DATABASE OPEN RESETLOGS. REPLICATE CONTROLFILE FROM ‘$ORACLE_HOME/dbs/cf1. RESTORE DATABASE SKIP TABLESPACE temp1. Performing Incomplete Recovery by Using a Backup Control file Assume that both the database and archived redo log 1234 were lost due to a disk crash. # Because you specified a restore destination. Performing Incomplete Recovery Until a Log Sequence Number This example assumes that log sequence 1234 was lost due to a disk crash and the database needs to be recovered by using available archived redo logs. ALTER DATABASE MOUNT.R030 – Oracle Database Notes Version 1. RUN { SET UNTIL SEQUENCE 1234 THREAD 1. SQL “DROP TABLESPACE temp1”. You do not need to restore tablespace readonly1 because it has not changed since log 1234. # recovers through log 1233 SQL “ALTER DATABASE OPEN RESETLOGS”.f’. STARTUP FORCE MOUNT. #Recover database until log SEQUENCE 1234 RESTORE CONTROLFILE TO ‘/vobs/orable/dbs/cf1. RECOVER DATABASE. SQL “CREATE TABLESPACE temp1 DATAFILE ‘/vobs/oracle/dbs/temp1. Replicating a restored control file This restores a control file to a temporary location and replicates it manually STARTUP NOMOUNT.0 Page 108/135 Date: 29.

# recovers through SCN 999 SQL “ALTER DATABASE OPEN RESETLOGS”.0 Page 109/135 Date: 29. Examples: Showing Channel Configurations . Specify the channel name with the same identifier used in the ALLOCATE CHANNEL command. MAXSETSIZE. 1. . DEVICE TYPE.08. RESTORE DATABASE. RMAN then makes three identical backups of datafiles 5 and 6 to tape with channel ch2 and then releases it: RUN { SET BACKUP COPIES = 3. Performing Incomplete Recovery to a specified SCN This example recovers the database until a specified SCN: STARTUP MOUNT.2. } 25.8 Show To display the current CONFIGURE command settings. DEFAULT DEVICE TYPE.This example shows commands relevant for displaying automatic channel configurations: SHOW SHOW SHOW SHOW SHOW CHANNEL. RELEASE CHANNEL ch1. RECOVER DATABASE UNTIL SCN 1000. Example. The output of SHOW consists of the CONFIGURE commands used to set the configuration. This command is optional because RMAN automatically releases all channels allocated when the RUN command terminates.2. ALLOCATE CHANNEL ch2 DEVICE TYPE sbt MAXPIECESIZE = 3000. RMAN default configurations are suffixed with #defaullt. then releases it.6.2007 6. RUN { ALLOCATE CHANNEL ch1 TYPE sbt. ALLOCATE CHANNEL ch1 DEVICE TYPE sbt FILESPERSET = 2 RATE = 1000.R030 – Oracle Database Notes Version 1. Releasing a channel – This example makes three identical backup sets of datafiles 1 to 4 to tape with channel ch1.4.3. BACKUP DATAFILE 5.2. BACKUP CHANNEL ch1 DATAFILE 1. } 25. ALL.7 Release Channel To release a channel while maintaining the connection to the target database instance.

If change tracking is enabled. you should resynchronize your recovery catalog at intervals less than the CONTROL_FILE_RECORD_KEEP_TIME setting. Note: The maximum size of the control file is port specific. that file’s STATUS in V$BACKUP reflects the backup status of the older version of the file. A restored or re-created controlfile does not contain the information Oracle needs to fill V$BACKUP accurately. “ACTIVE” indicates that the file is marked as currently being backed-up.3. Note: V$BACKUP is not useful if the controlfile currently in use is restored backup or new controlfile created since the media failure occurred.2.1 Enabling and Disabling Change Tracking You can enable or disable change tracking when the database is open.log’. 2. . this view might contain misleading information on restored files. because after this number of days. are candidates for overwrites by newer information.2007 25.0 Page 110/135 Date: 29. RMAN uses the change-tracking file to identify changed blocks for incremental backups. There is a new background process responsible for writing data to the block change-tracking file. In the STATUS column. 1. 25. if you have not resynchronized.9 Determining Datafile Backup Status To view the backup status of a datafile. and information has been overwritten. you can use the dictionary table V$BACKUP. not the most current version. which is called Blocks Change Writer (CTWR). This table lists all online files and gives their backup status. the larger the control file will be.3 Improving Incremental Backup Performance: Change Tracking RMAN’s change tracking feature for incremental backups improves incremental backup performance by recording changed blocks in each datafile in a change-tracking file. 25. Entries older than the number of days. You can enable this tracking mechanism by issuing the following command: SQL> ALTER DATABASE ENABLE BLOCK CHANGE TRACKING USING FILE ‘/rman_bkups/change. 25.08. this information can not be propagated to the recovery catalog. use this SQL statement: SQL> ALTER DATABASE DISABLE BLOCK CHANGE TRACKING. This command creates a binary file called /rman_bkups/change. depending on the number of: • Backups performed • Archive logs created • Days (minimum number) this information is stored in the control file You can specify the minimum number of days this information is kept in the control file using the parameters CONTROL_FILE_RECORD_KEEP_TIME. To alter the change tracking setting. See your OS specific Oracle documentation.2. you must use SQL*Plus to connect to the target database with the administrator privileges. Also. At a minimum. if you have restored a backup of a file.log for tracking purposes. The larger the CONTROL_FILE_RECORD_KEEP_TIME settings is.R030 – Oracle Database Notes Version 1. To disable change tracking. the information in the controlfile will be overwritten with the most recently created information. Thus. thus avoiding the need to scan every block in the datafile.10 Propagating Information from the Control File The size of the target database’s control file will grow. “INACTIVE” indicates that the file is not currently being backed-up.

To see whether change tracking is currently enabled. Certain checks are performed when attempting to create an incremental backup at level greater than 0.4.2007 3. 25. A full backup copies all blocks into the backup set. Tuesday: Take an incremental physical backup $ rman target sys/<password>@acct catalog rman/rman RMAN> BACKUP INCREMENTAL LEVEL 2 DATABASE.4. The following two backup types are available. Wednesday: Take a cumulative physical backup $ rman target sys/<password>@acct catalog rman/rman RMAN> BACKUP INCREMENTAL LEVEL 1 DATABASE. but the level 0 backup is considered to be part of the incremental strategy.0 Page 111/135 Date: 29.2 Incremental An incremental backup at a level greater than 0 copies only those blocks that changed since the last incremental backup. you can query V$BLOCK_CHANGE_TRACKING.R030 – Oracle Database Notes Version 1. No blocks are skipped when backing up archivelogs or control files.4. 25. . 25.08.1 Physical Incremental Backup (On Sunday) Sunday: Take a complete physical backup $ rman target sys/<password>@acct catalog rman/rman RMAN> BACKUP INCREMENTAL LEVEL 0 DATABASE. 25. status FROM V$BLOCK_CHANGE_TRACKING. Backing up full database (including current control file) $ rman target sys/<password>@acct catalog rman/rman RMAN> BACKUP DATABASE INCLUDE CURRENT CONTROLFILE.4. and is not considered to be part of the incremental backup strategy. An incremental backup at level 0 is identical in content to a full backup.4 Types of Recovery Manager Backups The backup_type applies to all backup_specifications in the backup_specification_list. Monday: Take an incremental physical backup $ rman target sys/<password>@acct catalog rman/rman RMAN> BACKUP INCREMENTAL LEVEL 2 DATABASE. skipping only datafile blocks that have never been used.3 Incremental Backup Sets An incremental backup is a backup of one or more datafiles that contains only those blocks that have been modified since a previous backup at the same or lower level. SQL> SELECT filename. A full backup has no effect on subsequent incremental backups.1 Full This is the default if neither full or incremental is specified. you can query from SQL*Plus.3. 25. unused blocks are not written out.

$ rman TARGET SYS/oracle@test1 CATALOG test1/test1@catdb RMAN> DROP DATABASE INCLUDING BACKUPS.7 Image Copies An image copy is a bit-for-bit identical copy of a database file. archive redo logs and backup pieces. RMAN> BACKUP AS COMPRESSED BACKUPSET TABLESPACE users2. RMAN automatically determine which datafiles belong to each tablespace and performs the image copy for each. then you must use the DROP DATABASE INCLUDING BACKUPS form of the command.8.5 Compressed Backups RMAN has been enhanced to provide binary compression for backup sets. RMAN> CONFIGURE DEVICE TYEP SBT BACKUP TYPE TO COMRPESSED BACKUPSET. In many cases. the binary compression algorithm used by RMAN is optimized for use with oracle datafiles. COPY command is deprecated in Oracle 10g’s version. Example: In this example. control files and control file copies. copies and backups belonging to the database.8 Drop Database in RMAN Deletes the target database and if RMAN is connected to a recovery catalog. RMAN> CONFIGURE DEVICE TYPE DISK BACKUP TYPE TO COMPRESSED BACKUPSET. the COPY command made image copies of datafiles. making it a better alternative than using operating system file system or tape device compression scheme. you connect to test1 database and deletes the datafiles as well as all backup copies and archived logs associated with the database. 25.1 • • • . Using BACKUP AS COPY command to make an image copy of both SYSTEM and SYSAUX tablespaces. reducing the amount of disk space required to make a backup. sysaux.R030 – Oracle Database Notes Version 1.6 Configuring Compressed Backup sets as Default for Tape or Disk It’s easy to make compression the default for disk or tape using the CONFIGURE command. RMAN removes all datafiles. un-register it.0 Page 112/135 Date: 29. and control files belonging to the target database. This example backups the entire database and archived logs. online logs. In previous versions of RMAN. the additional overhead required to compress the backup set is offset by the reduced I/O load when writing the backup set to disk. 25. 25. In addition. which must either mounted exclusive and not open If you want RMAN to delete archived logs. 25.08. RMAN creates image copies when the AS COPY option is used with the BACKUP command. Restrictions Execute this command only at the RMAN prompt You must be connected to the target database.2007 25. producing compressed backup sets: RMAN> BACKUP AS COMPRESSED BACKUPSET DATABASE PLUS ARCHIVELOG. RMAN can create image copies of datafiles and datafile copies. RMAN> BACKUP AS COPY TABLESPACE system.

1 The Flash Recovery Area The flash recovery area feature let’s you setup a location on disk where the database can create and manage a variety of backup and recovery-related files. At the beginning of a backup strategy. you must set the two-initialization parameters DB_RECOVERY_FILE_DEST_SIZE.10 RMAN Recovery Catalog Views Recovery Catalog Views RC_ARCHIVED_LOG RC_BACKUP_CONTROLFILE RC_BACKUP_DATAFILE RC_BACKUP_PIECE RC_BACKUP_REDOLOG RC_BACKUP_SET RC_DATABASE RC_DATAFILE RC_RMAN_CONFIGURATION RC_LOG_HISTORY Corresponding V$ Views V$ARCHIVED_LOG V$BACKUP_DATAFILE V$BACKUP_DATAFILE V$BACKUP_PIECE V$BACKUP_REDOLOG V$BACKUP_SET V$DATABASE V$DATAFILE V$RMAN_CONFIGURATION V$LOG_HISTORY 26 FLASHBACK TECHNOLOGY 26. retaining them as long as they are needed for restore and recovery activities. During restore and recovery of the database. with the same results as restoring the database from a full backup taken at the SCN of the most recently applied incremental level 1 backup. or maximum space to use for flash recovery area for this database and DB_RECOVERY_FILE_DEST. disk quota. and deleting them when they are no longer needed to restore your database and space is needed for some other backup and recovery related purpose.1 • • • • Files that can be stored in the Flash Recovery Area Online redo logs Archived redo logs Control files RMAN’s own working files for backup and restore operations 26. . while providing the same recovery advantages as an image copy backups. RMAN creates an image copy backup of the datafile. RMAN can restore from this incrementally updated copy and then apply changes from the redo logs. such as daily. which specifies the location of the flash recovery area. at regular intervals. A backup strategy based on incrementally updated backups can help minimize time required for media recovery of your database.1. 26. space in use and total number of files in the flash recovery area SQL> SELECT * FROM V$RECOVERY_FILE_DEST.9 Incrementally Updated Backups: Rolling Forward Image Copy Backups Oracle’s Incrementally Updated Backups feature lets you avoid the overhead of taking full image copy backup of datafiles. level 1 incremental backups are taken and applied to the image copy backup.0 Page 113/135 Date: 29.2007 25. 26. 25.1 Using the V$RECOVERY_FILE_DEST View You can query the V$RECOVERY_FILE_DEST view to find out the current location. With Automatic Disk-Based Backup and Recovery.1.R030 – Oracle Database Notes Version 1. Use of the flash recovery is strongly recommended. you can create a flash recovery area which automates management of backup-related files. Then.08. which specifies the disk quota. rolling it forward to the point in time when the level 1 incremental was created.2.1.2 Initialization parameters for the Flash Recovery Area To enable the flash recovery area. Using a flash recovery area simplifies the ongoing administration of your database by automatically naming files.

triggers and constraints. and you know that at 9:30am. For example. end time. as they would have appeared at that time. Example: If. that employee’s data was correctly stored in the database. and without taking any part of the database offline. . ‘yyyy-mm-dd h:mi:ss’) WHERE name = ‘john’. and not requiring the DBA to find and restore applicationspecific properties. April 4. Oracle Flashback Transaction Query lets you view changes made by a single transaction. for instance. the following query retrieves the state of the employee record for ‘JOHN’ at 9:30am. In data recovery context. Using Flashback Table causes the contents of one or more individual tables to revert to their state at some past SCN or time. including start time. you could query the contents of the table as of a time before the deletion to find out what data had been lost.2007 26. or by all the transactions during a period of time. This feature can be used both to recover lost data values and to audit changes to the tables queried. re-insert the lost data in the database. 26. with minimal impact to the running database. This missing row is re-created with its previous contents. if appropriate. Step 2: SQL> INSERT INTO employee (SELECT * FROM employee AS OF TIMESTAMP TO_TIMESTAMP(‘2003-04-04 09:30:00’.0 Page 114/135 Date: 29. 2003: Step 1: SQL> SELECT * FROM employee AS OF TIMESTAMP TO_TIMESTAMP(‘2003-04-04 09:30:00’. and.08. an employee ‘JOHN’ had been deleted from your EMPLOYEE table. Querying the past state of the table is achieved using the AS OF clause of the SELECT statement. it is useful to be able to query the state of a table at a previous time. Flashback Table restores tables while automatically maintaining associated attributes such as current indexes. viewing results.3 Oracle Flashback Table Oracle Flashback Table provides the DBA the ability to recover a table or set of tables to a specified point in time in the past very quickly. you discover that at 12:30pm. ‘yyyy-mm-dd h:mi:ss’) WHERE name = ‘john’). easily. You can also retrieve metadata about the differing versions of the rows.2 Oracle Flashback Query Oracle Flashback Query feature lets you specify a target time and then run queries against your database. To recovery from an unwanted change like an erroneous update to a table. Oracle Flashback Version Query lets you view all the versions of all the rows that ever existed in one or more tables in a specified time interval.R030 – Oracle Database Notes Version 1. In many cases Flashback Table eliminates the need to perform more complicated point-in-time recovery operations. a user could choose a target time before the error run a query to retrieve the contents of the lost rows. operation and transaction id of the transaction that created the version.

Table Dropped If you are sure that you will not want to recover a table later. along with its dependent objects in the recycle bin so that they can be recovered later. LOB segments and LOB index segments. Instead. You do not have to restore any data from backups. by using the PURGE option of the DROP TABLE statement as shown in this example: SQL> DROP TABLE employee_demo PURGE.08. you must also understand how the recycle bin works. you can drop it immediately and permanently. such as point-in-time recovery. instead of placing it in the recycle bin. which are stored in the recycle bin includes indexes.0 Page 115/135 Date: 29. You can also specify the target point-in-time for the FLASHBACK TABLE operation using an SCN: SQL> FLASHBACK TABLE employee TO SCN 123456. the database does not immediately remove the space associated with the table. 26. 26. • Performing Flashback Table: . and does not lead to any loss of recent transactions or downtime.4. It can be used to recover after the accidental drop of a table. When you drop a table. The table and its dependent objects will remain in the recycle bin until they are purged from the recycle bin. When a table is dropped. and the rest of your database remains available while the Flashback Table operation is being performed.2007 Flashback Table uses information in the undo tablespace to restore the table. constraints. and how to access and manage its contents. the database will store the table. Dependent objects. • The employee table is restored to its state when the database was at the time specified by the timestamp. To understand how to use Oracle Flashback Drop. ‘YYYY-MM-DD HH24:MI:SS’). • Row movement must be enabled on the table for which you are issuing the FLASHBACK TABLE statement. nested tables. The Flashback Drop operation recovers the table from the recycle bin.The following SQL*Plus statement performs a FLASHBACK TABLE operation on the table employee. SQL> FLASHBACK TABLE employee TO TIMESTAMP TO_TIMESTAMP(‘2003-04-04 09:30:00’. Flashback Drop is substantially faster than other recovery mechanism that can be used in this situation. For example.1 Recycle Bin The recycle bin is a logical container for all dropped tables and their dependent objects. the table is renamed and along with the associated objects. You can enable row movement with the following SQL statement: SQL> ALTER TABLE employee ENABLE ROW MOVEMENT.R030 – Oracle Database Notes Version 1. it is placed in the Recycle Bin of the database. . this statement places EMPLOYEE_DEMO table and its dependent objects in the recycle bin: SQL> DROP TABLE employee_demo.4 Oracle Flashback Drop – Undo a DROP TABLE Operation Oracle Flashback Drop reverses the effects of a DROP TABLE operation. triggers.

26. type FROM recyclebin. 2. To view the contents of the recycle bin. 26. 3. You can also use the recycle bin name of an object with PURGE TABLE. Once purged. changes its name back to and purges its entry from the recycle bin.3.int2_admin_emp. 26.0 Page 116/135 Date: 29. You can specify either the name of the table in the recycle bin or the original table name.int_admin_emp You can assign a new name to the restored table by specifying the RENAME TO clause: For example: SQL> FLASHBACK TABLE “bin$gk3lsj/3akk5hg3j2lkl5j3d==$0” TO BEFORE DROP RENAME TO hr. hr. use the USER_RECYCLEBIN and DBA_RECYCLEBIN views.4.1 PURGE TABLE – Purging a Table and Dependent Objects The PURGE TABLE command purges an individual table and all of its dependent objects from the recycle bin.4. This example shows the syntax. original_name. This example shows the required syntax: SQL> SELECT * FROM “BIN$KSD8DB9L345KLA==$0”.2 PURGE RECYCLE BIN – Purging all objects in the User’s Recycle Bin The PURGE RECYCLEBIN command purges the contents of the recycle bin for the currently logged-in user. .4.3.4. objects can no longer be retrieved from the bin using Flashback Drop. using the table’s original name: SQL> PURGE TABLE emp.3. To view only objects in the recycle bin. SQL> PURGE TABLE “BIN$KSD8DB9L345KLA==$0”. The following example restores BIN$gk3lsj/3akk5hg3j2lkl5j3d==$0 table.2 Performing Flashback Drop on Tables in the Recycle Bin Use the FLASHBACK TABLE … TO BEFORE DROP statement to recover objects from the recycle bin. 26. SQL> PURGE RECYCLEBIN. use the SQL*Plus command SHOW RECYCLE BIN.4.3 Viewing and Querying Objects in the Recycle Bin 1.3 Purging Objects from the Recycle Bin The PURGE command is used to permanently purge objects from the recycle bin.2007 26.08. SQL> SHOW RECYCLEBIN.R030 – Oracle Database Notes Version 1. This example uses the views to determine the original names of the dropped objects: SQL> SELECT object_name as recycle_name. SQL> FLASHBACK TABLE “bin$gk3lsj/3akk5hg3j2lkl5j3d==$0” TO BEFORE DROP.

as specified by time.5. Because FLASHBACK DATABASE does not require you to restore a backup. SQL> SELECT OLDEST_FLASHBACK_SCN. returning the database to (or to just before) target time. Start SQL*Plus and ensure that the database is mounted. Run the FLASHBACK DATABASE statement to return the database to a prior TIMESTAMP or SCN. and requires only limited application of redo compared to media recovery. Shutdown and start the database in Mount Mode SQL> SHUTDOWN SQL> STARTUP MOUNT 3. 2.0 Page 117/135 Date: 29. 2. Follow the process outlined here: 1. This value is in minutes. your current database files revert to their contents at a part time.5 Flashback Database Oracle Flashback Database provides a more efficient direct alternative to database point-in-time recovery. SQL> ALTER SYSTEM SET DB_FLASHBACK_RETENTION_TARGET=60. . The end product is much like the result of a database point-in-time recovery. set the DB_FLASHBACK_RETENTION_TARGET initialization parameter and issue the ALTER DATABASE FLASHBACK ON statement. but can be much faster because it does not require you to restore datafiles from backup. It is unlike the other flashback features in that it operates at a physical level. SCN or log sequence number. Set the DB_FLASHBACK_RETENTION_TARGET parameter to the desired value. Now the database can be opened for normal use. 26. 4. Flashback Database uses flashback logs to access past versions of data blocks.08. When you use Flashback Database. SQL> ALTER DATABASE OPEN. (or) SQL> FLASHBACK DATABASE TO TIMESTAMP (SYSDATE-1/24). Enable the Flashback Database feature for the whole database SQL> ALTER DATABASE FLASHBACK ON. The following SQL*Plus queries show you the latest and earliest SCN in the flashback window: SQL> SELECT CURRENT_SCN FROM V$DATABASE. it is usually much faster than incomplete recovery. 26.1 To Enable Flashback Database To enable Flashback Database. For example: SQL> FLASHBACK DATABASE TO SCN 4693. Performs a flashback database operation.5.R030 – Oracle Database Notes Version 1. OLDEST_FLASHBACK_TIME FROM V$FLASHBACK_DATABASE_LOG. Query the target database to determine the range of possible flashback SCNs. The value for this parameter is set to 60 minutes in this example.2 To perform the FLASHBACK DATABASE 1.2007 26. SQL> STARTUP MOUNT. as well as some information from the archived redo log. but not open. 3.

R030 – Oracle Database Notes Version 1. ‘YYYY-MM-DD HH24:MI:SI’).5. 26. open the database with Resetlogs option. Open the database to examine the results of the Flashback Database operation.The following command flash back the database to a particular SCN: RMAN> FLASHBACK DATABASE TO SCN 46963. Finally.0 Page 118/135 Date: 29. You can perform some queries to make sure you have recovered the data you need. FLASHBACK DATABASE to a specific Time: . SQL> ALTER DATABASE OPEN RESETLOGS. FLASHBACK DATABASE to a specific SCN: .08. .3 To Disable Flashback Database You can disable flashback logging for the entire database with this command SQL> ALTER DATABASE FLASHBACK OFF.2007 4.The following command uses SQL date conversion functions to specify the target time RMAN> FLASHBACK DATABASE TO TIMESTAMP(‘2003-03-11 16:00:00.

dname. delimited format and variable length records • Manipulate data files with SQL functions before inserting the data into database columns • Supports a wide range of data types including DATE. . sequential key values in specified columns • Use your operating system’s file or record management system to access data files • Load data from disk or tape • Provide thorough reporting capabilities so you can easily adjust and load all records. loading selected rows into each table • Combines multiple physical records into a single logical record. By default SQL*Loader requires the table to be empty before it inserts any records. INFILE specifies that data is found in the control file and not in an external file INTO TABLE is the table into which the data can be loaded into (dept).“ACCOUNTING”.”RESEARCH”. PACKED DECIMAL and ZONED DECIMAL • Load multiple tables during the same run. treats a single physical record as a multiple logical records • Generate unique. SQL*Loader can perform the following: • Load data from multiple data files of different types • Handle fixed-format. BINARY.0 Page 119/135 Date: 29. The control file contains the following DDL definitions: Example: $ vi case1.”CLEVELAND” :wq • • • • The control file starts with LOAD DATA statement. “SARATOGA” 10.08.’ OPTIONALLY ENCLOSED BY ‘ “ ‘ (deptno.R030 – Oracle Database Notes Version 1. loc) BEGINDATA 12.ctl LOAD DATA INFILE * INTO TABLE dept FIELDS TERMINATED BY ‘.2007 27 WORKING WITH SQL*LOADER SQL*Loader moves data from external flat files into Oracle database.

ctl log=case.ctl load data infile * into table dept fields teminated by ‘.log data=etc.dis discardmax=2 $sqlldr parfile=par.”SARATOGA” 10.file Case 1: Loads the data from the controlfile into the table dept $ vi case1.”INT’L”. FINANCE. CLEVELAND 11.”ACCOUNTING”.ctl log=case.log $ sqlldr control=case.dat userid=steeve/abc errors=40 load=2000 discard=abc.”ART”.log data=etc. loc) begin data 12.RESEARCH.R030 – Oracle Database Notes Version 1.ctl log=case1. “SALEM” 13. “BOSTON” 21.log .ctl log=case1.dat userid=steeve/abc errors=40 load=2000 discard=abc.PHILA 22.08. “SAN FRAN” :wq $ sqlldr = userid=scott/tiger control=case1.”SALES”. the command is: Syntax: $ sqlldr <options> The options are: userid controlfile log bad data discard discardmax skip load errors rows direct bindsize silent parfile Username and password Control file name Log file name Bad file name Data file name Discard file name No of discards to allow Number of logical records to skip (Default 0) Number of logical records to load (Default 0) Number of errors to allow (Default 0) Number of rows in conventional path Direct path data saves (Default 64 in conventional.”SALES”.0 Page 120/135 Date: 29.file – file with the parameters control=case.2007 To invoke SQL*Loader. all in direct) Size of conventional path bind array in bytes (system-dependent) Suppress messages during run Parameter file Examples: $ sqlldr userid=scott/manager control=case1. dname.dis discardmax=2 or $ vi par.’ optionally enclosed by ‘ “ ‘ (deptno. ROCHESTER 42.

“president”. Sequence function generates unique keys for loaded data. loadseq sequence (max. ename. Position (41:48) decimal external. hiredate date (20) “dd-month-yyyy”.”jones”.1312. 7782.0 Page 121/135 Date: 29.50 10 7839 King President 5500 10 7934 Miller Clerk 7782 920.ctl log=case3. comm.7698.”salesman”.00 300. sal position (32.17-NOV-1981.20-FEB-1981. “ optionally enclosed by ‘”” (empno..ctl log=case2.3123.7689.00. char terminated by ‘: ’.00 30 7654 Martin Salesman 7693 1312. job..dat’ INSERT Into table tmp (empno position (01:04) integer external. “clerk”.log .dat 7782 Clark Manager 7839 2572 .log Case 3: Adds the data into emp table using sequence function ..23-JAN-1982.dat to the table emp $ vi case2. “clark”.75.30:103 7654.09-JUN-1981.5500.”martin”.7839. mgr.30:103 $ sqlldr userid=scott/tiger control=case3.1400.2572.ctl LOAD DATA Infile ‘case2. 7839. SQL> alter table emp add (projno number. mgr position (27:30) integer external.300.”miller”.00 20 7566 Jones Manager 7839 1600.08.00 30 $ sqlldr userid=scott/tiger control=case2.39) decimal external..28-SEP-1981.10:102 7934.ctl load data infile * append into table emp fields terminated by “.50. deptno position (50:51) integer external) :wq $ vi case2.10:102 7566.00.”salesman”. comm. “manager”..R030 – Oracle Database Notes Version 1. projno.50 1400.2007 Case 2: Loads the data of case2.”allen”. sal. job position (17:25) char. loadseq number) $ vi case3.”manager”.. deptno. ename position (06:15) char.00.1)) begin data 7782.50.00.02-APR-1981.1600.10:101 7839 “king”.920.20:101 7499.

0 Page 122/135 Date: 29. Inserting negative numbers. comm position (41:48) decimal external. discardmax is used to specify a maximum number of discards and also rejecting records due to duplicate values in a unique index or due to invalid data. mgr position (27:30) integer external. deptno position (50:51) integer external. sal position (32:39) decimal external.dat *7782 clark manager 7839 2752.log Case 5: Explains how to use sqlldr to breakdown repeating groups in a flat file and load the data into normalized tables one record may generate multiple rows.ctl log=case5.log .ctl log=case4.2007 Case 4: Combines multiple records into one logical record using CONTINUEIF. deptno position (17:18) char.dat’ badfile ‘case5.ctl load data infile ‘case5. ename position (6:15) char. projno position (29:31) integer external) :wq $ vi case5. mgr position (20:23) integer external) into table proj when proj != ‘ ‘ (empno position (1:4) integer external. job position (17:25) char.08. projno position (25:27) integer external) into table proj when projno != ‘ ‘ (empno position (1:4) integer external. and use of when clause and also loading the same field (empno) into multiple tables.dat 1234 baker 10 999 101 102 103 1234 joker 10 999 102 103 104 2664 young 20 2983 101 102 104 :wq $ sqlldr userid=scott/tiger control=case5.R030 – Oracle Database Notes Version 1.dsc’ discardmax 999 replace continueif this (1) = ‘*’ into table emp (empno position (1:4) integer external. hiredate position (52:60) integer external) :wq $ vi case4. $ vi case4.dsc’ replace into table emp (empno position (1:4) integer external.50 -10 2512-Nov-85 *7839 king president 5500. $ vi case5.00 2505-Apr-83 *7934 miller manager 7839 3123.bad’ discardfile ‘case5.ctl load data infile ‘case4.75 2517-Jun-85 :wq $ sqlldr userid=scott/tiger control=case4.dat’ discardfile ‘case4. ename position (6:15) char.

0 Page 123/135 Date: 29. job position (17:25) char.dat. deptno position (50:51) integer external nullif deptno=blanks) :wq $ sqlldr userid=scott/tiger case6. mgr position (27:30) integer external nullif mgr=blanks. com position (41:48) decimal external nullif comm=blanks.08.2007 Case 6: loads the data into table EMP using the direct path load method and also builds the indexes $ vi case6.ctl log=case6.ctl load data infile ‘case6. insert into table emp sorted indexes (empid) (empno position (1:4) integer external nullif empno=blanks.R030 – Oracle Database Notes Version 1. sal position (32:39) decimal external nullif sal=blanks.log direct=true . ename position (6:15) char.

2 Disadvantages • You must devote an entire disk partition to a single db file leading to Wasted disk space. • Can require more volume than buffered I/O configuration.log’ SIZE 20M REUSE.08. temp.3 Creating a Database Using Raw Devices For example. • Increased output performances using asynchronous I/O. • Savings in the memory usage because the Oracle server doesn’t use the Unix buffer cache for db block reads/writes. • I/O load balancing and adding files to your database can be more difficult with raw device. . 100). 100). Character device drivers accesses the raw devices through the special files in the /dev directory bypassing the Unix I/O buffer. you have syst. this results in the fewer instructions per I/O. • They limit your ability to improve performance.2007 28 WORKING WITH RAW DEVICES A raw device doesn’t have any characteristics like other regular file systems. • They can be used concurrently with the filesystem.1 Advantages • Faster performance because the Oracle server bypasses the Unix buffer cache and eliminate the filesystem. A raw device doesn’t have any characteristics like other regular file systems.log’ SIZE 20M REUSE.dbf’’ SIZE 20000K REUSE DEFAULT STORAGE (INITIAL 50K NEXT 50K MINEXTENTS 2 MAXEXTENTS SQL> CREATE ROLLBACK SEGMENT rbs1 TABLESPACE urbs.R030 – Oracle Database Notes Version 1. SQL> ALTER ROLLBACK SEGMENT rbs1 ONLINE. the syntax is as follows: SQL> CREATE DATABASE rdb CONTROLFILE REUSE DATAFILE ‘/dev/rdsk/c0t0d0s1’ SIZE 25M LOGFILE ‘/disk1/oradata/DEMO/redo1. Then to create the database. Character device drivers accesses the raw devices through the special files in the /dev directory bypassing the Unix I/O buffer. 28.0 Page 124/135 Date: 29. • Moving datafiles around which is an option in a Unix FS is potentially impossible in raw device. ‘/disk2/oradata/DEMO/redo2. By default these will be owned by root. • Handling of bad blocks may be a problem without proper hardware. Character device drivers will support these RAW devices. • They are most beneficial for files that are receives sequential writes. • May reduce random access read performance. 28. SQL> CREATE TABLESPACE USERTS DATAFILE ‘/dev/rdsk/c0t0c0s2’ SIZE 20M REUSE DEFAULT STORAGE (INITIAL 50K NEXT 50K MINEXTENTS 2 MAXEXTENTS SQL> CREATE TABLESPACE UTEMP DATAFILE ‘/dev/rdsk/c0t0c0s3’ SIZE 20M REUSE DEFAULT STORAGE (INITIAL 50K NEXT 50K MINEXTENTS 2 MAXEXTENTS SQL> CREATE TABLESPACE URBS DATAFILE ‘/dev/rdsk/c0t0c0s4’ SIZE 20000K REUSE DEFAULT STORAGE (INITIAL 50K NEXT 50K MINEXTENTS 2 MAXEXTENTS SQL> CREATE TABLESPACE DATATS DATAFILE ‘$ORACLE_HOME/dbs/data1. • Backing up raw devices can be cumbersome when compared to backing up of Filesystem db files. • It does not allow for tablespace growth. Character device drivers will support these RAW devices. roll. So change the ownership and group permissions to Oracle and DBA. Asynchronous I/O is available in many Unix platforms but require the use of row disk devices/special kernel configuration. 100). indx partitions. 100). user. Enable asynchronous I/O by setting the async-write/use-async-I/O to true increased throughput. 28.

dd… Now using tar: $ tar Pcvf /temp/bckup.tar sys. .2007 28. You can use this basic syntax for all backup and recovery procedures. rbs.dd. First extract the respective file $ tar Pxvf /temp/bckup.dd rbs. Now you can use regular backup utilities like tar on these files. Suppose you have files: sys.0 Page 125/135 Date: 29.4.dd This command extracts data from the block device roll and in the file ‘sys.dd 2. The conv argument converts the character or block or block data into block mode. 28.2 RECOVERY Suppose we need to recover the datafile /dev/c0t0d0s1 for this 1.dd.08.4 Backup and recovery When you are working with RAW devices and additional layer is introduced in the backup and recovery procedures.dd temp. you have to restore the data $ dd if=’/temp/sys.tar /tmp/sys.dd’. Here the output file is the block device and not the device.1 BACKUP First you have to use the Unix command dd which takes two arguments If=input file – this is the name and path of the character device Of=output file – target file Example: $ dd if=’/dev/c0t0d0s1’ of=/temp/sys.4. Now using this file. temp.R030 – Oracle Database Notes Version 1.dd’ of=/dev/c0t0d0s1’ conv=bmode Note: The difference between this command and previous command.dd… 28.

1 Naming Locks DMBS_LOCK. Description Allocate a unique lock ID to a named lock Request a lock of a specific mode Convert a lock from one more to another Release a lock Put a procedure to sleep for a specified time Specify the name of the lock for which you want to generate a unique ID Returns to the caller the handle to the lock ID generated Specify the number of seconds to wait after the last ALLOCATE_UNIQUE 29. 30). EXPIRATION_SECS IN INTEGER DEFAULT 864000). use the request function. For example: SQL> SELECT * FROM dba_locks.REQUEST (ID IN VARCHAR2. change the lock mode.08. The following procedures are callable from DBMS_LOCK package: Function/procedure ALLOCATE_UNIQUE REQUEST CONVERT RELEASE SLEEP 29. ‘s’.REQUEST(3300. Lock name Lock hande Expiration secs For example: SQL> EXEC dbms_lock. give it a unique name.: LOCKHANDLE. It is possible to request a lock for a specific mode.1.R030 – Oracle Database Notes Version 1. DBMS_LOCK.1 DBMS_LOCK Package Creating user locks with Oracle lock management services – You can use Oracle lock management services for your applications. /*Locking in share mode*/ .2 Requesting a Lock To request a lock with a given mode.ALLOCATE_UNIQUE (LOCKNAME IN VARCHAR2.1.0 Page 126/135 Date: 29. and release it. TIMEOUT_IN “ “ maxwait RELEASE_ON_COMMIT IN BOOLEAN “” false).allocate_unique(‘testlock’. LOCKHANDLE OUT VARCHAR2.2007 29 DBMS PACKAGES 29. 20. If you get lock id as 3300 then: SQL> EXEC DBMS_LOCK. The Oracle lock management services are available through procedures in the DBMS_LOCK package. LOCKMODE IN INTEGER DEFAULT x_mode. true).

SQL> EXEC DBMS_LOCK.CONVERT (ID IN INTEGER. DMBS_LOCK.0 Page 127/135 Date: 29.:lockhandle.R030 – Oracle Database Notes Version 1. use the SLEEP procedure.1. To convert the lock from shared to exclusive SQL> EXEC DBMS_LOCK.SLEEP(10).null). The following table shows the procedures than can be called: Function/procedure Description Create_pipe Explicitly create the pipe Pack_message Build message in the local buffer Send_message Send messages on the named pipe Receive_message Copy message from named pipe into local buffer Next_item_type Return data type of next item in buffer Unpack_message Access next item in buffer Remove_message Remove the message Purge Purge the contents of named pipes Reset_buffer Purge the contents of the local buffer Unique_session_name Return a unique session name .CONVERT(3300. LOCKHANDLE ‘’ VARCAHR2. sent through Oracle pipes < is buffered in SGA. To suspend the session for a given period of time. 29.2 DBMS_PIPE The DBMS_PIPE package allows tow or more sessions in the same instance to communicate. Information.3 Converting a Lock To convert a lock from one mode to another DBMS_LOCK.08. SQL> EXEC DBMS_LOCK. LOCKMODE ‘’ INTEGER. Return integer 0 Success 1 Timeout 2 Deadlock 3 Parameter error 5 Don’t own lock specified by ID or lock handle illegal lock handle Example: 1. To release a lock: DBMS_LOCK. 2. All information in the pipes is lost when the instance is down. TIMEOUT ‘’NUMBER default maxwait) return integer.SLEEP(SECONDS IN NUMBER).RELEASE (ID IN INTEGER).2007 29. Oracle pipes are similar in concept to the pipes in UNIX. but Oracle pipes are not implemented using the operating system pipe mechanisms. 3.’x’.RELEASE(3300).

R030 – Oracle Database Notes Version 1.0

Page 128/135 Date: 29.08.2007

To create a new pipe: DBMS_PIPE.CREATE_PIPE(PIPE_NAME IN VARCHAR2 MAXPIPESIZE IN INTEGER DEFAULT 8192 PRIVATE IN BOLLEAN DEFAULT true) Return integer; Pipe name Maxpipesize Private For example:
SQL> EXEC DBMS_PIPE.CREATE_PIPE(‘testpipe’, 8192, true);

Specify the name of the pipe that you are creating. The name must be unique across the instance. Specify the maximum size allowed for the pipe in bytes. The total sizes of all the messages on the pipe cannot exceed this amount. Use the default TRUE, to create a private pipe. Public pipes can be created implicitly when you call the SEND_MESSAGE.

1. To remove explicitly: Pipes create implicitly by SEND_MESSAGE are automatically removed when empty. DMBS_PIPE.REMOVE_PIPE(PIPENAME IN VARCHAR2) Return integer;
SQL> EXEC DBMS_PIPE.REMOVE_PIPE(‘TESTPIPE’);

2. To purge, empty, the contents of a pipe, call PURGE. DBMS_PIPE.PURGE(PIPENAME IN VARCHAR2);
SQL> EXEC DBMS_PIPE.PURGE(‘TESTPIPE’);

3. Receive a message: To receive a message from a pipe, first call RECEIVE_MESSAGE to copy the message into the local message buffer. When you receive a message, it is removed from the pipe, that is, a message can only be received once. DBMS_PIPE.RECEIVE_MESSAGE(PIPENAME IN VARCHAR2, TIMEOUT IN INTEGER DEFAULT maxwait) return integer; For example:
Status:=dbms_pipe.send_message(‘proc1’,10); Status:=dbms_pipe.receive_message(‘testpipe’,10);

Where status is a variable and proc1 is pl/sql program.

R030 – Oracle Database Notes Version 1.0

Page 129/135 Date: 29.08.2007

29.3 DBMS_ALERT Package - Creating Alerts The DBMS_ALERT package provides support for the asynchronous notification of database events. By appropriate use of this package and database triggers, an application can cause itself to be notified whenever values of interest in the database are changed. The following table shows the procedures included in this package: Function/procedure Register Remove Signal Wait any Wait one Set_Defaults 1. To set default using alerts: DBMS_ALERT.SET_DEFAULTS(POLLING_INTERVAL IN NUMBER); For example:
SQL> EXEC DBMS_ALERT.SET_DEFAULT(120);

Description Receive mail from an alert Disable notification from an alert Signal an alert (send message to registered session) Wait time out seconds to receive alert message from an alert registered for session Wait time out seconds to receive message from named alert Set polling interval

2. To register an alert: DBMS_ALERT.REGISTER (ALTERNATE IN VARCHAR2); For example:
SQL> EXEC DBMS_ALERT.REGISTER(‘ALERT1’);

3. To signal message: DBMS_ALERT.SIGNAL (ALERTNAME IN VARCHAR2, MESSAGE_TEXT IN VARCHAR2); For example:
SQL> EXEC DBMS_ALERT.SIGNAL(‘alert1’, ‘hello’);

4. To remove alerts: DBMS_ALERT.REMOVE(ALERTNAME IN VARCHAR2); For example:
SQL> EXEC DBMS_ALERT.REMOVE(‘alert1’);

R030 – Oracle Database Notes Version 1.0

Page 130/135 Date: 29.08.2007

29.4 DBMS_JOBS Package This packages allows control of the Oracle job queues. Oracle job queue allow DBA’s to schedule, execute and eliminate jobs from within Oracle itself independent of the operating system queuing mechanisms. 1. To submit a job:
SQL> ed ins.sql Begin For I in 1..10 loop Insert into test values (I); End loop; End; / X NUMBER; DBMS_JOB.SUBMIT(:x, ‘program name’, SYSDATE, NEXTINTERVAL);

For example:
SQL> EXEC DBMS_JOB.SUBMIT(:x,’ins.sql’, sysdate, sysdate+1/(24*60*60);

2. To remove the job DBMS_JOB.REMOVE (JOBNUMBER); For example:
SQL> SELECT * FROM dba_jobs

If job number is 99 then
SQL> EXEC DBMS_JOB.REMOVE(99);

3. To change a specified job: DBMS_JOB.CHANGE(JOBNUMBER, SYSDATE, NEXT); For example:
SQL> EXEC DBMS_JOB.CHANGE(99,NULL, SYSDATE+1); /* changing the interval from 1 second to 1 day */

4. To run a job: DBMS_JOB.RUN(JOBNUMBER); For example:
SQL> EXEC DBMS_JOB.RUN(99);

You have to see the job number in DBA_JOBS TABLE. The parameters specified are: Name Program name, which you want to submit as a job Sysdate From which date you want to start a job Next The next interval when you want to execute the job Job number The number assigned to a job

Login as root and do the following: 1.0 2. /disk2.0 –m oracle10g # passwd oracle10g Changing password for user oracle10g New UNIX password: Retype new UNIX password: .08.R030 – Oracle Database Notes Version 1.2. in case if the internal disk goes corrupted.2007 30 INSTALLATION OF ORACLE10G ON RED HAT ENTERPRISE LINUX 4 Install Oracle on Red hat Enterprise Linux 4 (kernel 2.6. Create group dba # groupadd –g 1000 oinstall # groupadd –g 2000 dba 3.9-5) • • Make sure you have enough disk space to install Oracle. so those disk problems won’t stop the show. preferably we need a special filesystem (other than “ROOT”) Also try to avoid Database Engine and Database Files on the same file system: The most preferred (or minimum requirements are): / /usr /oraeng /var /tmp /disk1 /disk2 /disk3 /flash 100MB 7000MB 2000MB 1000MB 1000MB 2000MB 2000MB 2000MB 2000MB In the above example. the /disk1. # useradd –u 10001 –g oinstall –G dba –d /oraeng/app/oracle/product/10.0 Page 131/135 Date: 29. Create the directory structure to hold the software # mkdir –p /oraeng/app/oracle/product/10. And make sure your external drives are running with either RAID-0 or RAID-5. and /disk3 are external disk subsystems. The reason why we have like this. Create a user called “oracle10g” in which user account you will be installing the software.2. we can simply re-install Linux after replacing the drive and everything can function normally.

/usr/openwin/lib export PATH=$ORACLE_HOME/bin:/bin:/usr/bin:/usr/ccs/bin:/usr/ucb/bin:$PATH:. .conf file # vi /etc/sysctl. Now login as oracle10g user 7.d vi s99kernel echo 2147486348 > /proc/sys/kernel/shmmax echo 4096 > /proc/sys/kernel/shmmni echo 2097152 > /proc/sys/kernel/shmall echo 65536 > /proc/sys/fs/file-max echo 1024 65000 > /proc/sys/net/ipv4/ip_local_port_range echo 250 32000 100 128 > /proc/sys/kernel/sem :wq # chmod 755 S99kernel # Append the following parameters to the /etc/sysctl.bash_profile export ORACLE_SID=ORCL export ORACLE_HOME=/oraeng/app/oracle/product/10.2007 4.bash_profile 8.0 export LD_LIBRARY_PATH=$ORACLE_HOME/lib. Update your profile to suit your environment and do the following: $ vi . Now login as oracle10g and start he installation process $ startx $ cd /mnt/cdrom $ sh runInstaller .core.rmem_max=262144 net.user/ucblib. # init 6 6.wmem_default=262144 net.R030 – Oracle Database Notes Version 1.core. Change the owner of all the slices to “oracle10g’ # # # # # chown –R oracle10g:oinstall /oraeng chown –R oracle10g:dba /disk1 /disk2 /disk3 /flash Set the SHMMAX & Semaphores cd /etc/rc.2.d/rc5.conf net. Reboot the server to get changed values into effect.08.0 Page 132/135 Date: 29. Export CLASS_PATH=$ORACLE_HOME/jlib :wq $ .rmem_default=262144 net.core.wmem_max=262144 :wq 5.core.

SunOS 5. enter a command similar to the following: # pkginfo –I SUNWarc SUNWsprox SUNWxwfnt SUNWi15cs SUNWi1cs SUNWbtool SUNWhea SUNWlibm SUNWlibms SUNWsprot SUNWtoo SUNWi1of If the package is not installed.9: Match Library (libm) patch The following additional patches are required for Numa Systems: 115675-01.9: Miscellaneous SunOS Commands Patch 113875-01.9: Kernel Patch 111722-04. enter a command similar to the following: # /usr/sbin/patchadd –p | grep patch_number (without version number) . depending on the installation type.so Patch To determine whether an operating system patch is installed. SunOS 5. SunOS 5.R030 – Oracle Database Notes Version 1.9: /usr/lib/liblgrp. the required packages are: SUNWarc SUNWhea SUNWsprox SUNWxwfnt SUNWi15cs SUNWi1cs SUNWlibm SUNWlibms SUNWsprot SUNWtoo SUNWbtool SUNWi1of To determine whether the required packages are installed. then install it In addition.08. SunOS 5.2007 31 INSTALLATION OF ORACLE10G ON SUN SPARC (SOLARIS 9) System Requirements: ram swap CD-ROM 1024MB minimum twice the ram Oracle uses iso9660 format CD-rom disks with rockridge extensions Disk Space Requirements 400MB disk space in the /tmp directory Between 1. SunOS 5.9: liblgrp API 113471-08. you need to verify that the following patches are installed on the system.5GB of disk space for the oracle software. Patches for Solaris 9 112233-11. 1.2GB of disk space for a preconfigured database that uses file system storage (optional) OS Requirements One of the following 64-bit OS versions Solaris 8 update 7 or later Solaris 9 update 6 or later Solaris 10 On Solaris 9.0 Page 133/135 Date: 29.5GB and 3.

2. # useradd –u 10001 –g oinstall –G dba –d /oraeng/app/oracle/product/10. Login as oracle10g and append the following in profile $ vi .08.0 2./runInstaller .2007 1. Configure Kernel Parameters Open the /etc/system file in any text editor and if necessary.user/ucblib./usr/openwin/lib export LD_LIBRARY_PATH PATH=$ORACLE_HOME/bin:/bin:/usr/bin:/usr/ccs/bin:/usr/ucb/bin:$PATH:.0 export DISPLAY :wq $ cd /cdrom/cdrom0 $ .R030 – Oracle Database Notes Version 1.0 Page 134/135 Date: 29.0 export ORACLE_HOME ORACLE_SID=ORCL export ORACLE_SID LD_LIBRARY_PATH=$ORACLE_HOME/lib. Create the directory structure to hold the software # mkdir –p /oraeng/app/oracle/product/10.profile ORACLE_HOME=/oraeng/app/oracle/product/10.0 –m oracle10g # passwd oracle10g Changing password for user oracle10g New UNIX password: Retype new UNIX password: 4. Create group dba 3. export PATH CLASS_PATH=$ORACLE_HOME/jlib export CLASS_PATH DISPLAY=<host_name>:0.2. add lines similar to the following: # vi /etc/system set noexec_user_stack=1 set semsys:seminfo_semmni=100 set semsys:seminfo_semmns=1024 set semsys:seminfo_semms1=256 set semsys:seminfo_semvmx=32767 set shmsys:seminfo_seminfo_shmmax_4294967295 set shmsys:shminfo_shmmin=1 set shmsys:shminfo_shmmni=100 set shmsys:shminfo_shmseg=10 :wq # reboot 6. # groupadd –g 1000 oinstall # groupadd –g 2000 dba Create a user called “oracle10g” in which user account you will be installing the software. Change the owner of all the slices to “oracle10g’ # chown –R oracle10g:oinstall /oraeng # chown –R oracle10g:dba /disk1 /disk2 /disk3 /flash 5.2.

23 Schema. 21 BIGFILE Tablespace. 15 Control file. 131 Install Oracle on Solaris. 25 . 7 Rollback segments. 11 SQL*Loader. 30 Control files. 97 Redo-log.08. 119 Storage parameters. 15 UNDO tablespace. 7 init.R030 – Oracle Database Notes Version 1. 133 Instance. 20 Storage Parameters. 8 PGA.ora. 12 Tablespaces. 97 Recovery Manager (RMAN). 7 SCN.2007 32 INDEX ASM. 124 Recovery Catalog Schema.0 Page 135/135 Date: 29. 20 SYSAUX Tablespace. 9 Raw devices. 12 Install Oracle on Linux.

Master your semester with Scribd & The New York Times

Special offer for students: Only $4.99/month.

Master your semester with Scribd & The New York Times

Cancel anytime.