This will analyze the partitioned table SCOTT, using the ESTIMATE method of ing the partitioned table, and using a sample of 10 percent of the rows when analyzingthe partition.analyz-Ora
Trang 1And 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 beenvery 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 velocityand 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 SQLstatement for this operation:
CREATE TABLE temp_emp ASSELECT * FROM employeeWHERE 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’twant to accidentally lose this data should the database crash or the session fail Coredumps always happen when they are the most inconvenient, don’t you think?
TI P Of course, in creating your own TEMP_ table, you may want to add STORAGEclauses, 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 asthis It allows us to create a table using another table as a template, and then will evenpopulate the table for us Notice the subquery that selects from the EMPLOYEE table allthe 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.”
Trang 26 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 theEMPLOYEE table:
DELETE FROM employeeWHERE 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 employeeSELECT * 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_countFrom user_tables a, (select count(*) emp_count from employee) bWhere 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 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 dothat lookup will not be very efficient Likewise, if the value NO shows up only once inthe column and the table is very large, an index lookup will certainly be preferable to
sig-a full tsig-able scsig-an
Unfortunately, the normal statistics Oracle generates don’t provide a table dataview 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
Beyond Simple Database Management
P A R T
III
Trang 3Oracle 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 areskewed and some imbalance exists If the data is not skewed, histograms will likelynot help performance
You create histograms via the ANALYZE command, for both tables and indexes Anexample of creating a histogram on the DEPT column in the EMPLOYEE table wouldlook something like this:
ANALYZE TABLE EMPLOYEE COMPUTE STATISTICS FOR COLUMNSDeptno SIZE 10;
A histogram has a fixed width, but variable height The width of the histogram ismeasured in “buckets.” The histogram we just created, then, will be 10 buckets longand 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 equalnumber 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 onthe histograms you’ve created for the EMPLOYEE table Table 16.3 lists the primaryviews that contain histogram information
TABLE 16.3: DATA DICTIONARY VIEWS THAT PERTAIN TO HISTOGRAMS
*_PART_HISTOGRAMS Partitions in a partitioned table
*_SUBPART_HISTOGRAMS Table subpartitions
INDEX_HISTOGRAM Any index analyzed with ANALYZE INDEX…VALIDATE
STRUCTURE
* These views will be prefixed with ALL, USER, or DBA
Trang 4Analyzing with Oracle Supplied Packages
In addition to the ANALYZE command, you can use one of the Oracle-supplied 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 theirparameters, see Appendix D Using these packages in many cases can be easier thanrunning the ANALYZE command For example, you can analyze the entire database or
pack-an entire schema, a process that otherwise would require the issupack-ance of a great ber of ANALYZE commands
num-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 thedatabase 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 thedatabase 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 asthe 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 base Note that this procedure allows you to analyze a partition in an object, whetherthat object is a partitioned table or a partitioned index Here’s an example of runningthe DBMS_DDL.ANALYZE_OBJECT procedure:
data-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
Beyond Simple Database Management
P A R T
III
Trang 5This will analyze the partitioned table SCOTT, using the ESTIMATE method of ing the partitioned table, and using a sample of 10 percent of the rows when analyzingthe partition.
analyz-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 thedata you request with your SELECT statements
In this section we show you how to get your hands on the execution plans of yourSQL statements, and even those of other users’ SQL running in your system You’lllearn how to read a SQL statement’s execution, so you can know how you’re gettingyour data All of this is in preparation for tuning your SQL statement so it runs like agreased 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 planvia 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 givenSQL statement
Tracing Oracle Sessions and TKPROF
One method of generating execution plans for SQL statements is to trace the user sion in which the statement is running Once you have traced the session, you usethe Oracle utility TKPROF to format the trace file into a more readable format You set
ses-a flses-ag in TKPROF so thses-at it will generses-ate ses-an execution plses-an for eses-ach SQL stses-atement
Trang 6that’s run Let’s first look at the process for tracing your Oracle session, and then we’llgenerate 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 ofany 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 theinit.oraparameter 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 orALTER 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 databasecan 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 queryingV$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:
Beyond Simple Database Management
P A R T
III
Trang 7where db_name is the name of the database, and spid is the operating system processidentifier (SPID) value from V$PROCESS for the session being traced Thus, a tracefile’s name might look like ora8i_ora_1102.trc on Unix for a database called ora8iand 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$PROCESSfor the session being traced The SPID is zero filled to five digits (Before Oracle8i youhad to do some pretty wild conversions to get the right trace filename, but this is nolonger 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 theSQL statements on which you want to see the executions plans, you’ll run the TKPROFutility 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 sessionFor 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 thatstatement
• Cumulative disk I/O statistics for parse, execute, and fetch operations for thatstatement
• Total number of rows processed for that session
• Optimizer goal used for the query
• Number of library cache misses encountered by the query
Trang 8• 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
AGGREGATE={YES/NO} The default YES causes identical SQL statements to be shown
only once in the report, and the overall run statistics are bined Setting aggregate to NO causes identical SQL state-ments to be shown individually
com-EXPLAIN=USER/PASSWORD Creates an execution plan for each SQL statement executed,
using the schema selected for the plan Selected schemamust 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 thenpopulates the script with INSERT statements that will causethe 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 madeEXECPU = By CPU execution time spentEXECU = By number of buffers for current read during
executeEXEDSK = By number of disk reads during executeEXEELA = By elapsed execution time
EXEMIS = By number of library cache misses during executeEXEQRY = By number of buffers for consistent read during
execute
Beyond Simple Database Management
P A R T
III
Trang 9TABLE 16.5: TKPROF COMMAND-LINE PARAMETERS (CONTINUED)
FCHELA = By elapsed fetch timeFCHQRY = By number of buffers for consistent read during
fetchFCHROW = By number of rows fetchedPRSCNT = By number of times parse was calledPRSCPU = By CPU parse time spent
PRSCU = By number of buffers for the current read during
parsingPRSDSK = By number of disk reads during parsingPRSELA = By elapsed parsing time
PRSMIS = By number of misses in library cache during
parsingPRSQRY = By number of buffers for consistent read during
parsingUSERID = 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 filecreated 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 itdoes not exist If the alternate table does exist, TKPROF willdelete any existing rows in that table and then populate it
Trang 10About Setting TIMED_STATISTICS
You’ll notice that some information reported in trace files and in the ultimate TKPROFoutput 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 thedatabase 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_STATISTICSenabled all the time The truth is that there is not that much overhead associated withhaving it set this way The benefits are significant, and leaving the parameter enabledprovides the DBA with additional information for database tuning
Finally, note that TIMED_STATISTICS is a dynamic parameter; it can be turned on or offusing 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 Thetrace 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 haveused 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 anoutput 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 anyrecursive 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.trcSort options: default
***********************************************************************
Beyond Simple Database Management
P A R T
III
Trang 11select 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
Trang 12Fetch 29 0.02 0.41 3 52 0 23 - - - - - - - -total 55 0.14 1.77 3 52 0 23Misses in library cache during parse: 11
2 user SQL statements in session
12 internal SQL statements in session
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_tableDefault 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 sion information, the name of the trace file, and the sorting done on the output
ver-Then comes the SQL statement, and then this section, which gives statistics for theSQL 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 0Execute 1 0.00 0.00 0 0 0 0Fetch 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
Beyond Simple Database Management
P A R T
III
Trang 13TABLE 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 ing connections and disk I/O waits
network-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 lar interest to the DBA
particu-Disk Reads vs Query + Current Because physical I/O is always much moreexpensive than logical I/O, look at the total values in the disk column compared to thetotal 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 todetermine if you are getting good hits out of the buffer cache Anything less than 90percent is bad news
Trang 14Disk Reads vs Total Rows Returned If you have a large number of physicalreads 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 arereading 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 inListing 16.1, we combine the total QUERY and CURRENT columns (280 + 4 = 284) andtake the total of the ROWS column (1), giving an astounding 284:1 ratio of blocks readfor each row Experts say that ratios greater than 20:1 beg to be tuned; the standard issomewhat lower for indexed lookups or partitioned table/index accesses Shoot forabout 5:1 to 10:1 maximum
Parse Rate vs Executions If the number of parses relative to the number of cutions is high, review your SQL statements for reusability and check your applications
exe-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 Oracletools and applications If the ratio is low, you may be able to tune your application totake advantage of Oracle’s array fetching feature Review your application developmentmanuals (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 thefollowing lines of the output:
Misses in library cache during parse: 1Optimizer goal: CHOOSE
Parsing user id: 25 (SCOTT)
These statements tell you that you had a library cache miss during SQL statement cution; that the optimizer goal is set to CHOOSE; and that SCOTT is the user whoexecuted this particular bit of SQL If multiple users executed the statement, the userwho last executed the statement is listed
exe-Next comes the execution plan for the statement: This plan actually contains twoexecution plans, as shown just below, and you’ll find detailed discussions of how toread them in the upcoming section “Reading and Interpreting Execution Plans.”
Beyond Simple Database Management
P A R T
III
Trang 15Rows Row Source Operation - -
Finally, you get some summary information for the session traced This tion includes the number of user and internal (recursive) SQL statements, the number
informa-of sessions and users, and so on This summary section also tells you which schemawas 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 ments, we would issue a command like this:
state-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/tigersort= (fchela, fchdsk)
The following command eliminates system calls from the output and creates ascript called insert.sql that will load the TKPROF results into an Oracle table:
TKPROF ora00104.trc traceout.txt explain=scott/tigersort= (fchela, fchdsk) insert=insert.sql
What if you wanted to create a sql script that contained all the SQL statements inthe 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/tigersort= (fchela, fchdsk) insert=insert.sql record=record.sql
Trang 16As you can see, TKPROF is a powerful tool for overall performance tuning It’s erally not used as a proactive monitoring tool, however, because the cost of sessionand database tracing can be expensive Oracle does offer some alternatives, whichwe’ll discuss next.
gen-Using SQL*Plus Autotrace
Because tracing is expensive in terms of system resources and a bit cumbersome toimplement, Oracle offers some other choices for monitoring One is the excellentSQL*Plus Autotrace facility, which was added in the Oracle 7.3 days Autotrace allowsyou to generate execution plans after every SQL statement It also provides you withadditional 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 thenread 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_
point-Listing 16.2: Setting Up the Plan Table for Autotrace
C:\>sqlplus plan/planSQL*Plus: Release 8.1.6.0.0 - Production on Sat Dec 30 01:40:26 2000(c) Copyright 1999 Oracle Corporation All rights reserved
SQL> grant all on plan_table to scott;
Trang 17When Autotrace is running, Oracle will return to you the execution plan of everySQL statement that executes You’ll also get various runtime information, such asphysical 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 ify that it’s allocating enough memory for sorting Sorts to disk are going to be slower onthe order of a magnitude than a sort in memory When tuning SQL, make every attempt toget sort operations overall, whether to disk or memory, down to 0 Sort stats can tell youwhen an index needs to be built Operations such as ORDER BY, DISTINCT, and GROUP BYcan force Oracle to perform sort operations if indexes are not available on the objectsbeing queried
Ver-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 onSQL> select count(*) from EMPLOYEE;
COUNT(*) -32014Execution 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
Trang 18Using EXPLAIN PLAN
The old standby method of generating execution plans is to use the SQL commandEXPLAIN PLAN (see Appendix F for the complete syntax of this command) Asexplained for Autotrace just above, EXPLAIN PLAN requires the presence of a plantable that is generated by executing the utlxplan.sql script Execute this script in theschema in which you want to generate execution plans
The EXPLAIN PLAN command requires that you feed it a SQL statement and anidentifier for the statement In return, the EXPLAIN PLAN command populatesPLAN_TABLE with the execution plan for that SQL statement A call to the EXPLAINPLAN command looks like this:
EXPLAIN PLAN set statement_id=’1’ FORSELECT COUNT(*) FROM EMPLOYEE;
To get the execution plan out of the plan table, you query PLAN_TABLE There areseveral 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/admindirectory The primary difference between the two is that utlxplp.sqlprovides some parallel query statistics An example of the utlxpls.sql output isshown 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 nothave direct access This may be the case when an application does not afford you theopportunity to turn on tracing before the application executes Or it might be that a
Beyond Simple Database Management
P A R T
III
Trang 19DBA notices odd behavior in a particular user’s session (perhaps it’s using substantialCPU 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 INSQL_TRACE BOOLEAN IN );
The procedure takes three parameters The first two, the user SID and SERIAL#, arederived from V$SESSION; together they uniquely identify the user session The finalparameter is a Boolean, either TRUE (session trace turned on) or FALSE (session traceturned off)
Let’s say we want to trace the session that Scott is currently running First, wequery the V$SESSION table to determine the SID and SERIAL# column values for hissession:
SQL> select sid, serial#
PL/SQL procedure successfully completed
Once you’ve collected all the trace information you need, end the trace of the sessionwith 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 thatyou’ve learned how to get hold of one, let’s examine its parts and see what it tells us
Trang 20The 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 rowsetspassed to them Some operations can return rowsets as they are being processed, andother operations wait until the entire rowset is processed before working on it All ofthese 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 thatappear 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 onSELECT a.empno, a.ename, b.dnameFROM 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 meansthat Oracle starts with the deepest operations first (those indented the farthest) andmoves up from there The preceding example shows three operations, each markedwith an operation number at the far left Operation 1 is a hash join Operation 2 is afull table access of the DEPT table Operation 3 is a full table access of the EMPLOYEEtable For now, don’t worry about what these operations are Just try to understandwhich 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 foregoingexample, step 1 is the parent step to steps 2 and 3.) Beyond Simple Database Management
P A R T
III