Tải bản đầy đủ (.pdf) (40 trang)

Tài liệu ORACLE8i- P19 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (396.58 KB, 40 trang )

CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
716
And here are the results:
TABLE_NAME PCT_FREE PCT_USED

EMPLOYEE 1 1
It’s pretty obvious that the problem is that the block storage settings have been
very badly done indeed.
3. Let’s fix the block storage parameters with an ALTER TABLE command:
ALTER TABLE employee PCTFREE 20 PCTUSED 40;
Of course, you will set your PCTFREE and PCTUSED values based on the velocity
and nature of changes to the table.
4. Having fixed the table’s block storage parameters, we now move the chained
rows from the EMPLOYEE table to a temporary table called TEMP_EMP. (This
temporary table is not a global temporary table, mind you, but one we’ll create
simply to populate this data. Afterward, we’ll remove the table.) Here is the SQL
statement for this operation:
CREATE TABLE temp_emp AS
SELECT * FROM employee
WHERE rowid IN (select head_rowid from chained_rows);
NOTE Note that we don’t use a “real” temporary table for this table because we don’t
want to accidentally lose this data should the database crash or the session fail. Core
dumps always happen when they are the most inconvenient, don’t you think?
TIP Of course, in creating your own TEMP_ table, you may want to add STORAGE
clauses, TABLESPACE clauses, and the like, but for our purposes here we’ve not done so.
The CREATE TABLE…AS SELECT… command (CTAS) is very useful for operations such as
this. It allows us to create a table using another table as a template, and then will even
populate the table for us. Notice the subquery that selects from the EMPLOYEE table all
the rows based on the ROWIDs stored in the CHAINED_ROWS table.
5. Before we continue, please raise your right hand and repeat after me: “I will back
up my database, or at least the object I’m removing chained rows from, before I do the


next step. I promise, so help me, Codd.”
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
717
6. Having done the necessary backup (you did keep your promise, didn’t you?),
you’re ready to delete records. First clear the offending chained rows from the
EMPLOYEE table:
DELETE FROM employee
WHERE rowid in (select head_rowid from chained_rows);
COMMIT;
7. Insert the rows from the TEMP_EMP table to repopulate the EMPLOYEE table
with the chained rows that were deleted:
INSERT INTO employee
SELECT * FROM temp_emp;
8. All that remains is to make sure the number of rows in the table is correct, and
that there are no chained rows remaining. To do this, ANALYZE the table again,
and then run the same checksum query as before (step 1):
ANALYZE TABLE employee COMPUTE STATISTICS;
SELECT a.table_name, a.chain_cnt, b.emp_count, a.chain_cnt/b.emp_count
From user_tables a, (select count(*) emp_count from employee) b
Where a.table_name=’EMPLOYEE’;
The results of this query are:
TABLE_NAME CHAIN_CNT EMP_COUNT A.CHAIN_CNT/B.EMP_COUNT

EMPLOYEE 0 32014 0
9. It appears we still have 32,014 rows in the table, and our chain count is now 0.
All systems go. Complete the process by dropping the temporary table you
created.

Histograms: Analyzing Data Distribution
Sometimes column data in a table is skewed so that one or two values make up a sig-
nificant percentage of the values in the column of the table. This may cause fluctuat-
ing query performance on that table. When you access the table looking for a value
(such as NO) that is present in a great percentage of the rows, using an index to do
that lookup will not be very efficient. Likewise, if the value NO shows up only once in
the column and the table is very large, an index lookup will certainly be preferable to
a full table scan.
Unfortunately, the normal statistics Oracle generates don’t provide a table data
view that is wide enough that we can determine whether a specific query would bene-
fit from an index or a full table scan. The normal statistics do track the number of dis-
tinct values in the table, but they do not track the distribution of those values. In
THE ORACLE OPTIMIZER
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
718
Oracle 7.3, histograms were introduced in an effort to correct this omission. His-
tograms are performance enhancers in cases where data values in a column are
skewed and some imbalance exists. If the data is not skewed, histograms will likely
not help performance.
You create histograms via the ANALYZE command, for both tables and indexes. An
example of creating a histogram on the DEPT column in the EMPLOYEE table would
look something like this:

ANALYZE TABLE EMPLOYEE COMPUTE STATISTICS FOR COLUMNS
Deptno SIZE 10;
A histogram has a fixed width, but variable height. The width of the histogram is
measured in “buckets.” The histogram we just created, then, will be 10 buckets long
and will remain 10 buckets long forever unless we re-create it. The height of the his-
togram is balanced along the width of the bucket. Thus every bucket has an equal
number of rows.
TIP If you are using bind variables in your SQL (which is good), Oracle will not be able
to use histograms when generating the execution plan.
Now you can examine one of the data dictionary views and find information on
the histograms you’ve created for the EMPLOYEE table. Table 16.3 lists the primary
views that contain histogram information.
TABLE 16.3: DATA DICTIONARY VIEWS THAT PERTAIN TO HISTOGRAMS
View Name Histogram Information Provided
*_PART_HISTOGRAMS Partitions in a partitioned table
*_SUBPART_HISTOGRAMS Table subpartitions
*_TAB_HISTOGRAMS Nonpartitioned tables
INDEX_HISTOGRAM Any index analyzed with ANALYZE INDEX…VALIDATE
STRUCTURE
* These views will be prefixed with ALL, USER, or DBA.
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
719
Analyzing with Oracle Supplied Packages
In addition to the ANALYZE command, you can use one of the Oracle-supplied pack-
ages to analyze the database. Here we’ll briefly look at these Oracle packages that per-
form the same actions as the ANALYZE command. For a complete listing of their
parameters, see Appendix D. Using these packages in many cases can be easier than

