Sie sind auf Seite 1von 0

Performance Tuning (IZ0-033)

Table of Contents
Performance Tuning Overview....................................................................................................................................... 3
Diagnostic and Tuning Tools ......................................................................................................................................... 5
Oracle Configuration Parameters .................................................................................................................................. 5
Performance Tuning Views............................................................................................................................................ 5
The Alert Log................................................................................................................................................................. 6
Trace Files ..................................................................................................................................................................... 7
Background Trace Files ............................................................................................................................................. 7
Event Trace Files ....................................................................................................................................................... 7
User Trace Files......................................................................................................................................................... 8
TKPROF..................................................................................................................................................................... 8
UTLBSTAT/UTLESTAT............................................................................................................................................... 10
StatsPack..................................................................................................................................................................... 10
Oracle Enterprise Manager (OEM) GUI Performance Tools....................................................................................... 11
The OEM Architecture.............................................................................................................................................. 11
The OEM Console.................................................................................................................................................... 11
Oracle Diagnostics Pack .......................................................................................................................................... 12
Oracle Tuning Pack.................................................................................................................................................. 13
Oracle-provided Tuning Scripts ................................................................................................................................... 13
The Explain Facility...................................................................................................................................................... 14
The AUTOTRACE Facility........................................................................................................................................... 15
Tuning Applications and Design Tuning .................................................................................................................... 15
OLTP Versus DSS Tuning Requirements ................................................................................................................... 15
The Optimizer .............................................................................................................................................................. 16
Optimizer Statistics................................................................................................................................................... 17
Plan Stability................................................................................................................................................................ 19
Materialized Views....................................................................................................................................................... 20
Indexes......................................................................................................................................................................... 20
Partitions...................................................................................................................................................................... 21
Clusters........................................................................................................................................................................ 22
Tuning The Shared Pool ............................................................................................................................................... 22
Tuning the Library Cache............................................................................................................................................. 23
Tuning the Dictionary Cache........................................................................................................................................ 23
To Improve Performance............................................................................................................................................. 23
The Large Pool ............................................................................................................................................................ 24
The J ava Pool .............................................................................................................................................................. 24


Performance Tuning (IZ0-033)

Tuning the Database Buffer Cache.............................................................................................................................. 26
Related Topics............................................................................................................................................................. 27
Tuning Oracle Redo and Archiving ............................................................................................................................. 28
Tuning Disk I/O.............................................................................................................................................................. 28
Tuning Segment I/O..................................................................................................................................................... 29
Tuning Sort I/O............................................................................................................................................................. 30
Tuning Locking and Contention .................................................................................................................................. 30
Latches......................................................................................................................................................................... 32
Free List Contention..................................................................................................................................................... 32
Operating System Tuning............................................................................................................................................. 32
The Resource Manager............................................................................................................................................... 32


Performance Tuning (IZ0-033)

Performance Tuning Overview
In releases prior to 9i, Oracle promoted the Oracle Tuning Methodology as the way to tune Oracle databases and
applications. This is a top-down tuning approach that follows these six steps, addressing the highest-payoff areas
first:

Step: Tune The...
1 Data Design
2 Application Design
3 Memory Allocation
4 I/O and Physical Structure
5 Resource Contention
6 Underlying Platform

90% of all tuning problems are resolved within the first 2 steps above. Exam questions, however, concentrate
mainly on the last 4 steps.
In 9i, Oracle Corporation favors a set of prioritized Performance Tuning Principles, instead of their older Oracle
Tuning Methodology:

Priority: Principle:
1 Define the problem and a tuning goal.
2 Examine host system and gather oracle statistics.
3 Identify the problem in the common problems cited in the
manual Oracle9i Database Performance Methods (manual
#A87504-02).
4 Analyze the problem by the statistics from step 2.
5 Identify change(s) to make and implement them.
6 If the tuning goal of step 1 is accomplished, stop. Otherwise
perform steps 5 & 6 again until the tuning goal is met.

Oracle promotes the newer Performance Tuning Principles as best for tuning Production systems, and the older
Oracle Tuning Methodology as best for tuning Development systems. The new approach is also better for tuning
packaged (vended) applications, since customers can not usually change the data design or application design in this
case (steps 1 and 2 of the older methodology).
Tuning should be goal-oriented -- you set goals, then measure your progress towards those goals throughout the
tuning process. Tuning is an iterative process -- it may be ongoing and cycle through several problems and
resolutions before you have achieved all your tuning goals. Tuning may occur within the context of a Service Level
Agreement (SLA) -- a written document that specifies what the IT department guarantees for end users with respect to
the performance of a particular application or system.


Performance Tuning (IZ0-033)

Goal-oriented tuning means establishing a statistical picture of system performance, called a benchmark.
Benchmark statistics can then be re-taken as the tuning process proceeds, to see if you are meeting your tuning
goals. This Cramsession tells you how to gather Oracle statistics at length in the next section.
Tuning goals should be:
Specific So everyone understands them and can agree whether or not they have been met.
Measurable - So you can determine when and if they are met.

For Online Transaction Processing (OLTP) applications, performance usually means optimizing throughput - the
amount of work accomplished by the system in a given period of time. For Decision Support (DSS) or Data
Warehouse (DW) applications, performance usually means minimizing response time - how long it takes for the
system to respond to a given user query.
The three main computer hardware resources to tune for good Oracle performance:
CPU
Disk I/O
Memory

Often you will face tuning trade-offs - situations where you may have to maximize performance of one application or
program at the expense of some others, or where you may have to trade-off between better performance versus
increasing the hardware expenditures to get there.
Performance problems and the need for tuning present themselves at different points in the application lifecycle.
You may need to tune:
During application design
When configuring a new system or an upgrade to an existing system
After changes in workload
There are dependencies between these stages of lifecycle tuning. For example, the choices you make during
application design affect performance at other stages in the application lifecycle.
A basic principle in tuning is to change one aspect of the system at one time. Then test it and measure it. Then go
on to the next change. This iterative process of making one change at a time promotes safety and allows you to
know the exact impact of each change you make. If you change several things at once, you won't know the impact of
each change, and you could even make negative progress due to side-effects or unanticipated consequences of the
changes you made.
The most common tuning problems are:
Poorly-written application SQL
Inefficient SQL execution plans
Improperly size System Global Area (SGA) memory structures
Excessive file I/O
Waits for database resources

The entire IT organization must work together to resolve tuning problems. Each member fulfills a different role in the
tuning process:
Programmers and Developers - Tune their programs and their SQL.


Performance Tuning (IZ0-033)

Database Administrators - Tune Oracle itself, its configuration, memory settings, etc. May advise programmers
in their role.
System Administrators - Tune on the "platform level" (the operating system), configure hardware resources to
support all others in their roles.
Managers - Coordinate the process and roles among IT professionals.
Systems Analysts Design Oracle databases that meet application needs and performance requirements, using
Oracle9I features to achieve this goal.

Diagnostic and Tuning Tools
Oracle Configuration Parameters
Oracle's behavior is configured by configuration parameters (traditionally called the init.ora parameters after the file
in which they reside). Some parameters (or parms) may be set dynamically (while Oracle is up and running), while
others require a recycle (shutting down Oracle and restarting it) in order to take effect. 9i's addition of the Server
Parameter file (or spfile) is what enables the dynamic, permanent alteration of oracle configuration parameters.
There are over 250 documented configuration parameters and over 400 undocumented ones. Undocumented parms
all start with the underscore character (_). The Exam only covers documented parameters.
Before we look at where to collect and view Oracle tuning information, remember that the init.ora parm
TIMED_STATISTICS must be TRUE in order for Oracle to gather timing information on database usage. Either set
this value in the init.ora file and recycle Oracle, or dynamically issue:
ALTER SYSTEM SET TIMED_STATISTICS = TRUE
If this parameter is off you will not get Oracle statistics when you run any of the performance tools. Set this
parm to FALSE if you're not using the statistics because it causes system overhead (it slows performance to have it
on).
For the Exam, you'll have to know the init.ora parameters relevant to performance tuning. This CramSession covers
them at appropriate points.

