You are on page 1of 52

ITD Global Delivery, India

Oracle Diagnostic Tools


Satyam Kumar
Nadeem A Mohammed

2003 IBM Corporation

ITD Global Delivery, India

Agenda
Understanding AWR
Overview of ADDM and ASH reports
Remote Diagnostics Report (RDA)
Understanding event 10046
TKPROF
Explain Plan
SQLTRP
Errorstack tracing
2

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
What is AWR (Automatic workload repository)?
The AWR is an oracle tool starting from oracle 10GR1used to collects
and stores database statistics relating to problem detection and
tuning.
AWR is a replacement for the statspack utility which helps gather
database performance statistics.
The AWR is used to collect performance statistics including:
Wait events used to identify performance problems.
Time model statistics indicating the amount of DB time
associated with a process from the V$SESS_TIME_MODEL and
V$SYS_TIME_MODEL views.
Active Session History (ASH) statistics from the
V$ACTIVE_SESSION_HISTORY view.
Some system and session statistics from the V$SYSSTAT and
V$SESSTAT views.
Object usage statistics, operating system statistics.
Resource intensive SQL statements.

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
What is AWR (Automatic workload repository)?
This information is accumulated in memory and periodically
flush/written to the database; to the tables that make up awr.
The awr is exists as a set of tables and other objects in the SYSAUX
tablespace.
The level of awr statistics gathered is controlled by parameter
STATISTICS_LEVEL (Dynamic).
The parameter STATISTICS_LEVEL can be set BASIC, ALL or
TYPICAL (Typical is the default setting)
Can change on ALTER SYSTEM or ALTER SESSSION level.
Periodically by default once an hour they are flushed to disk, to the
awr which is called snapshot.
the flushing to disk is done by the background process MMON
(Manageability monitor). This use of background process is the key
to the efficiency of the statistics collection process.

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
What is AWR (Automatic workload repository)?
The MMON is having direct access of memory structures that makes
up SGA and therefore the statistics within them.
AWR statistics are save as a snapshot to the awr by MMON
processes by default 60 mins (1 hr).
By default, the snapshots are stored for 8 days before being
overwritten.
The awr is the set of tables located in SYSUX tablespace, these
tables cannot be relocated..
AWR is the set of tables which owned by SYSMAN schema.
Snapshot can be thought as the collection/copy of the contents of
many views at the time of snapshot taken,
These statistics would be gathered with DBMS_STATS .

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
AWR (Automatic workload repository) architecture

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
What is AWR (Automatic workload repository)?
DBMS_WORLOAD for snapshots

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
Workload repository views?
The following workload repository views are available:

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
What is AWR (Automatic workload repository)?
To run AWR report we can use the SQL scripts or use Enterprise
Manager.

Generate AWR Report using command line


AWRRPT.SQL : Report for current instance youre logged on
AWRRPTI.SQL : Report for any instance in AWR
Report scripts in $ORACLE_HOME/rdbms/admin/awr* , ash* ,
addm*

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
What is AWR (Automatic workload repository)?
Generate AWR Report using command line
AWRRPT.SQL : Report for current instance youre logged on
AWRRPTI.SQL : Report for any instance in AWR
Listing the last day's Completed Snapshots
Snap
Instance
DB Name
Snap Id
Snap Started
Level
------------ ------------ --------- ------------------ ----V1024
V1024
177 26 May 2009 00:00
1
178 26 May 2009 01:00
1
Specify the Begin and End Snapshot Ids
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
Enter value for begin_snap: 177
Begin Snapshot Id specified: 177
Enter value for end_snap: 178
End
Snapshot Id specified: 178
Specify the Report Name
~~~~~~~~~~~~~~~~~~~~~~~
The default report file name is awrrpt_1_177_178.html. To use this name,
press <return> to continue, otherwise enter an alternative.
Enter value for report_name:

10

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR
Generating the AWR Report
Generate an AWR Report with Enterprise Manager

11

2003 IBM Corporation

ITD Global Delivery, India

Overview of the AWR Report


Understanding Response Time

Database response time is the time the RDBMS took


to satisfy a request
Response Time = CPU time + Wait time
Oracle keeps track of these metrics for all sessions

AWR snapshots capture total CPU and wait times at a


certain point in time
An AWR report will obtain the difference of the
snapshot data
An AWR report aggregates the response time for all
sessions between snapshots
12

2003 IBM Corporation

ITD Global Delivery, India

Overview of the AWR Report