running the ANALYZE command. For example, you can analyze the entire database or
an entire schema, a process that otherwise would require the issuance of a great num-
ber of ANALYZE commands.
DBMS_UTILITY.ANALYZE_DATABASE
The DBMS_UTILITY.ANALYZE_DATABASE procedure analyzes the entire database,
with the exception of data dictionary objects. Following is an example of a statement
to run the procedure:
Exec DBMS_UTILITY.ANALYZE_DATABASE(‘ESTIMATE’, estimate_rows=>1000);
This example will analyze the entire database except for SYS objects. Each object in the
database will be analyzed using 1000 as the number of rows to scan to generate esti-
mated statistics. You can also compute database statistics when using this procedure.
DBMS_UTILITY.ANALYZE_SCHEMA
The DBMS_UTILITY.ANALYZE_SCHEMA procedure analyzes a specific schema in the
database. In the following example:
Exec DBMS_UTILITY.ANALYZE_SCHEMA
(’SCOTT’,’ESTIMATE’, estimate_rows=>1000);
the SCOTT schema is analyzed. The procedure does an ESTIMATE scan, using 1000 as
the number of rows to scan to generate the estimated statistics. You can also choose
to compute statistics for all objects in the schema.
DBMS_DDL.ANALYZE_OBJECT
The DBMS_DDL.ANALYZE_OBJECT procedure analyzes a specific object in the data-
base. Note that this procedure allows you to analyze a partition in an object, whether
that object is a partitioned table or a partitioned index. Here’s an example of running
the DBMS_DDL.ANALYZE_OBJECT procedure:
Exec DBMS_UTILITY.ANALYZE_OBJECT
(‘TABLE’, ‘SCOTT’, ’EMPLOYEE’, ’ESTIMATE’, estimate_rows=>1000);
This call will analyze the EMPLOYEE table in the SCOTT schema. It will use 1000 rows
to estimate the table statistics.
THE ORACLE OPTIMIZER
Beyond Simple

Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
720
DBMS_UTILITY.ANALYZE_PART_OBJECT
The DBMS_UTILITY.ANALYZE_PART_OBJECT procedure analyzes a partition of a spe-
cific partitioned object in the database. An example of running this procedure would
be as follows:
Exec DBMS_UTILITY.ANALYZE_PART_OBJECT
(‘TABLE’, ‘PART_TAB’, ’T’, ’E’,sample_clause=>’SAMPLE 10 PERCENT’);
This will analyze the partitioned table SCOTT, using the ESTIMATE method of analyz-
ing the partitioned table, and using a sample of 10 percent of the rows when analyzing
the partition.
Oracle Execution Plans
The “bottom line” output of the optimizer is the execution plan—the heart of a SQL
statement’s operation. The execution plan is Oracle’s plan of attack for getting the
data you request with your SELECT statements.
In this section we show you how to get your hands on the execution plans of your
SQL statements, and even those of other users’ SQL running in your system. You’ll
learn how to read a SQL statement’s execution, so you can know how you’re getting
your data. All of this is in preparation for tuning your SQL statement so it runs like a
greased monkey on fire. (Apologies to PETA. No animals were injured in the making
of this book.)
Generating SQL Execution Plans
Before you can read and interpret an execution plan, you must first generate the plan

via any of the following methods:
• Use TKPROF to analyze the session’s trace file and generate execution plans.
• Use the AUTOTRACE command in SQL*Plus.
• Use the EXPLAIN PLAN command to generate the execution path for a given
SQL statement.
Tracing Oracle Sessions and TKPROF
One method of generating execution plans for SQL statements is to trace the user ses-
sion in which the statement is running. Once you have traced the session, you use
the Oracle utility TKPROF to format the trace file into a more readable format. You set
a flag in TKPROF so that it will generate an execution plan for each SQL statement
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
721
that’s run. Let’s first look at the process for tracing your Oracle session, and then we’ll
generate a report on the resulting trace file using TKPROF.
Tracing Your Session
To trace a session in which you’ll execute a SQL statement (including execution of
any PL/SQL program units), issue the command
ALTER SESSION SET SQL_TRACE=TRUE;
Oracle will create a trace file in the user_dump_dest directory that is defined in the
init.ora parameter file.
Table 16.4 shows other database parameters that affect tracing.
TABLE 16.4: INIT.ORA PARAMETERS THAT AFFECT TRACING
Parameter Name Description
USER_DUMP_DEST This is the directory for user-directed dumps on a database. You can
change this parameter dynamically with either the ALTER SYSTEM or
ALTER SESSION command.
TIMED_STATISTICS Allows timing statistics to be enabled (see Chapter 15).