Performance Tuning Views
Oracle internally maintains its own set of tables to track objects in the database, called the data dictionary (or the
catalog). The dictionary contains statistics, information Oracle uses to determine data access paths, as well as
dynamically updated real-time performance information.
There are two major categories of Oracle-maintained tables. Those beginning with the letters DBA_ are called the
DBA views. They contain information on the database objects (tables, views, etc). There are over 170 of these
views. The second group of catalog tables are called the "V dollar sign views;" their names are preceded by V$. The
V$ views are dynamically updated by Oracle and contain real-time performance information. While users query the V$
views, they are based on the underlying internal "X dollar sign" tables Oracle maintains. There are over 255 V$ views.
Remember:
DBA views are only available when the database is OPEN, whereas V$ views are available when database is in
MOUNT or NOMOUNT state.
Most V$ view names are singular while DBA view names are typically plural.
V$ views typically contain lowercase text data, while DBA views usually contain uppercase text. This is the kind
of fact it pays to recall in case you are forced to guess on the coding of a WHERE clause during the exam.
Oracle starts collecting V$ data after the instance is started, and this data is lost whenever the instance is shut
down. DBA view data is more static and is not lost upon instance shut down.


Performance Tuning (IZ0-033)

V$ views useful for performance issues include:

View: Usage:
V$SGASTAT System Global Area (SGA) component sizes. The SGA
is Oracles shared memory area
V$EVENT_NAME Database events that may require waits
V$SYSTEM_EVENT Lists wait events for all sessions
V$SESSION_EVENT Lists wait events for a particular session
V$SESSION_WAIT Wait events in progress for a particular session
V$STATNAME Matches a name to statistics given only by number in
V$SESSTAT and V$SYSSTAT
V$SYSSTAT System statistics for all sessions
V$SESSTAT System statistics for particular, currently-connected
sessions
V$SESSION Current connection info for particular sessions
V$WAITSTAT Block contention statistics

DBA views useful for performance issues include:

View: Usage:
DBA_TABLES Table storage, row, and block info
DBA_INDEXES Index storage, row, and block info
INDEX_STATS Index statistics - depth and dispersion
DBA_DATA_FILES Datafile naming, location, and size
DBA_SEGMENTS Segment space info
DBA_HISTOGRAMS Histogram definitions for tables and indexes

The Alert Log
Oracle writes important error and informational events during its operation to its Alert log. This file is appended to if it
exists, or created automatically by Oracle if it does not exist. You are responsible for managing the file's growth. The
location is specified by the init.ora parameter BACKGROUND_DUMP_DEST. The filename is in the form SIDalrt.log
for Windows systems and alert_SID.log for Unix and Linux systems, where "SID" is replaced by the SID (instance
identifier).
The kinds of messages in the Alert log include space errors, log thread changes, and checkpoint notifications. The
worst errors are those prefaced by ORA-0600. These are internal errors that are largely undocumented, but usually


Performance Tuning (IZ0-033)

point to data corruption or database structural problems. Sites usually track ORA-0600 errors through Oracle
Enterprise Manager (OEM) event alerts or by writing scripts that process the Alert Log and notify them.

Trace Files
Oracle Trace Files contain textual information generated either by server processes or trace events. They may
originate from Oracle itself or be initiated by users. You are responsible for managing (periodically erasing) old trace
files from directories where they are written.

Background Trace Files
These are written by Oracle to the destination set by the init.ora parameter BACKGROUND_DUMP_DEST. Traces
from Oracle background processes:

Process: Abbrev: Unix Name: Windows Name:
Process Monitor PMON Pmon_nnnn.trc sidPMON.trc
System Monitor SMON Smon_nnnn.trc sidSMON.trc
Database Writer DBWn DbwN_nnnn.trc sidDBWn.trc
Log Writer LGWR Lgwr_nnnn.trc sidLGWR.trc
Checkpoint CKPT Ckpt_nnnn.trc sidCKPT.trc
Archiver ARCn ArcN_nnnn.trc sidARCn.trc

Event Trace Files
These are also written to the BACKGROUND_DUMP_DEST. These records occur when traced events occur. You
turn on tracing for these events by adding the relevant line to the init.ora file. Example:
EVENT=" 10046 trace name context forever, level 12"
The number designates the event to trace, while the level tells how much tracing information will be collected. Most
event traces are not documented so you must rely on Oracle Corp World-wide Support for help when using them.


Performance Tuning (IZ0-033)

User Trace Files
These are written to the USER_DUMP_DEST directory. Sometimes they are generated by Oracle when an error
occurs in a user's Server Process, but more commonly, Oracle writes them at your request. Activate user tracing by:
Instance level - Turn on by setting the init.ora parameter SQL_TRACE=TRUE (default value is FALSE).
Instance-level tracing generates lots of I/O!
Session level - Turn it on in your own session by issuing ALTER SESSION SET SQL_TRACE = TRUE (default
is FALSE). Turn it off when done by issuing ALTER SESSION SET SQL_TRACE=FALSE.
Session level for other people's sessions - DBAs may need to trace someone else's session. Do this by: 1)
identifying the SID and SERIAL# for the user's session by querying the table V$SESSION; 2) activate tracing by
issuing the command DBMS_SESSION.SET_SQL_TRACE_IN_SESSION with a TRUE argument or
parameter; and 3) turn off tracing when done by issuing DBMS_SESSION.SET_SQL_TRACE_IN_SESSION
again with a FALSE argument.
User trace files have these naming formats:
Windows - ora12345.trc
Unixes and Linuxes - ora_1234.trc

Set the init.ora parameter MAX_DUMP_FILE_SIZE to specify the maximum size a generated user trace file can be.
Set this value as K (kilobytes), M (megabytes), unlimited, or just as an unlabelled number (this specifies the maximum
size in terms of OS blocks).

TKPROF
To interpret user trace files, you must run the Oracle-provided command line utility called Trace Kernel Profile (or
TKPROF) against them. Example:
$ tkprof ora_1252.trc trace.txt
This processes user trace file ora_1252.trc and sends formatted output to file trace.txt. Now read the report in file
trace.txt to learn what you need to know about the user's SQL.


Performance Tuning (IZ0-033)

You can optionally specify any of these TKPROF command line options (place them at the end of the command):

Option: Usage:
EXPLAIN Generates an Explain Plan for each statement to the
PLAN_TABLE
TABLE Stores execution plan in the specified table (instead of the
PLAN_TABLE)
SYS Tells whether recursive SQL statements (statements internally
executed against the data dictionary) are included
SORT Orders the statements in the output
RECORD Specifies a filename into which SQL statements are written
PRINT Places a limit on how many SQL statements will be included
INSERT Creates a SQL script that can create a table called
TKPROF_TABLE with statistics
AGGREGATE Tells whether multiple executions of the same SQL statement
are counted
WAITS Gives summary statistics for wait events

The above parameter SORT offers you 22 different sort options. These can be applied in any of three phases of SQL
statement execution:
Parse - Parses SQL statement and readies it for execution.
Execute - SQL statement execution.
Fetch - When a row of a result set is returned to the user (a SQL FETCH operation).

To interpret TKPROF formatted output, remember these labels in the output report and their meanings:

Statistic
Label:
Meaning:
Count Number of times Parses, Executes, and Fetch phases
CPU Number of CPU seconds spent on all Parses, Executes, and
Fetches
Elapsed Elapsed time for all three phases
Disk Total number of data blocks read during the three phases
Query Total number of rollback blocks read from the SGA during the
three phases
Current Total number of data blocks read from the SGA during the three
phases


Performance Tuning (IZ0-033)

phases
Rows Number of rows affected by Execute phase for INSERT,
UPDATE, or DELETE; or, number of rows affected by Fetch
phase for SELECTs

In general, identify SQL statements that need tuning by seeing which ones consume a lot of CPU; take a long time in
Parse, Execute, or Fetch; read many data blocks from disk and few from the SGA; or access many data blocks but
return few rows.

UTLBSTAT/UTLESTAT
One way to collect and report Oracle performance statistics is via the Oracle-provided utility scripts, UTLBSTAT.SQL
and UTLESTAT.SQL. The B stands for "Begin collecting statistics," the E for "End collecting statistics." Here's how
to use these utilities:
1. Ensure the instance has been "up" long enough to allow the V$ views to become populated with meaningful
statistics (at least 30 minutes)
2. Run UTLBSTAT.SQL to create temporary statistical tables and initially accumulate statistics into them
3. After at least 15 minutes has passed, run UTLESTAT.SQL to calculate metrics since the UTLBSTAT.SQL
script was run and to end the process. This also creates the file named REPORT.TXT in the user's current
directory.
4. Review the textual information in the REPORT.TXT file with any standard text editor. This contains the SQL
statements executed, and all sorts of performance statistics relating to them.