Understanding Response Time
AWR reports this aggregated RDBMS response time
as: DB Time
Comparing DB Time for good / bad periods is helpful
When DB Time is higher during bad period, problem is in the
RDBMS
When DB Time is lower during bad period, problem may be
outside the RDBMS

9
13

2003 IBM Corporation

ITD Global Delivery, India

Overview of the AWR Report


Understanding Response Time

AWR shows the Top 5 Timed Events


Provides a clue to whats happening
Drives the analysis

14

10

2003 IBM Corporation

ITD Global Delivery, India

Overview of the AWR Report


Limitations of the AWR Report

AWR uses data aggregated across sessions


If sessions have similar workloads, then AWR data is useful
If sessions have very different workloads, then AWR data can
be too fuzzy

AWR uses snapshots at points in time


If interval is too large (usually greater than 1 hour), then AWR
data may not be focused closely on when problem occurred
Small intervals are costly to obtain

ASH Reports and 10046 traces overcome many of


these limitations

11
15

2003 IBM Corporation

ITD Global Delivery, India

AWR SQL Report (awrsqrpt.sql)


The AWR SQL reporting utility is used to focus on the historical performance of
a single SQL statement (identified by SQL_ID). It will tell you performance
statistics and execution plans for each execution within a specified period (even
if the statement had different child cursors). The awrsqrpt.sql script is found in
the $ORACLE_HOME/rdbms/admin directory. Please note you must have a
license to use this script.
Focus on a particular SQL
Supply SQL_ID and snapshots
Shows performance metrics for the SQL during snap interval
Shows all execution plans captured in AWR for the SQL
Useful for:
Finding previous good execution plan
Comparing stats between good and bad performance
Elapsed time per execution
How to Generate:
AWRSQRPT.SQL : For current instance
AWRSQRPI.SQL : For any instance in AWR
16

13

2003 IBM Corporation

ITD Global Delivery, India

Overview of the AWR Report


Compare two snapshot intervals
Supply begin/end snapshots for each set of intervals
Provides absolute and percent difference between nearly all metrics,
including SQL
Useful for:
Comparing good performance vs. bad performance
Quickly highlights areas to investigate
How to Generate:
From EM, Automatic Workload Repository > Snapshots; Action =
Compare Periods
AWRDDRPT.SQL : For current instance
AWRDDRPI.SQL : For any instance in AWR

17

14

2003 IBM Corporation

ITD Global Delivery, India

Primary Sections
Snapshot Overview
Top 5 Timed Events
Init.ora parameters
Secondary Sections
SQL Statistics
Segment Statistics
IO Stats

12
18

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR-Related Reports


ADDM
The ADDM reporting utility creates a report of its database performance findings. The
addmrpt.sql script is found in the $ORACLE_HOME/rdbms/admin directory. Please
note you must have a license to use this script.
Scheduled to run automatically by MMON to detect problems proactively
Each time a snapshot is taken, ADDM is triggered automatically to run on last 2
snapshots
Results of ADDM analysis are stored in awr and accessible through DB control
We can invoke ADDM manually
STATISTICS_LEVEL should be TYPICAL
or ALL
How to Generate:
From EM, Advisor Central > ADDM
ADDMRPT.SQL : For current instance
($ORACLE_HOME/rdbms/admin/admrpt.sql)

15
19

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR-Related Reports


ADDM
The Automatic Database Diagnostic Monitor (ADDM) analyzes data in the Automatic
Workload Repository (AWR) to identify potential performance bottlenecks.
For each of the identified issues it locates the root cause and provides
recommendations for correcting the problem.
An ADDM analysis task is performed and its findings and recommendations stored in
the database every time an AWR snapshot is taken provided the STATISTICS_LEVEL
parameter is set to TYPICAL or ALL
*ADDM analysis includes the following.
CPU load
Memory usage
I/O usage
Resource intensive SQL
Resource intensive PL/SQL and Java
RAC issues
Application issues
Database configuration issues
Concurrency issues
Object contention
15
20

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR-Related Reports


ADDM
ADDM findings (problems) are listed in order of potential impact on database
performance, along with recommendations to resolve the issue and the symptoms.

Recommendations may include:

15
21

Hardware changes
Database configuration changes
Schema changes
Application changes
Using other advisors
2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR-Related Reports


ASH Report