MAX_DUMP_FILE_SIZE Defines the maximum size of the trace file.
SQL_TRACE Enables the Oracle trace facility. Can be turned on for a session with
ALTER SESSION or database-wide with ALTER DATABASE.
WARNING Although it is possible to do so, setting TRACE on for the entire database
can have negative effects on system performance. You can usually do what you need to do
by tracing a session rather than the database.
You can find the specific location of the user_dump_dest directory by querying
V$PARAMETER:
SELECT name, value FROM v$parameter WHERE name = ’user_dump_dest’;
The name of the trace file on a Unix system is typically in this form:
{db_name}_ora_{spid}.ora
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
722
where db_name is the name of the database, and spid is the operating system process
identifier (SPID) value from V$PROCESS for the session being traced. Thus, a trace
file’s name might look like ora8i_ora_1102.trc on Unix for a database called ora8i
and for a session with a SPID of 1102.
On NT the filename format is a bit different:
{db_name}{spid}.ora
where db_name is the name of the database, and spid is the SPID value from V$PROCESS
for the session being traced. The SPID is zero filled to five digits. (Before Oracle8i you

had to do some pretty wild conversions to get the right trace filename, but this is no
longer true.)
NOTE As always with Oracle, anything can change. The naming convention of trace files
is not documented all that well, and may change in subsequent releases.
Using TKPROF to Reformat the Trace File
Once the trace file has been generated and you have completed the execution of the
SQL statements on which you want to see the executions plans, you’ll run the TKPROF
utility. TKPROF reads the trace file and formats and sorts it into a friendlier format.
For the entire session traced, TKPROF output provides
• Total counts for parse, execute, and fetch operations
• Total CPU and elapsed time for parse, execute, and fetch operations
• Cumulative disk I/O statistics for parse, execute, and fetch operations
• Total number of rows processed by the session
For each individual statement execution, TKPROF provides
• Total counts for parse, execute, and fetch operations for that statement
• Total CPU and elapsed time for parse, execute, and fetch operations for that
statement
• Cumulative disk I/O statistics for parse, execute, and fetch operations for that
statement
• Total number of rows processed for that session
• Optimizer goal used for the query
• Number of library cache misses encountered by the query
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
723
• An execution plan for each SQL statement executed (if the EXPLAIN parameter
of TKPROF is used)
Following is the syntax for the TKPROF command, and Table 16.5 lists its command-

line parameters:
TKPROF tracefile outputfile [explain= ] [table= ]
[print= ] [insert= ] [sys= ] [sort= ]
TABLE 16.5: TKPROF COMMAND-LINE PARAMETERS
Parameter Description
AGGREGATE={YES/NO} The default YES causes identical SQL statements to be shown
only once in the report, and the overall run statistics are com-
bined. Setting aggregate to NO causes identical SQL state-
ments to be shown individually.
EXPLAIN=USER/PASSWORD Creates an execution plan for each SQL statement executed,
using the schema selected for the plan. Selected schema
must have the CREATE SESSION system grant and have access
to the objects accessed during SQL statement execution.
FILENAME ONE The trace to be formatted.
FILENAME TWO The output file that will contain the formatted TKPROF results.
INSERT={filename} Causes TKPROF to create a SQL script called filename that
contains commands to create a database table. TKPROF then
populates the script with INSERT statements that will cause
the trace file statistics to be INSERTed into the created table.
PRINT={n} Lists only the first n SQL statements. The default is to print all
statements.
RECORD={file_name} Creates a SQL script that contains all nonrecursive SQL exe-
cuted by the session so it is available for replay if desired.
SORT {options} Sorts the SQL statements on the options specified. Valid
options:
EXECNT = By number of execute calls made
EXECPU = By CPU execution time spent
EXECU = By number of buffers for current read during
execute
EXEDSK = By number of disk reads during execute

EXEELA = By elapsed execution time
EXEMIS = By number of library cache misses during execute
EXEQRY = By number of buffers for consistent read during
execute
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
724
TABLE 16.5: TKPROF COMMAND-LINE PARAMETERS (CONTINUED)
Parameter Description
EXEROW = By number of rows processed during execute
FCHCNT = By number of times fetch was called
FCHCPU = By CPU fetch time spent
FCHCU = By number of buffers for current read during fetch
FCHDSK = By number of disk reads during fetch
FCHELA = By elapsed fetch time
FCHQRY = By number of buffers for consistent read during
fetch
FCHROW = By number of rows fetched
PRSCNT = By number of times parse was called
PRSCPU = By CPU parse time spent
PRSCU = By number of buffers for the current read during
parsing

PRSDSK = By number of disk reads during parsing
PRSELA = By elapsed parsing time
PRSMIS = By number of misses in library cache during
parsing
PRSQRY = By number of buffers for consistent read during
parsing
USERID = Sort by the USERID of user who parsed the cursor
SYS={YES/NO} Enables (default) and disables the inclusion of SQL state-
ments that are issued by SYS in the TKPROF output file,
including recursive SQL or any statement executed by SYS.
This parameter has no effect on the output to the SQL file
created by use of the INSERT parameter.
TABLE={schema.table_name} Directs TKPROF to load execution plans temporarily into an
alternate table. (By default, TKPROF uses PROF$PLAN_TABLE.)
TKPROF will create, use, and remove the alternate table if it
does not exist. If the alternate table does exist, TKPROF will
delete any existing rows in that table and then populate it.
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
725
About Setting TIMED_STATISTICS
You’ll notice that some information reported in trace files and in the ultimate TKPROF
output from those trace files (as well as in execution plans generated using SET AUTO-
TRACE ON) is dependent on the TIMED_STATISTICS parameter being enabled in the
database init.ora file. This is because TIMED_STATISTICS provides elapsed-time infor-
mation for each operation that is being traced.
There is a great deal of contention over the advisability of leaving TIMED_STATISTICS
enabled all the time. The truth is that there is not that much overhead associated with