StatsPack
Statspack was introduced in Oracle8i Release 3 as an improved utility for reporting. It was designed to supercede the
older UTLBSTAT/UTLESTAT utilities. Here's how to use StatsPack:
1. Run the Oracle-provided script SPCREATE.SQL as user SYSDBA to create the PERFSTAT schema and all
its objects (tables, indexes, packages).
2. Change the default PERFSTAT schema password of PERFSTAT to something better. It is also
recommended to put the schema in its own tablespace.
3. Review the three log files created by SPCREATE.SQL to ensure it ran OK (SPCUSR.LIS, SPCTAB.LIS, and
SPCPKG.LIS). If anything went wrong, you can run the script SPDROP.SQL as user SYSDBA to clean up
and start over.
4. Run the procedure STATSPACK.SNAP two or more times as the user PERFSTAT to accumulate statistics.
Or, you may schedule this script to run automatically for you at intervals through script SPAUTO.SQL (this
uses DBMS_JOBS to schedule snapshot statistics data collection -- of course, to use DBMS_JOBS you must
have set the init.ora parameter JOB_QUEUE_PROCESSES to a non-zero value).
5. Run the procedure SPREPORT.SQL. Specify starting and ending points for the statistical period you want to
investigate. The report will be written to any file name you specify.
6. View the report with any text editor.

Tuning info you get from StatsPack includes SQL statements, which you can order by Gets, Reads, Executions, or
Parse Calls. There are thresholds SQL statements must meet or exceed in order to be included in the StatsPack


Performance Tuning (IZ0-033)

report. A SQL statement must have at least 10,000 Gets, 1,000 Reads, 100 Executions, or 1,000 Parse Calls to be
included in the StatsPack report.
The report output by StatsPack is much more clear and readable than that produced by UTLBSTAT/UTLESTAT. The
report provides lots of performance information both for SQL statements and the Oracle system as a whole. Note that
each execution of UTLBSTAT/UTLESTAT replaces the previous statistics; StatsPack keeps older statistics until you
delete them.
StatsPack and UTLBSTAT/UTLESTAT are two basic tools you use to collect the benchmark statistics referred to in the
first section "Performance Tuning Overview" in this CramSession. They are a more readable alternative than directly
querying the V$ tables and doing calculations using their data yourself.

Oracle Enterprise Manager (OEM) GUI Performance Tools
While StatsPack and UTLBSTAT/UTLESTAT provide textual reports with statistics over specified time periods, Oracle
Enterprise Manager (OEM) offers a set of graphical user interface (GUI) tools to help monitor and measure Oracle
performance.

The OEM Architecture
OEM features a flexible three-tier architecture:
One Oracle Intelligent Agent process runs on each node that will be monitored (regardless of how many
Oracle databases reside on that node). This agent process can collect local data through its Data Gatherer,
carry out actions, and manage that node's instances, databases, and listeners. It runs on the node under the
user id DBSNMP.
The middle tier is the Oracle Management Server (OMS). Having this middle tier gives you great flexibility in
the mapping between the other two tiers and in arranging your system topology to best manage Oracle. The
OEM Repository that holds OEM configuration and usage information resides in this layer.
The DBA "control point" is a workstation that runs the Oracle Enterprise Manager Console. The OEM Console
seamlessly integrates various OEM performance tools and provides for control of and reporting from the Oracle
Intelligent Agent processes residing on the various monitored nodes.
The next several subsections describe specific OEM GUI components that make up the OEM architecture. Oracle
Corp re-packages the OEM components in every new release, so the 9I packaging of the components differs from that
of previous releases.

The OEM Console
The OEM Console allows you to see and manage Events and Jobs on the local or remote managed nodes
(assuming Oracle Intelligent Agent runs on each managed node). Event management includes the ability to get an
email or page when either user-defined or Oracle-default events occur. You can also automatically run a fixit job in
response to an event. The control of jobs is provided through a full job scheduling system. Customization is achieved
by programming in the TCL command language (TCL scripting).


Performance Tuning (IZ0-033)

OEM Console GUI components include:

Component: Usage:
Instance Manager Start, stop and manage Oracle instances
Schema Manager Create and manage Schemas
Security Manager Create and manage user ids, privileges, and roles
Storage Manager Create and manage tablespaces and datafiles
Replication Manager Create and manage snapshots and data replication
Workspace Manager Use 9i's new Workspace Management feature

Oracle Diagnostics Pack
The Oracle Diagnostics Pack contains these GUI tools to help identify and diagnose database problems:

Component: Usage:
Performance
Overview
A handy, high-level, single-screen summary of Oracle's
current operations and performance. Helps you identify
immediate problems at a glance.
Performance Manager Presents real-time performance information in a GUI
format. It monitors: disk I/O, contention, instance
statistics, sort and throughput loads, memory usage for
all SGA components, and top resource users.
Top Sessions Displays the sessions using the most resources (as you
define them).
Lock Monitor Identifies which users are locking resources, and what
kinds of locks are applied.
Top SQL Identifies which SQL statements are using the most
resources (as you define them).
Trace Data Viewer GUI for viewing trace file output (an alternative to
TKPROF)
Capacity Planner Helps estimate future system resource needs based on
current and projected workloads.



Performance Tuning (IZ0-033)

Oracle Tuning Pack
These GUI OEM components are specifically designed to help you tune Oracle:

Component: Usage:
Oracle Expert Wizard that implements the Oracle Tuning
Methodology
SQL Analyze Analyzes and rewrites SQL for better performance
Index Tuning Wizard Analyzes index usage
Outline Management Helps manage Stored Outlines, an Oracle feature that
provides plan stability
Reorg Wizard Aids in reorganization of tables and indexes
Tablespace Map Shows segment & extent mapping to tablespaces

Oracle-provided Tuning Scripts
Oracle provides a variety of scripts for performance tuning. Some are run only once, during Oracle installation, to
create V$ or performance statistics tables. Others can be run at anytime to dynamically collect tuning statistics, or to
generate reports based on those statistics.
Some of these scripts underlie the graphical tools provided by the Oracle Enterprise Manager (OEM), or the statistics
collection and reporting tools mentioned earlier (UTLBSTAT/UTLESTAT and StatsPack). Important Oracle-provided
scripts include:

Script: Usage:
UTLBSTAT.SQL Starts collecting statistics for analysis
UTLESTAT.SQL Ends statistics collection
SPCREATE.SQL Creates schema objects for StatsPack. Run as
SYSDBA
STATSPACK.SNAP Manually gathers StatsPack statistics
SPAUTO.SQL Schedules automatic collection of StatsPack statistics
SPREPORT.SQL Generates report and tuning recommendations from
Statspack
UTLLOCKT.SQL Displays locking contention information
CATBLOCK.SQL Builds dictionary views for monitoring locking
contention (e.g., DBA_BLOCKERS and
DBA_WAITERS). Run as the user SYS
CATPARR.SQL Creates the V$CACHE view, which helps you
optimally size the database buffer cache. Run as the
user SYS


Performance Tuning (IZ0-033)

DBMSPOOL.SQL Create Package DBMS_SHARED_POOL with
procedures KEEP and UNKEEP, used to pin or unpin
a Package, Trigger or Sequence in memory. Run as
the user SYS
UTLCHAIN.SQL Builds table CHAINED_ROWS to identify chained
and/or migrated rows
PLUSTRCE.SQL Creates database role PLUSTRACE, required for
using the AUTOTRACE facility. Run this script as
user id SYS
UTLXPLAN.SQL Builds a PLAN_TABLE for Explain command
description of SQL access paths. Run under the user
id that will do the Explains
UTLXPLS.SQL Queries PLAN_TABLE (excludes any Parallel Query
information)
UTLXPLP.SQL Queries PLAN_TABLE (includes any Parallel Query
Information)

The Explain Facility
The Explain Plan facility allows you to look at the way Oracle accesses data for individual SQL statements (referred
to as the access plan or just the plan). You generate its information either through the TKPROF command (against
user trace files) or by issuing the EXPLAIN PLAN FOR command. Here's how to use the EXPLAIN PLAN FOR
statement:
For your first use of this facility only, you must create a PLAN_TABLE to hold the output from the EXPLAIN
statement. Run the script UTLXPLAN.SQL to do this.
Run the SQL statement you want to analyze like this:
EXPLAIN PLAN FOR ---the SQL statement goes here--- ;
This populates the PLAN_TABLE. It does not actually execute the SQL statement, it just collects info on how
Oracle would execute it!
Query the PLAN_TABLE for info on how Oracle would execute the SQL statement. Read lines in this table
from the inner-most to the outer-most. Work your way up and out towards the leftmost operations in the plan.
When two lines have the same indentation in the output, the topmost is executed first.