The ASH report utility is useful for determining the amount of active sessions, what they were doing,
and which SQL statements were most active during a period of time. It is especially useful for
analyzing transient performance issues. The ashrpt.sql script is found in the
$ORACLE_HOME/rdbms/admin directory.
NOTE: You must have a license to use this script.
Stores the history of database time
Samples session activity in the system
Comprises of one-second samples of ACTIVE sessions on the instance
It extracts only samples of information from v$instance
We can run ASHRPT.SQL to generate ASH report.
ASH samples are stored in a circular buffer memory
Will be written to the disk during snapshot or if the buffer is full
This buffer is from SGA and is 2MB per CPU ( fixed )
ADDM uses ASH data heavily
Some important attributes of ASH samples are current session id,sql,wait event id.
V$ACTIVE_SESSION_HISTORY/ DBA_HIST_ACTIVE_SESS_HISTORY gives more details

16
22

2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR-Related Reports


ASH Report
Oracle collects Active Session History (ASH) statistics (mostly wait statistics for different events)
for all active sessions every second from v$session and stores them in a circular FIFO buffer in
the SGA. ASH records are very recent session history within the last 5-10 mins. The MMNL
(Manageability Monitor light - shows up as "Manageability Monitor light 2" process) process, if
the buffer fills up before the AWR flushes (by default every hour) the MMNL process will flush the
data to disk (data stored in dba_hist_active_session_history).
NOTE: You must have a license to use this script.
ASH collects the following:
SQL_ID
SID
Client ID, Service ID
Program, Module, Action
Object, File, Block
Wait event number, actual wait time (if session is waiting)

ASH Report

16
23

It is possible to run a report on the ASH data collected, the report generates information
about SQL that ran during the time you specify and it includes blocking and wait details.
ashrpt.sql- $ORACLE_HOME/rdbms/admin (information on SQL which includes
blocking and wait details, the script will ask what you to specify a time and if the report
is to be generated in text to html.)
2003 IBM Corporation

ITD Global Delivery, India

Overview of AWR-Related Reports


ASH Report
An ASH report details statistics from the in-memory performance monitoring tables. The report provides:
Top User Events (frequent wait events)
Details to the wait events
Top Queries
Top Sessions
Top Blocking Sessions
Top DB Objects (Note: be wary of the QRTZ_LOCKS result. This table is what Quartz, our third-party Java
scheduler, uses as a locking mechanism. As a result, any contention is intentional and will not affect
performance).
Activity Over Time
To generate the ASH report:
Log in to the machine hosting Oracle.
At a command prompt issue the following command: sqlplus system
@$ORACLE_HOME/rdbms/admin/ashrpt.sql
When you are asked for the system password, type it in and press Enter.
Specify a format for the report and press Enter.
Specify the begin time for the report and press Enter (e.g., -1:30 is one hour and 30 minutes before from the
present time).
Specify the duration for the report and press Enter (for example, a value of 30 indicates that the report should
cover from the begin time to 30 minutes after that time; leaving the duration empty specifies that the report
should cover from the begin time to the current time).
Name the report and press Enter.
Issue the quit command to exit from SQLPlus.
16 The report is generated at the path where the SQLPlus command was issued.
2003 IBM Corporation
24

ITD Global Delivery, India

Remote Diagnostic Agent (RDA)


RDA is a utility that can be download from the Metalink to collect diagnostic
information from an oracle environment.
RDA (Remote diagnosis agent) provide as suite of data collection and diagnosis
scripts that aid in the analysis and and support of oracle products. This powerful tool
(Diagnosis respurce) can help us predict system beahivor, prioritize your action and
prevent potential issues before it occurs.
This utility is focused on collecting information from the running database that will aid
in the problem diagnosis .
When a looging call with the oracle support, oracle support will often the request to
install RDA utility, run it and upload to the metalink for further analysis.
Oracle will provide the RDA fils which needs to be unizpped
tar -xvf rda.tar
tar -cxvf rda.gz
Now run the rda:
./rda.sh -v or rda.pl v
View rda report:
open rda_index.htm from the rda output directory.

25

37

2003 IBM Corporation

ITD Global Delivery, India

Remote Diagnostic Agent (RDA)


Remote Diagnostic Agent (RDA) is a set of command line diagnostic scripts that are
executed by an engine written in the Perl programming language. RDA is used to
gather detailed information about an Oracle environment; the data gathered is in turn
used to aid in problem diagnosis. The output is also useful for seeing the overall
system configuration.
RDA can be executed using a setup profile. A setup profile consists of a list of data
collection modules and predefined settings. Therefore, the data collected using a
profile can be slightly different than using the module separately. Profiles are typically
used to setup all modules required to diagnose a specific class of problems. The
DB_Perf profile is the suggest module to use for RDA when troubleshooting
performance tuning issues.
Following benifits of RDA:
--Identification of multiple issues in one test.
--minimized downtime by resolving the potential issue before they occur.
- Resolution of known issue.
--collection of complete and accurate technical information in a single step.
-- Use of analytical tools to simplify resolution