having it set this way. The benefits are significant, and leaving the parameter enabled
provides the DBA with additional information for database tuning.
Finally, note that TIMED_STATISTICS is a dynamic parameter; it can be turned on or off
using either the ALTER SYSTEM or ALTER SESSION commands.
Output Generated by TKPROF
Let’s look at an example from the wealth of information provided by TKPROF. The
trace file you use will be generated by a session that issued just one query:
SELECT COUNT(*) FROM employee;
Once you have the trace file, you process it with TKPROF. For this sample, we have
used the following TKPROF command line:
TKPROF ora00104.trc traceout.txt explain=scott/tiger sys=no
This command causes TKPROF to process the trace file ora00104.trc and create an
output file called traceout.txt. Using the EXPLAIN parameter, we instructed
TKPROF to create execution plans (which is what we are after in this chapter). Finally,
using SYS=NO, we instructed Oracle to remove all SYS queries, which includes any
recursive SQL.
Listing 16.1 shows the output trace file, including the execution plan.
Listing 16.1: TKPROF Output File
TKPROF: Release 8.1.6.0.0 - Production on Fri Dec 29 23:51:07 2000
(c) Copyright 1999 Oracle Corporation. All rights reserved.
Trace file: ora00104.trc
Sort options: default
***********************************************************************
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
726
select count(*)
from
EMPLOYEE
call count cpu elapsed disk query current rows

Parse 1 0.03 1.30 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 2 0.06 0.46 281 280 4 1

total 4 0.09 1.76 281 280 4 1
Misses in library cache during parse: 1
Optimizer goal: CHOOSE
Parsing user id: 25 (SCOTT)
Rows Row Source Operation

1 SORT AGGREGATE
32014 INDEX FAST FULL SCAN (object id 20774)
Rows Execution Plan

0 SELECT STATEMENT GOAL: CHOOSE
1 SORT (AGGREGATE)
32014 INDEX GOAL: ANALYZED (FAST FULL SCAN) OF ‘ID_EMP’
(NON-UNIQUE)
********************************************************************************
OVERALL TOTALS FOR ALL NON-RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows


Parse 1 0.03 1.30 0 0 0 0
Execute 2 0.01 0.01 0 0 0 0
Fetch 2 0.06 0.46 281 280 4 1

total 5 0.10 1.77 281 280 4 1
Misses in library cache during parse: 1
Misses in library cache during execute: 1
OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
call count cpu elapsed disk query current rows

Parse 12 0.10 1.09 0 0 0 0
Execute 14 0.02 0.27 0 0 0 0
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
727
Fetch 29 0.02 0.41 3 52 0 23

total 55 0.14 1.77 3 52 0 23
Misses in library cache during parse: 11
2 user SQL statements in session.
12 internal SQL statements in session.
14 SQL statements in session.
1 statement EXPLAINed in this session.
********************************************************************************
Trace file: ora00104.trc
Trace file compatibility: 8.00.04
Sort options: default

1 session in tracefile.
2 user SQL statements in trace file.
12 internal SQL statements in trace file.
14 SQL statements in trace file.
13 unique SQL statements in trace file.
1 SQL statements EXPLAINed using schema:
SCOTT.prof$plan_table
Default table was used.
Table was created.
Table was dropped.
127 lines in trace file.
The output file starts out with a header that includes simply the banner with ver-
sion information, the name of the trace file, and the sorting done on the output.
Then comes the SQL statement, and then this section, which gives statistics for the
SQL statement parse phase, execute phase, and fetch phase:
call count cpu elapsed disk query current rows

Parse 1 0.03 1.30 0 0 0 0
Execute 1 0.00 0.00 0 0 0 0
Fetch 2 0.06 0.46 281 280 4 1

total 4 0.09 1.76 281 280 4 1
Table 16.6 defines the information provided for each phase.
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA

www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
TABLE 16.6 COLUMNS IN TKPROF’S SQL EXECUTION STATISTICS
Column Name Description of Contents
CALL A list of the SQL execution phase being reported, with totals at the bottom.
COUNT Number of times the phase occurred. Statements that are parsed once but
executed 10 times will have a 1 in the Parse line for this column, and a 10
in the Execute line for this column.
CPU If TIMED_STATISTICS is enabled, this column shows the CPU time required
for the phases.
ELAPSED If TIMED_STATISTICS is enabled, this shows the total elapsed time required
for the phases. Includes non-CPU time such as time required by network-
ing connections and disk I/O waits.
DISK Total number of disk reads required.
QUERY One part of logical reads. Add this to values in CURRENT column to get
the total number of logical reads.
CURRENT Second part of logical reads. Add this to values in QUERY column to get
the total number of logical reads.
ROWS Total number of rows processed. Only the fetch stage will display non-0
numbers for this column.
Pertinent Ratios in TKPROF Output
In the SQL execution output of the TKPROF output, there are several ratios of particu-
lar interest to the DBA.
Disk Reads vs. Query + Current Because physical I/O is always much more
expensive than logical I/O, look at the total values in the disk column compared to the
total combined values of the query and current columns (DISK : QUERY + CURRENT).
This ratio is a measure of the database buffer cache hit ratio, so use that formula to
determine if you are getting good hits out of the buffer cache. Anything less than 90
percent is bad news.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING

728
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
Disk Reads vs. Total Rows Returned If you have a large number of physical
reads as well as a large number of rows returned, some possible culprits could be sig-
nificant full table scans, or even an undersized SGA.
Total Blocks Read vs. Total Rows Returned Review the number of blocks read
(CURRENT + QUERY) and the number of rows returned to the user (ROWS). If you are
reading a great many blocks and returning only a single row, there may be a better way
to write your SQL statement. Or it may be that changing the database architecture
(indexes particularly) could improve the query’s performance. In the output shown in
Listing 16.1, we combine the total QUERY and CURRENT columns (280 + 4 = 284) and
take the total of the ROWS column (1), giving an astounding 284:1 ratio of blocks read
for each row. Experts say that ratios greater than 20:1 beg to be tuned; the standard is
somewhat lower for indexed lookups or partitioned table/index accesses. Shoot for
about 5:1 to 10:1 maximum.
Parse Rate vs. Executions If the number of parses relative to the number of exe-
cutions is high, review your SQL statements for reusability and check your applications
to make sure they are reusing cursors.
Rows Fetched vs. Number of Fetches The ratio of rows fetched to the number
of fetches is a measure of the effectiveness of the array fetch facility in certain Oracle
tools and applications. If the ratio is low, you may be able to tune your application to
take advantage of Oracle’s array fetching feature. Review your application development
manuals (PRO*C, Java) for more information on how to take advantage of array fetching.
After the numbers associated with the execution of the SQL statement come the
following lines of the output:
Misses in library cache during parse: 1
Optimizer goal: CHOOSE