Since output accumulates in the PLAN_TABLE, you might wish to truncate it before each SQL statement you analyze.
Or use the SET STATEMENT_ID= qualifier on the EXPLAIN PLAN FOR statement to identify outputs from separate
executions.
You can also read plan output by running either of the Oracle-provided scripts UTLXPLS.SQL or UTLXPLP.SQL to
write a formatted report.



Performance Tuning (IZ0-033)

The AUTOTRACE Facility
The AUTOTRACE facility is only available from within SQL*Plus. Use it by
issuing SET AUTOTRACE ON from within SQL*Plus. Then, for each SQL
statement you run, you get both its execution plan (just like you get from the
EXPLAIN PLAN FOR facility), plus you get run-time statistics on that
statement's execution.
You read the plan information lines exactly the same way as you do the lines
EXPLAIN PLAN FOR places in the PLAN_TABLE. Unlike EXPLAIN PLAN
FOR, AUTOTRACE does execute the SQL statement (that's how it provides
you statistics on its execution). Also, unlike EXPLAIN PLAN FOR,
AUTOTRACE does clean out the PLAN_TABLE contents automatically
upon each execution.
You must perform these preliminary steps one time before using
AUTOTRACE:
Create your PLAN_TABLE by running the Oracle-provided script
UTLXPLAN.SQL.
Create the database role PLUSTRACE by running the Oracle-provided
script PLUSTRCE.SQL as the user id SYS.
Grant the new PLUSTRACE role to every user who will be using the
AUTOTRACE feature

Tuning Applications and Design
Tuning
Exam questions on application design focus on special Oracle features
designed to enhance query performance. This section discusses the
features on the Exam.

OLTP Versus DSS Tuning Requirements
Online Transaction Processing (OLTP) applications feature many short,
repetitive transactions and often have a large number of users. The
performance goal is to optimize throughput. B-tree and Reverse key
indexes are useful tools, and you've got to keep database statistics up-to-
date if data volumes change frequently. Block sizes are typically small.
Decision Support Systems (DSS) have little update activity and often
involve full table scans. The goal is to optimize response time. Bit-map
indexes, hash clusters, index-organized tables, and large block sizes are
useful tools to meet this goal.
Hybrid systems combine OLTP and DSS application characteristics. They
are therefore most difficult to tune.



Performance Tuning (IZ0-033)

The Optimizer
The optimizer is that component of Oracle that figures out how to access data for SQL statements (it creates the plan
or access path). Oracles two methods of optimization are:
Rule Based Optimizer (RBO) Uses a set of rules of thumb to determine access paths. RBO is older and
considered more primitive.
Cost Based Optimizer (CBO) - Determines the most efficient data access paths by picking the data access
alternative that costs the least in terms of resources (disk I/O, CPU, etc.). This is the newer, recommended
approach.
The choice of optimizer (or optimizer mode) can be set at these levels:
Statement
Session
Instance

If set at more than one level, the order of precedence (highest to lowest) is in the order above (Statement setting
overrides Session setting which overrides Instance setting). If not set anywhere, the setting defaults to CBO if
statistics have been collected, or RBO if no statistics have been collected.
On SQL Statements, optimizer hints can be encoded to tell the optimizer what do to. Hints are coded with this syntax:
SELECT /*+ hint_goes_here */ .
Oracle has over 40 hints. The optimizer mode hints include:

Hint: Usage:
RULE Uses RBO
FIRST_ROWS CBO optimizes for quickest retrieval of the first rows to be
returned
FIRST_ROWS_n CBO optimizes for returning the first N rows.
N can only be: 1, 10, 100 or 1000 !
ALL_ROWS CBO optimizes for retrieval of all rows

To control the optimizer at the Session level, use this command:
ALTER SESSION SET OPTIMIZER_MODE=ALL_ROWS;
You can code the same keywords on the Session level as in the table above for hints, plus you can encode:
CHOOSE Oracle uses CBO if statistics exist for any table involved in the query, otherwise it uses the RBO.
To control the optimizer at the Instance level, set the parm OPTIMIZER_MODE= in the init.ora file. If not coded, it
defaults to CHOOSE. You can encode the same five options as on the Session level:
RULE, FIRST_ROWS, FIRST_ROWS_n, ALL_ROWS, or CHOOSE.



Performance Tuning (IZ0-033)

Optimizer Statistics
CBO requires that you collect statistics on the data to create optimal plans. These stats are stored by Oracle in its
Data Dictionary or catalog. Statistics include such data as: the size of table or index, number of rows it contains, row
length, and cardinality (how many different values a column contains). Statistics can be collected at these levels:
table, index, schema, or the entire database. The main ways to gather statistics are:
The ANALYZE SQL command
The package DBMS_UTILITY.ANALYZE_SCHEMA
The package DBMS_STATS
Through the OEM Console
Copying statistics from one database to another

Heres an example ANALYZE command that gathers table statistics:
ANALYZE TABLE employee_table COMPUTE STATISTICS;
To delete them later, run: ANALYZE TABLE emp DELETE STATISTICS;
Common ANALYZE statement clauses include:

Clause: Usage:
COMPUTE
STATISTICS
Gather full object statistics
ESTIMATE
STATISTICS
Estimate stats based on the sample value you
supply (defaults to 1,064 rows)
ESTIMATE
STATISTICS SAMPLE
nnn ROWS
Estimate stats based on sample number of rows
specified
ESTIMATE
STATISTICS SAMPLE
nn PERCENT
Estimate stats based on sample percentage of rows
FOR TABLE Gather table stats only (no column stats)
FOR COLUMNS Gather stats only for specified column(s)
FOR ALL INDEXES Gather stats for all indexes on the table (no table
stats)
FOR ALL INDEXED
COLUMNS
Gather stats only on indexed columns
FOR ALL LOCAL
INDEXES
Gather stats on all local indexes of a partitioned
table

Use DBMS_UTILITY to analyze all objects in a schema by running:
DBMS_UTILITY.ANALYZE_SCHEMA


Performance Tuning (IZ0-033)

Or collect statistics on the entire database by running:
DBMS_UTILITY.ANALYZE_DATABASE
DBMS_STATS is newer and recommended over DBMS_UTILITY. Key DBMS_STATS procedures are:

Procedure: Usage:
GATHER_TABLE_STATS Gathers stats on a table
GATHER_INDEX_STATS Gather stats on an index
GATHER_SCHEMA_STATS Gather stats on a schema
GATHER_DATABASE_STATS Gather stats on the entire database
GATHER_SYSTEM_STATS Gather I/O and CPU performance statistics
for the server

Options for DBMS_STATS.GATHER_SCHEMA_STATS include:

Option: Usage:
GATHER STALE Gathers stats for tables marked for monitoring by
the ALTER TABLEMONITORING command
GATHER EMPTY Gathers stats for tables which have no stats
GATHER AUTO Automatically gathers stats Oracle determines
suitable based on user behavior
AUTO_SAMPLE_SIZE Automatically determines sample size and whether
Histogram stats are suitable
METHOD_OPT of
REPEAT
Re-gathers histogram stats
METHOD_OPT of
SKEW_ONLY
Gathers histogram stats whenever data is skewed
(not uniformly distributed)

To view statistics from the Data Dictionary, inspect these tables:
DBA_TABLES
DBA_INDEXES
DBA_TAB_COL_STATISTICS
USER_TAB_COL_STATISTICS


Performance Tuning (IZ0-033)

To copy statistics between databases, follow this procedure:
Create a new table to hold the stats by running DBMS_STATS.CREATE_STAT_TABLE
Capture current stats into that table by running DBMS_STATS.EXPORT_SCHEMA_STATS
Run the command-line Export utility to export the contents of the STATS table to a flat file
Copy the export dump file to the server where youll load the stats
Create a new table to hold the stats by running DBMS_STATS.CREATE_STAT_TABLE
Run the command-line Import utility to bring the stats into the new STATS table
Bring the stats into the data dictionary by running DBMS_STATS.IMPORT_SCHEMA_STATS