26

37

2003 IBM Corporation

ITD Global Delivery, India

RDA 4 Documentation Index


Document
Knowledge Article
Getting Started
Note 314422.1
Download RDA
Note 314422.1
RDA 4 Release Notes
Note: 414970.1
FAQ
Note: 330363.1
Training
Note: 330344.1
Troubleshooting Guide
Note: 330362.1
RAC Cluster Guide
Note: 359395.1
HP OpenVMS Guide
Note: 171748.1
HP OpenVMS Troubleshooting Guide
Note: 366522.1
RDA EXAMPLE

27

38

2003 IBM Corporation

ITD Global Delivery, India

EVENT: 10046 (Extended SQL Trace)

Able to capture WAITs and BINDs


Can be set within a session or in a session that is already running
Ideally, the application is designed to turn it on/off itself
Capture the trace as completely as possible

Traces found in user_dump_dest or background_dump_dest

TKProf formats the output


v9.x and higher, TKProf handles wait time info
Trace Analyzer Script (see Note 224270.1)

19
28

2003 IBM Corporation

ITD Global Delivery, India

10046:WHAT IS IT AND HOW TO TAKE THIS


chronological order of database calls made by SQL/PLSQL/Session
1 - Enable standard SQL_TRACE functionality (Default)
4 - PLUS trace bind values
8 - PLUS trace waits
12 - both trace bind values and waits

Using Event 10046


==============
Initialization parameter:

event = "10046 trace name context forever, level 12"


BE CAREFUL! Do this only on a test instance or one with very few users

20
29

2003 IBM Corporation

ITD Global Delivery, India

10046
From SQL*Plus
SQL> alter session set events '10046 trace name context forever, level
12';
SQL> issue some SQL . . .
SQL> select close the cursor from dual; -- closes cursor for prev.
query
SQL> alter session set events '10046 trace name context off';
Using DBMS_SYSTEM.SET_EV

SQL> exec sys.dbms_system.set_ev(1, 322, 10046, 12,


'');
SQL> issue some SQL . . .
SQL> exec sys.dbms_system.set_ev(1, 322, 10046, 0, '');

21
30

2003 IBM Corporation

ITD Global Delivery, India

10046

Using ORADEBUG:

SQL> oradebug setospid 12345


SQL> oradebug event 10046 trace name context forever, level 12
Wait for some SQL to be captured. . .
SQL> oradebug event 10046 trace name context off

10G: Using DBMS_MONITOR.SESSION_TRACE_ENABLE

EXECUTE DBMS_MONITOR.SESSION_TRACE_ENABLE(session_id => 27,


serial_num => 60, waits => TRUE, binds => TRUE);
Wait for some SQL to be captured. . .
EXECUTE DBMS_MONITOR.SESSION_TRACE_DISABLE(27,60);

22
31

2003 IBM Corporation

ITD Global Delivery, India

Using Enterprise Manager to Enable and View SQL Tracing

SELECT * FROM dba_enabled_traces;


23
32

2003 IBM Corporation

ITD Global Delivery, India

Using Enterprise Manager to View Enabled Traces


You can enable, disable, and view SQL tracing on the Top Modules, Top Actions, and Top
Client pages. You navigate to these pages from the Database Control home page and
then click the Performance tab. You select Top Consumers from the Additional
Monitoring link, and choose Top Services, Top Modules, Top Actions, Top Clients,
and Top Sessions.
You can query the DBA_ENABLED_TRACES view to determine the traces enabled. The
DBA_ENABLED_TRACES view contains the following columns:
TRACE_TYPE: Trace type: CLIENT_ID, SESSION, SERVICE, SERVICE_MODULE,
SERVICE_MODULE_ACTION
PRIMARY_ID: Primary qualifier (specific client identifier or service name)
QUALIFIER_ID1: Secondary qualifier (specific module name)
QUALIFIER_ID2: Additional qualifier (specific action name)
WAITS: TRUE if waits are traced
BINDS: TRUE if binds are traced
INSTANCE_NAME: Instance name for tracing restricted to named instances

33

24

2003 IBM Corporation

ITD Global Delivery, India

UNDER WHAT SCENARIOS WE SHOULD GO FOR THIS