Parsing user id: 25 (SCOTT)
These statements tell you that you had a library cache miss during SQL statement exe-
cution; that the optimizer goal is set to CHOOSE; and that SCOTT is the user who
executed this particular bit of SQL. If multiple users executed the statement, the user
who last executed the statement is listed.
Next comes the execution plan for the statement: This plan actually contains two
execution plans, as shown just below, and you’ll find detailed discussions of how to
read them in the upcoming section “Reading and Interpreting Execution Plans.”
729
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
730
Rows Row Source Operation

1 SORT AGGREGATE
32014 INDEX FAST FULL SCAN (object id 20774)
Rows Execution Plan

0 SELECT STATEMENT GOAL: CHOOSE
1 SORT (AGGREGATE)
32014 INDEX GOAL: ANALYZED (FAST FULL SCAN) OF ‘ID_EMP’
(NON-UNIQUE)

Next up in the TKPROF output are the total overall statistics for the entire session.
These are in the same format as the earlier individual statement statistics, but here
they’re divided into statistics for recursive SQL and nonrecursive SQL.
Finally, you get some summary information for the session traced. This informa-
tion includes the number of user and internal (recursive) SQL statements, the number
of sessions and users, and so on. This summary section also tells you which schema
was used to generate the execution plan for the SQL statements.
Examples of Running TKPROF
Let’s study a few examples of running TKPROF. This first example shows TKPROF with
no parameters other than the required input and output file names:
TKPROF ora00104.trc traceout.txt
If we wanted to execute a TKPROF, generating execution plans for all SQL state-
ments, we would issue a command like this:
TKPROF ora00104.trc traceout.txt explain=scott/tiger
Say we wanted to sort this report by the total elapsed time spent fetching, and then
by the total disk reads during the fetch stage. Here’s the command for that report:
TKPROF ora00104.trc traceout.txt explain=scott/tiger
sort= (fchela, fchdsk)
The following command eliminates system calls from the output and creates a
script called insert.sql that will load the TKPROF results into an Oracle table:
TKPROF ora00104.trc traceout.txt explain=scott/tiger
sort= (fchela, fchdsk) insert=insert.sql
What if you wanted to create a .sql script that contained all the SQL statements in
the trace file? If you wanted to run this script from SQL*Plus to replay all SQL state-
ments on a database, you would include the RECORD parameter as shown here:
TKPROF ora00104.trc traceout.txt explain=scott/tiger
sort= (fchela, fchdsk) insert=insert.sql record=record.sql
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com

Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
731
As you can see, TKPROF is a powerful tool for overall performance tuning. It’s gen-
erally not used as a proactive monitoring tool, however, because the cost of session
and database tracing can be expensive. Oracle does offer some alternatives, which
we’ll discuss next.
Using SQL*Plus Autotrace
Because tracing is expensive in terms of system resources and a bit cumbersome to
implement, Oracle offers some other choices for monitoring. One is the excellent
SQL*Plus Autotrace facility, which was added in the Oracle 7.3 days. Autotrace allows
you to generate execution plans after every SQL statement. It also provides you with
additional information such as physical and logical read information.
Setting up Autotrace doesn’t take a lot of effort. The user/schema you are signed in
to must have a plan table (PLAN_TABLE) installed; without this table, you’ll get an error
message. The PLAN_TABLE is populated with the current SQL execution plan and then
read. The execution plan is formatted and presented to the user automatically.
To create the PLAN_TABLE, use the Oracle script utlxplan.sql in the $ORACLE_
HOME/rdbms/admin directory.
Because the signed-on user must have the plan table installed in order to run Auto-
trace, the DBA may need to create multiple plan tables. An even better arrangement is
to create one plan table, grant everyone else access to it, and set up synonyms point-
ing to that table. (Grants and synonyms are covered in Chapter 21 on database secu-
rity.) In Listing 16.2 you can see an example of creating PLAN_TABLE using the
utlxplan.sql script. We log in as user PLAN, which has already been created for this
purpose. We then grant the user SCOTT access to the plan table, facilitating access
through a synonym.
Listing 16.2: Setting Up the Plan Table for Autotrace
C:\>sqlplus plan/plan
SQL*Plus: Release 8.1.6.0.0 - Production on Sat Dec 30 01:40:26 2000
(c) Copyright 1999 Oracle Corporation. All rights reserved.

Connected to:
Oracle8i Enterprise Edition Release 8.1.6.0.0 - Production
With the Partitioning option
JServer Release 8.1.6.0.0 - Production
SQL> @d:\oracle\ora816\rdbms\admin\utlxplan.sql
Table created.
SQL> grant all on plan_table to scott;
Grant succeeded.
SQL> connect scott/tiger
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
732
Connected.
SQL> create synonym plan_table for plan.plan_table;
Synonym created.
With the plan table established, you can enable Autotrace, with the command SET
AUTOTRACE ON. Note that this command works only in SQL*Plus; it does not work
with Server Manager.
When Autotrace is running, Oracle will return to you the execution plan of every
SQL statement that executes. You’ll also get various runtime information, such as
physical and logical reads that occurred during the execution of the SQL statement,
and the number of sorts and disk sorts that occurred.