Plan Stability
Whenever you perform an Oracle upgrade or change database configuration parameters, there is always the
possibility that your actions will have the side-effect of changing existing program plans (access paths to data).
Plan Stability stores the preferred execution plan for a SQL statement in the data dictionary (as a stored outline). It
is a mechanism to avoid un-desired changes to plans. To use this feature, do the following:
1. All stored outlines use the OUTLN schema. Change the OUTLN default password, and give it its own default
and temporary tablespaces. Move its two tables OL$ and OL$HINTS out of the SYSTEM tablespace to
OUTLN's own tablespace.
2. Create stored outlines for the SQL you want to have plan stability by using the CREATE OR REPLACE
OUTLINE statement.
3. Activate stored outlines by setting the init.ora parameter USE_STORED_OUTINES=TRUE and restarting the
instance. Or you can dynamically activate this by running: ALTER SYSTEM SET
USE_STORED_OUTLINES=TRUE, or choose to activate it only for certain categories or groups of stored
outlines.
Manage outlines by the Oracle package OUTLN_PKG and the commands ALTER OUTLINE and DROP OUTLINE.
View stored outline info by querying the views DBA_OUTLINES and DBA_OUTLINE_HINTS.
To generate stored outlines for every statement, set the init.ora parameter CREATE_STORED_OUTLINES=TRUE.
Obviously this impacts performance.
9I also supports private outlines, outlines that reside in the users session and are only available to that user. Use
the CREATE PRIVATE OUTLINE statement to create private outlines. Activate private outlines in the session with
ALTER SESSION SET USE_PRIVATE_OUTLINES=TRUE, and de-activate them in the session by running this same
statement with the value of FALSE.


Performance Tuning (IZ0-033)

Materialized Views
Materialized views speed up queries by storing data in 1) pre-joined or 2) pre-calculated form. For pre-calculated form,
the calculations are typically those of the functions SUM, COUNT, MIN, MAX, or AVG. Materialized views do the "up
front" work so that queries run faster by not having to perform this work in real time. This gives you the option to speed
up queries by doing some of the work at a more convenient time. Materialized views are a good tool for faster data
access when their use is well planned.

Use the CREATE MATERIALIZED VIEW statement with some of these keywords to create materialized views:

Keyword: Use:
REFRESH
COMPLETE
Materialized view is completely updated by using all base
table data
REFRESH
FAST
Materialized view is updated by only applying that base
table data that has changed
ON COMMIT Refresh occurs after each commit (resource-intensive but
very current materialized view data)
ON DEMAND Refresh as demanded (by using packages like
DBMS_MVIEW and DBMS_JOB).
START
WITH...NEXT
For specifying refresh dates and times
FORCE Keep materialized view in sync with base table(s) (as
determined by other keywords). The default.
NEVER Do not keep the materialized view data in sync with
underlying table(s)

Use the DBMS_MVIEW package to manually refresh materialized views. The procedures REFRESH,
REFRESH_DEPENDENT, and REFRESH_ALL_MVIEWS are used for manual refreshes.
Usually youll use Oracles automated refresh feature for convenience. Automatic refreshes are defined by creating
the materialized view with the ON COMMIT option or by scheduling the refresh with the DBMS_MVIEW and
DBMS_JOB packages.

Indexes
Indexes speed data access at the cost of the disk space required for their storage. Indexes can also slow down
updates (because the update must internally update the index as well as the table). The six kinds of Oracle indexes
are:
B-tree Index stores keys (indexed data values) with the row ids where they are located in the database.
Compressed B-tree saves storage space by not storing duplicate occurrences of the indexed column(s)
value.
Function-based Applies a function to the index column. Useful where the function is typically applied to the
value in the WHERE clause for retrieval.


Performance Tuning (IZ0-033)

Reverse-key Useful when index column contains sequential numbers. It reverses the bytes in each column
that is indexed. Example key of 12345 becomes 54321.
Bitmap Stores a binary mapping of row values called a bitmap. Differs from all other index types in that it is
best applied to low-cardinality data (data having few different values, for example, GENDER is either M or F).
Best for data warehousing or other read-only applications because updating the bitmap is relatively slow.
Specify by the keywords CREATE BITMAP INDEX.
Index-Organized Tables (IOT) Stores the row itself in the index (rather than a row id that points to the row in
the data table). This avoids the extra I/O required to follow the row id and get the row from the table, plus table
rows are stored in index order. Specify by the keywords ORGANIZATION INDEX on the CREATE TABLE
statement.

Rebuild an index with this statement:
ALTER INDEX index_name REBUILD ONLINE;
The keyword ONLINE allows users to continue DML on the underlying table while this operation proceeds. You can
use this statement to move an index to a new tablespace.
Coalescing an index rebuilds the index online by coalescing index leaf blocks. The statement can not be used to
move an index to a new tablespace:
ALTER INDEX index_name COALESCE;
Data Dictionary views to inspect issues regarding indexes include DBA_INDEXES, DBA_SEGMENTS, and
DBA_TABLES.

Partitions
Partitioning allows Oracle to store a very large table in multiple tablespaces. Query performance can be enhanced
because Oracles optimizer is smart and only searches partition(s) in which the desired row resides. The four kinds of
Oracle partitioning are:
Range Partitions are defined as continuous ranges of data values. The highest range may be specified as
MAXVALUE (this ensures all values can be inserted somewhere in the table).
List Partitions are defined by lists of values for each partition. The classic example of list partitioning is a table
that contains data divided by groupings of the 50 state codes.
Hash Data is inserted and retrieved to and from partitions based on the application of a hash function.
Obviously, the hash function must provide consistent results when applied to the same value, so that that value
may be both inserted and then later retrieved.
Composite Combines both range and hash partitioning, so that you can use range partitioning but still get an
even number of values in each range. This option uses the syntax PARTITION BY RANGE SUBPARTITION
BY HASH.

Indexes on partitioned tables can be classified as:
Local Partition Index The number of partitions in the index matches the number of partitions in its underlying
table
Global Partition Index The number of partitions in the index do not match the number of partitions in its
underlying table



Performance Tuning (IZ0-033)

Indexes can also be classified as:
Prefix Partition Index The leftmost column of the index is the same as the underlying tables partition key
column.
Non-Prefix Partition Index The leftmost column of the index is not the same as the underlying tables
partition key column.

Clusters
Oracle supports two kinds of clusters: index and hash.
Index Clusters store data from one or more tables in the same physical blocks. Use them when:
The table data will always be retrieved together (not individually).
There will be little update activity after the initial data load.
There are roughly equal numbers of child records for each parent key.

Hash Clusters use a hashing algorithm to store and retrieve rows quickly without using an index. Use them when:
SQL statements will use equality matches on the indexed column in their WHERE clauses.
There will be little update activity after the initial load.
There is uniform distribution of values in the indexed column.
There will be a predictable number of values in the indexed column.

Tuning The Shared Pool
The SGA (System Global Area) is memory allocated to Oracles use. The SGA contains the Shared Pool, the area
that caches the most popular SQL and PL/SQL statements and ages out the lesser-used ones by a Least Recently
Used (LRU) algorithm. The Shared Pools three components are:
Library Cache Holds the most popular SQL and PL/SQL statements. See what it holds by viewing:
V$SQL The first 80 characters of the SQL statement text, plus statistics.
V$SQLAREA Same as V$SQL, but only for statements that are cached in memory, parsed, and
ready for execution.
V$SQLTEXT Complete text of the SQL statement.
V$SQL_PLAN Execution plan info for the SQL statement.
Dictionary Cache Contains the most popularly-referenced Data Dictionary information for Oracles reference.
Uses an LRU algorithm to manage its contents.
User Global Area (UGA) Caches application and user session information. Only present if the Shared Server
option is being used. If you are not using the Shared Server option, this information is kept in the Process
Global Area (PGA).



Performance Tuning (IZ0-033)

Tuning the Library Cache
To tune the Library Cache, recall that Oracle only considers SQL or PL/SQL statements equivalent if their hashed
values match. The hash values are computed based on converting the characters in the statements to their ASCII
equivalents and applying a hashing algorithm.
Query V$LIBARYCACHE to monitor the Library Cache. The GETHITRATIO is how often a parsed copy of the SQL or
PL/SQL statement was found in the cache. The PINHITRATIO is how often executed statements found the associated
parsed SQL or PL/SQL in the cache. Both ratios should be over 90% for good OLTP performance, somewhat lower
for decision support systems. RELOADS show the number of times an executed statement had to be re-parsed,
while INVALIDATIONS occur when a SQL statement in the cache is marked as invalid and has to be re-parsed. For
good performance, RELOADS should be under 1% and the number of INVALIDATIONS low.
Instead of querying the V$LIBRARYCACHE dynamic performance view, you could get the same information from
UTLBSTAT/UTLESTAT, StatsPack, or the OEM GUI tools. These alternatives could be used for any of the
performance monitoring and tuning this Cramsession covers. We focus on the V$ views because most the exam
questions are couched in this manner.

Tuning the Dictionary Cache
Use the view V$ROWCACHE to calculate the data dictionary cache hit ratio:
SELECT 1 (SUM(getmisses)/SUM(gets)) FROM V$ROWCACHE ;
The data dictionary cache hit ratio should be over 85% for good performance.