particular session / process / background process
( slow / hang / errors )
qtune
system wide ?

WHAT IS MISSING IN TKPROF OUTPUT


no bind values
no failing statement
time is for individual statement
wait events p1/p2/p3

10046 Trace File Example

34

25

2003 IBM Corporation

ITD Global Delivery, India

Overall Pattern
=====================
PARSING IN CURSOR #1 len=69 dep=0 uid=26 oct=42 lid=26 tim=1773902376 hv=1509700594
ad='7b526d78'
alter session set events '10046 trace name context forever, level 12'
END OF STMT
EXEC #1:c=0,e=0,p=0,cr=0,cu=0,mis=1,r=0,dep=0,og=4,tim=1773812376
WAIT #1: nam='SQL*Net message to client' ela= 22 p1=1111838976 p2=1 p3=0
=====================
PARSING IN CURSOR #2 len=34 dep=1 uid=26 oct=3 lid=26 tim=1774173376 hv=677152330 ad='7b584040'
SELECT c1 from fred where c2 = :b1
END OF STMT
PARSE #2:c=0,e=0,p=0,cr=0,cu=0,mis=1,r=0,dep=1,og=0,tim=1774173376
BINDS #2:
bind 0: dty=2 mxl=22(21) mal=00 scl=00 pre=00 oacflg=13 oacfl2=1 size=24 offset=0
bfp=0556b0bc bln=22 avl=02 flg=05
value=1
EXEC #2:c=30043,e=30000,p=0,cr=0,cu=0,mis=0,r=0,dep=1,og=4,tim=1774233376
FETCH #2:c=0,e=0,p=0,cr=1,cu=2,mis=0,r=0,dep=1,og=4,tim=1774233376
BINDS #2:
bind 0: dty=2 mxl=22(21) mal=00 scl=00 pre=00 oacflg=13 oacfl2=1 size=24 offset=0
bfp=0555ded8 bln=22 avl=02 flg=05
value=2
EXEC #2:c=30043,e=30000,p=0,cr=0,cu=0,mis=0,r=0,dep=1,og=4,tim=1774603376
FETCH #2:c=0,e=0,p=0,cr=1,cu=2,mis=0,r=0,dep=1,og=4,tim=1774613376
=====================
XCTEND rlbk=0, rd_only=1
STAT #2 id=1 cnt=0 pid=0 pos=0 obj=5025 op='TABLE ACCESS FULL FRED '

26
35

2003 IBM Corporation

ITD Global Delivery, India

What is this stuff?


PARSING IN CURSOR #1 len=69 dep=0 uid=26 oct=42 lid=26 tim=1773902376
hv=1509700594 ad='7b526d78'
alter session set events '10046 trace name context forever, level 12'
END OF STMT
CURSOR #1 Gets reused within this session. Enables association of events with each cursor.
dep=0
Recursive depth. 0 is a cursor, everything else is either PL/SQL or true recursive SQL.
oct=42 Oracle Command Type. Type of SQL operation. 42= Alter Session. See octdef.h.
lid=26 Privilege user ID.
tim= 1773902376 microsecond time since some arbitrary value. Not clock or date time.
hv=1509700594 Hash value of SQL string. Used to get hash bucket for Library Cache. Not

necessarily unique, unless combined with address. Repeatable value across


platforms for a given Oracle version.
ad='7b526d78 Address of this objects handle in the Library Cache.
Combined with hash value, this gives an absolute unique identifier of this object
in the Library Cache. Established dynamically when cursor is first created.

27
36

2003 IBM Corporation

ITD Global Delivery, India

EXEC #2:c=30043,e=30000,p=0,cr=0,cu=0,mis=0,r=0,dep=1,og=4,tim=1774233376
FETCH #2:c=0,e=0,p=0,cr=1,cu=2,mis=0,r=0,dep=1,og=4,tim=1774233376
PARSE #2:c=0,e=0,p=0,cr=0,cu=0,mis=1,r=0,dep=1,og=0,tim=1774173376
c= 30043 CPU time in microseconds
e= 30000 Elapsed time
p=0
Physical reads
cr=0
consistent reads
cu=0
current mode gets
mis=1
Library Cache misses. This case, 1, means we just had a hard parse.
r=0
rows processed
dep=1
recursive depth
og=4
Optimizer mode: 1= All_Rows; 2= First_Rows, 3=Rule, 4= Choose.
tim=1773812376 The ubiquitous timestamp, in microseconds. Not wall clock time.

37

28

2003 IBM Corporation