NOTE About Sorting: When examining run statistics, watch the sorts that occur. If you
see lots of sorts to disk, shown as
sorts (disk), check the SORT_AREA_SIZE setting. Ver-
ify that it’s allocating enough memory for sorting. Sorts to disk are going to be slower on
the order of a magnitude than a sort in memory. When tuning SQL, make every attempt to
get sort operations overall, whether to disk or memory, down to 0. Sort stats can tell you
when an index needs to be built. Operations such as ORDER BY, DISTINCT, and GROUP BY
can force Oracle to perform sort operations if indexes are not available on the objects
being queried.
Listing 16.3 shows output from a SQL*Plus session with Autotrace enabled.
Listing 16.3: Output from SQL*Plus with Autotrace
SQL> set autotrace on
SQL> select count(*) from EMPLOYEE;
COUNT(*)

32014
Execution Plan

0 SELECT STATEMENT Optimizer=CHOOSE (Cost=43 Card=1)
1 0 SORT (AGGREGATE)
2 1 INDEX (FAST FULL SCAN) OF ‘ID_EMP’ (NON-UNIQUE) (Cost=43
Card=32014)
Statistics

0 recursive calls
4 db block gets
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

733
280 consistent gets
0 physical reads
1 sorts (memory)
0 sorts (disk)
1 rows processed
Using EXPLAIN PLAN
The old standby method of generating execution plans is to use the SQL command
EXPLAIN PLAN (see Appendix F for the complete syntax of this command). As
explained for Autotrace just above, EXPLAIN PLAN requires the presence of a plan
table that is generated by executing the utlxplan.sql script. Execute this script in the
schema in which you want to generate execution plans.
The EXPLAIN PLAN command requires that you feed it a SQL statement and an
identifier for the statement. In return, the EXPLAIN PLAN command populates
PLAN_TABLE with the execution plan for that SQL statement. A call to the EXPLAIN
PLAN command looks like this:
EXPLAIN PLAN set statement_id=’1’ FOR
SELECT COUNT(*) FROM EMPLOYEE;
To get the execution plan out of the plan table, you query PLAN_TABLE. There are
several versions of queries that do this, but Oracle provides a couple that work rela-
tively well. Called utlxpls.sql and utlxplp.sql, they are both found in the $ORACLE_
HOME/rdbms/admin directory. The primary difference between the two is that utlxplp
.sql provides some parallel query statistics. An example of the utlxpls.sql output is
shown just below (utlxplp.sql looks pretty much the same). In the upcoming sec-
tion on reading execution plans, we’ll actually dissect this particular plan.
Plan Table

| Operation | Name | Rows | Bytes| Cost | Pstart| Pstop |

| SELECT STATEMENT | | 1 | | 43 | | |

| SORT AGGREGATE | | 1 | | | | |
| INDEX FAST FULL SCAN |ID_EMP | 32K| | 43 | | |

Tracing Other Users’ Sessions
Sometimes a DBA or other user needs to trace another’s session to which they do not
have direct access. This may be the case when an application does not afford you the
opportunity to turn on tracing before the application executes. Or it might be that a
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
734
DBA notices odd behavior in a particular user’s session (perhaps it’s using substantial
CPU resources or doing lots of disk sorts), and you want to trace the session unobtru-
sively. Oracle8i provides a procedure to do just that: It’s a procedure called
SET_SQL_TRACE_IN_SESSION, in the largely undocumented package DBMS_SYSTEM.
(See Chapter 20 and Appendix D for a look at Oracle-supplied packages.)
Here’s the definition of the procedure:
DBMS_SYSTEM.SET_SQL_TRACE_IN_SESSION
(SID NUMBER IN
SERIAL# NUMBER IN
SQL_TRACE BOOLEAN IN );
The procedure takes three parameters. The first two, the user SID and SERIAL#, are
derived from V$SESSION; together they uniquely identify the user session. The final

parameter is a Boolean, either TRUE (session trace turned on) or FALSE (session trace
turned off).
Let’s say we want to trace the session that Scott is currently running. First, we
query the V$SESSION table to determine the SID and SERIAL# column values for his
session:
SQL> select sid, serial#
2 from v$session
3 where username=’SCOTT’;
SID SERIAL#

13 5407
Now we execute the SET_SQL_TRACE_IN_SESSION procedure of DBMS_SESSION to
start tracing this session, as follows:
SQL> exec dbms_system.set_sql_trace_in_session(13,5407,TRUE);
PL/SQL procedure successfully completed.
Once you’ve collected all the trace information you need, end the trace of the session
with this command:
SQL> exec dbms_system.set_sql_trace_in_session(13,5407,FALSE);
PL/SQL procedure successfully completed.
Reading and Interpreting Execution Plans
In our opinion, reading and interpreting execution plans is a bit of an art. Now that
you’ve learned how to get hold of one, let’s examine its parts and see what it tells us.
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
735
The Execution Plan’s Order of Operations
Each step in the execution plan has an output in the form of a row source that is
passed on to the next step. Some steps, called access paths, produce the row sources