To Improve Performance
Set the size of the Shared Pool via the init.ora parameter SHARED_POOL_SIZE. Set it dynamically like this:
ALTER SYSTEM SET SHARED_POOL_SIZE = 800M;
The value you set dynamically can not exceed the init.ora parameter SGA_MAX_SIZE. Oracle decides how to
allocate the memory among the SGA components (you do not set those values individually).
Since large PL/SQL packages can hog the Shared Pool, Oracle allows you to keep them in the Shared Pool
Reserved Area. Set the init.ora parm SHARED_POOL_RESERVED_SIZE to any value up to 50% of the size of the
SHARED_POOL_SIZE. By default it is 5%. Monitor view V$DB_OBJECT_CACHE to optimally size the Shared Pool
Reserved Area.
You can permanently keep (or pin) frequently-used packages and triggers in memory. Pinned packages are stored in
the Shared Pool Reserved Area space. Before you can pin anything, you must run the Oracle-supplied script
DBMSPOOL.SQL one time. Then, pin a package like this:
EXECUTE DBMS_SHARED_POOL.KEEP(package_name);
You can make sure it got pinned by interrogating V$DB_OBJECT_CACHE. Pinning only lasts for the lifetime of the
instance. If you shutdown and startup Oracle, you must re-pin the package again by running the same statement.
You can make best use of the Library Cache by encouraging your developers to reuse code. Use coding standards to
ensure the common use of case, spacing, and lines in the application code SQL. Also have programmers use bind
variables (rather than hard-coded literal values), as in this example:
SELECT row_info FROM my_table WHERE row_key_value = :row_key;
Here, avoiding the hard-coding of the row_key_value means code reuse. The semi-colon denotes the bind variable.
You also affect statement sharing by the setting of the init.ora parameter CURSOR_SHARING:



Performance Tuning (IZ0-033)

CURSOR_SHARINGPa
rameter:
Usage:
EXACT Default. Two SQL statements must match exactly
to be considered sharable.
FORCE New in 8i. Allows more sharing of SQL statements.
SIMILAR New in 9i. Recommended. Allows two SQL
statements to be shared even if they differ by literal
values (that do not change the statements
meaning).

Oracle logically replaces literal values with bind variables in order to achieve cursor sharing for similar SQL
statements.

The Large Pool
Optional Oracle features like Recovery Manager (RMAN) and Parallel Query (PQ) can hog up the Shared Pool. Fix
this by creating a Large Pool. Set the init.ora parameter LARGE_POOL_SIZE to a size in bytes. If you dont set this
parameter, there is no Large Pool, unless youve set PARALLEL_AUTOMATIC_TUNING to TRUE, in which case
Oracle creates and sizes it for you.
Measure use of the Large Pool by running:
SELECT name, bytes FROM V$SGASTAT WHERE pool = large pool;
Since you can not resize the Large Pool by the ALTER SYSTEM command, you must change it by changing
LARGE_POOL_SIZE in the init.ora file and recycling Oracle.

The J ava Pool
If you use Oracles Java Virtual Machine (JVM), be sure to configure the Java Pool. Oracle loads over 4,000 J ava
classes at startup, so it configures the J ava Pool of 20M bytes within the Shared Pool by default. Oracle recommends
you re-set this to at least 50M by the init.ora parm JAVA_POOL_SIZE. This caches J ava state and runtime info.
Check use of the J ava Pool by running:
SELECT name, bytes FROM V$SGASTAT WHERE pool = java pool;
Since you can not resize the J ava Pool by the ALTER SYSTEM command, you must change it by changing
JAVA_POOL_SIZE in the init.ora file and recycling Oracle.

Tuning the Shared Server Option (SSO)
By default, 9I uses the Dedicated Server architecture, where each user process is serviced by its own Server
Process running on the Oracle database server. The alternative is the Shared Server option (SSO), where Server
Processes are shared among multiple user processes. (This was called the Multi-threaded Server (MTS) prior to 9I).
SSO is more scalable than the dedicated configuration.


Performance Tuning (IZ0-033)

SSO consists of:

Component: Role:
User Process On the client, manages the connection to the database
server
Oracle Net
Listener
Listens for new, incoming connection requests on the
database server. Directs each request to the least busy
dispatcher process
Dispatcher
Process
Accesses user requests and places them in the request
queue. There is one request queue, and it resides in the
SGA.
Shared Server
Process
Handles user SQL.
Response Queue Shared server processes place the SQL result sets here.
There is one response queue for each dispatcher process

To tune SSO, you want to ensure that no user waits for either:
A dispatcher
A shared server process

Inspect V$QUEUE, V$DISPATCHER, and V$DISPATCHER_RATE to determine how busy the dispatchers are.
Increase the number of dispatchers by a statement like this:
ALTER SYSTEM SET DISPATCHERS = tcp, 10;
The number you specify is the total number you want (not how many more to add).
Dispatchers are specific for a communications protocol. Each Dispatcher serves only a single protocol!
Inspect Shared Server process performance by calculating the busy ratio from V$SHARED_SERVER and
V$SHARED_SERVER_MONITOR. High or increasing ratios mean you need to spawn more Shared Server
processes. Do so like this:
ALTER SYSTEM SET SHARED_SERVERS = 10 ;
The number you specify is the total number you want (not how many more to add).


Performance Tuning (IZ0-033)

Relevant init.ora parms:

Init.ora Parm: Usage:
DISPATCHERS How many Dispatchers to start up (permissible
encoding is 0 to 5)
MAX_DISPATCHERS Maximum number allowed (default is 5)
SHARED_SERVERS How many to start. A value of 0 means
Dedicated Server architecture only
MAX_SHARED_SERVERS Maximum number allowed (default is 20 or 2
times value of SHARED_SERVERS)
CIRCUITS How many virtual circuits to handle
incoming/outgoing network connections
PROCESSES Maximum number of OS processes that can
access the instance

Tuning the Database Buffer Cache
The Database Buffer Cache holds popular blocks so that Oracle does not have to do real disk I/O to satisfy all data
requests. The bigger the database buffer, and the more efficiently it is used, the less real I/O Oracle performs and the
faster it runs.
The Database Buffer Cache holds blocks from tables, indexes, clusters, Large Object (LOB) segments, LOB indexes,
rollback segments, and temporary segments. It uses a Least Recently Used (LRU) algorithm to ensure the most-
used blocks stay in the buffer. The state of each buffer block can be:
Free Buffer is open for use.
Pinned Buffer is in use by a server process.
Clean Buffer was just released from a pin, and can be re-used again because the data in the buffer was not
changed.
Dirty Buffer is not in use, but contains committed data that has not yet been written to disk by the Database
Writer (DBWn) background process.

The Dirty List or Write List is used to ensure Dirty buffers do eventually get written to disk.
The performance of the Database Buffer Cache is best measured by the hit ratio how many reads Oracle satisfies
from the buffer rather than from real I/O. The hit ratio should be greater than 90% for good performance on OLTP
systems. View V$SYSSTAT for this information. (Or, of course, use UTLBSTAT/UTLESTAT, StatsPack, or the OEM
GUI for this purpose). Make the buffer bigger by increasing the init.ora parameter DB_CACHE_SIZE to increase the
hit ratio. You can increase it dynamically by running:
ALTER SYSTEM SET DB_CACHE_SIZE = n;
Get advice on the size of the buffer cache through 9Is new Buffer Cache Advisory feature. Set the init.ora
parameter DB_CACHE_ADVICE=ON. Let Oracle collect statistics on its use for at least 30 minutes. Then inspect
view V$DB_CACHE_ADVICE to see what Oracle recommends.
Make better use of the database buffer by dividing it into up to three areas or pools:


Performance Tuning (IZ0-033)

Keep Used to cache segments you want to retain in the buffer.
Recycle Used to cache segments you do not generally want to
retain in the buffer.
Default Segments not designated for the Keep or Recycle pools.