ITD Global Delivery, India

Binds, if level 4 or 12 chosen


BINDS #2:
bind 0: dty=2 mxl=22(21) mal=00 scl=00 pre=00 oacflg=13 oacfl2=1 size=24 offset=0
bfp=0555ded8 bln=22 avl=02 flg=05
value=2
dty=2
mxl=22(21)
mal=00
scl=00
pre=00
oacflg=13
oacfl2=1
size=24

Data type, see dtydef.h


Maximum length, private max length (may not always apply)
Total # of array elements
Scale, for datetime and interval types
Precision, also for datetime and interval types
Bitmask for various things, see uacdef.h
Extension of oacflg, see uacdef.h
Size and offset identify location of value for this bind
variable

offset=0
bfp=0555ded8 UGA buffer pointer
bln=22
Buffer length
avl=02
Value length
flg=05
Bitmask, see kxs.h
value=2
Actual value of bind variable

38

29

2003 IBM Corporation

ITD Global Delivery, India

Wait Events
WAIT #1: nam='SQL*Net message to client' ela= 22 p1=1111838976 p2=1 p3=0

nam='SQL*Net
ela= 22
p1=1111838976
p2=1
p3=0

Name of event, see v$event_name


Elapsed time, in microseconds
P2, P2, P3 are specific to the event
Refer to WebIV for event of interest

SELECT owner , segment_name , segment_type


FROM dba_extents
WHERE file_id = &AFN
AND &BLOCKNO BETWEEN block_id AND block_id +
blocks -1

Wait events always occur BEFORE the action it relates to


See next slide
30

2003 IBM Corporation

ITD Global Delivery, India

Execution Plan, After the Fact


STAT #2 id=1 cnt=0 pid=0 pos=0 obj=5025 op='TABLE ACCESS FULL FRED '

id=1
cnt=0
pid=0
pos=0
obj=5025
op='TABLE ACCESS FULL FRED

Operation ID
Count of output rows
Parent Operation ID
Position
Object #
Operation

Extremely valuable for SQL tuning because we see exactly how many
rows were involved in each plan step vs. the EXPLAIN PLAN where we
only see an estimate of the rows

40

31

2003 IBM Corporation

ITD Global Delivery, India

TKPROF Utility
Usage: tkprof tracefile outputfile [explain= ] [table= ]
[print= ] [insert= ] [sys= ] [sort= ]
table=sch.tname
explain=un/pw
print=<n>
aggregate=yes|no
insert=filename
sys=no
record=filename
waits=yes|no
sort=option

Use 'sch.tname' with 'explain=' option


Connect to ORACLE and issue EXPLAIN PLAIN
List the first <n> SQL statements
Do(not) merge identical SQL statements
Generate script to load results in the db
Suppress SQL statements run as user SYS
Record non-recursive statements
Record summary for any wait events
Set one or more sort options

$ tkprof <trace file> <result> sys=no

41

32

2003 IBM Corporation

ITD Global Delivery, India

Command Line Options


Sys
(the default) traces all recursive SQL used for your statement; setting sys=NO omits this. You
are not usually interested in the underlying SQL that is performed in the background. Note that
sys=no does not exclude SQL from PL/SQL, although this is also labeled recursive.
YES

Explain
Runs EXPLAIN under the specified username, and prints the EXPLAIN output together with the
SQL statements. The users need not currently have a PLAN_TABLE but must have the privilege
to create it. Note that the execution plans are the ones that would be chosen when TKPROF
was run.
Waits
This option is new in Oracle9i; it produces a summary of all waits found in the trace file. Note,
however, that there is no documented or supported way for customers to produce wait
information in their trace files. You can only achieve that with event 1046 level 8, to be
discussed later in this lesson.

42

33

2003 IBM Corporation

ITD Global Delivery, India


Sort
Allows you to sort the output file in order of resource used. These are the supported options:
prscnt number of times parse was called
prscpu cpu time parsing
prsela elapsed time parsing
prsdsk number of disk reads during parse
prsqry number of buffers for consistent read during parse
prscu
number of buffers for current read during parse
prsmis number of misses in library cache during parse
execnt number of execute was called
execpu cpu time spent executing
exeela elapsed time executing
exedsk number of disk reads during execute
exeqry number of buffers for consistent read during execute
execu
number of buffers for current read during execute
exerow number of rows processed during execute
exemis number of library cache misses during execute
fchcnt number of times fetch was called
fchcpu cpu time spent fetching
fchela elapsed time fetching
fchdsk number of disk reads during fetch
fchqry number of buffers for consistent read during fetch
fchcu
number of buffers for current read during fetch
fchrow number of rows fetched
userid userid of user that parsed the cursor