from the database. Other steps, such as sort operations, just manipulate the rowsets
passed to them. Some operations can return rowsets as they are being processed, and
other operations wait until the entire rowset is processed before working on it. All of
these approaches affect your tuning efforts. All of these operations put together ulti-
mately produce the output that you requested in your SQL statement. So our first task
is to determine the order in which the operations run.
The optimizer’s job is to find the most efficient way to get to the required output.
In doing so, it chooses from a variety of possible access paths and picks the ones that
appear to be the most efficient. As the optimizer selects these paths, it assigns an effi-
ciency cost to the various paths and execution plans.
Example 1
Here’s the first example of an execution plan (generated using Autotrace in SQL*Plus)
and its related query:
SET autotrace on
SELECT a.empno, a.ename, b.dname
FROM EMPLOYEE a, dept b
WHERE a.deptno=b.deptno;
Execution Plan

0 SELECT STATEMENT Optimizer=CHOOSE (Cost=2590 Card=6723 Bytes=242028)
1 0 HASH JOIN (Cost=2590 Card=6723 Bytes=242028)
2 1 TABLE ACCESS (FULL) OF ‘DEPT’ (Cost=1 Card=21 Bytes=462)
3 1 TABLE ACCESS (FULL) OF ‘EMPLOYEE’ (Cost=2581 Card=32014 Bytes=448196)
When parsing an execution plan, Oracle uses a reverse transversal algorithm. Ein-
stein might have loved this term, but for the rest of us it’s a little abstract. It means
that Oracle starts with the deepest operations first (those indented the farthest) and
moves up from there. The preceding example shows three operations, each marked
with an operation number at the far left. Operation 1 is a hash join. Operation 2 is a
full table access of the DEPT table. Operation 3 is a full table access of the EMPLOYEE
table. For now, don’t worry about what these operations are. Just try to understand

which one takes place first. (In case you were wondering, the second column of num-
bers in the execution plan identifies the parent step of the plan. In the foregoing
example, step 1 is the parent step to steps 2 and 3.)
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
736
Here are some basic rules to keep in mind about execution plans:
1. The statement that is indented the most is the first step.
2. If two or more statements are indented at the same level, the topmost of these
statements is executed first.
3. An index lookup associated with a table scan should be considered a single step.
This is important because certain types of index scans are not coupled with
table lookups.
4. If a parent step can process the row source returned from the child operation,
Oracle will execute that step. This process can be cascaded up the entire execu-
tion plan chain until execution reaches an operation that requires all row sources
to be executed. The operations that typically require all row sources are sorts and
certain types of joins. (We’ll discuss such operations later in this chapter.)
Based on these rules, the full table scan of DEPT (operation 2) is executed first. This
is followed by the full table scan of EMPLOYEE (operation 3) and then the hash join
(operation 1). Again, ignore the actual purpose of the operations for now.
Example 2

Let’s look now at a slightly more complicated example. Here is the query:
SET autotrace on
SELECT a.empno, a.ename, b.dname
FROM EMPLOYEE a, dept b
WHERE a.deptno=b.deptno
and empno<7600;
and the resulting execution plan:
Execution Plan

0 SELECT STATEMENT Optimizer=CHOOSE (Cost=46 Card=30 Bytes=1080)
1 0 HASH JOIN (Cost=46 Card=30 Bytes=1080)
2 1 TABLE ACCESS (FULL) OF ‘DEPT’ (Cost=1 Card=21 Bytes=462)
3 1 TABLE ACCESS (BY INDEX ROWID) OF ‘EMPLOYEE’ (Cost=44
Card=144 Bytes=2016)
4 3 INDEX (RANGE SCAN) OF ‘ID_EMP’ (NON-UNIQUE) (Cost=4 Card=144)
In this execution plan, the first column is the step number of the step in the plan. A
parent step is the topmost statement, or any statement to which another statement is
related. Here, statement 0 is the parent statement for the entire plan. Statement 1 is
the parent statement for statements 2 and 3. The parent statement in an execution
plan can be seen in the second column of the plan itself. A child step is any step that
has a parent. All statements in this plan are children of another step, except step 0.
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
737
This execution plan has four operations. The first two are the same as in Example 1:
a hash join (operation 1) and a full table scan of the DEPT table (operation 2). From
this point, things begin to differ. This time, operation 3 is a table access by index
ROWID; and there’s another step, operation 4, which is an index range scan lookup.

So, in what order do these steps execute? You might be tempted to say 4, 2, 3, 1,
but you’d be wrong. Operation 4 is an index scan that is associated with operation 3
(granted, we have not covered access paths yet, so you are excused if you missed this
one). Therefore, operation 4 will not run until operation 3 runs. The correct order is
really 2, 4, 3, and then 1. Here is what is really happening:
First we do the full table scan of the DEPT table. This is a hash join (see step 1). So,
during the full table scan, the entire DEPT is loaded into memory.
Now, Oracle needs to make the join on DEPTNO between the DEPT table and the
EMPLOYEE table. It finds there is an index, ID_EMP, which contains the column
DEPTNO in it. That index is used in step 4 to speed up the query. Oracle will look for
the DEPTNO value in all the rows in the EMPLOYEE table, in step 3. That rowset is
returned to step 2, and processing continues, running steps 2-4-3 over and over until
all rows are processed.
Step 2 is special in that there is no additional processing (like a sort) that has to be
done to the rowsets being returned to it. Because of this, each time the step 2-4-3 iter-
ation occurs, the rowset returned to step 1 is passed on to the user without delay. If an
operation that required a sort of the entire rowset were present (for example, a
GROUP BY operation), the user would have to wait for the results until all the rows
were returned. In other words, some operations (such as nested loop operations) pass
rowsets up the line of execution as they get them, somewhat like a river of data. Some
operations (such as a sort merge join) must receive the entire rowset before passing it
upstream, something like a dam in the middle of a river.
When tuning a query, you might find that a particular operation is preventing the
initial results from being speedily returned. You may well want to tune that operation
to return rowsets as soon as they are received. This is often the case with OLTP sys-
tems. Typically, inclusion of indexes and removal of SORT and GROUP BY operations
will call for generating execution plans that return rowsets as they are processed. On
the other hand, your choice will be different if you are running a data warehouse or
EIS system. Since in this case you’re probably looking for good overall throughput
rather than a fast return of the first processed row, the best choice will be operations