Set the sizes of these pools via the init.ora parameters
DB_KEEP_CACHE_SIZE and DB_RECYCLE_CACHE_SIZE. The size of
the Default pool is whatever space is left over from the other two. Determine
which segments to cache where by viewing V$BH, V$CACHE, and
DBA_OBJECTS. Assign segments to the pools by statements like this:
ALTER TABLE my_table STORAGE (BUFFER_POOL KEEP);
ALTER INDEX my_index STORAGE (BUFFER_POOL
RECYCLE);
Watch buffer pool usage through V$BUFFER_POOL and
V$BUFFER_POOL_STATISTICS.
Oracles block size is set by the init.ora parameter DB_BLOCK_SIZE. 9I
allows you to have different block sizes for different tablespaces. For each
non-standard (or additional) block size for which you create a tablespace,
you are required to create a database buffer cache with that block size. Use
these new init.ora parms to specify the sizes of the database buffers for
these additional block sizes:
DB_2K_CACHE_SIZE DB_4K_CACHE_SIZE DB_8K_CACHE_SIZE
DB_16K_CACHE_SIZE DB_32K_CACHE_SIZE

Related Topics
As well as maximizing the database buffer hit ratio, youll also want to
minimize Free Buffer Waits and Buffer Busy Waits.
View the performance of Oracles Database Writer background process in
V$SYSTEM_EVENT and V$SYSSTAT. (Or, of course, use
UTLBSTAT/UTLESTAT, StatsPack, or the OEM GUI for this purpose). To
tune Database Writer:
On computers that do not support asynchronous I/O, set the init.ora
parameter DBWR_IO_SLAVES to create slave processes to simulate
asynchronous I/O.
Or create up to 10 Database Writers by setting the init.ora parameter
DB_WRITER_PROCESSES. The default for this parm is 1 (one
Database Writer). If you specify this parm, you should not specify
DBWR_IO_SLAVES.
In Oracle, caching a table in memory means that its buffers are not placed
on the least recently used end of the LRU list when they are accessed via a
full table scan. Instead they are placed on the most recently used end so
theyll tend to remain in the cache longer. Cache a table in memory by
creating it with the CACHE keyword on the CREATE TABLE statement. Or
run:
ALTER TABLE my_table CACHE;


Performance Tuning (IZ0-033)

Or even use a hint to cache:
SELECT /*+ CACHE */ column_name FROM my_table;

Tuning Oracle Redo and Archiving
The Redo Log Buffer is used by Oracle to cache redo records (database change records). These are eventually
written out to the redo logs on disk by the Log Writer (LGWR) background process. Recall that Oracle Redo Logs on
disk are written to in circular fashion by LGWR. If the database is in archivelog mode, Redo Log information is saved
to archive log files. Otherwise, Redo Log records are overwritten by LGWR (and destroyed) when that log file is next
reused.
To tune the redo log buffer, look in V$SYSSTAT and V$SESSION_WAIT. The goal is to ensure that the Redo Log
Buffer Retry Ratio is less than 1%, and that there is a low number of waits for the system event log buffer space.
The size of the redo log buffer is set in the init.ora parameter LOG_BUFFER. You can increase the size of this buffer
if this would help performance. You can also reduce the generation of redo by using the UNRECOVERABLE and
NOLOGGING keywords on CREATE statements for tables, indexes, and tablespaces. Of course, using these
keywords has implications for data recovery of which you need to be aware.
To tune the online redo log files, look for system events Log File Switch Completion and Log File Parallel Write in
V$SYSTEM_EVENT. Too frequent log switches or slow switches indicate that tuning is needed. Typical responses
are to add more online redo log files or to make them bigger.
If the database is in archivelog mode, you must manage Oracles background Archiver process to ensure:
The archive destination directory does not run out of space. Oracle hangs until this problem is fixed.
The archive background process(es) (ARCn) keep up with the Redo Log switching. If not, the system has to
wait for the Archiver to complete.

Monitor these events in V$ARCHIVE_DEST, V$ARCHIVE_PROCESSES, and V$SYSTEM_EVENT. Fix problems by
adding space to the archive log destination directory. Oracle will automatically start more archive processes if they
are needed. View V$ARCHIVE_PROCESSES to see how many you have. Set the init.ora parameter
LOG_ARCHIVE_MAX_PROCESSES if you want to start more archivers at instance startup. Valid values range from
1 through 10, with a default value of 1.

Tuning Disk I/O
For performance, you want to reduce the amount of physical I/O or real I/O that occurs on the system. Tune these
database structures to accomplish this: datafiles, the Database Writer background process, segment data blocks, sort
activity and temporary segments, and rollback segments.
To tune database I/O, set the init.ora parameter TIMED_STATISTICS to TRUE, and use StatsPack,
UTLBSTAT/UTLESTAT, OEM, or view V$FILESTAT, V$DATAFILE, and V$TEMPFILE to gather information. Then
tune using these recommendations:
Ensure there is not excessive I/O to the SYSTEM tablespace (which could indicate user objects reside there).
Ensure Oracle I/O does not contend with datafile I/O.
Balance real I/O across real devices and controllers.
Use Data Striping to distribute I/O. This technology writes a datafile across more than one I/O device. RAID or
OS-supported striping can accomplish this. Or, you can stripe manually in Oracle, by creating multiple datafiles,
each of which resides on a different device, for one tablespace. This works fine but requires some manual effort.


Performance Tuning (IZ0-033)

Use Locally Managed Tablespaces (LMT). These use bitmaps in datafile headers to manage space rather
than free lists in the Data Dictionary. This is faster and more efficient because Oracle does not have to access
the Data Dictionary so much just to manage space in the tablespaces. LMTs are recommended for all new
tablespaces you create. Specify their use on the CREATE TABLESPACE statement.
Set the init.ora parameter DB_FILE_MULTIBLOCK_READ_COUNT to something bigger than its default value
of 8. This determines how many database blocks a Server Process reads in one I/O operation during full table
scans. High values are especially warranted for read-only or data warehouse applications. Monitor full table
scan activity and impact by V$SESSION_LONGOPS.
Raw devices (aka also known as - asynchronous devices) give Oracle direct I/O authority, leaving out the
operating systems file system drivers. This traditionally was much faster than the alternative, file system I/O
(aka cooked devices or synchronous I/O), though on modern systems the difference may be negligible.
Ensure you have defined at least the minimum recommended tablespaces: SYSTEM, TOOLS, USERS, TEMP,
RBS, APPL_DATA, and APPL_IDX.
Use Automatic Undo Management (AUM) and let Oracle manage rollbacks. Recall that rollback segments
contain before-change images. J ust set the init.ora parameter UNDO_MANAGEMENT=AUTO and specify an
UNDO_TABLESPACE. You can also specify UNDO_RETENTION=seconds_value to tell how long to keep
rollback information after transactions commit. Increasing this value can eliminate SNAPSHOT TOO OLD
errors. Its default is 900 seconds. Monitor the Undo Tablespace by viewing DBA_TABLESPACE and
V$UNDOSTAT.
Use Oracle Flexible Architecture (OFA) in laying out the datafiles on the Oracle disks. This ensures better
performance by spreading out I/O across disks.
Minimize non-database I/O on the server (do not share the database server with other non-database activities,
for example, by using it as a file server or as another kind of server as well).

Tuning Segment I/O
A Database contains many tablespaces; Tablespaces each have one or more datafiles in which they store data;
Segments contain one or more extents; Extents consist of one or more contiguous oracle blocks; Blocks are
composed of contiguous operating system blocks (or pages). Here are some performance rules of thumb:
The oracle block size should optimally be a multiple of the operating systems block size.
Segments stored in Locally Managed Tablespaces (LMTs) perform better.
Larger extents perform better than smaller ones because they need to extend less and cause less I/O during full
table scans. (Their potential downside is more wasted space.)
The High Water Mark (HWM) is the highest block ID ever used to store data. A full table scan causes all
blocks up to the HWM to be read (even if some no longer contain data). Reset the HWM for greater efficiency
by rebuilding the table (either by exporting and re-importing it, or by the ALTER TABLEMOVE command).
Row migration occurs when a previously inserted row is updated and no longer fits in its original location. Chained
rows occur when an inserted row is longer than the size of a database block and must be stored by Oracle in a series
of two or more chained blocks. Eliminate these inefficiencies by the following:
Run the Oracle script UTLCHAIN.SQL one time to create the table CHAINED_ROWS
Run the command: ANALYZE TABLE my_table LIST CHAINED ROWS;
Copy the migrated and/or chained rows to another temporary table.
Delete them from the original table.
Re-insert them from the temporary table back into the original table.
Update the statistics by:


Performance Tuning (IZ0-033)

ANALYZE TABLE my_table COMPUTE STATISTICS;

Tuning Sort I/O
SQL statements that may cause sort I/O use these clauses: ORDER BY, GROUP BY, SELECT DISTINCT, UNION,
INTERSECT, MINUS, ANALYZE, CREATE INDEX, and joins between columns that are not indexed.
Measure sort activity by V$SYSSTAT, V$SORT_SEGMENT and V$SORT_USAGE.
To minimize real I/O in sorts:
Dont code the above clauses in SQL that cause sorts
Ensure that users Temporary tablespaces are defined with the keyword TEMPORARY.
Adjust the following init.ora parameters for optimal performance:

Init.ora Parm: Usage:
SORT_AREA_SIZE Amount of memory for each users server process for
in-memory sorts
SORT_AREA_
RETAINED_SIZE
Amount of memory retained from SORT_AREA_SIZE
after a sort completes. Defaults to same as
SORT_AREA_SIZE
PGA_AGGREGATE_
TARGET
Tells Oracle to manage its memory for all database
activities (including sorting) within this upper limit.
WORKAREA_SIZE_
POLICY
When AUTO, Oracle automatically manages memory
internally so that it does not exceed the
PGA_AGGREGATE_TARGET amount. Default is
MANUAL.

PGA_AGGREGATE_TARGET and WORKAREA_SIZE_POLICY are new in 9i. The former defaults to 0. If you
specify it, then you must set WORKAREA_SIZE_POLICY=AUTO.

Tuning Locking and Contention
A lock is a flag or indicator Oracle uses internally to control access to data. Oracle uses locks to ensure data updates
work without conflicts and to ensure data integrity (also called data consistency or data accuracy). Contention
occurs when two processes (users) each want access to the same data or resource at the same time, with access
rights that can not both be allowed if Oracle is to ensure data integrity. Locks on the same data are compatible if
Oracle can allow both at the same time; they are incompatible if Oracle can not allow them both simultaneously. To
enhance Oracle performance, reduce lock contention and locking incompatibilities. Processes that can not access
locks wait for them (are put to sleep by Oracle until the lock becomes available).
Oracle usually locks data at the row level (but can also lock at the table level). Locks are typically maintained until
either the user explicitly ends the transaction by issuing a COMMIT or ROLLBACK SQL statement, or until Oracle
implicitly (automatically) ends the transaction.


Performance Tuning (IZ0-033)

Oracle has two kinds of locks:
DML Locks (Aka TM locks) are applied on behalf of INSERT, UPDATE, and DELETE statements at the row
level (or sometimes at the table level)
DDL Locks (Aka TX locks) are applied to the Data Dictionary when table definitions are created or changed,
on the table level

The type of access a lock needs is called its lock mode. Lock modes for DML locks, for example, are Row Exclusive
(RX), Table Row Share (RS), Share (S), Share Row Exclusive (SRX), and Exclusive (X).
To monitor locks, first run the Oracle-supplied script CATBLOCK.SQL one time to create Data Dictionary views
DBA_BLOCKERS and DBA_WAITERS. Those two views show processes that are blocking others, or are waiting for
locks (respectively). Views V$LOCK and V$LOCKED_OBJECT also to monitor locks and locked objects. The
easiest way to monitor locks is simply to use the OEM GUI tool, the Lock Monitor.
To kill off a process holding a lock: get its SID and SERIAL# from V$SESSION.
Then issue: ALTER SYSTEM KILL SESSION sid,serial# ;
To minimize contention, code applications that:
Contain only short transactions (frequently issue COMMIT or ROLLBACK to end transactions)
Do not explicitly request table-level locks (i.e., do not issue the statement
LOCK TABLE IN EXCLUSIVE MODE)
Write efficient SQL

A deadlock occurs when two processes each hold an exclusive lock on a resource the other requires, and refuses to
give it up. Oracle automatically identifies deadlocks and resolves them by rolling back one of the transactions (killing
it and releasing its lock so that the other transaction can complete). Oracle writes a trace file to the
USER_DUMP_DEST directory with the details. The way to minimize deadlocks is to ensure that all applications
process resources in the same order.
Example: If two programs both process rows 17, 188944, and 3000, they should process those rows in the same
order. If they process tables A, B, and C, they should both process those tables in the same order.
Oracle manages locks by a queuing mechanism called an enqueue. The default number of enqueues is derived by
Oracle from the init.ora parameter SESSIONS. Or manually encode the init.ora parameter
ENQUEUE_RESOURCES=.



Performance Tuning (IZ0-033)

Latches
A latch is a special kind of lock Oracle uses internally to control access to its memory structures, or to serialize its
execution. Latches can be either:
Willing to Wait The process will wait for the latch and re-try
Immediate The process continues with other work if the latch is not immediately available
Monitor latches through view V$LATCH. Overall latch behavior can be seen through V$SYSTEM_EVENT, via
StatsPack, via UTLBSTAT/UTLESTAT, or via OEM Performance Manager. DBAs do not tune latches. Latch waits
indicate some other problem (e.g., insufficient space in the SGA), so you tune those root causes instead.

Free List Contention
Prior to 9I, DBAs had to watch for free list contention contention by processes wanting to simultaneously insert
data into a table. You would look in views V$SYSTEM_EVENT and V$WAITSTAT to see if free list contention was an
issue, then increase the number of free lists if needed:
ALTER TABLE my_table STORAGE (FREELISTS n) ;
With 9I, just use Automatic Segment-space Management for your tablespaces instead. Do this by specifying
SEGMENT SPACE MANAGEMENT AUTO when you create the tablespace. This uses bitmaps in the datafile
headers to manage space, totally eliminating the old free list contention problem.

Operating System Tuning
You engage in platform tuning to tune the underlying operating system (OS) on which Oracle runs.
On Unix and Linux systems, set kernel parameters properly (like SHMMAX, SHMMIN, MAXFILES, and NPROC).
Make sure that paging and swapping are working suitably, with commands like ipcs, ps, vmstat, top and sar. Never
page the SGA. Setting the init.ora parameter LOCK_SGA=TRUE prevents the OS from paging or swapping the SGA.
Under these OSs, each Oracle background process is distinct and consumes its own memory and CPU resources.
On Windows servers, the Oracle background processes run as threads under the single OS process oracle.exe.
Windows does paging only (no swapping). Be sure to turn off any unnecessary Windows services on your database
server via the Services panel.
Look at how many CPUs your system has. Then set the many CPU-related parameters in the init.ora file. They
include CPU_COUNT, PARALLEL_THREADS_PER_CPU, FAST_START_PARALLEL_ROLLBACK,
LOG_BUFFER, and PARALLEL_MAX_SERVERS.

The Resource Manager
In Oracle9I Enterprise Edition only, the Resource Manager (RM) helps you control resources and ensure they are
allocated to the processes you want. The resources it manages are: CPU; degree of parallelism; amount of undo
segment space; total number of active, concurrent sessions; and the maximum expected total time for a database
action.


Performance Tuning (IZ0-033)

To use Resource Manager, use the packages DBMS_RESOURCE_MANAGER_PRIVS and
DBMS_RESOURCE_MANAGER. Here are the steps:
Create the pending area Where all work will occur until later applied to the database.
Create one or more resource consumer groups Groups of users who have similar resource requirements
and priority.
Create one or more resource plans Collections of resource directives that determine how resources are
allocated to users.
Create one or more resource plan directives Which specify how many resources are allocated to each
resource plan.
Validate the resource consumer groups, plans, directives
Save the pending area (containing resource consumer groups, plans, and directives) to the database

You can define multiple resource plans; however, only one resource plan can be active for the instance at one time.
To set the instances resource plan dynamically, run:
ALTER SYSTEM SET RESOURCE_MANAGER_PLAN = plan_name ;
Automatic consumer group switching means that a user can be automatically switched to a secondary resource
group. This is set up and controlled by three resource plan directive parameters:
SWITCH_TIME How long a session must be active before RM switches the session to the group named in
SWITCH_GROUP. Default time is 1,000,000 seconds.
SWITCH_ESTIMATE If TRUE, RM uses the estimated execution time to decide whether to assign the session
to the SWITCH_GROUP before execution begins. Default is FALSE.
SWITCH_GROUP Group the user is switched to.
Remember that SWITCH_ESTIMATE must be set to TRUE for automatic consumer group switching to occur.
Monitor the RM through dynamic performance views V$SESSION, V$RSRC_CONSUMER_GROUP, and
V$RSRC_PLAN.
Also of interest: DBA_RSRC_CONSUMER_GROUPS, DBA_RSRC_CONSUMER_GROUPS_PRIVS,
DBA_RSRC_PLANS, DBA_RSRC_PLAN_DIRECTIVES, DBA_RSRC_MANAGER_SYSTEM_PRIVS, and
DBA_USERS. Or better yet, take the easy way out and use the GUI provided by the Resource Manager OEM tool.

Das könnte Ihnen auch gefallen