Example:
sort = exeela orders by elapsed time during execution;
sort = fchcpu execpu orders by fetch cpu time and execution

cpu time, whichever

is the largest.
43

34

2003 IBM Corporation

ITD Global Delivery, India

Sample TKProf
update

buffer_busy_tab set y = 5000

call
count
------- -----Parse
1
Execute
17
Fetch
0
------- -----total
18

cpu
elapsed
disk
query
current
-------- ---------- ---------- ---------- ---------0.01
0.00
0
0
0
0.07
162.56
0
268
123
0.00
0.00
0
0
0
-------- ---------- ---------- ---------- ---------0.08
162.57
0
268
123

rows
---------0
1071
0
---------1071

Misses in library cache during parse: 1


Rows
------0
1071

Row Source Operation


--------------------------------------------------UPDATE (cr=268 pr=0 pw=0 time=162556287 us)
TABLE ACCESS FULL OBJ#(66021) (cr=182 pr=0 pw=0 time=38403 us)

Elapsed times include waiting on following events:


Event waited on
Times
---------------------------------------Waited
enq: TX - row lock contention
87
SQL*Net message to client
17
SQL*Net message from client
17
buffer busy waits
1

44

35

Max. Wait
---------2.92
0.00
0.97
0.00

Total Waited
-----------162.45
0.00
9.71
0.00

2003 IBM Corporation

ITD Global Delivery, India

TKPROF: Example
Summary
OVERALL TOTALS FOR ALL RECURSIVE STATEMENTS
call
count
cpu
elapsed
disk
query
current
------- ------ -------- ---------- ---------- ---------- ---------Parse
0
0.00
0.00
0
0
0
Execute
0
0.00
0.00
0
0
0
Fetch
0
0.00
0.00
0
0
0
------- ------ -------- ---------- ---------- ---------- ---------total
0
0.00
0.00
0
0
0
Misses in library cache during parse: 0
2 user SQL statements in session.
0 internal SQL statements in session.
2 SQL statements in session.

rows
---------0
0
0
---------0

********************************************************************************
Trace file: /u01/app/oracle/admin/DB10gR1/udump/db10gr1_ora_1986.trc
Trace file compatibility: 10.01.00
Sort options: default
3
2
0
2
2
663
178

45

36

sessions in tracefile.
user SQL statements in trace file.
internal SQL statements in trace file.
SQL statements in trace file.
unique SQL statements in trace file.
lines in trace file.
elapsed seconds in trace file.

2003 IBM Corporation

ITD Global Delivery, India

EVENT: ERRORSTACK
WHAT IS IT AND HOW TO TAKE THIS
Levels:
0

Print the date and time / Dump the Oracle error stack

Dump the current sql statement and pl/sql call stack ,Dump the call stack

Dump the process state objects

Dump the open cursor array , Dump the context area

event="942 trace name ERRORSTACK level 3


alter session set events '942 trace name ERRORSTACK level 3';
alter system set events '942 trace name ERRORSTACK level 3 lifetime 2';
oradebug setorapid <pid>
oradebug dump errorstack 3

46

17

2003 IBM Corporation

ITD Global Delivery, India

UNDER WHAT SCENARIOS WE SHOULD GO FOR THIS


spin ( CPU 100% )
when we suspect Oracle code is playing the role
for a PID ( blocker ) if nothing is moving forward ( 10046 if its slow to see waits )
for a PID to get the current SQL

SPIN : Errorstack
HANG : Systemstate(3)/HangAnalyze(2)
SLOW : statspack/awr
DBLocking : Errorstack(Before this we will take
Systemstate/hanganalyze)

18
47

2003 IBM Corporation

ITD Global Delivery, India

Explain Plan
ORACLE_HOME/rdbms/admin/utlxpls - Displays the explain plan for last Explain command.
ORACLE_HOME/rdbms/admin/utlxplp Displays the parallel query info.

48

2003 IBM Corporation

ITD Global Delivery, India