that wait until all rows are processed.
Oracle provides two hints to help you indicate your choice to the CBO:
• If you use the /*+ FIRST_ROWS */ hint, Oracle will try to optimize to return the
first row as soon as possible.
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
738
• If you use the /*+ ALL_ROWS */ hint, Oracle will try to optimize using opera-
tions that process rows in bulk, rather than processing a row at a time.
Other hints, as well, can influence the CBO in this regard, and we’ll discuss them as
the chapter progresses.
An Easier Way to Follow the Execution Order
You might have had trouble understanding the two preceding examples of execution
order. We have an alternate method of diagramming operations that just might help.
The diagrams in this section walk you through the process of diagramming the execu-
tion order of a statement (we will use Example 2 for this discussion). The plan will
look a little like a tree, so that’s what we call it. Start from the top of the execution
plan at statement 1. That’s the top of your tree. On a piece of paper, draw a circle and
put the number 1 in it (see Figure 16.1). That’s step 1, which we also call a node.
FIGURE 16.1
Step 1 of
diagramming the

execution plan
Now draw a line starting from the bottom of circle 1 and moving southwest, as
shown in Figure 16.1. Draw another circle and put in a 2; this represents statement 2
(see Figure 16.2). The line indicates that the two statements are connected, and we’ll
get to that in a moment. So now we have a branch, which is all the nodes so far, con-
nected together from one common source.
FIGURE 16.2
Step 2 of the
execution plan
diagram
At this point, because statement 2 is the first operation (and it is an access path to
data), it is considered the driving table of the query. That means the entire query is
driven off the resulting row sources returned by this one access.
1
2
Driving Table
1
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.
739
NOTE In performance tuning, it’s critical that you are using the correct driving table. The
driving table of a query generally should be the row source returning the fewest numbers
of rows (the smallest row source).
Now, move on to step 3 in the execution plan. Since step 3 is at the same level as
step 2, it is a child of step 1 and returns a row source to step 1. Step 3 is also at the
same level of indention as step 2, so you’ll diagram step 3 as coming from step 1. Drop
a line southeast from the step 1 circle, draw another circle, and enter a 3 (Figure 16.3).
FIGURE 16.3

Step 3 of the execution
plan diagram
You’re now ready to deal with step 4. Since operation 4 is indented farther in than
step three, that makes 4 a child of 3. So we draw a line down southeast from the step 3
circle and create another circle for step 4 (Figure 16.4).
FIGURE 16.4
Step 4 of the
execution plan
diagram
Now that we have diagramed the statement, it’s easy to diagram its execution. Start
at step 1 and stay to the left. Continue downward to the left until you can go no far-
ther (step 2). When you have gone as far downward as possible on the left side of the
tree, the step you’re on at that point is the first step that executes. In this case, then,
you traverse the tree downward on the left from step 1 to step 2. Since there are no
more steps below step 2 on this branch of the tree, step 2 is the first one that executes.
Figure 16.5 demonstrates the steps of execution to this point.
1
23
4
1
2 3
ORACLE EXECUTION PLANS
Beyond Simple
Database Management
PART
III
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

CHAPTER 16 • ORACLE8i SQL PERFORMANCE MONITORING AND TUNING
740
FIGURE 16.5
Tracing the flow of
execution
Now, move to the right side of the leftmost branch of the tree and move up that
branch to the parent operation of that branch (step 1). Move to the next branch to the
right, and then all the way to the bottom of the branch again; you’re now at step 4.
Move to the right side of the tree. The bottom-most node of the tree (step 4) is the
next operation to execute. So the order of execution thus far is 2, 4. Move up the tree
to the next node; that is the next operation (step 3). Finally, move up to the parent
again (step 1). Since there are no more branches off to the right, the parent will now
execute. Figure 16.6 is the last diagram in the tracing of this process.
FIGURE 16.6
Conclusion of tracing
the flow of the
execution plan
You can use this diagramming method to trace the path of any execution plan. Just
remember that you list all like indented operations off their parent, with the first
operation to the left and others off to the right of that first one. Then just trace it as
you would trace your hand and fingers. Start from the left side, and follow all the fin-
gers. Every time you reach the bottom of a finger, trace back up. As you trace up,
those operations are firing.
TIP In execution plan diagrams, along with the numbers of the operations, we like to
show the number of rows being processed. (This data is not available when using Auto-
trace, but it is when using the EXPLAIN PLAN command.) We also like to note what opera-
tion is occurring (for example, we might show a SORT-MERGE-JOIN). This is very helpful
when you are trying to tune a SQL statement.
Parent operation
Third operation

First operation
1
23
4
Parent operation
Since step 2 is the
last on the leftmost
branch, it is the first
step that executes.
1
23
4
C
opyright ©2002 SYBEX, Inc., Alameda, CA
www.sybex.com
Please purchase PDF Split-Merge on www.verypdf.com to remove this watermark.

Tài liệu bạn tìm kiếm đã sẵn sàng tải về

Tải bản đầy đủ ngay
×