SQLTRPT
ORACLE_HOME/rdbms/admin/sqlrtpt.sql
Script that gets a single statement as input from the user (via SQLID),
Rem
tunes that statement, and then displays the text report.
SQL> @C:\oracle\product\11.2.0\dbhome_1\RDBMS\ADMIN\sqltrpt.sql
15 Most expensive SQL in the cursor cache
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SQL_ID
ELAPSED SQL_TEXT_FRAGMENT
------------- ---------- -----------------------------------------------------gtvg6a7quptab
23.42 DECLARE cnt
NUMBER; bid
NUMBER; eid
fskyn4u39manv
11.75 DECLARE job BINARY_INTEGER := :job; next_date TIMESTA
cvn54b7yz0s8u
10.40 select /*+ index(idl_ub1$ i_idl_ub11) +*/ piece#,lengt
:
15 Most expensive SQL in the workload repository
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
SQL_ID
ELAPSED SQL_TEXT_FRAGMENT
------------- ---------- -----------------------------------------------------b6usrg82hwsa3 348.42 call dbms_stats.gather_database_stats_job_proc ( )
59v4zh1ac3v2a 145.78 DECLARE job BINARY_INTEGER := :job; next_date TIMESTA
7mgr3uwydqq8j 114.81
select decode(open_mode, 'MOUNTED', 0,
424h0nf7bhqzd 105.02 SELECT sqlset_row(sql_id, force_matching_signature,
c0j6cx9kzjf7g
85.33 SELECT EXTRACTVALUE(VALUE(T), '/select_list_item/pos')
:

49

2003 IBM Corporation

ITD Global Delivery, India


Specify the Sql id
~~~~~~~~~~~~~~~~~~
Enter value for sqlid: 21dbvr4ttgdz5

1- Original
----------Plan hash value: 1147449465

Sql Id specified: 21dbvr4ttgdz5

-------------------------------------------------------------------------| Id | Operation
| Name | Rows | Bytes | Cost (%CPU)| Time |
-------------------------------------------------------------------------| 0 | SELECT STATEMENT |
| 29 | 870 | 715 (1)| 00:00:09 |
|* 1 | TABLE ACCESS FULL| TT1 | 29 | 870 | 715 (1)| 00:00:09 |
--------------------------------------------------------------------------

Tune the sql


~~~~~~~~~~~~
GENERAL INFORMATION SECTION
------------------------------------------------------------------------------Tuning Task Name : TASK_239
Tuning Task Owner : NAD12
Workload Type
: Single SQL Statement
Scope
: COMPREHENSIVE
:------------------------------------------------------------------------------Schema Name: NAD12
SQL ID : 21dbvr4ttgdz5
SQL Text : select object_id from tt1 where object_name ='DBA_TABLES'
------------------------------------------------------------------------------FINDINGS SECTION (2 findings)
------------------------------------------------------------------------------1- Statistics Finding
--------------------Table "NAD12"."TT1" was not analyzed.
Recommendation
-------------- Consider collecting optimizer statistics for this table.
:
:
2- Index Finding (see explain plans section below)
-------------------------------------------------The execution plan of this statement can be improved by creating one or
more
indices.

Predicate Information (identified by operation id):


--------------------------------------------------1 - filter("OBJECT_NAME"='DBA_TABLES')
2- Using New Indices
-------------------Plan hash value: 3856238888
------------------------------------------------------------------------------| Id | Operation
| Name
| Rows | Bytes | Cost (%CPU)| Time
------------------------------------------------------------------------------| 0 | SELECT STATEMENT |
| 32 | 960 | 2 (0)| 00:00:
|* 1 | INDEX RANGE SCAN| IDX$$_00EF0001 | 32 | 960 | 2 (0)| 00:00:
------------------------------------------------------------------------------Predicate Information (identified by operation id):
--------------------------------------------------1 - access("OBJECT_NAME"='DBA_TABLES')

Recommendation (estimated benefit: 99.72%)


------------------------------------------ Consider running the Access Advisor to improve the physical schema
design or creating the recommended index.

50

2003 IBM Corporation

ITD Global Delivery, India

References
Note: 376442.1 : Recommended Method for Obtaining 10046 trace for

Tuning

Note: 21154.1 : EVENT: 10046 "enable SQL statement tracing (including


binds/waits)
Note: 1058210.6 : How to Enable SQL_TRACE for Another Session Using Oradebug
Note: 39817.1 : Interpreting Raw SQL_TRACE and
DBMS_SUPPORT.START_TRACE output
Note: 41634.1 : TKProf Simplistic Overview
Note: 748642.1 :How to Generate an AWR Report and Create Baselines
http://docs.oracle.com/cd/B28359_01/server.111/b28274/autostat.htm#CHDBC
HHG

51

39

2003 IBM Corporation

ITD Global Delivery, India

Questions
?

52

2003 IBM Corporation

You might also like