Académique Documents
Professionnel Documents
Culture Documents
Student Guide
D52163GC20
Edition 2.0
October 2010
D69160
Disclaimer
This document contains proprietary information and is protected by copyright and other intellectual property laws. You may copy and
print this document solely for your own use in an Oracle training course. The document may not be modified or altered in any way.
Except where your use constitutes "fair use" under copyright law, you may not use, share, download, upload, copy, print, display,
perform, reproduce, publish, license, post, transmit, or distribute this document in whole or in part without the express authorization
of Oracle.
The information contained in this document is subject to change without notice. If you find any problems in the document, please
report them in writing to: Oracle University, 500 Oracle Parkway, Redwood Shores, California 94065 USA. This document is not
warranted to be error-free.
Restricted Rights Notice
If this documentation is delivered to the United States Government or anyone using the documentation on behalf of the United
States Government, the following notice is applicable:
U.S. GOVERNMENT RIGHTS
The U.S. Governments rights to use, modify, reproduce, release, perform, display, or disclose these training materials are restricted
by the terms of the applicable Oracle license agreement and/or the applicable U.S. Government contract.
Trademark Notice
Oracle and Java are registered trademarks of Oracle and/or its affiliates. Other names may be trademarks of their respective
owners.
Author
James Spiller, Tulika Srivastava
Technical Contributors and Reviewers
Abhinav Gupta, Branislav Valny, Clinton Shaffer, Donna Keesling, Ira Singer, Howard Bradley,
Sean Kim, Sue Harper, Teria Kidd
This book was published using:
Oracle Tutor
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Table of Contents
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Application Tracing..........................................................................................................................................5-1
Application Tracing.........................................................................................................................................5-2
Objectives ......................................................................................................................................................5-3
End-to-End Application Tracing Challenge ....................................................................................................5-4
End-to-End Application Tracing......................................................................................................................5-5
Location for Diagnostic Traces .......................................................................................................................5-6
What Is a Service? .........................................................................................................................................5-7
Using Services with Client Applications .........................................................................................................5-8
Tracing Services ............................................................................................................................................5-9
Use Enterprise Manager to Trace Services ...................................................................................................5-11
Service Tracing: Example ..............................................................................................................................5-12
Session Level Tracing: Example ....................................................................................................................5-14
Trace Your Own Session ...............................................................................................................................5-16
The trcsess Utility ...........................................................................................................................................5-17
Invoking the trcsess Utility ..............................................................................................................................5-18
The trcsess Utility: Example ...........................................................................................................................5-20
SQL Trace File Contents ................................................................................................................................5-21
SQL Trace File Contents: Example ................................................................................................................5-23
Formatting SQL Trace Files: Overview ..........................................................................................................5-24
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Statistics..........................................................................................................................................10-1
Optimizer Statistics ........................................................................................................................................10-2
Objectives ......................................................................................................................................................10-3
Optimizer Statistics ........................................................................................................................................10-4
Types of Optimizer Statistics ..........................................................................................................................10-5
Table Statistics (DBA_TAB_STATISTICS) ....................................................................................................10-6
Index Statistics (DBA_IND_STATISTICS) .....................................................................................................10-7
Index Clustering Factor ..................................................................................................................................10-9
Column Statistics (DBA_TAB_COL_STATISTICS) ........................................................................................10-11
Histograms .....................................................................................................................................................10-12
Frequency Histograms ...................................................................................................................................10-13
Viewing Frequency Histograms......................................................................................................................10-14
Height-Balanced Histograms .........................................................................................................................10-15
Viewing Height-Balanced Histograms ............................................................................................................10-16
Histogram Considerations ..............................................................................................................................10-17
Multicolumn Statistics: Overview ....................................................................................................................10-18
Expression Statistics: Overview .....................................................................................................................10-20
Gathering System Statistics ...........................................................................................................................10-21
Gathering System Statistics: Example ...........................................................................................................10-23
Mechanisms for Gathering Statistics ..............................................................................................................10-25
Statistic Preferences: Overview .....................................................................................................................10-26
When to Gather Statistics Manually ...............................................................................................................10-28
Manual Statistics Gathering ...........................................................................................................................10-29
Manual Statistics Collection: Factors .............................................................................................................10-30
Managing Statistics Collection: Example .......................................................................................................10-31
Optimizer Dynamic Sampling: Overview ........................................................................................................10-32
Optimizer Dynamic Sampling at Work............................................................................................................10-33
OPTIMIZER_DYNAMIC_SAMPLING.............................................................................................................10-34
Locking Statistics ...........................................................................................................................................10-36
Restoring Statistics ........................................................................................................................................10-37
Export and Import Statistics ...........................................................................................................................10-38
Quiz................................................................................................................................................................10-39
Summary ........................................................................................................................................................10-42
Practice 10: Overview ....................................................................................................................................10-43
Using Bind Variables .......................................................................................................................................11-1
Using Bind Variables ......................................................................................................................................11-2
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives ......................................................................................................................................................11-3
Cursor Sharing and Different Literal Values ...................................................................................................11-4
Cursor Sharing and Bind Variables ................................................................................................................11-6
Bind Variables in SQL*Plus ............................................................................................................................11-7
Bind Variables in Enterprise Manager ............................................................................................................11-8
Bind Variables in SQL Developer ...................................................................................................................11-9
Bind Variable Peeking ....................................................................................................................................11-10
Cursor Sharing Enhancements ......................................................................................................................11-12
The CURSOR_SHARING Parameter ............................................................................................................11-14
Forcing Cursor Sharing: Example ..................................................................................................................11-15
Adaptive Cursor Sharing: Overview ...............................................................................................................11-16
Adaptive Cursor Sharing: Architecture ...........................................................................................................11-17
Adaptive Cursor Sharing: Views.....................................................................................................................11-19
Adaptive Cursor Sharing: Example ................................................................................................................11-21
Interacting with Adaptive Cursor Sharing .......................................................................................................11-22
Quiz................................................................................................................................................................11-23
Summary ........................................................................................................................................................11-26
Practice 11: Overview ....................................................................................................................................11-27
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Profile
Before You Begin This Course
Before you begin this course, you should be familiar with SQL Language statements, and have
taken the Oracle Database 11g: Introduction to SQL course or have equivalent experience. It is
also recommended that you have taken the Oracle Database 11g: SQL Fundamentals I course.
How This Course Is Organized
Oracle Database 11g: SQL Tuning Workshop is an instructor-led course featuring lectures and
hands-on exercises. Online demonstrations and written practice sessions reinforce the concepts
and skills that are introduced.
Related Publications
Oracle Publications
Title
Oracle Database SQL Reference 11g Release 2 (11.2)
Part Number
E10592-04
E15222-02
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Preface
The following two lists explain Oracle University typographical conventions for words that
appear within regular text or within code samples.
Initial cap
Italic
Quotation
marks
Object or Term
User input;
commands;
column, table, and
schema names;
functions;
PL/SQL objects;
paths
Triggers;
user interface object
names, such as
button names
Titles of
courses and
manuals;
emphasized
words or phrases;
placeholders or
variables
Lesson or module
title referenced
within a course
Example
Use the SELECT command to view
information stored in the LAST_NAME
column of the EMPLOYEES table.
Enter 300.
Log in as scott
Assign a When-Validate-Item trigger to
the ORD block.
Click the Cancel button.
For more information on the subject see
Oracle SQL Reference Manual
Do not save changes to the database.
Enter hostname, where hostname is the
host on which the password is to be changed
This subject is covered in Lesson 3, Working with
Objects.
Object or term
Commands,
functions
Syntax variables
Example
SELECT employee_id
FROM employees
CREATE ROLE role
Forms triggers
Lowercase
Column names,
table names
Filenames,
PL/SQL objects
Bold
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Typographic Conventions
This course uses simplified navigation paths, such as the following example, to direct you
through Oracle Applications.
(N) Invoice > Entry > Invoice Batches Summary (M) Query > Find (B) Approve
This simplified path translates to the following:
1. (N) From the Navigator window, select Invoice then Entry then Invoice Batches
Summary.
2. (M) From the menu, select Query then Find.
3. (B) Click the Approve button.
Notations:
(N) = Navigator
(M) = Menu
(T) = Tab
(B) = Button
(I) = Icon
(H) = Hyperlink
(ST) = Sub Tab
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
After completing this lesson, you should be able to:
List the major architectural components of Oracle
Database server
Explain memory structures
Describe background processes
Correlate logical and physical storage structures
Objectives
This lesson provides an overview of the Oracle Database server architecture. You learn about
physical and logical structures and about the various components.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
BGP1
BGP2
BGP3
BGPn
Database
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
User
process
User
process
Listener
process
Dispatcher
Shared
Server
D000
S000
Connection
SQL> Select
User
process
Server
process
Dedicated
Server
User
SGA
Server host
User processes sometimes called client or foreground processes are created to run the
software code of an application program. Most environments have separate machines
for the client processes. A user process also manages communication with a
corresponding server process through a program interface.
Oracle Database server creates server processes to handle requests from connected
user processes. A server process communicates with the user process and interacts
with the instance and the database to carry out requests from the associated user
process.
An Oracle Database instance can be configured to vary the number of user processes for
each server process. In a dedicated server configuration, a server process handles requests
for a single user process.
A shared server configuration enables many user processes to share a small number of
shared server processes, minimizing the number of server processes and maximizing the use
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The Oracle Database server runs a listener that is responsible for handling network
connections. The application connects to the listener that creates a dedicated server process
or handles the connection to a dispatcher.
Connections and sessions are closely related to user processes, but are very different in
meaning:
A session represents the state of a current database user login to the database instance.
For example, when a user starts SQL*Plus, the user must provide a valid database
username and password, and then a session is established for that user. A session lasts
from the time a user connects until the user disconnects or exits the database
application.
Note: Multiple sessions can be created and exist concurrently for a single Oracle database
user using the same username. For example, a user with the username/password of HR/HR
can connect to the same Oracle Database instance several times.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
of available system resources. One or more dispatcher processes are then used to queue
user process requests in the SGA and dequeue shared server responses.
Redo log
buffer
Java
pool
Server
process
Shared pool
Large pool
Streams
pool
Server
process
Background
process
Aggregated
PGA
System Global Area (SGA): The SGA is shared by all server and background
processes. The SGA includes the following data structures:
-
Database buffer cache: Caches blocks of data retrieved from the database files
Redo log buffer: Caches recovery information before writing it to the physical files
Shared pool: Caches various constructs that can be shared among sessions
Large pool: Optional area used for certain operations, such as Oracle backup and
recovery operations, and I/O server processes
Java pool: Used for session-specific Java code and data in the Java Virtual
Machine (JVM)
Streams pool: Used by Oracle Streams to store information about the capture and
apply processes
Program Global Areas (PGA): Memory regions that contain data and control
information about a server or background process. A PGA is suballocated from the
aggregated PGA area.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Database
buffer
cache
DBWn
Data files
Database writer
process
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Redo log
buffer
LGWR
Log writer
process
Redo log
files
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Shared Pool
Server
process
Library cache
SQL queries
PL/SQL functions
Control structures
SGA
Library
cache
Data
dictionary Result
cache
cache
(row cache)
Locks
Control
structures
Shared pool
Shared Pool
The shared pool portion of the SGA contains the following main parts:
The library cache includes the sharable parts of SQL statements, PL/SQL procedures
and packages. It also contains control structures such as locks.
The result cache is composed of the SQL query result cache and the PL/SQL function
result cache. This cache is used to store results of SQL queries or PL/SQL functions to
speed up their future executions.
Note: In general, any item in the shared pool remains until it is flushed according to a modified
LRU algorithm.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Shared Pool
SGA
DBWn
2
Data
files
Server
process
Database
buffer cache
Redo log
buffer
Shared pool
Control
files
Library cache
User
process
Redo
log files
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Any changed blocks in the buffer cache are marked as dirty buffers; that is, the buffers
are not the same as the corresponding blocks on the disk. These buffers are not immediately
written to disk by the DBWn processes.
SGA
DBWn
Database
buffer cache
Data
files
Server
process
Redo log
SGA
buffer
Shared pool
3
Control
files
Library cache
User
process
Redo
log files
LGWR
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Large Pool
SGA
Parallel execution
Recovery Manager
Shared server
I/O buffer
Free
memory
Response
queue
Request
queue
Large pool
Large Pool
You can configure an optional memory area called the large pool to provide large memory
allocations for:
Session memory for the shared server, the Oracle XA interface (used where
transactions interact with more than one database), or parallel execution buffers
By allocating the above memory components from the large pool, Oracle Database can use
the shared pool primarily for caching the shared part of SQL and PL/SQL constructs. The
shared pool was originally designed to store SQL and PL/SQL constructs. Using the large
pool avoids fragmentation issues associated with having large and small allocations sharing
the same memory area. Unlike the shared pool, the large pool does not have an LRU list.
You should consider configuring a large pool if your instance uses any of the following:
Parallel execution: Parallel query uses shared pool memory to cache parallel execution
message buffers.
Recovery Manager: Recovery Manager uses the shared pool to cache I/O buffers
during backup and restore operations.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Large Pool
Shared server: In a shared server architecture, the session memory for each client
process is included in the shared pool.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Java pool
Streams pool
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Sort area
Hash join area
Bitmap merge area
Bitmap create area
Server
process
User
Session
Data
Cursor
Status
SQL
Area
SQL work areas are allocated to support memory-intensive operators, such as the ones
listed in the slide. Generally, bigger work areas can significantly improve the
performance of a particular operator at the cost of higher memory consumption.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Background Process
RCBG
MMON
Database
buffer
cache
SGA
CKPT
PMON
CJQ0
QMNn
Redo log
buffer
SMON
MMAN
Shared pool
DBWn
LGWR
ARCn
Background Process
The background processes commonly seen in non-RAC, non-ASM environments can include
the following:
Database writer process (DBWn): Asynchronously writes modified (dirty) buffers in the
database buffer cache to disk
Log writer process (LGWR): Writes the recovery information called redo information in
the log buffer to a redo log file on disk
Checkpoint process (CKPT): Records checkpoint information in control files and each
data file header
System Monitor process (SMON): Performs recovery at instance startup and cleans up
unused temporary segments
Process monitor process (PMON): Performs process recovery when a user process
fails
Result cache background process (RCBG): Used to maintain the result cache in the
shared pool
Job queue process (CJQ0): Runs user jobs used in batch processing through the
Scheduler
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Background Process
Archiver processes (ARCn): Copies redo log files to a designated storage device after
a log switch has occurred
Queue monitor processes (QMNn): Monitors the Oracle Streams message queues
Memory Manager background process (MMAN): Used to manage SGA and PGA
memory components automatically
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Shared pool
Java
pool
Streams
pool
Fixed SGA
Large pool
Database
buffer cache
Redo log
buffer
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
PGA_AGGREGATE_TARGET
Server
process
Server
process
Background
process
Aggregated
PGA
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Untunable
PGA
Free
Private
SQL areas
Buffer cache
Large pool
Shared pool
Java pool
Streams pool
MEMORY_TARGET + STATISTICS_LEVEL
Other SGA
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Control file
Data files
Parameter file
Backup files
Password file
Control file: Contain data about the database itself (that is, physical database structure
information). These files are critical to the database. Without them, you cannot open
data files to access the data in the database.
Data files: Contain the user or application data of the database, as well as metadata
and the data dictionary
Online redo log files: Allow for instance recovery of the database. If the database
server crashes and does not lose any data files, the instance can recover the database
with the information in these files.
The following additional files are important for the successful running of the database:
Parameter file: Is used to define how the instance is configured when it starts up
Password file: Allows sysdba, sysoper, and sysasm to connect remotely to the
database and perform administrative tasks
Backup files: Are used for database recovery. You typically restore a backup file when
a media failure or user error has damaged or deleted the original file.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Archived redo log files: Contain an ongoing history of the data changes (redo) that are
generated by the instance. Using these files and a backup of the database, you can
recover a lost data file. That is, archive logs enable the recovery of restored data files.
Trace files: Each server and background process can write to an associated trace file.
When an internal error is detected by a process, the process dumps information about
the error to its trace file. Some of the information written to a trace file is intended for the
developer, whereas other information is for Oracle Support Services.
Alert log file: These are special trace entries. The alert log of a database is a
chronological log of messages and errors. Each instance has one alert log file. It is
recommended that you review this periodically.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Physical
Database
Schema
Tablespace
Only 1 with
bigfile
tablespaces
Data file
0, 1, or many
Undo tablespaces
never have 0
Segment
Extent
Oracle data
block
OS block
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Data Blocks
At the finest level of granularity, an Oracle databases data is stored in data blocks. One data
block corresponds to a specific number of bytes of physical database space on the disk. A
data block size is specified for each tablespace when it is created. A database uses and
allocates free database space in Oracle data blocks.
Extents
The next level of logical database space is an extent. An extent is a specific number of
contiguous data blocks (obtained in a single allocation) that are used to store a specific type of
information.
Segments
The level of logical database storage above an extent is called a segment. A segment is a set
of extents that are allocated for a certain logical structure. Different types of segments include:
Index segments: Each index has an index segment that stores all of its data. For a
partitioned index, each partition has an index segment.
Undo segments: One UNDO tablespace is created for each database instance. This
tablespace contains numerous undo segments to temporarily store undo information.
The information in an undo segment is used to generate read-consistent database
information and, during database recovery, to roll back uncommitted transactions for
users.
Temporary segments: Temporary segments are created by the Oracle Database when
a SQL statement needs a temporary work area to complete execution. When the
statement finishes execution, the temporary segments extents are returned to the
instance for future use. Specify either a default temporary tablespace for every user, or a
default temporary tablespace that is used across the database.
The Oracle Database dynamically allocates space. When the existing extents of a segment
are full, additional extents are added. Because extents are allocated as needed, the extents of
a segment may or may not be contiguous on the disk.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
clusters, and database links. In general, schema objects include everything that your
application creates in the database.
Segment
Extents
Data
blocks
Disk
blocks
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
The first time an Oracle Database server process requires a
particular piece of data, it searches for the data in the:
a. Database Buffer Cache
b. PGA
c. Redo Log Buffer
d. Shared Pool
Answer: a
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Which of the following is not a database logical structure?
a. Tablespace
b. Data File
c. Schema
d. Segment
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The SYSAUX tablespace is used for core functionality and the
SYSTEM tablespace is used for additional database
components such as the Enterprise Manager Repository.
a. True
b. False
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
List the major architectural components of the Oracle
Database server
Explain memory structures
Describe background processes
Correlate logical and physical storage structures
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 1: Overview
This practice covers the following topics:
Listing the different components of an Oracle Database
server
Looking at some instance and database components
directly on your machine
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 1: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 1 - Page 34
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 2
Chapter 2 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 2 - Page 2
Objectives
After completing this lesson, you should be able to:
Describe what attributes of a SQL statement can make it
perform poorly
List the Oracle tools that can be used to tune SQL
List the tuning tasks
Objectives
This lesson gives you an understanding of the tuning process and the different components of
an Oracle Database that may require tuning.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Stale optimizer statistics: SQL execution plans are generated by the cost-based
optimizer (CBO). For CBO to effectively choose the most efficient plan, it needs accurate
information on the data volume and distribution of tables and indexes referenced in the
queries. Without accurate optimizer statistics, the CBO can easily be mislead and
generate suboptimal execution plans.
Suboptimal execution plan selection: The CBO can sometimes select a suboptimal
execution plan for a SQL statement. This happens for most part because of incorrect
estimates of some attributes of that SQL statement, such as its cost, cardinality, or
predicate selectivity.
Poorly constructed SQL: If the SQL statement is designed poorly, there is not much
that the optimizer can do to improve its performance. A missing join condition leading to
a Cartesian product, or the use of more expensive SQL constructs like UNION in place of
UNION ALL, are just a couple of examples of inefficient SQL design.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Additional reasons for poor performance might be connected with hardware-related
issues, such as memory, I/Os, CPUs, and so on.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
These four main causes of poor SQL optimization can have a drastic impact on performance.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
5. The UNION operator, as opposed to the UNION ALL operator, ensures that there are no
duplicate rows in the result set. However, this requires an extra step, a unique sort, to
eliminate any duplicates. If you know that there are no rows in common between the two
UNIONed queries, use UNION ALL instead of UNION. This eliminates the unnecessary
sort.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
4. The fourth query uses a data type conversion function in it to make the data types match
in the comparison. The problem here is that the TO_CHAR function is applied to the
column value, rather than to the constant. This means that the function is called for every
row in the table. It would be better to convert the literal once, and not convert the column.
This is better queried as:
SELECT * FROM employees
WHERE salary = TO_NUMBER(:sal)
Automatic
In-memory
statistics
MMON
SGA
60 min
AWR
ASH
ADDM
Snapshots
Alerts
Snapshots
AST
Statspack
ADDM
results
AWR report
Proactive monitoring:
-
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Oracle Database 11g further automates the SQL tuning process by identifying
problematic SQL statements, running SQL Tuning Advisor on them, and
implementing the resulting SQL profile recommendations to tune the statement
without requiring user intervention. This automation uses the AUTOTASK
framework through a new task called Automatic SQL Tuning Task that runs every
night by default.
Reactive monitoring:
-
The Oracle Database has powerful new data sources and performance-reporting
capabilities. Enterprise Manager provides an integrated performance management
console that uses all relevant data sources. Using a drill-down method, you can
manually identify bottlenecks with just a few mouse clicks.
New data sources are introduced to capture important information about your databases
healthfor example, new memory statistics (for current diagnostics) as well as statistics
history stored in Automatic Workload Repository (AWR).
Note: Accessing Enterprise Manager or tools discussed here may require additional licenses
and certain privileges generally reserved for database administrators.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Alert
log
SQL
traces
tkprof
trcsess
Optimizer
statistics
Perf
views
Direct
ADDM
Hang
SGA analyzer
and
advisors monitor
SPA
AWR
baseline
SQL
statistics
System
Session
statistics
EM
Metric
AWR
perf
base
reports pages
line
Statspack
Base/
Segment
statistics
Wait
model
Histograms
Time
model
Metrics
OS
statistics
Service
statistics
ASH
Alerts
SQL
report
Compared
periods
ASH
report
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Home
Run
ADDM
Performance
Nonidle
wait
classes
Top
Consumers
Top
Activity
Wait
class
details
Top
SQL
Duplicate Blocking
Hang Instance
SQL
Sessions Analysis Locks
Top
Sessions
Top
Services
Top
Modules
Top
Actions
Instance
Activity
Top
Files
AWR
Baselines
Top
Objects
SPA
Wait
event
histograms
SQL
Tuning
Advisor
SQL
Tuning
Sets
Enable/Disable
aggregation
View
Enable/Disable
SQL
trace file
SQL trace
System
statistics
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
discovered by the optimizer will be stored in the SQL plan history, but will not be used until
they are approved.
Identifying high-load SQL statements is one of the most important tasks you should
perform. The ADDM is the ideal tool for this particular task.
By default, the Oracle Database gathers optimizer statistics automatically. For this, a job
is scheduled to run in the maintenance windows.
Operating system statistics provide information about the usage and performance of the
main hardware components as well as the performance of the operating system itself.
You can maintain the existing execution plan of SQL statements over time by using
stored statistics or SQL plan baselines.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Possibly
needs SQL
tuning
Scalable
application
Scalable
application
Needs
instance/RAC
tuning
No gain achieved
by adding
CPUs/nodes
Wait
time
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Poor SQL and index design, resulting in a higher number of logical input/output (I/O) for
the same number of rows returned
However, design is not the only problem. The physical implementation of the application can
be the weak link, as in the following examples:
Systems can move to production environments with poorly written SQL that cause high
I/O.
The production environment can use different execution plans than those generated in
testing.
Inefficient memory usage places high stress on the operating virtual memory subsystem.
This affects performance and availability.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
5. Getting database I/O wrong: Many sites lay out their databases poorly over the
available disks. Other sites specify the number of disks incorrectly because they
configure disks by disk space and not by I/O bandwidth.
6. Redo log setup problems: Many sites run with too small redo log files. Small redo logs
cause system checkpoints to continuously put a high load on the buffer cache and the
I/O system. If there are very few redo logs, the archive cannot keep up, and the
database waits for the archive process to catch up.
7. Excessive serialization: Serialization of data blocks in the buffer cache due to shortage
of undo segments is particularly common in applications with large numbers of active
users and a few undo segments. Use Automatic Segment Space Management (ASSM)
and automatic undo management to solve this problem.
8. Long full table scans: Long full table scans for high-volume or interactive online
operations could indicate poor transaction design, missing indexes, or poor SQL
optimization. Long table scans, by nature, are I/O-intensive and not scalable.
9. High amounts of recursive (SYS) SQL: Large amounts of recursive SQL executed by
SYS could indicate that space management activities, such as extent allocations, take
place. This is not scalable and impacts user response time. Use locally managed
tablespaces to reduce recursive SQL due to extent allocation. Recursive SQL executed
under another user ID is probably SQL and PL/SQL, so this is not a problem.
10. Deployment and migration errors: In many cases, an application uses too many
resources because the schema owning the tables has not been successfully migrated
from the development environment or from an older implementation. Examples of this
are missing indexes or incorrect statistics. These errors can lead to suboptimal
execution plans and poor interactive user performance. When migrating applications of
known performance, export the schema statistics to maintain plan stability using the
DBMS_STATS package.
Although these errors are not directly detected by ADDM, ADDM highlights the resulting highload SQL.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
override proven optimal execution plans. For these reasons, schemas, schema
statistics, and optimizer settings should be managed together as a group to ensure
consistency of performance.
Simple design
Data modeling
Tables and indexes
Using views
Writing efficient SQL
Cursor sharing
Using bind variables
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Simple tables
Well-written SQL
Indexing only as required
Retrieving only required information
If the table design is so complicated that nobody can fully understand it, the table is
probably designed badly.
If SQL statements are so long and involved that it would be impossible for any optimizer
to effectively optimize it in real time, there is probably a bad statement, underlying
transaction, or table design.
If there are many indexes on a table and the same columns are repeatedly indexed,
there is probably a bad index design.
If queries are submitted without suitable qualification (the WHERE clause) for rapid
response for online users, there is probably a bad user interface or transaction design.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Data Modeling
Data Modeling
Data modeling is important in successful relational application design. This should be done in
a way that quickly and accurately represents the business practices. Apply your greatest
modeling efforts to those entities affected by the most frequent business transactions. Use of
modeling tools can then rapidly generate schema definitions and can be useful when a fast
prototype is required.
Normalizing data prevents duplication. When data is normalized, you have a clear picture of
the keys and relationships. It is then easier to perform the next step of creating tables,
constraints, and indexes. A good data model ultimately means that your queries are written
more efficiently.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Data Modeling
Table Design
Default values
Constraints
Materialized views
Clusters
Partitioning
Table Design
Table design is largely a compromise between flexibility and performance of core
transactions. To keep the database flexible and able to accommodate unforeseen workloads,
the table design should be very similar to the data model, and it should be normalized to at
least third normal form. However, certain core transactions can require selective
denormalization for performance purposes.
Use the features supplied with Oracle Database to simplify table design for performance, such
as storing tables prejoined in clusters, adding derived columns and aggregate values, and
using materialized views or partitioned tables. Additionally, create check constraints and
columns with default values to prevent bad data from getting into the tables.
Design should be focused on business-critical tables so that good performance can be
achieved in areas that are the most used. For noncritical tables, shortcuts in design can be
adopted to enable a more rapid application development. If, however, a noncore table
becomes a performance problem during prototyping and testing, remedial design efforts
should be applied immediately.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Table Design
Index Design
Index Design
Index design is also a largely iterative process based on the SQL that is generated by
application designers. However, it is possible to make a sensible start by building indexes that
enforce foreign key constraints (to reduce response time on joins between primary key tables
and foreign key tables) and creating indexes on frequently accessed data, such as a persons
name. Primary keys and unique keys are automatically indexed except for the DISABLE
VALIDATE and DISABLE NOVALIDATE RELY constraints. As the application evolves and
testing is performed on realistic sizes of data, certain queries need performance
improvements, for which building a better index is a good solution.
The following indexing design ideas should be considered when building a new index.
Appending Columns to an Index or Using Index-Organized Tables
One of the easiest ways to speed up a query is to reduce the number of logical I/Os by
eliminating a table scan from the execution plan. This can be done by creating an index over
all the columns of the table referenced by the query. These columns are the select list
columns, WHERE clause columns, and any required join or sort columns. This technique is
particularly useful in speeding up an online applications response times when timeconsuming I/Os are reduced. This is best applied when testing the application with
properly-sized data for the first time. The most aggressive form of this technique is to build an
index-organized table (IOT).
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Index Design
Using Views
Using Views
Views can speed up and simplify application design. A simple view definition can mask data
model complexity from the programmers whose priorities are to retrieve, display, collect, and
store data. Views are often used to provide simple row and column-level access restrictions.
However, though views provide clean programming interfaces, they can cause suboptimal,
resource-intensive queries when nested too deeply. The worst type of view use is creating
joins on views that reference other views, which in turn reference other views. In many cases,
developers can satisfy the query directly from the table without using a view. Because of their
inherent properties, views usually make it difficult for the optimizer to generate the optimal
execution plan.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Using Views
Hard parsing: A SQL statement is submitted for the first time, and no match is found in
the shared pool. Hard parses are the most resource-intensive and are not scalable
because they perform all the operations involved in a parse.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Soft parsing: A SQL statement is submitted for the first time, and a match is found in
the shared pool. The match can be the result of previous execution by another user. The
SQL statement is shared, which is good for performance. However, soft parses are not
ideal because they still require syntax and security checking, which consume system
resources.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Case
White space
Comments
Object references
Bind variables
Write referenced triggers and procedures when using application development tools.
Develop format standards for all statements, including those in PL/SQL code.
Develop rules for the use of white space (spaces, tabs, returns).
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Develop rules for the use of comments (preferably keeping them out of the SQL
statements themselves).
Use the same names to refer to identical database objects. If possible, prefix each object
with a schema name.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Performance Checklist
Performance Checklist
Verify that all SQL statements are optimal and understand their resource usage.
Validate that middleware and programs that connect to the database are efficient in their
connection management and do not log on and log off repeatedly.
Validate that the SQL statements use cursors efficiently. Each SQL statement should be
parsed once and then executed multiple times. This happens mostly when bind variables
are not used properly and the WHERE clause predicates are sent as string literals.
Validate that all schema objects are correctly migrated from the development
environment to the production database. This includes tables, indexes, sequences,
triggers, packages, procedures, functions, Java objects, synonyms, grants, and views.
Ensure that any modifications made in testing are made to the production system.
As soon as the system is rolled out, establish a baseline set of statistics from the
database and operating system. This first set of statistics validates or corrects any
assumptions made in the design and rollout process.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Performance Checklist
SQL Developer
SQL Developer is shipped with Oracle Database 11g Release 2, and is the default tool
for this class.
SQL*Plus
The SQL*Plus environment may also be used to run all SQL commands covered in this
course.
Note: See Appendix C titled Using SQL Developer for information about using SQL
Developer, including simple instructions on installing version 2.1.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
SQL Developer
Creating reports
You can connect to any target Oracle database schema using standard Oracle database
authentication. When connected, you can perform operations on objects in the database.
Appendix C
Appendix C of this course provides an introduction on using the SQL Developer interface. It
also provides information about creating a database connection, interacting with data using
SQL and PL/SQL, and so on.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
You execute subprograms by using either an anonymous PL/SQL block or the EXECUTE
command.
If you use the DBMS_OUTPUT package procedures to print text to the screen, you must
first execute the SET SERVEROUTPUT ON command in your session.
Note
To launch SQL*Plus in the Linux environment, open a Terminal window and enter the
sqlplus command.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
For more information about how to use SQL*Plus, see the SQL*Plus User's Guide and
Reference.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
_________automatically identifies bottlenecks within Oracle
Database and makes recommendations on the options
available for fixing these bottlenecks.
a. ASH
b. AWR
c. ADDM
d. Snapshots
Answer: c
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Normalizing data results in a good data model, which ultimately
means that your queries are written more efficiently.
a. True
b. False
Answer: a
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Views should be used carefully because, though they provide
clean programming interfaces, they can cause suboptimal,
resource-intensive queries when nested too deeply.
a. True
b. False
Answer: a
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Identify the characteristics that must be supported by an
application designed for SQL execution efficiency.
a. Use concurrent connections to the database.
b. Use cursors so that SQL statements are parsed once and
executed multiple times.
c. Use bind variables.
Answer: b, c
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
Describe what attributes of a SQL statement can make it
perform poorly
List the Oracle tools that can be used to tune SQL
List the tuning tasks
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 2: Overview
This practice covers the following topics:
Rewriting queries for better performance
Rewriting applications for better performance
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 2: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 2 - Page 40
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 3
Chapter 3 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 3 - Page 2
Objectives
After completing this lesson, you should be able to:
Describe the execution steps of a SQL statement
Discuss the need for an optimizer
Explain the various phases of optimization
Control the behavior of the optimizer
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
ESS
DDL
INSERT
UPDATE
DELETE
MERGE
SELECT
TCS
COMMIT
ROLLBACK
SAVEPOINT
SET TRANSACTION
DECLARE
CONNECT
OPEN
CLOSE
DESCRIBE
WHENEVER
PREPARE
EXECUTE
FETCH
CREATE
DROP
ALTER
RENAME
TRUNCATE
GRANT
REVOKE
AUDIT
NOAUDIT
COMMENT
SessionCS
SystemCS
ALTER SESSION
SET ROLE
ALTER SYSTEM
Data definition language (DDL) statements define, alter the structure of, and drop
schema objects.
Transaction control statements (TCS) manage the changes made by DML statements
and group DML statements into transactions.
System Control statements change the properties of the Oracle Database instance.
Embedded SQL statements incorporate DDL, DML, and TCS within a procedural
language program, such as PL/SQL and Oracle precompilers. This incorporation is done
using the statements listed in the slide under the ESS category.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: SELECT statements are the most used statements. While his course focuses mainly on
queries, it is important to note that any type of SQL statement is subject to optimization.
Private
SQL area
Private
SQL area
Private
SQL area
Shared
SQL area
Private
SQL area
Private
SQL area
Shared
SQL area
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
User
process
User
process
User
process
User
process
Server
process
Server
process
Private
SQL area
Private
SQL area
Client
Server
Server
process
Server
process
Server
process
Private
SQL area
Private
SQL area
Private
SQL area
Aggregated
PGA
SGA
Shared
SQL area
Shared
SQL area
Library cache
Buffer cache
Data dictionary
cache
Redo log
buffer
Result cache
Java pool
Other
SHARED_POOL
Streams pool
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
query?
yes
describe?
no
yes
no
DESCRIBE
no
more?
yes
DEFINE
no
more?
yes
yes
reparse?
no
yes
bind?
no
BIND
no
more?
yes
PARALLELIZE
EXECUTE
query?
yes
FETCH
no
yes
execute
others?
no
more?
yes
no
CLOSE
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Create a cursor.
Parse the statement.
Describe query results.
Define query output.
Bind variables.
Parallelize the statement.
Execute the statement.
Fetch rows of a query.
Close the cursor.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
SELECT
INSERT
UPDATE
MERGE
DELETE
CREATE
ALTER
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Steps 7 Through 9
Execute:
Drives the SQL statement to produce the desired results
Fetch rows:
Into defined output variables
Query results returned in table format
Array fetch mechanism
Steps 7 Through 9
At this point, Oracle Database has all the necessary information and resources, so the
statement is run. If the statement is a query (without the FOR UPDATE clause) statement, no
rows need to be locked because no data is changed. If the statement is an UPDATE or a
DELETE statement, however, all rows that the statement affects are locked until the next
COMMIT, ROLLBACK, or SAVEPOINT for the transaction. This ensures data integrity.
For some statements, you can specify a number of executions to be performed. This is called
array processing. Given n number of executions, the bind and define locations are assumed to
be the beginning of an array of size n.
In the fetch stage, rows are selected and ordered (if requested by the query), and each
successive fetch retrieves another row of the result until the last row has been fetched.
The final stage of processing a SQL statement is closing the cursor.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Steps 7 Through 9
variable b1 varchar2
execute dbms_sql.parse
(:c1
,'select null from dual where dummy = :b1'
,dbms_sql.native);
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Parse
call
Parsed representation
Existing shared
SQL area?
No
(Hard parse)
Parse operation
(Optimization)
Execute statement
Shared
SQL area
Determines whether the process issuing the statement has the privileges to run it
Determines whether or not there is an existing shared SQL area containing the parsed
representation of the statement in the library cache. If so, the user process uses this
parsed representation and runs the statement immediately. If not, Oracle Database
generates the parsed representation of the statement, and the user process allocates a
shared SQL area for the statement in the library cache and stores its parsed
representation there.
Note the difference between an application making a parse call for a SQL statement and
Oracle Database actually parsing the statement.
A parse call by the application associates a SQL statement with a private SQL area.
After a statement has been associated with a private SQL area, it can be run repeatedly
without your application making a parse call.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
A parse operation by Oracle Database allocates a shared SQL area for a SQL
statement. After a shared SQL area has been allocated for a statement, it can be run
repeatedly without being reparsed.
Both parse calls and parsing can be expensive relative to execution, so perform them as
rarely as possible.
Note: Although parsing a SQL statement validates that statement, parsing only identifies
errors that can be found before statement execution. Thus, some errors cannot be caught by
parsing. For example, errors in data conversion or errors in data (such as an attempt to enter
duplicate values in a primary key) and deadlocks are all errors or situations that can be
encountered and reported only during the execution stage.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Use the
index.
Read
each row
and check.
Statistics
Use the
index
I have a plan!
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Use the
index.
Read
each row
and check.
Statistics
Use Full
Table Scan
Generate a plan
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer
Transformer
Statistics
Estimator
Dictionary
Plan Generator
Execution Plan
Shared
SQL area
Parsed representation
(query blocks)
CBO
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Original query:
B*-tree Index
SELECT *
FROM emp
WHERE job = 'CLERK' OR deptno = 10;
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Original query:
SELECT *
FROM accounts
WHERE custno IN
(SELECT custno FROM customers);
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Original query:
Index
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Original query:
Index
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Original query:
Index
SELECT *
FROM emp, dept
WHERE emp.deptno = 20 AND emp.deptno = dept.deptno;
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Cost-Based Optimizer
Piece of code:
Estimator
Plan generator
Plan generator:
Cost-Based Optimizer
The combination of the estimator and plan generator code is commonly called the cost-based
optimizer (CBO).
The estimator generates three types of measures: selectivity, cardinality, and cost. These
measures are related to each other. Cardinality is derived from selectivity and often the cost
depends on cardinality. The end goal of the estimator is to estimate the overall cost of a given
plan. If statistics are available, the estimator uses these to improve the degree of accuracy
when computing the measures.
The main function of the plan generator is to try out different possible plans for a given query
and pick the one that has the lowest cost. Many different plans are possible because of the
various combinations of different access paths, join methods, and join orders that can be used
to access and process data in different ways and produce the same result. The number of
possible plans for a query block is proportional to the number of join items in the FROM clause.
This number rises exponentially with the number of join items.
The optimizer uses various pieces of information to determine the best path: WHERE clause,
statistics, initialization parameters, supplied hints, and schema information.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Cost-Based Optimizer
Estimator: Selectivity
Selectivity =
Estimator: Selectivity
Selectivity represents a fraction of rows from a row set. The row set can be a base table, a
view, or the result of a join or a GROUP BY operator. The selectivity is tied to a query
predicate, such as last_name = 'Smith', or a combination of predicates, such as
last_name = 'Smith' AND job_type = 'Clerk'. A predicate acts as a filter that
filters a certain number of rows from a row set. Therefore, the selectivity of a predicate
indicates the percentage of rows from a row set that passes the predicate test. Selectivity lies
in a value range from 0.0 to 1.0. A selectivity of 0.0 means that no rows are selected from a
row set, and a selectivity of 1.0 means that all rows are selected.
If no statistics are available, the optimizer either uses dynamic sampling or an internal default
value, depending on the value of the OPTIMIZER_DYNAMIC_SAMPLING initialization
parameter. When statistics are available, the estimator uses them to estimate selectivity. For
example, for an equality predicate (last_name = 'Smith'), selectivity is set to the
reciprocal of the number n of distinct values of LAST_NAME because the query selects rows
that contain one out of n distinct values. Thus, even distribution is assumed. If a histogram is
available in the LAST_NAME column, the estimator uses it instead of the number of distinct
values. The histogram captures the distribution of different values in a column, so it yields
better selectivity estimates.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Estimator: Selectivity
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: It is important to have histograms in columns that contain values with large variations in
the number of duplicates (data skew).
Estimator: Cardinality
Cardinality = Selectivity * Total number of rows
Estimator: Cardinality
The cardinality of a particular operation in the execution plan of a query represents the
estimated number of rows retrieved by that particular operation. Most of the time, the row
source can be a base table, a view, or the result of a join or GROUP BY operator.
When costing a join operation, it is important to know the cardinality of the driving row source.
With nested loops join, for example, the driving row source defines how often the system
probes the inner row source.
Because sort costs are dependent on the size and number of rows to be sorted, cardinality
figures are also vital for sort costing.
In the example in the slide, based on assumed statistics, the optimizer knows that there are
203 different values in the DEV_NAME column, and that the total number of rows in the
COURSES table is 1018. Based on this assumption, the optimizer deduces that the selectivity
of the DEV_NAME='ANGEL' predicate is 1/203 (assuming there are no histograms), and also
deduces the cardinality of the query to be (1/203)*1018. This number is then rounded off to
the nearest integer, 6.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Estimator: Cardinality
Estimator: Cost
#SRds*sreadtim
#MRds*mreadtim +
Cost=
CPU cost
#CPUCycles/cpuspeed
sreadtim
Estimator: Cost
The cost of a statement represents the optimizers best estimate of the number of
standardized inputs/outputs (I/Os) it takes to execute that statement. Basically, the cost is a
normalized value in terms of a number of single block random reads
The standard cost metric measured by the optimizer is in terms of number of single block
random reads, so one cost unit corresponds to one single block random read. The formula
shown in the slide combines three different cost units:
Estimated time for the CPU to process the statement into one standard cost unit
The model includes CPU costing because in most cases CPU utilization is as important as
I/O; often it is the only contribution to the cost (in cases of in-memory sort, hash, predicate
evaluation, and cached I/O).
This model is straightforward for serial execution. For parallel execution, necessary
adjustments are made while computing estimates for #SRds, #MRds, and #CPUCycles.
Note: #CPUCycles includes CPU cost of query processing (pure CPU cost) and CPU cost of
data retrieval (CPU cost of the buffer cache get).
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Estimator: Cost
Plan Generator
select e.last_name, d.department_name
from
employees e, departments d
where e.department_id = d.department_id;
Join order[1]: DEPARTMENTS[D]#0 EMPLOYEES[E]#1
NL Join: Cost: 41.13 Resp: 41.13 Degree: 1
SM cost: 8.01
HA cost: 6.51
Best:: JoinMethod: Hash
Cost: 6.51 Degree: 1 Resp: 6.51 Card: 106.00
Join order[2]: EMPLOYEES[E]#1 DEPARTMENTS[D]#0
NL Join: Cost: 121.24 Resp: 121.24 Degree: 1
SM cost: 8.01
HA cost: 6.51
Join order aborted
Final cost for query block SEL$1 (#0)
All Rows Plan:
Best join order: 1
+----------------------------------------------------------------+
| Id | Operation
| Name
| Rows | Bytes | Cost |
+----------------------------------------------------------------+
| 0
| SELECT STATEMENT
|
|
|
|
7 |
| 1
| HASH JOIN
|
|
106 | 6042 |
7 |
| 2
|
TABLE ACCESS FULL | DEPARTMENTS|
27 |
810 |
3 |
| 3
|
TABLE ACCESS FULL | EMPLOYEES |
107 | 2889 |
3 |
+----------------------------------------------------------------+
Plan Generator
The plan generator explores various plans for a query block by trying out different access
paths, join methods, and join orders. Ultimately, the plan generator delivers the best execution
plan for your statement. The slide shows you an extract of an optimizer trace file generated for
the select statement. As you can see from the trace, the plan generator has six possibilities, or
six different plans to test: Two join orders, and for each, three different join methods. It is
assumed that there are no indexes in this example.
To retrieve the rows, you can start to join the DEPARTMENTS table to the EMPLOYEES table.
For that particular join order, you can use three possible join mechanisms that the optimizer
knows: Nested Loop, Sort Merge, or Hash Join. For each possibility, you have the cost of the
corresponding plan. The best plan is the one shown at the end of the trace.
The plan generator uses an internal cutoff to reduce the number of plans it tries when finding
the one with the lowest cost. The cutoff is based on the cost of the current best plan. If the
current best cost is large, the plan generator tries harder (in other words, explores more
alternate plans) to find a better plan with lower cost. If the current best cost is small, the plan
generator ends the search swiftly because further cost improvement is not significant. The
cutoff works well if the plan generator starts with an initial join order that produces a plan with
a cost close to optimal. Finding a good initial join order is a difficult problem.
Note: Access path, join methods, and plan are discussed in more detail in the lessons titled
Optimizer Operators and Interpreting Execution Plans.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Plan Generator
CURSOR_SHARING determines what kind of SQL statements can share the same
cursors:
-
FORCE: Forces statements that may differ in some literals, but are otherwise
identical, to share a cursor, unless the literals affect the meaning of the statement
SIMILAR: Causes statements that may differ in some literals, but are otherwise
identical, to share a cursor, unless the literals affect either the meaning of the
statement or the degree to which the plan is optimized. Forcing cursor sharing
among similar (but not identical) statements can have unexpected results in some
decision support system (DSS) applications, or applications that use stored
outlines.
EXACT: Only allows statements with identical text to share the same cursor. This is
the default.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
When set to MANUAL (the default), you must specify, by using the RESULT_CACHE
hint, that a particular result is to be stored in the cache.
When set to FORCE, all results are stored in the cache. For the FORCE setting, if the
statement contains a [NO_]RESULT_CACHE hint, the hint takes precedence over
the parameter setting.
The memory size allocated to the result cache depends on the memory size of the SGA
as well as the memory management system. You can change the memory allocated to
the result cache by setting the RESULT_CACHE_MAX_SIZE parameter. The result cache
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
being utilized for the operation. As of Oracle Database 10g, Release 2, the default value
of this parameter is a value that corresponds to the maximum I/O size that can be
performed efficiently. This value is platform-dependent and is calculated at instance
startup for most platforms.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
is disabled if you set its value to 0. The value of this parameter is rounded to the largest
multiple of 32 KB that is not greater than the specified value. If the rounded value is 0,
the feature is disabled.
OPTIMIZER_INDEX_CACHING
OPTIMIZER_INDEX_COST_ADJ
OPTIMIZER_FEATURES_ENABLED
OPTIMIZER_MODE: ALL_ROWS, FIRST_ROWS, FIRST_ROWS_n
OPTIMIZER_CAPTURE_SQL_PLAN_BASELINES
OPTIMIZER_USE_SQL_PLAN_BASELINES
OPTIMIZER_DYNAMIC_SAMPLING
OPTIMIZER_USE_INVISIBLE_INDEXES
OPTIMIZER_USE_PENDING_STATISTICS
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
ALL_ROWS: The optimizer uses a cost-based approach for all SQL statements in
the session regardless of the presence of statistics and optimizes with a goal of
best throughput (minimum resource use to complete the entire statement). This is
the default value.
FIRST_ROWS: The optimizer uses a mix of cost and heuristics to find a best plan
for fast delivery of the first few rows. Using heuristics sometimes leads the query
optimizer to generate a plan with a cost that is significantly larger than the cost of a
plan without applying the heuristic. FIRST_ROWS is available for backward
compatibility and plan stability; use FIRST_ROWS_n instead.
Note: Invisible indexes, pending statistics, and dynamic sampling are discussed later in this
course.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
For example, if you upgrade your database from release 10.1 to release 11.1, but you
want to keep the release 10.1 optimizer behavior, you can do so by setting this
parameter to 10.1.0. At a later time, you can try the enhancements introduced in
releases up to and including release 11.1 by setting the parameter to 11.1.0.6. However,
it is not recommended to explicitly set the OPTIMIZER_FEATURES_ENABLE parameter
to an earlier release. To avoid possible SQL performance regression that may result
from execution plan changes, consider using SQL plan management instead.
9.0.0 to 9.2.0
10.1.0 to 10.1.0.5
10.2.0 to 10.2.0.2
11.1.0.6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
The _________step provides information about the select list
items and is relevant when entering dynamic queries through
an OCI application.
a. Parse
b. Define
c. Describe
d. Parallelize
Answer: c
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Which of the following steps is performed by the query
optimizer?
a. Generating a set of potential plans for the SQL statement
based on available access paths
b. Estimating and comparing the cost of each plan
c. Selecting the plan with the lowest cost
d. All of the above
Answer: d
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The expected number of rows retrieved by a particular
operation in the execution plan is known as its:
a. Cost
b. Cardinality
c. Optimization quotient
d. Selectivity
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
Describe the execution steps of a SQL statement
Describe the need for an optimizer
Explain the various phases of optimization
Control the behavior of the optimizer
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 3: Overview
This practice covers exploring a trace file to understand the
optimizers decisions.
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 3: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 4
Chapter 4 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 4 - Page 2
Objectives
After completing this lesson, you should be able to:
Gather execution plans
Display execution plans
Interpret execution plans
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
In addition to the row source tree (or data flow tree for parallel operations), the plan table
contains information about the following:
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The EXPLAIN PLAN results help you determine whether the optimizer selects a particular
execution plan, such as nested loops join.
The EXPLAIN PLAN command enables you to view the execution plan that the
optimizer might use to execute a SQL statement. This command is very useful because
it outlines the plan that the optimizer may use and inserts it in a table called
PLAN_TABLE without executing the SQL statement. This command is available from
SQL*Plus or SQL Developer.
V$SQL_PLAN provides a way to examine the execution plan for cursors that were
recently executed. Information in V$SQL_PLAN is very similar to the output of an
EXPLAIN PLAN statement. However, while EXPLAIN PLAN shows a theoretical plan
that can be used if this statement was executed, V$SQL_PLAN contains the actual plan
used.
V$SQL_PLAN_MONITOR displays plan-level monitoring statistics for each SQL statement
found in V$SQL_MONITOR. Each row in V$SQL_PLAN_MONITOR corresponds to an
operation of the execution plan that is monitored.
The Automatic Workload Repository (AWR) infrastructure and Statspack store execution
plans of top SQL statements. Plans are recorded into DBA_HIST_SQL_PLAN or
STATS$SQL_PLAN.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Plan and row source operations are dumped in trace files generated by DBMS_MONITOR.
The SQL management base (SMB) is a part of the data dictionary that resides in the
SYSAUX tablespace. It stores statement log, plan histories, and SQL plan baselines, as
well as SQL profiles.
The event 10053, which is used to dump cost-based optimizer (CBO) computations may
include a plan.
Starting with Oracle Database 10g, Release 2, when you dump process state (or
errorstack from a process), execution plans are included in the trace file that is
generated.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
An advantage of using the DBMS_XPLAN package table functions is that the output is
formatted consistently without regard to the source.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
EXPLAIN PLAN
SET STATEMENT_ID
= 'text'
FOR statement
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
SQL>
2
3
4
5
EXPLAIN PLAN
SET STATEMENT_ID = 'demo01' FOR
SELECT e.last_name, d.department_name
FROM hr.employees e, hr.departments d
WHERE e.department_id = d.department_id;
Explained.
SQL>
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
PLAN_TABLE
PLAN_TABLE:
Is automatically created to hold the EXPLAIN PLAN output.
You can create your own using utlxplan.sql.
Advantage: SQL is not executed
Disadvantage: May not be the actual execution plan
PLAN_TABLE is hierarchical.
Hierarchy is established with the ID and PARENT_ID
columns.
PLAN_TABLE
There are various available methods to gather execution plans. Now, you are introduced only
to the EXPLAIN PLAN statement. This SQL statement gathers the execution plan of a SQL
statement without executing it, and outputs its result in the PLAN_TABLE table. Whatever the
method to gather and display the explain plan, the basic format and goal are the same.
However, PLAN_TABLE just shows you a plan that might not be the one chosen by the
optimizer. PLAN_TABLE is automatically created as a global temporary table and is visible to
all users. PLAN_TABLE is the default sample output table into which the EXPLAIN PLAN
statement inserts rows describing execution plans. PLAN_TABLE is organized in a tree-like
structure and you can retrieve that structure by using both the ID and PARENT_ID columns
with a CONNECT BY clause in a SELECT statement. While a PLAN_TABLE table is
automatically set up for each user, you can use the utlxplan.sql SQL script to manually
create a local PLAN_TABLE in your schema and use it to store the results of EXPLAIN PLAN.
The exact name and location of this script depends on your operating system. On UNIX, it is
located in the $ORACLE_HOME/rdbms/admin directory. It is recommended that you drop and
rebuild your local PLAN_TABLE table after upgrading the version of the database because the
columns might change. This can cause scripts to fail or cause TKPROF to fail, if you are
specifying the table.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
PLAN_TABLE
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: If you want an output table with a different name, first create PLAN_TABLE manually
with the utlxplan.sql script, and then rename the table with the RENAME SQL statement.
The output is the same as shown in the slide. In this example, you can substitute the name of
another plan table instead of PLAN_TABLE and demo01 represents the statement ID.
TYPICAL displays the most relevant information in the plan: operation ID, name and option,
number of rows, bytes, and optimizer cost. The last parameter for the DISPLAY function is the
one corresponding to filter_preds. This parameter represents a filter predicate or
predicates to restrict the set of rows selected from the table where the plan is stored. When
value is null (the default), the plan displayed corresponds to the last executed explain plan.
This parameter can reference any column of the table where the plan is stored and can
contain any SQL constructfor example, subquery or function calls.
Note: Alternatively, you can run the utlxpls.sql (or utlxplp.sql for parallel queries)
script (located in the ORACLE_HOME/rdbms/admin/ directory) to display the execution plan
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
stored in PLAN_TABLE for the last statement explained. This script uses the DISPLAY table
function from the DBMS_XPLAN package.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 4 - Page 17
EXPLAIN PLAN
SET STATEMENT_ID
= 'text'
FOR statement
If the target plan table also stores plan statistics columns (for example, it is a table used to
capture the content of the fixed view V$SQL_PLAN_STATISTICS_ALL), additional format
keywords can be used to specify which class of statistics to display when using the DISPLAY
function. These additional format keywords are IOSTATS, MEMSTATS, ALLSTATS and LAST.
Note: Format keywords can be prefixed with the - sign to exclude the specified information.
For example, -PROJECTION excludes projection information.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
AUTOTRACE
AUTOTRACE
When running SQL statements under SQL*Plus or SQL Developer, you can automatically get
a report on the execution plan and the statement execution statistics. The report is generated
after successful SQL DML (that is, SELECT, DELETE, UPDATE, and INSERT) statements. It is
useful for monitoring and tuning the performance of these statements.
To use this feature, you must have a PLAN_TABLE available in your schema, and then have
the PLUSTRACE role granted to you. The database administrator (DBA) privileges are required
to grant the PLUSTRACE role. The PLUSTRACE role is created and granted to the DBA role by
running the supplied $ORACLE_HOME/sqlplus/admin/plustrce.sql script.
On some versions and platforms, this is run by the database creation scripts. If this is not the
case on your platform, connect as SYSDBA and run the plustrce.sql script.
The PLUSTRACE role contains the select privilege on three V$ views. These privileges are
necessary to generate AUTOTRACE statistics.
AUTOTRACE is an excellent diagnostic tool for SQL statement tuning. Because it is purely
declarative, it is easier to use than EXPLAIN PLAN.
Note: The system does not support EXPLAIN PLAN for statements performing implicit type
conversion of date bind variables. With bind variables in general, the EXPLAIN PLAN output
might not represent the real execution plan.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
AUTOTRACE
OFF
ON
SET AUTOTRACE
TRACE[ONLY]
EXPLAIN
STATISTICS
SHOW AUTOTRACE
Note: If both the EXPLAIN and STATISTICS command options are omitted, execution plans
and statistics are displayed by default.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
AUTOTRACE: Examples
AUTOTRACE: Examples
You can control the report by setting the AUTOTRACE system variable. The following are some
examples:
SET AUTOTRACE ON: The AUTOTRACE report includes both the optimizer execution
plan and the SQL statement execution statistics.
SET AUTOTRACE TRACEONLY EXPLAIN: The AUTOTRACE report shows only the
optimizer execution path without executing the statement.
SET AUTOTRACE ON STATISTICS: The AUTOTRACE report shows the SQL statement
execution statistics and rows.
SET AUTOTRACE TRACEONLY: This is similar to SET AUTOTRACE ON, but it
suppresses the printing of the users query output, if any. If STATISTICS is enabled, the
query data is still fetched, but not printed.
SET AUTOTRACE OFF: No AUTOTRACE report is generated. This is the default.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
AUTOTRACE: Examples
AUTOTRACE: Statistics
SQL> show autotrace
autotrace OFF
SQL> set autotrace traceonly statistics
SQL> SELECT * FROM oe.products;
288 rows selected.
Statistics
-------------------------------------------------------1334 recursive calls
0 db block gets
686 consistent gets
394 physical reads
0 redo size
103919 bytes sent via SQL*Net to client
629 bytes received via SQL*Net from client
21 SQL*Net roundtrips to/from client
22 sorts (memory)
0 sorts (disk)
288 rows processed
AUTOTRACE: Statistics
The statistics are recorded by the server when your statement executes and indicate the
system resources required to execute your statement. The results include the following
statistics:
recursive calls is the number of recursive calls generated at both the user and
system level. Oracle Database maintains tables used for internal processing. When
Oracle Database needs to make a change to these tables, it internally generates an
internal SQL statement, which in turn generates a recursive call.
consistent gets is the number of times a consistent read was requested for a block.
physical reads is the total number of data blocks read from disk. This number
equals the value of physical reads direct plus all reads into buffer cache.
redo size is the total amount of redo generated in bytes.
bytes sent via SQL*Net to client is the total number of bytes sent to the client
from the foreground processes.
bytes received via SQL*Net from client is the total number of bytes received
from the client over Oracle Net.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
AUTOTRACE: Statistics
sorts (memory) is the number of sort operations that were performed completely in
memory and did not require any disk writes.
sorts (disk) is the number of sort operations that required at least one disk write.
The client referred to in the statistics is SQL*Plus. Oracle Net refers to the generic process
communication between SQL*Plus and the server, regardless of whether Oracle Net is
installed. You cannot change the default format of the statistics report.
Note: db block gets indicates reads of the current block from the database. consistent
gets are reads of blocks that must satisfy a particular system change number (SCN).
physical reads indicates reads of blocks from disk. db block gets and consistent
gets are the two statistics that are usually monitored. These should be low compared to the
number of rows retrieved. Sorts should be performed in memory rather than on disk.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
ADDRESS
CHILD_NUMBER
POSITION
PARENT_ID
ID
ADDRESS
HASH_VALUE
The ADDRESS and HASH_VALUE columns can be used to join with V$SQLAREA to add the
cursor-specific information.
The ADDRESS, HASH_VALUE, and CHILD_NUMBER columns can be used to join with V$SQL to
add the child cursorspecific information.
The PLAN_HASH VALUE column is a numerical representation of the SQL plan for the cursor.
By comparing one PLAN_HASH_VALUE with another, you can easily identify whether the two
plans are the same or not (rather than comparing the two plans line-by-line).
Note: Since Oracle Database 10g, SQL_HASH_VALUE in V$SESSION has been
complemented with SQL_ID, which you retrieve in many other V$ views. SQL_HASH_VALUE is
a 32-bit value and is not unique enough for large repositories of AWR data. SQL_ID is a 64-bit
hash value, which is more unique, the bottom 32 bits of which are SQL_HASH_VALUE. It is
normally represented as a character string to make it more manageable.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
V$SQL_PLAN_STATISTICS_ALL enables
side-by-side comparisons of the optimizer estimates with
the actual execution statistics.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
V$SQLAREA
V$SQL
V$SQL_WORKAREA
V$SQLSTATS
Estimated statistics
for each row source
V$SQL_PLAN
Execution statistics
for each row source
V$SQL_PLAN_STATISTICS
V$SQL_PLAN_STATISTICS_ALL
SQL_ID is the SQL identifier of the parent cursor in the library cache.
VERSION_COUNT is the number of child cursors that are present in the cache under this
parent.
V$SQL lists statistics on shared SQL areas and contains one row for each child of the original
SQL text entered:
ADDRESS represents the address of the handle to the parent for this cursor.
SQL_ID is the SQL identifier of the parent cursor in the library cache.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
V$SQL_PLAN contains the execution plan information for each child cursor loaded in the
library cache. The ADDRESS, HASH_VALUE, and CHILD_NUMBER columns can be used to join
with V$SQL to add the child cursorspecific information.
V$SQL_PLAN_STATISTICS provides execution statistics at the row source level for each
child cursor. The ADDRESS and HASH_VALUE columns can be used to join with V$SQLAREA to
locate the parent cursor. The ADDRESS, HASH_VALUE, and CHILD_NUMBER columns can be
used to join with V$SQL to locate the child cursor using this area.
V$SQL_PLAN_STATISTICS_ALL contains memory usage statistics for row sources that use
SQL memory (sort or hash join). This view concatenates information in V$SQL_PLAN with
execution statistics from V$SQL_PLAN_STATISTICS and V$SQL_WORKAREA.
V$SQL_WORKAREA displays information about work areas used by SQL cursors. Each SQL
statement stored in the shared pool has one or more child cursors that are listed in the V$SQL
view. V$SQL_WORKAREA lists all work areas needed by these child cursors.
V$SQL_WORKAREA can be joined with V$SQLAREA on (ADDRESS, HASH_VALUE) and with
V$SQL on (ADDRESS, HASH_VALUE, CHILD_NUMBER).
You can use this view to find answers to the following questions:
What are the top 10 work areas that require the most cache area?
For work areas allocated in the AUTO mode, what percentage of work areas run using
maximum memory?
V$SQLSTATS displays basic performance statistics for SQL cursors, with each row
representing the data for a unique combination of SQL text and optimizer plan (that is, unique
combination of SQL_ID and PLAN_HASH_VALUE). The column definitions for columns in
V$SQLSTATS are identical to those in the V$SQL and V$SQLAREA views. However, the
V$SQLSTATS view differs from V$SQL and V$SQLAREA in that it is faster, more scalable, and
has a greater data retention (the statistics may still appear in this view, even after the cursor
has been aged out of the shared pool). Note that V$SQLSTATS contains a subset of columns
that appear in V$SQL and V$SQLAREA.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Statistics displayed in V$SQL are normally updated at the end of query execution. However,
for long-running queries, they are updated every five seconds. This makes it easy to see the
impact of long-running SQL statements while they are still in progress.
Querying V$SQL_PLAN
SELECT PLAN_TABLE_OUTPUT FROM
TABLE(DBMS_XPLAN.DISPLAY_CURSOR('47ju6102uvq5q'));
SQL_ID 47ju6102uvq5q, child number 0
------------------------------------SELECT e.last_name, d.department_name
FROM hr.employees e, hr.departments d WHERE
e.department_id =d.department_id
Plan hash value: 2933537672
-------------------------------------------------------------------------------| Id | Operation
| Name
| Rows | Bytes | Cost (%CPU|
-------------------------------------------------------------------------------|
0 | SELECT STATEMENT
|
|
|
|
6 (100|
|
1 | MERGE JOIN
|
|
106 | 2862 |
6 (17|
|
2 |
TABLE ACCESS BY INDEX ROWID| DEPARTMENTS |
27 |
432 |
2
(0|
|
3 |
INDEX FULL SCAN
| DEPT_ID_PK |
27 |
|
1
(0|
|* 4 |
SORT JOIN
|
|
107 | 1177 |
4 (25|
|
5 |
TABLE ACCESS FULL
| EMPLOYEES
|
107 | 1177 |
3
(0|
-------------------------------------------------------------------------------Predicate Information (identified by operation id):
--------------------------------------------------4 - access("E"."DEPARTMENT_ID"="D"."DEPARTMENT_ID")
filter("E"."DEPARTMENT_ID"="D"."DEPARTMENT_ID")
24 rows selected.
Querying V$SQL_PLAN
You can query V$SQL_PLAN using the DBMS_XPLAN.DISPLAY_CURSOR() function to
display the current or last executed statement (as shown in the example). You can pass the
value of SQL_ID for the statement as a parameter to obtain the execution plan for a given
statement. SQL_ID is the SQL_ID of the SQL statement in the cursor cache. You can retrieve
the appropriate value by querying the SQL_ID column in V$SQL or V$SQLAREA. Alternatively,
you could select the PREV_SQL_ID column for a specific session out of V$SESSION. This
parameter defaults to null in which case the plan of the last cursor executed by the session is
displayed. To obtain SQL_ID, execute the following query:
SELECT e.last_name, d.department_name
FROM hr.employees e, hr.departments d
WHERE e.department_id =d.department_id;
SELECT SQL_ID, SQL_TEXT FROM V$SQL
WHERE SQL_TEXT LIKE '%SELECT e.last_name,%' ;
13saxr0mmz1s3
47ju6102uvq5q
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Querying V$SQL_PLAN
The FORMAT parameter controls the level of detail for the plan. In addition to the standard
values (BASIC, TYPICAL, SERIAL, ALL, and ADVANCED), there are additional supported
values to display run-time statistics for the cursor:
IOSTATS: Assuming that the basic plan statistics are collected when SQL statements
are executed (either by using the GATHER_PLAN_STATISTICS hint or by setting the
statistics_level parameter to ALL), this format shows I/O statistics for ALL (or only
for LAST) executions of the cursor.
MEMSTATS: Assuming that the Program Global Area (PGA) memory management is
enabled (that is, the pga_aggregate_target parameter is set to a nonzero value),
this format allows to display memory management statistics (for example, execution
mode of the operator, how much memory was used, number of bytes spilled to disk, and
so on). These statistics only apply to memory-intensive operations, such as hash joins,
sort or some bitmap operators.
ALLSTATS: A shortcut for 'IOSTATS MEMSTATS'
LAST: By default, plan statistics are shown for all executions of the cursor. The LAST
keyword can be specified to see only the statistics for the last execution.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
CHILD_NUMBER is the child number of the cursor to display. If not supplied, the execution plan
of all cursors matching the supplied SQL_ID parameter are displayed. CHILD_NUMBER can be
specified only if SQL_ID is specified.
Object statistics
Time-model statistics
Some system and session statistics
Active Session History (ASH) statistics
Object statistics that determine both access and usage statistics of database segments
Some of the system and session statistics collected in the V$SYSSTAT and V$SESSTAT
views
SQL statements that produce the highest load on the system, based on criteria, such as
elapsed time, CPU time, buffer gets, and so on
The database automatically generates snapshots of the performance data once every hour
and collects the statistics in the workload repository. The data in the snapshot interval is then
analyzed by ADDM. The ADDM compares the differences between snapshots to determine
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
which SQL statements to capture based on the effect on the system load. This reduces the
number of SQL statements that need to be captured over time.
Creating snapshots:
Dropping snapshots:
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
In the example, the range of snapshot IDs to drop is specified from 22 to 32. The optional
database identifier is 3310949047. If you do not specify a value for dbid, the local database
identifier is used as the default value.
ASH data that belongs to the time period specified by the snapshot range is also purged when
the DROP_SNAPSHOT_RANGE procedure is called.
Modifying Snapshot Settings
You can adjust the interval and retention of snapshot generation for a specified database ID.
However, note that this can affect the precision of the Oracle diagnostic tools.
The INTERVAL setting specifies how often (in minutes) snapshots are automatically
generated. The RETENTION setting specifies how long (in minutes) snapshots are stored in
the workload repository. To adjust the settings, use the MODIFY_SNAPSHOT_SETTINGS
procedure, as in the following example:
Exec DBMS_WORKLOAD_REPOSITORY.MODIFY_SNAPSHOT_SETTINGS( -retention
=> 43200, interval => 30, dbid => 3310949047);
In this example, the retention period is specified as 43,200 minutes (30 days), and the interval
between each snapshot is specified as 30 minutes. If NULL is specified, the existing value is
preserved. The optional database identifier is 3310949047. If you do not specify a value for
dbid, the local database identifier is used as the default value. You can check the current
settings for your database instance with the DBA_HIST_WR_CONTROL view.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
You can drop a range of snapshots using the DROP_SNAPSHOT_RANGE procedure. To view a
list of the snapshot IDs along with database IDs, check the DBA_HIST_SNAPSHOT view. For
example, you can drop the following range of snapshots:
Exec DBMS_WORKLOAD_REPOSITORY.DROP_SNAPSHOT_RANGE - (low_snap_id =>
22, high_snap_id => 32, dbid => 3310949047);
V$ACTIVE_SESSION_HISTORY
V$ metric views
DBA_HIST views:
DBA_HIST_ACTIVE_SESS_HISTORY
DBA_HIST_BASELINE DBA_HIST_DATABASE_INSTANCE
DBA_HIST_SNAPSHOT
DBA_HIST_SQL_PLAN
DBA_HIST_WR_CONTROL
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
PLAN_TABLE_OUTPUT
-----------------------------------------------------------------------------------SQL_ID 454rug2yva18w
-------------------select /* example */ * from hr.employees natural join hr.departments
Plan hash value: 4179021502
---------------------------------------------------------------------------------| Id | Operation
| Name
| Rows | Bytes | Cost (%CPU)| Time
|
---------------------------------------------------------------------------------|
0 | SELECT STATEMENT
|
|
|
|
6 (100)|
|
|
1 | HASH JOIN
|
|
11 |
968 |
6 (17)| 00:00:01 |
|
2 |
TABLE ACCESS FULL| DEPARTMENTS |
11 |
220 |
2
(0)| 00:00:01 |
|
3 |
TABLE ACCESS FULL| EMPLOYEES
|
107 | 7276 |
3
(0)| 00:00:01 |
----------------------------------------------------------------------------------
'ALL' )) tf
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
no rows selected
You can take a manual AWR snapshot rather than wait for the next snapshot (which
occurs every hour). Then check to see if it has been captured in DBA_HIST_SQLTEXT:
SQL> exec dbms_workload_repository.create_snapshot;
PL/SQL procedure successfully completed.
SQL> SELECT SQL_ID, SQL_TEXT FROM dba_hist_sqltext WHERE SQL_ID
=' 454rug2yva18w';
SQL_ID
SQL_TEXT
--------------
-------------------------------
454rug2yva18w
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
3. Using the SQL_ID, verify that this statement has been captured in the
DBA_HIST_SQLTEXT dictionary view. If the query does not return rows, it indicates that
the statement has not yet been loaded in the AWR.
SQL> SELECT SQL_ID, SQL_TEXT FROM dba_hist_sqltext WHERE SQL_ID
=' 454rug2yva18w';
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
+
CONTROL_MANAGEMENT_PACK_ACCESS=DIAGNOSTIC+TUNING
SQL monitoring
Every
second
V$SQL_MONITOR
V$SQL_PLAN_MONITOR
DBMS_SQLTUNE.REPORT_SQL_MONITOR
V$SQL
V$SQL_PLAN
V$ACTIVE_SESSION_HISTORY
V$SESSION_LONGOPS
V$SESSION
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
After the execution ends, monitoring information is not deleted immediately, but is kept in the
V$SQL_MONITOR view for at least one minute. The entry is eventually deleted so its space
can be reclaimed as new statements are monitored.
The V$SQL_MONITOR and V$SQL_PLAN_MONITOR views can be used in conjunction with the
following views to get additional information about the execution that is monitored:
V$SQL, V$SQL_PLAN, V$ACTIVE_SESSION_HISTORY, V$SESSION_LONGOPS, and
V$SESSION
Instead, you can use the SQL monitoring report to view SQL monitoring data.
The SQL monitoring report is also available in a GUI version through Enterprise Manager and
SQL Developer
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
times. These statistics are refreshed in near real time as the statement executes, generally
once every second.
In a different session
SQL Text
-------------------------select count(*) from sales
Global Information
Status
: EXECUTING
Instance ID
: 1
Session ID
: 125
SQL ID
: fazrk33ng71km
SQL Execution ID
: 16777216
Plan Hash Value
: 1047182207
Execution Started
: 02/19/2008 21:01:18
First Refresh Time : 02/19/2008 21:01:22
Last Refresh Time
: 02/19/2008 21:01:42
-----------------------------------------------------------| Elapsed |
Cpu
|
IO
| Other
| Buffer | Reads |
| Time(s) | Time(s) | Waits(s) | Waits(s) | Gets |
|
-----------------------------------------------------------|
22 |
3.36 |
0.01 |
19 |
259K | 199K |
------------------------------------------------------------
To uniquely identify two executions of the same SQL statement, a composite key called
an execution key is generated. This execution key consists of three attributes, each
corresponding to a column in V$SQL_MONITOR:
-
An internally generated identifier to ensure that this primary key is truly unique
(SQL_EXEC_ID)
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The report also shows you some important statistics calculated so far.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
==================================================================================
Starts |
Rows
| Activity |
Activity Detail
| Progress |
| (Actual) | (percent) |
(sample #)
|
|
1 |
|
|
|
|
1 |
|
|
|
|
1 |
42081K |
100.00 | Cpu (4)
| 74%
|
==================================================================================
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The last column, Progress, shows progress monitoring information for the operation from the
V$SESSION_LONGOPS view. In this report, it shows that, so far, the TABLE ACCESS FULL
operation is 74% complete. This column only appears in the report after a certain amount of
time, and only for the instrumented row sources.
Note: Not shown by this particular report, the Memory and Temp columns indicate the amount
of memory and temporary space consumed by corresponding operation of the execution plan.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
In this report, the Activity Detail (sample #) column shows that most of the database time,
100%, is consumed by operation Id 2 (TABLE ACCESS FULL of SALES). So far, this activity
consists of 4 samples, which are only attributed to CPU.
(pid= )
(pid=1)
(pid=2)
(pid=2)
(pid=4)
(pid=4)
(pid=1)
(pid=7)
(pid=7)
(pid=9)
(pos=1)
(pos=1)
(pos=2)
(pos=1)
(pos=2)
(pos=2)
(pos=1)
(pos=2)
(pos=1)
root/parent
parent/child
child/leaf
parent/child
child/leaf
child/leaf
parent/child
child/leaf
parent/child
child/leaf
Executed
first
Parent/Child
Root/Parent
Executed next
Level 1
From
top/down
Parent/Child
Level 2
From left/right
Child/Leaf
Parent/Child
Child/Leaf
Child/Leaf
Child/Leaf
Parent/Child
Level 3
Child/Leaf
Level 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
1. Take the ID with the lowest number and place it at the top.
2. Look for rows which have a PID (parent) equal to this value.
3. Place these in the tree below the Parent according to their POS values from the lowest
to the highest, ordered from left to right.
4. After all the IDs for a parent have been found, move down to the next ID and repeat the
process, finding new rows with the same PID.
The first thing to determine in an explain plan is which node is executed first. The method in
the slide explains this, but sometimes with complicated plans it is difficult to do this and also
difficult to follow the steps through to the end. Large plans are exactly the same as smaller
ones, but with more entries. The same basic rules apply. You can always collapse the plan to
hide a branch of the tree which does not consume much of the resources.
Standard explain plan interpretation:
1. Start at the top.
2. Move down the row sources until you get to one which produces data, but does not
consume any. This is the start row source.
3. Look at the siblings of this row source. These row sources are executed next.
4. After the children are executed, the parent is executed next.
5. Now that this parent and its children are completed, work back up the tree, and look at
the siblings of the parent row source and its parents. Execute as before.
6. Move back up the plan until all row sources are exhausted.
Standard tree interpretation:
1. Start at the top.
2. Move down the tree to the left until you reach the left node. This is executed first.
3. Look at the siblings of this row source. These row sources are executed next.
4. After the children are executed, the parent is executed next.
5. Now that this parent and its children are completed, work back up the tree, and look at
the siblings of the parent row source and its parents. Execute as before.
6. Move back up the tree until all row sources are exhausted.
If you remember the few basic rules of explain plans and with some experience, you can read
most plans easily.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
FILTER
NESTED
LOOPS
1
6
3
TABLE ACCESS FULL
EMP
TABLE ACCESS
BY ROWID
DEPT
5: The rows are passed back to the controlling nested loops join step (ID=2), which
uses them to execute the lookup of rows in the PK_DEPT index in ID=5.
4: The ROWIDs from the index are used to lookup the other information from the DEPT
table in ID=4.
6: After ID=2 has exhausted its row sources, a full table scan of SALGRADE in ID=6 (at
the same level in the tree as ID=2, therefore, its sibling) is executed.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note that children are executed before parents, so although structures for joins must be set up
before the child execution, the children are notated as executed first. Probably, the easiest
way is to consider it as the order in which execution completes, so for the NESTED LOOPS join
at ID=2, the two children {ID=3 and ID=4 (together with its child)} must have completed their
execution before ID=2 can be completed.
A-Rows corresponds to the number of rows produced by the corresponding row source.
Buffers corresponds to the number of consistent reads done by the row source.
Starts indicates how many times the corresponding operation was processed.
For each row from the EMP table, the system gets its ENAME, SAL, JOB, and DEPTNO.
Then the system accesses the DEPT table by its unique index (PK_DEPT) to get DNAME using
DEPTNO from the previous result set.
If you observe the statistics closely, the TABLE ACCESS FULL operation on the EMP table
(ID=3) is started once. However, operations from ID 5 and 4 are started 14 times; once for
each EMP rows. At this step (ID=2), the system gets all ENAME, SAL, JOB, and DNAME.
The system now must filter out employees who have salaries outside the range of salaries in
the salary grade table. To do that, for each row from ID=2, the system accesses the
SALGRADE table using a FULL TABLE SCAN operation to check if the employees salary is
outside the salary range. This operation only needs to be done 12 times in this case because
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
at run time the system does the check for each distinct salary, and there are 12 distinct
salaries in the EMP table.
0
1
2
3
2
5
1
7
select
,
,
from
where
SELECT STATEMENT
NESTED LOOPS
NESTED LOOPS
TABLE ACCESS BY INDEX ROWID
INDEX RANGE SCAN
TABLE ACCESS BY INDEX ROWID
INDEX RANGE SCAN
TABLE ACCESS BY INDEX ROWID
INDEX UNIQUE SCAN
1
LOCATIONS
LOC_CITY_IX
DEPARTMENTS
DEPT_LOCATION_IX
EMPLOYEES
EMP_EMP_ID_PK
2
3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
5. Now that this parent and its children are completed, walk back up the tree, and look at
the siblings of the parent row source and its parents. Execute as before. The sibling of
ID=2 at the same level in the plan is ID=7. This has a child ID=8, which is executed
first. The index unique scan produces ROWIDs, which are used to lookup in the
EMPLOYEES table in ID=7.
6. Move back up the plan until all row sources are exhausted. Finally this is brought
together with the NESTED LOOPS at ID=1, which passes the results back to ID=0.
7. The execution order is: 4 3 6 5 2 8 7 1 0
Here is the complete description of this plan:
The inner nested loops is executed first using LOCATIONS as the driving table, using an index
access on the CITY column. This is because you search for departments in Seattle only.
The result is joined with the DEPARTMENTS table, using the index on the LOCATION_ID join
column; the result of this first join operation is the driving row source for the second nested
loops join.
The second join probes the index on the EMPLOYEE_ID column of the EMPLOYEES table. The
system can do that because it knows (from the first join) the employee ID of all managers of
departments in Seattle. Note that this is a unique scan because it is based on the primary key.
Finally, the EMPLOYEES table is accessed to retrieve the last name.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
4. After the children operation, the parent operation is next. The NESTED LOOPS join at
ID=2 is executed next bringing together the underlying data.
0
1
2
3
4
5
6
1
2
2
4
4
SELECT STATEMENT
SORT AGGREGATE
HASH JOIN
TABLE ACCESS FULL T3
HASH JOIN
TABLE ACCESS FULL T1
TABLE ACCESS FULL T2
1
2
3
4
5
The system first hashes the T3 table (Operation ID=3) into memory.
The system outputs the maximum value from the previous result set.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: A special hint was used to make sure T3 would be first in the plan.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
You can also use Enterprise Manager to understand execution plans, especially because it
displays the Order column.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The plan is such that the driving table has the best filter.
The join order in each step means that the fewest number of rows are returned to the
next step (that is, the join order should reflect going to the best not-yet-used filters).
The join method is appropriate for the number of rows being returned. For example,
nested loop joins through indexes may not be optimal when many rows are returned.
Views are used efficiently. Look at the SELECT list to see whether access to the view is
necessary.
There are any unintentional Cartesian products (even with small tables).
Each table is being accessed efficiently: Consider the predicates in the SQL statement
and the number of rows in the table. Look for suspicious activity, such as a full table
scans on tables with large number of rows, which have predicates in the WHERE clause.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
If any of these conditions are not optimal, consider restructuring the SQL statement or the
indexes available on the tables.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Also, a full table scan might be more efficient on a small table, or to leverage a better
join method (for example, hash join) for the number of rows returned.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
A user needs to be granted some specialized privileges to
generate AUTOTRACE statistics.
a. True
b. False
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Answer: a
Quiz
An EXPLAIN PLAN command executes the statement and
inserts the plan used by the optimizer into a table.
a. True
b. False
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Which of the following is not true about a PLAN_TABLE?
a. The PLAN_TABLE is automatically created to hold the
EXPLAIN PLAN output.
b. You cannot create your own PLAN_TABLE.
c. The actual SQL command is not executed.
d. The plan in the PLAN_TABLE may not be the actual
execution plan.
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
After monitoring is initiated, an entry is added to the
_______view. This entry tracks key performance metrics
collected for the execution.
a. V$SQL_MONITOR
b. V$PLAN_MONITOR
c. ALL_SQL_MONITOR
d. ALL_SQL_PLAN_MONITOR
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
Gather execution plans
Display execution plans
Interpret execution plans
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 4: Overview
This practice covers the following topics:
Using different techniques to extract execution plans
Using SQL monitoring
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 4: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 5
Application Tracing
Chapter 5 - Page 1
Application Tracing
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Application Tracing
Application Tracing
Chapter 5 - Page 2
Application Tracing
Objectives
After completing this lesson, you should be able to do the
following:
Configure the SQL Trace facility to collect session
statistics
Use the trcsess utility to consolidate SQL trace files
Format trace files using the tkprof utility
Interpret the output of the tkprof command
Application Tracing
Chapter 5 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Client
Client OE
Client OE
Clients
Client
Client JF/Session 6
Client C4
CRM
ERP
CRM
CRM
ERP
CRM
Dedicated
server
Dedicated
server
Dedicated
server
Shared
server
Shared
server
Shared
server
Trace
file
Trace
file
Trace
file
Trace
file
Trace
file
Trace
file
Application Tracing
Chapter 5 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Service
Module
Action
Session
Client
Client identifier: Specifies an end user based on the logon ID, such as HR
The primary interface for end-to-end application tracing is Enterprise Manager. Other tools
listed in the slide are discussed later in this lesson.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Application Tracing
Chapter 5 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Previous Location
ADR Location
Foreground process
traces
USER_DUMP_DEST
$ADR_HOME/trace
Background process
traces
BACKGROUND_DUMP_DEST
$ADR_HOME/trace
BACKGROUND_DUMP_DEST
$ADR_HOME/alert
$ADR_HOME/trace
Core dumps
CORE_DUMP_DEST
$ADR_HOME/cdump
Incident dumps
USER_DUMP_DEST
BACKGROUND_DUMP_DEST
$ADR_HOME/incident/incdir_n
V$DIAG_INFO
$ADR_HOME/trace <= Oracle Database 11g trace critical error trace
Application Tracing
Chapter 5 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
What Is a Service?
What Is a Service?
The concept of a service was first introduced in Oracle8i as a means for the listener to
perform connection load balancing between nodes and instances of a cluster. However, the
concept, definition, and implementation of services have been dramatically expanded. A
service organizes work execution within the database to make it more manageable,
measurable, tunable, and recoverable. A service is a grouping of related tasks within the
database with common functionality, quality expectations, and priority relative to other
services. A service provides a single-system image for managing competing applications that
run within a single instance and across multiple instances and databases.
Services can be configured, administered, enabled, disabled, and measured as a single entity
using standard interfaces, Enterprise Manager, and SRVCTL,.
Services provide availability. Following outages, a service is recovered quickly and
automatically at surviving instances.
Services provide an additional dimension to performance tuning. With services, workloads are
visible and measurable. Tuning by service and SQL replaces tuning by session and SQL in
the majority of systems where sessions are anonymous and shared.
From a tracing point of view, a service provides a handle that permits capturing trace
information by service name regardless of the session.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Application Tracing
Chapter 5 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
What Is a Service?
ERP=(DESCRIPTION=
(ADDRESS=(PROTOCOL=TCP)(HOST=mynode)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=ERP)))
url="jdbc:oracle:oci:@ERP"
url="jdbc:oracle:thin:@(DESCRIPTION=
(ADDRESS=(PROTOCOL=TCP)(HOST=mynode)(PORT=1521))
(CONNECT_DATA=(SERVICE_NAME=ERP)))"
Application Tracing
Chapter 5 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Tracing Services
CLIENT_IDENTIFIER
SESSION_ID
SERVICE_NAMES
MODULE
ACTION
Combination of SERVICE_NAME, MODULE, ACTION
Tracing Services
An application can qualify a service by MODULE and ACTION names to identify the important
transactions within the service. This enables you to locate the poorly performing transactions
for categorized workloads. This is important when you monitor performance in systems using
connection pools or transaction processing monitors. For these systems, the sessions are
shared, which makes accountability difficult. SERVICE_NAME, MODULE, ACTION,
CLIENT_IDENTIFIER, and SESSION_ID are actual columns in V$SESSION.
SERVICE_NAME is set automatically at login time based on the connect descriptor, and
SESSION_ID is automatically set by the database when a session is created. MODULE and
ACTION names are set by the application by using the DBMS_APPLICATION_INFO PL/SQL
package or special Oracle Call Interface (OCI) calls. MODULE should be set to a name that is
recognizable by the user for the program that currently executes. Likewise, ACTION should be
set to a specific action or task that a user performs within a module (for example, entering a
new customer). CLIENT_IDENTIFIER can be set using the
DBMS_SESSION.SET_IDENTIFIER procedure.
The traditional method of tracing each session produces trace files with SQL commands that
may contain the trace information for multiple end users or applications. Unless all database
sessions are being traced, some information from the end user sessions may be missed. This
results in a hit-or-miss approach to diagnose problematic SQL.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Application Tracing
Chapter 5 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Tracing Services
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
With the criteria that you provide (SERVICE_NAME, MODULE, or ACTION), specific trace
information is captured in a set of trace files and combined into a single output trace file. This
enables you to produce trace files that contain SQL that is relevant to a specific workload. It is
also possible to do the same for CLIENT_IDs and SESSION_IDs.
Application Tracing
Chapter 5 - Page 10
Application Tracing
Chapter 5 - Page 11
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
exec DBMS_MONITOR.SERV_MOD_ACT_TRACE_ENABLE('AP');
exec DBMS_MONITOR.SERV_MOD_ACT_TRACE_ENABLE('AP', 'PAYMENTS', 'QUERY_DELINQUENT');
exec DBMS_MONITOR.CLIENT_ID_TRACE_ENABLE
(client_id=>'C4', waits => TRUE, binds => FALSE);
Application Tracing
Chapter 5 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Application Tracing
Chapter 5 - Page 13
EXEC dbms_monitor.DATABASE_TRACE_ENABLE(TRUE,TRUE);
EXEC dbms_monitor.DATABASE_TRACE_DISABLE();
EXEC dbms_monitor.SESSION_TRACE_ENABLE(session_id=>
27, serial_num=>60, waits=>TRUE, binds=>FALSE);
EXEC dbms_monitor.SESSION_TRACE_DISABLE(session_id
=>27, serial_num=>60);
Use the DATABASE_TRACE_DISABLE procedure to disable SQL tracing for the whole
database or a specific instance.
Similarly, you can use the SESSION_TRACE_ENABLE procedure to enable tracing for a given
database session identifier on the local instance. The SID and SERIAL# information can be
found from V$SESSION.
Application Tracing
Chapter 5 - Page 14
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: SQL Trace involves some overhead, so you usually do not want to enable SQL Trace at
the instance level.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Use the SESSION_TRACE_DISABLE procedure to disable the trace for a given database
session identifier and serial number.
Application Tracing
Chapter 5 - Page 15
Enabling trace:
Disabling trace:
EXEC DBMS_SESSION.SESSION_TRACE_DISABLE();
Application Tracing
Chapter 5 - Page 16
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Client
Client
Client
CRM
ERP
CRM
Dedicated
server
Dedicated
server
Dedicated
server
Shared
server
Shared
server
Shared
server
Trace
file
Trace
file
Trace
file
Trace
file
Trace
file
Trace
file
CRM
CRM
TRCSESS
trcsess
Trace file
for CRM service
ERP
tkprof
Trace file
for one client
Report
file
Application Tracing
Chapter 5 - Page 17
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
[output=output_file_name]
[session=session_id]
[clientid=client_identifier]
[service=service_name]
[action=action_name]
[module=module_name]
[<trace file names>]
Trace
file
Trace
file
Trace
file
TRCSESS
Consolidated
trace file
output specifies the file where the output is generated. If this option is not specified,
standard output is used for the output.
session consolidates the trace information for the session specified. The session
identifier is a combination of session index and session serial number, such as 21.2371.
You can locate these values in the V$SESSION view.
clientid consolidates the trace information for the given client identifier.
service consolidates the trace information for the given service name.
action consolidates the trace information for the given action name.
module consolidates the trace information for the given module name.
<trace file names> is a list of all the trace file names, separated by spaces, in
which trcsess should look for trace information. The wildcard character * can be
used to specify the trace file names. If trace files are not specified, all the files in the
current directory are taken as input to trcsess. You can find trace files in ADR.
Application Tracing
Chapter 5 - Page 18
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: One of the session, clientid, service, action, or module options must be
specified. If there is more than one option specified, the trace files, which satisfy all the criteria
specified are consolidated into the output file.
Application Tracing
Chapter 5 - Page 19
First session
Third session
Application Tracing
Chapter 5 - Page 20
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Wait event data for each SQL statement, and a summary for each trace file
If the cursor for the SQL statement is closed, SQL Trace also provides row source information
that includes:
Row operations showing the actual execution plan of each SQL statement
Application Tracing
Chapter 5 - Page 21
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Using the SQL Trace facility can have a severe performance impact and may result in
increased system overhead, excessive CPU usage, and inadequate disk space.
Application Tracing
Chapter 5 - Page 22
====================
PARSING IN CURSOR #2 len=23 dep=0 uid=85 oct=3 lid=85 tim=1280410994003145 hv=40
69246757 ad='4cd57ac0' sqlid='f34thrbt8rjt5'
select * from employees
END OF STMT
PARSE #2:c=3000,e=2264,p=0,cr=0,cu=0,mis=1,r=0,dep=0,og=1,plh=1445457117,
tim=1280410994003139
EXEC #2:c=0,e=36,p=0,cr=0,cu=0,mis=0,r=0,dep=0,og=1,plh=1445457117,
tim=1280410994003312
FETCH #2:c=0,e=215,p=0,cr=3,cu=0,mis=0,r=1,dep=0,og=1,plh=1445457117,
tim=1280410994003628
FETCH #2:c=0,e=89,p=0,cr=5,cu=0,mis=0,r=15,dep=0,og=1,plh=1445457117,
tim=1280410994004232
FETCH #2:c=0,e=60,p=0,cr=1,cu=0,mis=0,r=1,dep=0,og=1,plh=1445457117,
tim=1280410994107857
STAT #2 id=1 cnt=107 pid=0 pos=1 obj=73933 op='TABLE ACCESS FULL EMPLOYEES (cr=15
pr=0 pw=0 time=0 us cost=3 size=7383 card=107)'
XCTEND rlbk=0, rd_only=1, tim=1280410994108875
=====================
Application Tracing
Chapter 5 - Page 23
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Trace
file
Trace
file
Trace
file
Trace
file
Trace
Trace
file
Trace
file
Trace
file
Trace
file
file
trcsess
Consolidated
trace file
tkprof
Concatenated
trace file
Report
file
Run tkprof on each individual trace file, producing a number of formatted output files,
one for each session.
Concatenate the trace files, and then run tkprof on the result to produce a formatted
output file for the entire instance.
Run the trcsess command-line utility to consolidate tracing information from several
trace files, then run tkprof on the result.
tkprof does not report COMMITs and ROLLBACKs that are recorded in the trace file.
Application Tracing
Chapter 5 - Page 24
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Set the TIMED_STATISTICS parameter to TRUE when tracing sessions because no
time-based comparisons can be made without this. TRUE is the default value with Oracle
Database 11g.
Application Tracing
Chapter 5 - Page 25
outputfile: Specifies the file to which tkprof writes its formatted output
waits: Specifies whether to record the summary for any wait events found in the trace
file. Values are YES or NO. The default is YES.
sorts: Sorts traced SQL statements in the descending order of specified sort option
before listing them into the output file. If more than one option is specified, the output is
sorted in the descending order by the sum of the values specified in the sort options. If
you omit this parameter, tkprof lists statements into the output file in the order of first
use.
print: Lists only the first integer sorted SQL statements from the output file. If you omit
this parameter, tkprof lists all traced SQL statements. This parameter does not affect
the optional SQL script. The SQL script always generates insert data for all traced SQL
statements.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Application Tracing
Chapter 5 - Page 26
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
aggregate: If set to NO, tkprof does not aggregate multiple users of the same SQL
text.
insert: Creates a SQL script to store the trace file statistics in the database. tkprof
creates this script with the name you specify for sqlscriptfile. This script creates a
table and inserts a row of statistics for each traced SQL statement into the table.
sys: Enables and disables the listing of SQL statements issued by the SYS user, or
recursive SQL statements, into the output file. The default value of YES causes tkprof
to list these statements. The value of NO causes tkprof to omit them. This parameter
does not affect the optional SQL script. The SQL script always inserts statistics for all
traced SQL statements, including recursive SQL statements.
table: Specifies the schema and name of the table into which tkprof temporarily
places execution plans before writing them to the output file. If the specified table
already exists, tkprof deletes all rows in the table, uses it for the EXPLAIN PLAN
statement (which writes more rows into the table), and then deletes those rows. If this
table does not exist, tkprof creates it, uses it, and then drops it. The specified user
must be able to issue INSERT, SELECT, and DELETE statements against the table. If the
table does not already exist, the user must also be able to issue the CREATE TABLE
and DROP TABLE statements. This option allows multiple individuals to run tkprof
concurrently with the same user in the EXPLAIN value. These individuals can specify
different TABLE values and avoid destructively interfering with each others processing
on the temporary plan table. If you use the EXPLAIN parameter without the TABLE
parameter, tkprof uses the PROF$PLAN_TABLE table in the schema of the user
specified by the EXPLAIN parameter. If you use the TABLE parameter without the
EXPLAIN parameter, tkprof ignores the TABLE parameter. If no plan table exists,
tkprof creates the PROF$PLAN_TABLE table and then drops it at the end.
explain: Determines the execution plan for each SQL statement in the trace file and
writes these execution plans to the output file. tkprof determines execution plans by
issuing the EXPLAIN PLAN statement after connecting to the system with the user and
password specified in this parameter. The specified user must have CREATE SESSION
system privileges. tkprof takes longer to process a large trace file if the EXPLAIN
option is used.
record: Creates a SQL script with the specified file name statementfile with all the
nonrecursive SQL statements in the trace file. This can be used to replay the user
events from the trace file.
width: An integer that controls the output line width of some tkprof output, such as
the explain plan. This parameter is useful for post-processing of tkprof output.
The input and output files are the only required arguments.
Application Tracing
Chapter 5 - Page 27
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Description
prscnt
prscpu
prsela
prsdsk
prsqry
prscu
prsmis
execnt
execpu
exeela
exedsk
exeqry
execu
Application Tracing
Chapter 5 - Page 28
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Description
exerow
exemis
fchcnt
fchcpu
fchela
fchdsk
fchqry
fchcu
fchrow
userid
Application Tracing
Chapter 5 - Page 29
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
EXECUTE
FETCH
This step translates the SQL statement into an execution plan and includes
checks for proper security authorization and checks for the existence of
tables, columns, and other referenced objects.
EXECUTE
This step is the actual execution of the statement by the Oracle server.
For the INSERT, UPDATE, and DELETE statements, this step modifies the
data (including sorts when needed). For the SELECT statements, this step
identifies the selected rows.
FETCH
This step retrieves rows returned by a query and sorts them when needed.
Fetches are performed only for the SELECT statements.
Note: The PARSE value includes both hard and soft parses. A hard parse refers to the
development of the execution plan (including optimization); it is subsequently stored in the
library cache. A soft parse means that a SQL statement is sent for parsing to the database,
but the database finds it in the library cache and only needs to verify things, such as access
rights. Hard parses can be expensive, particularly due to the optimization. A soft parse is
mostly expensive in terms of library cache activity 25
Application Tracing
Chapter 5 - Page 30
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
CPU
Elapsed
Disk
Query
Current
Rows
cpu
elapsed
disk
query
current rows
-------- ---------- ---------- ---------- ---------- ---
Parse
1
Execute
1
Fetch
2
------- ------
0.03
0.06
0
0
0
0.06
0.30
1
3
0
0.00
0.46
0
0
0
-------- ---------- ---------- ---------- ----------
total
0.09
0.83
0
0
1
--1
Next to the CALL column, tkprof displays the following statistics for each statement:
Count: Number of times a statement was parsed, executed, or fetched (Check this
column for values greater than 1 before interpreting the statistics in the other columns.
Unless the AGGREGATE = NO option is used, tkprof aggregates identical statement
executions into one summary table.)
CPU: Total CPU time in seconds for all parse, execute, or fetch calls
Elapsed: Total elapsed time in seconds for all parse, execute, or fetch calls
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Application Tracing
Chapter 5 - Page 31
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Disk: Total number of data blocks physically read from the data files on disk for all
parse, execute, or fetch calls
Query: Total number of buffers retrieved in consistent mode for all parse, execute, or
fetch calls (Buffers are usually retrieved in consistent mode for queries.)
Current: Total number of buffers retrieved in current mode (Buffers typically are
retrieved in current mode for data manipulation language statements. However, segment
header blocks are always retrieved in current mode.)
Rows: Total number of rows processed by the SQL statement (This total does not
include rows processed by subqueries of the SQL statement. For SELECT statements,
the number of rows returned appears for the fetch step. For the UPDATE, DELETE, and
INSERT statements, the number of rows processed appears for the execute step.)
Note
Application Tracing
Chapter 5 - Page 32
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
...
Application Tracing
Chapter 5 - Page 33
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
These provide the number of rows processed for each operation executed on the rows and
additional row source information, such as physical reads and writes; cr = consistent reads,
w = physical writes, r = physical reads, time = time (in microseconds).
Parsing User ID
This is the ID of the last user to parse the statement.
Row Source Operation
The row source operation shows the data sources for execution of the SQL statement. This is
included only if the cursor has been closed during tracing. If the row source operation does
not appear in the trace file, you may then want to view the output of the EXPLAIN PLAN.
Execution Plan
If you specify the EXPLAIN parameter on the tkprof command line, tkprof uses the
EXPLAIN PLAN command to generate the execution plan of each SQL statement traced.
tkprof also displays the number of rows processed by each step of the execution plan.
Note: Be aware that the execution plan is generated at the time that the tkprof command is
run and not at the time the trace file was produced. This could make a difference if, for
example, an index has been created or dropped since tracing the statements.
Optimizer Mode or Hint
This indicates the optimizer hint that is used during the execution of the statement. If there is
no hint, it shows the optimizer mode that is used.
Application Tracing
Chapter 5 - Page 34
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
cpu
elapsed
disk
query
current
------- --------- -------- -------- --------0.00
0.00
0
0
0
0.00
0.00
0
0
0
0.02
0.10
72
1459
0
------- --------- -------- -------- --------0.02
0.10
72
1459
0
rows
--------0
0
1
--------1
...
Application Tracing
Chapter 5 - Page 35
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
cpu
elapsed
disk
query
current
-------- ---------- --------- --------- ---------0.00
0.00
0
0
0
0.00
0.00
0
0
0
0.00
0.00
1
77
0
-------- ---------- --------- --------- ---------0.00
0.00
1
77
0
rows
---------0
0
1
---------1
Application Tracing
Chapter 5 - Page 36
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Which command would you use to create a trace file of your
SQL*Plus session in a dedicated server environment?
a. alter session set
tracefile_identifier='mytraceid';
b. EXEC
DBMS_SESSION.SESSION_TRACE_ENABLE(waits =>
TRUE, binds => FALSE);
c. trcsess output=mytrace.trc clientid='HR
session'
$ORACLE_BASE/diag/rdbms/orcl/orcl/trace/*.t
rc
d. tkprof *mytrace*.trc mytrace.txt SYS=NO
Answer: b
Application Tracing
Chapter 5 - Page 37
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The _____ utility formats the trace file into a readable format.
a. trcsess
b. tkprof
c.
d.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
SQL Developer
SQL*Plus Autotrace
Answer: b, c
Application Tracing
Chapter 5 - Page 38
Quiz
In an environment with an applications server that uses a
connection pool, you will use ________ to identify which trace
files need to be combined to get an overall trace of the
application.
a. trcsess
b. tkprof
c.
d.
SQL Developer
DBMS_APPLICATION_INFO
Answer: d
Application Tracing
Chapter 5 - Page 39
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
Configure the SQL Trace facility to collect session
statistics
Use the trcsess utility to consolidate SQL trace files
Format trace files using the tkprof utility
Interpret the output of the tkprof command
Application Tracing
Chapter 5 - Page 40
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 5: Overview
This practice covers the following topics:
Creating a service
Tracing your application using services
Interpreting trace information using trcsess and tkprof
Application Tracing
Chapter 5 - Page 41
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 5: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Application Tracing
Chapter 5 - Page 42
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 6
Optimizer Operators
Chapter 6 - Page 1
Optimizer Operators
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Optimizer Operators
Chapter 6 - Page 2
Optimizer Operators
Objectives
After completing this lesson, you should be able to:
Describe the SQL operators for tables and indexes
List the possible access paths
Objectives
This lesson helps you understand the execution plans that use operators related to table and
index access methods.
Optimizer Operators
Chapter 6 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Unary operations
Access Path
Binary operations
Joins
N-ary operations
Ams row source is a set of rows returned by a step in the
execution plan .
Unary operations: Operations that act on only one input, such as an access path
N-ary operations: Operations that act on several inputs, such as a relational operator
Access paths are ways in which data is retrieved from the database. In general, index access
paths should be used for statements that retrieve a small subset of table rows, while full scans
are more efficient when accessing a large portion of the table. Online transaction processing
(OLTP) applications, which consist of short-running SQL statements with high selectivity, are
often characterized by the use of index access paths. Decision support systems (DSS), on the
other hand, tend to use partitioned tables and perform full scans of the relevant partitions.
Optimizer Operators
Chapter 6 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Access Paths
1. Full Table Scan
Tables
2. Rowid Scan
3. Sample Table Scan
4. Index Scan (Unique)
5. Index Scan (Range)
6. Index Scan (Full)
7. Index Scan (Fast Full)
Indexes
Optimizer Operators
Chapter 6 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
No suitable index
Low selectivity filters (or no filters)
Small table
High degree of parallelism
Full table scan hint: FULL (<table name>)
Lack of index: If the query is unable to use any existing indexes, it uses a full table scan
(unless a ROWID filter or a cluster access path is available). For example, if there is a
function used on the indexed column in the query, the optimizer cannot use the index
and instead uses a full table scan. If you need to use the index for case-independent
searches, either do not permit mixed-case data in the search columns or create a
function-based index, such as UPPER(last_name) on the search column.
Large amount of data (low selectivity): If the optimizer thinks that the query accesses
enough blocks in the table, it may use a full table scan even though indexes might be
available.
High degree of parallelism: A high degree of parallelism for a table skews the
optimizer towards full table scans over range scans. Examine the DEGREE column in
ALL_TABLES for the table to determine the degree of parallelism.
Optimizer Operators
Chapter 6 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Full table scan hints: Use the FULL(table alias) hint to instruct the optimizer to
use a full table scan.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 8
ROWID Scan
-----------------------------------------------------------------| Id | Operation
| Name | Rows | Bytes | Cost |
-----------------------------------------------------------------|
0 | SELECT STATEMENT
|
|
1 |
37 |
1|
|
1 | TABLE ACCESS BY USER ROWID| EMP |
1 |
37 |
1|
------------------------------------------------------------------
Row migration
ROWID Scan
The rowid of a row specifies the data file and data block containing the row and the location of
the row in that block. Locating a row by specifying its rowid is the fastest way to retrieve a
single row because the exact location of the row in the database is specified.
To access a table by rowid, the system first obtains the rowids of the selected rows, either
from the statements WHERE clause or through an index scan of one or more of the tables
indexes. The system then locates each selected row in the table based on its rowid.
Mostly, the optimizer uses rowids after retrieving them from an index (See the Index Scans
slides.). The table access might be required for columns in the statement that are not present
in the index. A table access by rowid does not need to follow every index scan. If the index
contains all the columns needed for the statement, table access by rowid might not occur.
Rowids are the systems internal representation of where data is stored. Accessing data
based on position is not recommended because rows can move around due to row migration
and chaining, and also after export and import.
Note: Due to row migration, a rowid can sometimes point to an address different from the
actual row location, resulting in more than one block being accessed to locate a row. For
example, an update to a row may cause the row to be placed in another block with a pointer in
the original block. The rowid, however, still has only the address of the original block.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Optimizer Operators
Chapter 6 - Page 9
Block 6959Row 2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
ROWID Scan
SAMPLE option: To perform a sample table scan when sampling by rows, the system
reads a specified percentage of rows in the table and examines each of these rows to
determine whether it satisfies the statements WHERE clause.
SAMPLE BLOCK option: To perform a sample table scan when sampling by blocks, the
system reads a specified percentage of the tables blocks and examines each row in the
sampled blocks to determine whether it satisfies the statements WHERE clause.
The sample percent is a number specifying the percentage of the total row or block count to
be included in the sample. The sample value must be in the [0.000001 , 99.999999] range.
This percentage indicates the probability of each row, or each cluster of rows in the case of
block sampling, being selected as part of the sample. It does not mean that the database
retrieves exactly sample_percent of the rows of table.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Optimizer Operators
Chapter 6 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
SEED seed_value: Specify this clause to instruct the database to attempt to return the
same sample from one execution to the next. seed_value must be an integer between
0 and 4294967295. If you omit this clause, the resulting sample changes from one
execution to the next.
In row sampling, more blocks need to be accessed given a particular sample size, but the
results are usually more accurate. Block samples are less costly, but may be inaccurate; more
so with smaller samples.
Note: Block sampling is possible only during full table scans or index fast full scans. If a more
efficient execution path exists, Oracle Database does not perform block sampling. If you want
to guarantee block sampling for a particular table or index, use the FULL or INDEX_FFS hint.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 11
Indexes: Overview
Indexes
Storage techniques:
B*-tree indexes: The default and the most common
Normal
Function based: Precomputed value of a function or expression
Index-organized table (IOT)
Bitmap indexes
Cluster indexes: Defined specifically for cluster
Index attributes:
Key compression
Reverse key
Ascending, descending
Indexes: Overview
An index is an optional database object that is logically and physically independent of the
table data. Being independent structures, they require storage space. Just as the index of a
book helps you locate information fast, an Oracle Database index provides a faster access
path to table data. The Oracle Database may use an index to access data that is required by a
SQL statement, or it may use indexes to enforce integrity constraints. The system
automatically maintains indexes when the related data changes. You can create and drop
indexes at any time. If you drop an index, all applications continue to work. However, access
to previously indexed data might be slower. Indexes can be unique or
nonunique.
A composite index, also called a concatenated index, is an index that you create on multiple
columns (up to 32) in a table. Columns in a composite index can appear in any order and
need not be adjacent in the table.
For standard indexes, the database uses B*-tree indexes that are balanced to equalize
access times. B*-tree indexes can be normal, reverse key, descending, or function based.
B*-tree indexes: They are by far the most common indexes. Similar in construct to a
binary tree, B*-tree indexes provide fast access, by key, to an individual row or range of
rows, normally requiring few reads to find the correct row. However, the B in B*-tree
does not stand for binary, but rather for balanced.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Optimizer Operators
Chapter 6 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Indexes: Overview
Descending indexes: Descending indexes allow for data to be sorted from big to
small (descending) instead of from small to big (ascending) in the index structure.
Reverse key indexes: These are B*-tree indexes whereby the bytes in the key are
reversed. Reverse key indexes can be used to obtain a more even distribution of index
entries throughout an index that is populated with increasing values. For example, if you
use a sequence to generate a primary key, the sequence generates values such as
987500, 987501, 987502, and so on. With a reverse key index, the database logically
indexes 005789, 105789, 205789, and so on, instead of 987500, 987501, and 987502.
Because these reverse keys are now likely to be placed in different locations, this can
reduce contention for particular blocks that may otherwise be targets for contention.
However, only equality predicates can benefit from these indexes.
Index key compression: The basic concept behind a compressed key index is that
every entry is broken into twoa prefix and a suffix component. The prefix is built on the
leading columns of the concatenated index and has many repeating values. The suffix is
built on the trailing columns in the index key and is the unique component of the index
entry within the prefix. This is not compression in the same manner that ZIP files are
compressed; rather, this is an optional compression that removes redundancies from
concatenated (multicolumn) indexes.
Function-based indexes: These are B*-tree or bitmap indexes that store the computed
result of a function on a rows column or columns, and not the column data itself. You
can consider them as indexes on a virtual (derived or hidden) column. In other words, it
is a column that is not physically stored in the table. You can gather statistics on this
virtual column.
Index-organized tables: These are tables stored in a B*-tree structure. While rows of
data in a heap organized table are stored in an unorganized fashion (data goes
wherever there is available space), data in an IOT is stored and sorted by a primary key.
IOTs behave like regular tables as far as your application is concerned.
Bitmap join indexes: A bitmap join index is a bitmap index for the join of two or more
tables. A bitmap join index can be used to avoid actual joins of tables, or to greatly
reduce the volume of data that must be joined, by performing restrictions in advance.
Queries using bitmap join indexes can be sped up using bit-wise operations.
Application domain indexes: These are indexes you build with packages and store,
either in the database or even outside the database. You tell the optimizer how selective
your index is and how costly it is to execute, and the optimizer decides whether or not to
use your index based on that information.
Optimizer Operators
Chapter 6 - Page 13
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Branch
Index entry header
Key column length
Leaf
Optimizer Operators
Chapter 6 - Page 14
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Index Scans
Types of index scans:
Unique
Min/Max
Range (Descending)
Skip
Full and fast full
Index join
B : block
Table EMP
Index Scans
An index scan can be one of the following types:
A row is retrieved by traversing the index, using the indexed column values specified by the
statements WHERE clause. An index scan retrieves data from an index based on the value of
one or more columns in the index. To perform an index scan, the system searches the index
for the indexed column values accessed by the statement. If the statement accesses only
columns of the index, the system reads the indexed column values directly from the index,
rather than from the table.
The index contains not only the indexed value, but also the rowids of rows in the table that
have the value. Therefore, if the statement accesses other columns in addition to the indexed
columns, the system can find the rows in the table by using either a table access by rowid or a
cluster scan.
Note: The graphic shows a case where four rows are retrieved from the table using their
rowids obtained by the index scan.
Optimizer Operators
Chapter 6 - Page 15
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Index Scans
Optimizer Operators
Chapter 6 - Page 16
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 17
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
In the example in the slide, using index I_DEPTNO, the system accesses rows for which
EMP.DEPTNO=10. It gets their ROWIDs, fetches other columns from the EMP table, and finally,
applies the EMP.SAL >1000 filter from these fetched rows to output the final result.
Optimizer Operators
Chapter 6 - Page 18
Optimizer Operators
Chapter 6 - Page 19
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 20
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 21
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
All the columns in the table referenced in the query are included in the index.
A full scan can be used to eliminate a sort operation because the data is ordered by the index
key.
Note: An index full scan reads index using single-block input/output (I/O) (unlike a fast full
index scan).
Optimizer Operators
Chapter 6 - Page 22
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
db_file_multiblock_read_count = 4
multiblock read
SH
discard
SH=segment header
R=root block
B=branch block
L=leaf block
multiblock read
discard
...
discard
Optimizer Operators
Chapter 6 - Page 23
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
B1
Min F16 F20 F26 F30
B2
F10
F11
F12
F13
F14
F15
F16
F17
F18
F19
F20
F21
F22
F23
F24
F25
F26
F27
F28
F29
F30
F31
F32
F33
F34
F35
M10
M11
M12
M13
M14
M15
M16
M17
M18
M19
M20
M21
M22
M23
M24
M25
M26
M27
M28
M29
M30
M31
M32
M33
M34
M35
L1
L2
L3
L4
L5
L6
L7
L8
L9
L10
Optimizer Operators
Chapter 6 - Page 24
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The same process continues with the right part of this index. Note that out of a total of 10 leaf
blocks, only five are scanned.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
So the third and fourth leaf blocks [L3L4] are scanned and some values are retrieved. By
looking at the fourth entry in the first branch block [B1], the system determines that it is no
longer possible to find an F2x entry. Thus, it is not necessary to scan that subtree [L5].
Optimizer Operators
Chapter 6 - Page 25
where deptno = 10
where deptno = 20
where deptno = 30
Optimizer Operators
Chapter 6 - Page 26
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 27
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 28
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Null?
SSN
FNAME
LNAME
Y
Y
N
PERSON
Column
Null?
SSN
FNAME
LNAME
N
Y
N
PERSON
Optimizer Operators
Chapter 6 - Page 29
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Index-Organized Tables
Indexed
access on table
Accessing
index-organized table
ROWID
Non-key columns
Key column
Row header
Index-Organized Tables
An index-organized table (IOT) is a table physically stored in a concatenated index structure.
The key values (for the table and the B*-tree index) are stored in the same segment. An IOT
contains:
The B*-tree structure, which is based on the primary key of the table, is organized in the same
way as an index. The leaf blocks in this structure contain the rows instead of the ROWIDs. This
means that the rows in the IOT are always maintained in the order of the primary key.
You can create additional indexes on IOTs. The primary key can be a composite key.
Because large rows of an IOT can destroy the dense and efficient storage of the B*-tree
structure, you can store part of the row in another segment, which is called an overflow area.
Index-organized tables provide fast key-based access to table data for queries involving exact
match and range searches. Changes to the table data result only in updating the index
structure. Also, storage requirements are reduced because key columns are not duplicated in
the table and index. The remaining non-key columns are stored in the index structure. IOTs
are particularly useful when you use applications that must retrieve data based on a primary
key and have only a few, relatively short non-key columns.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Optimizer Operators
Chapter 6 - Page 30
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Index-Organized Tables
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: The descriptions mentioned here are correct if no overflow segments exist. Overflow
segments should be used with long rows.
Optimizer Operators
Chapter 6 - Page 31
Optimizer Operators
Chapter 6 - Page 32
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Bitmap Indexes
Table
File 3
Block 10
Index
Block 11
Block 12
<Blue,
<Green,
<Red,
<Yellow,
Key
10.0.3,
10.0.3,
10.0.3,
10.0.3,
Start
ROWID
12.8.3,
12.8.3,
12.8.3,
12.8.3,
100010000
000101000
010000000
001000000
End
ROWID
010000000
000000000
001100000
100000000
010010100>
100100000>
000001001>
001000010>
Bitmap
Bitmap Indexes
In a B*-tree, there is a one-to-one relationship between an index entry and a row; an index
entry points to a row. A bitmap index is organized as a B*-tree index but, with bitmap indexes,
a single index entry uses a bitmap to point to many rows simultaneously. If a bitmap index
involves more than one column, there is a bitmap for every possible combination. Each bitmap
header stores start and end ROWIDs. Based on these values, the system uses an internal
algorithm to map bitmaps onto ROWIDs. This is possible because the system knows the
maximum possible number of rows that can be stored in a system block. Each position in a
bitmap maps to a potential row in the table even if that row does not exist. The contents of that
position in the bitmap for a particular value indicate whether that row has that value in the
bitmap columns. The value stored is 1 if the row values match the bitmap condition; otherwise
it is 0. Bitmap indexes are widely used in data warehousing environments. These
environments typically have large amounts of data and ad hoc queries, but no concurrent data
manipulation language (DML) transactions because when locking a bitmap, you lock many
rows in the table at the same time. For such applications, bitmap indexing provides reduced
response time for large classes of ad hoc queries, reduced storage requirements compared to
other indexing techniques, dramatic performance gains even on hardware with a relatively
small number of CPUs or a small amount of memory, and efficient maintenance during
parallel DML and loads.
Optimizer Operators
Chapter 6 - Page 33
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Bitmap Indexes
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Unlike most other types of indexes, bitmap indexes include rows that have NULL
values. Indexing of nulls can be useful for some types of SQL statements, such as queries
with the aggregate function COUNT. The IS NOT NULL predicate can also benefit from bitmap
indexes. Although bitmaps are compressed internally, they are split in multiple leaves if the
number of rows increases.
Optimizer Operators
Chapter 6 - Page 34
| Operation
| Name
| Rows
---------------------------------------------------------------------------|
0 | SELECT STATEMENT
1 |
3 |
1 |
1 |
3 |
2 |
1 |
3 |
3 |
SORT AGGREGATE
Optimizer Operators
Chapter 6 - Page 35
(0)|
|
(0)|
|
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
----------------------------------------------------------------------------
Optimizer Operators
Chapter 6 - Page 36
FR 0 0 1 1 1 1 0 0 0 0 0 0
0 1 1 1 1 1 0 0 0 0 0
OR
DE 0 1 0 0 0 0 0 0 0 0 0 0
F 0 0 1 1 1 1 0 0 0 0 0 0
0 0 1 0 1 1 0 0 0 0 0
AND
M 1 1 1 0 1 1 0 1 0 1 1 1
SELECT * FROM EMEA_PERF_TEAM T WHERE country='FR' and gender='M';
Using IN (value_list)
Optimizer Operators
Chapter 6 - Page 37
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 38
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Bitmap Operations
BITMAP CONVERSION:
TO ROWIDS
FROM ROWIDS
COUNT
BITMAP INDEX:
SINGLE VALUE
RANGE SCAN
FULL SCAN
BITMAP
BITMAP
BITMAP
BITMAP
MERGE
AND/OR
MINUS
KEY ITERATION
Bitmap Operations
The slide summarizes all the possible bitmap operations. The following operations have not
been explained so far:
BITMAP CONVERSION FROM ROWID: B*-tree index converted by the optimizer into
BITMAP (cost is lower than other methods) to make these efficient bitmaps comparison
operations available. After the bitmap comparison has been done, the resultant bitmap is
converted back into ROWIDs (BITMAP CONVERSION TO ROWIDS) to perform the data
lookup.
BITMAP MERGE merges several bitmaps resulting from a range scan into one bitmap.
BITMAP MINUS is a dual operator that takes the second bitmap operation and negates
it by changing ones to zeros, and zeros to ones. The bitmap minus operation can then
be performed as a BITMAP AND operation using this negated bitmap. This would
typically be the case with the following combination of predicates: C1=2 and C2<>6.
BITMAP KEY ITERATION takes each row from a table row source and finds the
corresponding bitmap from a bitmap index. This set of bitmaps is then merged into one
bitmap in a BITMAP MERGE operation.
Optimizer Operators
Chapter 6 - Page 39
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Bitmap Operations
1.2.3
Sales
10.8000.3
<Rognes, 1.2.3, 10.8000.3, 100010010010100>
<Aix-en-Provence, 1.2.3, 10.8000.3, 000101000100000>
<Marseille, 1.2.3, 10.8000.3, 010000001000001>
Optimizer Operators
Chapter 6 - Page 40
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
sold to a Rognes customer. By storing the result of a join, the join can be avoided completely
for SQL statements using a bitmap join index.
Optimizer Operators
Chapter 6 - Page 41
Composite Indexes
MAKE
MODEL
CARS
Index columns
create index cars_make_model_idx on cars(make, model);
select *
from cars
where make = 'CITRON' and model = '2CV';
----------------------------------------------------------------| Id | Operation
| Name
|
----------------------------------------------------------------|
0 | SELECT STATEMENT
|
|
|
1 | TABLE ACCESS BY INDEX ROWID| CUSTOMERS
|
|* 2 |
INDEX RANGE SCAN
| CARS_MAKE_MODEL_IDX
|
-----------------------------------------------------------------
Composite Indexes
A composite index is also referred to as a concatenated index because it concatenates
column values together to form the index key value. In the illustration in the slide, the MAKE
and MODEL columns are concatenated together to form the index. It is not required that the
columns in the index are adjacent. And, you can include up to 32 columns in the index, unless
it is a bitmap composite index, in which case the limit is 30.
Composite indexes can provide additional advantages over single-column indexes:
Improved selectivity: Sometimes two or more columns or expressions, each with poor
selectivity, can be combined to form a composite index with higher selectivity.
Reduced I/O: If all columns selected by a query are in a composite index, the system
can return these values from the index without accessing the table.
A composite index is mainly useful when you often have a WHERE clause that references all,
or the leading portion of the columns in the index. If some keys are used in WHERE clauses
more frequently, and you decided to create a composite index, be sure to create the index so
that the more frequently selected keys constitute a leading portion for allowing the statements
that use only these keys to use the index.
Note: It is also possible for the optimizer to use a concatenated index even though your query
does not reference a leading part of that index. This is possible since index skip scans and
fast full scans were implemented.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Optimizer Operators
Chapter 6 - Page 42
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Composite Indexes
VISIBLE
Index
Index
OPTIMIZER_USE_INVISIBLE_INDEXES=FALSE
Update index.
Update index.
Update table.
Update table.
Optimizer Operators
Chapter 6 - Page 43
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 44
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Create indexes after inserting table data: Data is often inserted or loaded into a table
using either the SQL*Loader or an import utility. It is more efficient to create an index for
a table after inserting or loading the data.
Index the correct tables and columns: Use the following guidelines for determining
when to create an index:
Create an index if you frequently want to retrieve less than 15% of the rows in a
large table.
To improve performance on joins of multiple tables, index the columns used for
joins.
Columns suitable for indexing: Some columns are strong candidates for indexing:
-
The column contains many nulls, but queries often select all rows having a value.
Optimizer Operators
Chapter 6 - Page 45
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
There are many nulls in the column and you do not search on the not null values.
Virtual columns: You can create unique or nonunique indexes on virtual columns.
Order index columns for performance: The order of columns in the CREATE INDEX
statement can affect query performance. In general, specify the most frequently used
columns first.
Limit the number of indexes for each table: A table can have any number of indexes.
However, the more indexes there are, the more overhead is incurred as the table is
modified. Thus, there is a trade-off between the speed of retrieving data from a table and
the speed of updating the table.
Specify the tablespace for each index: If you use the same tablespace for a table and
its index, it can be more convenient to perform database maintenance, such as
tablespace backup.
Consider parallelizing index creation: You can parallelize index creation, just as you
can parallelize table creation. This speeds up index creation. However, an index created
with an INITIAL value of 5M and a parallel degree of 12 consumes at least 60 MB of
storage during index creation.
Consider creating indexes with NOLOGGING: You can create an index and generate
minimal redo log records by specifying NOLOGGING in the CREATE INDEX statement.
Because indexes created using NOLOGGING are not archived, perform a backup after
you create the index. Note that NOLOGGING is the default in a NOARCHIVELOG
database.
Optimizer Operators
Chapter 6 - Page 46
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Functions
If you apply a function to the indexed column in the WHERE clause, the index cannot be used; the index
is based on column values without the effect of the function. For example, the following statement does
not use an index on the salary column:
SELECT * FROM employees WHERE 1.10*salary > 10000
If you want an index to be used in this case, you can create a function-based index. Function-based
indexes were covered under Index Range Scan: Function-Based earlier in this lesson.
Optimizer Operators
Chapter 6 - Page 47
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The statistics are considered by the optimizer when deciding whether to use an index. If they
are outdated, they may influence the optimizer to make poor decisions about indexes.
Null Columns
If a column can contain nulls, it may prevent the use of an index on that column. This is
covered later in this lesson.
Slower Index
Sometimes the use of an index is not efficient. This is covered later in this lesson.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Old Statistics
Optimizer Operators
Chapter 6 - Page 48
Quiz
A full table scan sequentially reads all rows from a table and
filters out those that do not meet the selection criteria.
a. True
b. False
Answer: a
Optimizer Operators
Chapter 6 - Page 49
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Assuming that the column email has an index, the following
query will result in an index range scan:
Answer: b
Optimizer Operators
Chapter 6 - Page 50
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
To get optimum result from indexes:
a. Create indexes before inserting table data
b. Do not order index columns
c. Limit the number of indexes for each table
d. Do not specify the tablespace for each index
Answer: c
Optimizer Operators
Chapter 6 - Page 51
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned to:
Describe the SQL operators for tables and indexes
List the possible access paths
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Optimizer Operators
Chapter 6 - Page 52
Practice 6: Overview
This practice covers using different access paths for better
optimization.
Case 1 through case 13
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 6: Overview
Optimizer Operators
Chapter 6 - Page 53
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Operators
Chapter 6 - Page 54
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 7
Chapter 7 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 7 - Page 2
Objectives
After completing this lesson, you should be able to:
Describe the SQL operators for joins
List the possible access paths
Objectives
This lesson helps you understand the execution plans related to join operations.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Join Methods
A join:
Defines the relationship between two row sources
Is a method of combining data from two data sources
Is controlled by join predicates, which define how the
objects are related
Join methods:
Nested loops
Sort-merge join
Hash join
SELECT e.ename, d.dname
FROM dept d JOIN emp e USING (deptno)
WHERE e.job = 'ANALYST' OR e.empno = 9999;
Join predicate
Nonjoin predicate
SELECT e.ename,d.dname
FROM
emp e, dept d
WHERE e.deptno = d.deptno AND
(e.job = 'ANALYST' OR e.empno = 9999);
Join predicate
Nonjoin predicate
Join Methods
A row source is a set of data that can be accessed in a query. It can be a table, an index, a
nonmergeable view, or even the result set of a join tree consisting of many different objects.
A join predicate is a predicate in the WHERE clause that combines the columns of two of the
tables in the join.
A nonjoin predicate is a predicate in the WHERE clause that references only one table.
A join operation combines the output from two row sources (such as tables or views) and
returns one resulting row source (data set). The optimizer supports different join methods
such as the following:
Nested loop join: Useful when small subsets of data are being joined and if the join
condition is an efficient way of accessing the second table
Sort-merge join: Can be used to join rows from two independent sources. Hash joins
generally perform better than sort-merge joins. On the other hand, sort-merge joins can
perform better than hash joins if one or two row sources are already sorted.
Hash join: Used for joining large data sets. The optimizer uses the smaller of two tables
or data sources to build a hash table on the join key in memory. It then scans the larger
table, probing the hash table to find the joined rows. This method is best used when the
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Join Methods
Note: The slide shows you the same query using both the American National Standards
Institute (ANSI) and non-ANSI join syntax. The ANSI syntax is the first example.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
smaller table fits in the available memory. The cost is then limited to a single read pass
over the data for the two tables.
TAF
TAR
Driving
For each
IS
Inner
The optimizer uses nested loop joins when joining small number of rows, with a good driving
condition between the two tables. You drive from the outer loop to the inner loop, so the order
of tables in the execution plan is important. Therefore, you should use other join methods
when two independent row sources are joined.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
TAF
TAR
Driving
IRS
Inner
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Driving
NL
TAF
TAR
IRS
Inner
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Merged
MJ
SJ
SJ
TAF
IRS
Sorted
Independent
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Sort merge joins are useful when the join condition between two tables is an inequality
condition (but not a nonequality), such as <, <=, >, or >=.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Hash Join
HJ
Driving
TAF
TAR
Build hash
table in
memory
IS
Probe
Hash Join
To perform a hash join between two row sources, the system reads the first data set and
builds an array of hash buckets in memory. A hash bucket is little more than a location that
acts as the starting point for a linked list of rows from the build table. A row belongs to a hash
bucket if the bucket number matches the result that the system gets by applying an internal
hashing function to the join column or columns of the row.
The system starts to read the second set of rows, using whatever access mechanism is most
appropriate for acquiring the rows, and uses the same hash function on the join column or
columns to calculate the number of the relevant hash bucket. The system then checks to see
if there are any rows in that bucket. This is known as probing the hash table.
If there are no rows in the relevant bucket, the system can immediately discard the row from
the probe table.
If there are some rows in the relevant bucket, the system does an exact check on the join
column or columns to see if there is a proper match. Any rows that survive the exact check
can immediately be reported (or passed on to the next step in the execution plan). So, when
you perform a hash join, you must fetch all rows from the smallest row source to return the
first row to next operation.
Note: Hash joins are performed only for equijoins, and are most useful when joining large
amount of data.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Hash Join
Cartesian Join
Cartesian Join
A Cartesian join is used when one or more of the tables does not have any join conditions to
any other tables in the statement. The optimizer joins every row from one data source with
every row from the other data source, creating the Cartesian product of the two sets.
A Cartesian join can be seen as a nested loop with no elimination; the first row source is read
and then for every row, all the rows are returned from the other row source.
Note: Cartesian join is generally not desirable. However, it is perfectly acceptable to have one
with single-row row source (guaranteed by a unique index, for example) joined to some other
table.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Cartesian Join
Join Types
Join Types
Join operation types include the following:
Join (equijoin and nonequijoin): Returns rows that match predicate join
Outer join: Returns rows that match predicate join and row when no match is found
Semi join: Returns rows that match the EXISTS subquery. Find one match in the inner
table, then stop search.
Anti join: Returns rows with no match in the NOT IN subquery. Stop as soon as one
match is found.
Star join: This is not a join type, but just a name for an implementation of a performance
optimization to better handle the fact and dimension model.
Antijoin and semijoin are considered to be join types, even though the SQL constructs that
cause them are subqueries. Antijoin and semijoin are internal optimizations algorithms used to
flatten subquery constructs in such a way that they can be resolved in a join-like way.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Join Types
Nonequijoin
Equijoin
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Outer Joins
An outer join returns a row even if no match is found.
SELECT d.deptno,d.dname,e.empno,e.ename
FROM
emp e, dept d
WHERE e.deptno(+)=d.deptno;
DEPT
EMP
10
20
20
10
30
20
40
30
10
1
SELECT /*+ USE_HASH(e d) */
d.deptno,d.dname,e.empno,e.ename
FROM
emp e, dept d
WHERE e.deptno(+)=d.deptno;
2
3
Outer Joins
The simple join is the most commonly used within the system. Other joins open up extra
functionality, but have much more specialized uses. The outer join operator is placed on the
deficient side of the query. In other words, it is placed against the table that has the missing
join information. Consider EMP and DEPT. There may be a department that has no employees.
If EMP and DEPT are joined together, this particular department would not appear in the output
because there is no row that matches the join condition for that department. By using the
outer join, the missing department can be displayed.
1. Merge Outer joins: By default, the optimizer uses MERGE OUTER JOIN.
2. Outer join with nested loops: The left/driving table is always the table whose rows are
being preserved (DEPT in the example). For each row from DEPT, look for all matching
rows in EMP. If none is found, output DEPT values with null values for the EMP columns. If
rows are found, output DEPT values with these EMP values.
3. Hash Outer joins: The left/outer table whose rows are being preserved is used to build
the hash table, and the right/inner table is used to probe the hash table. When a match
is found, the row is output and the entry in the hash table is marked as matched to a
row. After the inner table is exhausted, the hash table is read over once again, and any
rows that are not marked as matched are output with null values for the EMP columns.
The system hashes the table whose rows are not being preserved, and then reads the
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Outer Joins
Note: You can also use the ANSI syntax for full, left, and right outer joins (not shown in the
slide).
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
table whose rows are being preserved, probing the hash table to see whether there was
a row to join to.
Semijoins
Semijoins look only for the first match.
DEPT
EMP
10
20
20
10
30
20
40
30
10
Semijoins
Semijoins return a result when you hit the first joining record. A semijoin is an internal way of
transforming an EXISTS subquery into a join. However, you cannot see this occur anywhere.
Semijoins return rows that match an EXISTS subquery without duplicating rows from the left
side of the predicate when multiple rows on the right side satisfy the criteria of the subquery.
In the above diagram, for each DEPT record, only the first matching EMP record is returned as
a join result. This prevents scanning huge numbers of duplicate rows in a table when all you
are interested in is if there are any matches.
When the subquery is not unnested, a similar result could be achieved by using a FILTER
operation and scanning a row source until a match is found, then returning it.
Note: A semijoin can always use a Merge join. The optimizer may choose nested-loop, or
hash joins methods to perform semijoins as well.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Semijoins
Antijoins
Reverse of what would have been returned by a join
SELECT deptno, dname
FROM
dept
WHERE deptno not in
(SELECT deptno FROM emp);
DEPT
EMP
10
20
20
10
30
20
40
30
10
EMP
DEPT
Antijoins
Antijoins return rows that fail to match (NOT IN) the subquery at the right side. For example,
an antijoin can select a list of departments which do not have any employee.
The optimizer uses a merge antijoin algorithm for NOT IN subqueries by default. However, if
the HASH_AJ or NL_AJ hints are used and various required conditions are met, the NOT IN
uncorrelated subquery can be changed. Although antijoins are mostly transparent to the user,
it is useful to know that these join types exist and could help explain unexpected performance
changes between releases.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Antijoins
Quiz
The _______ join is used when one or more of the tables do
not have any join conditions to any other tables in the
statement.
a. Hash
b. Cartesian
c. Non-equi
d. Outer
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The _______ join returns a row even if no match is found.
a. Hash
b. Cartesian
c. Semi
d. Outer
Answer: d
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The _______ join looks only for the first match.
a. Hash
b. Cartesian
c. Semi
d. Outer
Answer: c
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
In a hash join, the _______row source is used to build a hash
table.
a. Biggest
b. Smallest
c. Sorted
d. Unsorted
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned to:
Describe the SQL operators for joins
List the possible access paths
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 7: Overview
This practice covers the following topics:
Using different access paths for better optimization
Using the result cache
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 7: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 8
Chapter 8 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 8 - Page 2
Objectives
After completing this lesson, you should be able to:
Describe SQL operators for:
Clusters
In-List
Sorts
Filters
Set Operations
Objectives
This lesson helps you understand the execution plans that use common operators of other
access methods.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Clusters
ORD_NO PROD
----------101 A4102
102 A2091
102 G7830
102 N9587
101 A5675
101 W0824
QTY
-----20
11
20
26
19
10
ORD_NO
-----101
102
... -
ORD_DT
CUST_CD
----------05-JAN-97
R01
07-JAN-97
N45
Cluster Key
(ORD_NO)
101 ORD_DT
CUST_CD
05-JAN-97
R01
PROD
QTY
A4102
20
A5675
19
W0824
10
102
ORD_DT
CUST_CD
07-JAN-97
N45
PROD
QTY
A2091
11
G7830
20
N9587
26
Clusters
Clusters are an optional method for storing table data. A cluster is a group of tables that share
the same data blocks because they share common columns and are often used together. For
example, the ORDERS and ORDER_ITEMS table share the ORDER_ID column. When you
cluster the ORDERS and ORDER_ITEMS tables, the system physically stores all rows for each
order from both the ORDERS and ORDER_ITEMS tables in the same data blocks.
Cluster index: A cluster index is an index defined specifically for a cluster. Such an index
contains an entry for each cluster key value. To locate a row in a cluster, the cluster index is
used to find the cluster key value, which points to the data block associated with that cluster
key value. Therefore, the system accesses a given row with a minimum of two I/Os.
Hash clusters: Hashing is an optional way of storing table data to improve the performance
of data retrieval. To use hashing, you create a hash cluster and load tables into the cluster.
The system physically stores the rows of a table in a hash cluster and retrieves them
according to the results of a hash function. The key of a hash cluster (just as the key of an
index cluster) can be a single column or composite key. To find or store a row in a hash
cluster, the system applies the hash function to the rows cluster key value; the resulting hash
value corresponds to a data block in the cluster, which the system then reads or writes on
behalf of the issued statement.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Clusters
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Hash clusters are a better choice than using an indexed table or index cluster when a
table is queried frequently with equality queries.
Index cluster:
Tables always joined on the same keys
The size of the table is not known
In any type of searches
Hash cluster:
Tables always joined on the same keys
Storage for all cluster keys allocated initially
In either equality (=) or nonequality (<>) searches
Index clusters allow row data from one or more tables that share a cluster key value to
be stored in same block. You can locate these rows using a cluster index, which has one
entry per cluster key value and not for each row. Therefore, the index is smaller and less
costly to access for finding multiple rows. The rows with the same key are in a small
group of blocks. This means that in an index cluster the clustering factor is very good
and provides clustering for data from multiple tables sharing the same join key. The
smaller index and smaller group of blocks reduce the cost of access by reducing block
visits to the buffer cache. Index clusters are useful when the size of the tables is not
known in advance (For example: Creating a new table rather than converting an existing
one whose size is stable) because a cluster bucket is only created after a cluster key
value is used. They are also useful for all filter operations or searches. Note that full
table scans do not perform well on a table in a multiple table cluster as it has more
blocks than the table would have if created as a heap table.
Hash clusters allow row data from one or more tables that share a cluster key value to
be stored in same block. You can locate these rows using a system-provided or userprovided hashing function or using the cluster key value assuming that this is already
evenly distributed making the access to a row faster than using index clusters. Table
rows with the same cluster key values hash into the same cluster buckets and can be
stored in the same block or small group of blocks.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
This means that in a hash cluster the clustering factor is also very good and a row may
be accessed by its key with one block visit only and without needing an index. Hash
clusters allocate all the storage for all the hash buckets when the cluster is created, so
they may waste space. They also do not perform well other than on equality searches or
nonequality searches. Like index clusters if they contain multiple tables, full scans are
more expensive for the same reason.
Single-table hash clusters are similar to a hash cluster, but are optimized in the block
structures for access to a single table, thereby providing the fastest possible access to a
row other than by using a rowid filter. As they only have one table, full scans, if they
happen, cost as much as they would in a heap table.
Sorted hash clusters are designed to reduce costs of accessing ordered data by using a
hashing algorithm on the hash key. Accessing the first row matching the hash key may
be less costly than using an IOT for a large table because it saves the cost of a B*-tree
probe. All the rows that match on a particular hash key (For example: Account number)
are stored in the cluster in the order of the sort key or keys (For example: Phone calls),
thereby, eliminating the need for a sort to process the order by clause. These clusters
are very good for batch reporting, billing, and so on.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Sorting Operators
SORT operator:
HASH operator:
GROUP BY: For this operator
UNIQUE: Equivalent to SORT UNIQUE
Sorting Operators
Sort operations result when users specify an operation that requires a sort. Commonly
encountered operations include the following:
SORT AGGREGATE does not involve a sort. It retrieves a single row that is the result of
applying a group function to a group of selected rows. Operations such as COUNT and
MIN are shown as SORT AGGREGATE.
SORT UNIQUE sorts output rows to remove duplicates. It occurs if a user specifies a
DISTINCT clause or if an operation requires unique values for the next step.
SORT JOIN happens during a sort-merge join, if the rows need to be sorted by the join
key.
SORT GROUP BY is used when aggregates are computed for different groups in the
data. The sort is required to separate the rows into different groups.
SORT ORDER BY is required when the statement specifies an ORDER BY that cannot be
satisfied by one of the indexes.
HASH GROUP BY hashes a set of rows into groups for a query with a GROUP BY clause.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Sorting Operators
HASH UNIQUE hashes a set of rows to eliminate duplicates. It occurs if a user specifies
a DISTINCT clause or if an operation requires unique values for the next step. This is
similar to SORT UNIQUE.
Note: Several SQL operators cause implicit sorts (or hashes since Oracle Database 10g,
Release 2), such as DISTINCT, GROUP BY, UNION, MINUS, and INTERSECT. However, do
not rely on these SQL operators to return ordered rows. If you want to have rows ordered, use
the ORDER BY clause.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Inlist Iterator
Every value executed separately
deptno=1
deptno=2
Inlist Iterator
It is used when a query contains an IN clause with values or multiple equality predicates on
the same column linked with ORs.
The INLIST ITERATOR operator iterates over the enumerated value list, and every value is
executed separately.
The execution plan is identical to the result of a statement with an equality clause instead of
IN, except for one additional step. The extra step occurs when INLIST ITERATOR feeds the
equality clause with unique values from the list.
You can view this operator as a FOR LOOP statement in PL/SQL. In the example in the slide,
you iterate the index probe over two values: 1 and 2.
Also, it is a function that uses an index, which is scanned for each value in the list. An
alternative handling is UNION ALL of each value or a FILTER of the values against all the
rows, this is significantly more efficient.
The optimizer uses an INLIST ITERATOR when an IN clause is specified with values, and
the optimizer finds a selective index for that column. If there are multiple OR clauses using the
same index, the optimizer selects this operation rather than CONCATENATION or UNION ALL,
because it is more efficient.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Inlist Iterator
View Operator
create view V as select /*+ NO_MERGE */ DEPTNO, sal from emp ;
select * from V;
View Operator
Each query produces a variable set of data in the form of a table. A view simply gives a name
to this set of data.
When views are referenced in a query, the system can handle them in two ways. If a number
of conditions are met, they can be merged into the main query. This means that the view text
is rewritten as a join with the other tables in the query. Views can also be left as standalone
views and selected from directly as in the case of a table. Predicates can also be pushed into
or pulled out of the views as long as certain conditions are met.
When a view is not merged, you can see the VIEW operator. The view operation is executed
separately. All rows from the view are returned, and the next operation can be done.
Sometimes a view cannot be merged and must be executed independently in a separate
query block. In this case, you can also see the VIEW operator in the explain plan. The VIEW
keyword indicates that the view is executed as a separate query block. For example, views
containing GROUP BY functions cannot be merged.
The second example in the slide shows a nonmergeable inline view. An inline view is basically
a query within the FROM clause of your statement.
Basically, this operator collects all rows from a query block before they can be processed by
higher operations in the plan.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
View Operator
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
FILTER
CONCATENATION
UNION ALL/UNION
INTERSECT
MINUS
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
FILTER Operations
1
SELECT deptno, dname FROM dept d WHERE NOT EXISTS
(select 1 from emp e where e.deptno=d.deptno);
FILTER Operations
A FILTER operation is any operation that discards rows returned by another step, but is not
involved in retrieving the rows itself. All sorts of operations can be filters, including subqueries
and single table predicates.
In the example 1, FILTER applies to the groups that are created by the GROUP BY operation.
In the example 2, FILTER is almost used in the same way as NESTED LOOPS. DEPT is
accessed once, and for each row from DEPT, EMP is accessed by its index on DEPTNO. This
operation is done as many times as the number of rows in DEPT.
The FILTER operation is applied, for each row, after DEPT rows are fetched. The FILTER
discards rows for the inner query returned at least one row (select 1 from emp e where
e.deptno=d.deptno) is TRUE.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
FILTER Operations
Concatenation Operation
Concatenation Operation
CONCATENATION concatenates the rows returned by two or more row sets. This works like
UNION ALL and does not remove duplicate rows.
It is used with OR expansions. However, OR does not return duplicate rows, so for each
component after the first, it appends a negation of the previous components (LNNVL):
CONCATENATION
- BRANCH 1 - SAL=2
- BRANCH 2 - DEPTNO = 1 AND NOT row in Branch 1
The LNNVL function is generated by the OR clause to process this negation.
The LNNVL() function returns TRUE, if the predicate is NULL or FALSE.
So filter (LNNVL(SAL=2)) returns all rows for which SAL != 2 or SAL is NULL.
Note: The explain plan in the slide is from Oracle Database 11g Release 1.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Concatenation Operation
UNION
UNION ALL
SORT UNIQUE
UNION-ALL
INDEX FULL SCAN
INDEX FAST FULL SCAN
INTERSECT
INTERSECTION
SORT UNIQUE NOSORT
INDEX FULL SCAN
SORT UNIQUE
INDEX FAST FULL SCAN
MINUS
MINUS
SORT UNIQUE NOSORT
INDEX FULL SCAN
SORT UNIQUE
INDEX FAST FULL SCAN
1
2
3
3
1
5
1
2
1
2
3
3
3
3
3
3
4
5
INTERSECTION: Operation accepting two sets of rows and returning the intersection of
the sets, eliminating duplicates. Subrow sources are executed or optimized individually.
This is very similar to sort-merge-join processing: Full rows are sorted and matched.
MINUS: Operation accepting two sets of rows and returning rows appearing in the first
set, but not in the second, eliminating duplicates. Subrow sources are executed or
optimized individually. Similar to INTERSECT processing. However, instead of matchand-return, it is match-and-exclude.
UNION: Operation accepting two sets of rows and returning the union of the sets,
eliminating duplicates. Subrow sources are executed or optimized individually. Rows
retrieved are concatenated and sorted to eliminate duplicate rows.
UNION ALL: Operation accepting two sets of rows and returning the union of the sets,
and not eliminating duplicates. The expensive sort operation is not necessary. Use
UNION ALL if you know you do not have to deal with duplicates.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Hash clusters are a better choice than using an indexed table
or index cluster when a table is queried frequently with equality
queries.
a. True
b. False
Answer: a
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The ________ operator uses a temporary table to store
intermediate data.
a.
b.
c.
d.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Answer: a
Quiz
The following query uses the ________ operator:
SELECT * FROM emp WHERE empno IN (7876, 7900,
7902);
a.
b.
c.
d.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Answer: b
Quiz
A FILTER operation retrieves rows returned by another
statement.
a. True
b. False
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned to:
Describe SQL operators for:
Clusters
In-List
Sorts
Filters
Set Operations
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 8: Overview
This practice covers the following topics:
Using different access paths for better optimization
Case 14 to case 16
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 8: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 9
Chapter 9 - Page 1
Case Study:
Star Transformation
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
After completing this lesson, you should be able to:
Define a star schema
Show a star query plan without transformation
Define the star transformation requirements
Show a star query plan after transformation
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
PRODUCTS
TIMES
Fact table
Keys
PROD_ID
PROD_NAME
PROD_DESC
PROD_ID
TIME_ID
CHANNEL_ID
TIME_ID
DAY_NAME
CALENDAR_YEAR
SALES
CUSTOMERS
AMOUNT_SOLD
QUANTITY_SOLD
CHANNELS
CUST_ID
CHANNEL_ID
CUST_GENDER
CUST_CITY
Measures
CHANNEL_DESC
CHANNEL_CLASS
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
PRODUCTS
TIMES
SALES
CUSTOMERS
CHANNELS
COUNTRIES
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
CHANNELS
Hash Join
TIMES
CUSTOMERS
Hash Join
SALES
------------------------------------------| Id | Operation
| Name
|
------------------------------------------|
0 | SELECT STATEMENT
|
|
|
1 | HASH GROUP BY
|
|
|* 2 |
HASH JOIN
|
|
|* 3 |
TABLE ACCESS FULL | CHANNELS |
|* 4 |
HASH JOIN
|
|
|* 5 |
TABLE ACCESS FULL | TIMES
|
|* 6 |
HASH JOIN
|
|
|* 7 |
TABLE ACCESS FULL| CUSTOMERS |
|
8 |
TABLE ACCESS FULL| SALES
|
------------------------------------------Predicate Information (by operation id):
-------------------------------------------2 - access("S"."CHANNEL_ID"="CH"."CHANNEL_ID")
3 - filter("CH"."CHANNEL_DESC"='Catalog' OR
"CH"."CHANNEL_DESC"='Internet')
4 - access("S"."TIME_ID"="T"."TIME_ID")
5 - filter("T"."CALENDAR_QUARTER_DESC"='1999-Q1'
OR "T"."CALENDAR_QUARTER_DESC"='1999-Q2')
6 - access("S"."CUST_ID"="C"."CUST_ID")
7 - filter("C"."CUST_STATE_PROVINCE"='CA')
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Star Transformation
Star Transformation
To get the best possible performance for star queries, it is important to follow some basic
guidelines:
A bitmap index should be built on each of the foreign key columns of the fact table or
tables.
When a data warehouse satisfies these conditions, the majority of the star queries that run in
the data warehouse use a query execution strategy known as star transformation. Star
transformation provides very efficient query performance for star queries.
Star transformation is a powerful optimization technique that relies on implicitly rewriting (or
transforming) the SQL of the original star query. The end user never needs to know any of the
details about the star transformation. The systems CBO automatically selects star
transformation where appropriate. The optimizer creates an execution plan that processes a
star query using two basic phases:
The first phase retrieves exactly the necessary rows from the fact table (the result set).
Because this retrieval utilizes bitmap indexes, it is very efficient.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Star Transformation
The second phase joins this result set to the dimension tables. This operation is called a
semijoin.
Note: At least three tables are used in the query (two dimensions and one fact).
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Queries with a table hint that is incompatible with a bitmap access path
Tables with too few bitmap indexes. There must be a bitmap index on a fact table
column for the optimizer to generate a subquery for it.
Remote fact tables. However, remote dimension tables are allowed in the subqueries
that are generated.
Antijoined tables
Tables that are really unmerged views, which are not view partitions
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
0
1
1
0
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
BITMAP
MERGE
One bitmap
is Produced.
BITMAP
KEY
ITERATION
Dimension
Table
Access
Fact Table
Bitmap
Access
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Phase 1
BITMAP
Conversion
To Rowids
Multiple bitmaps
are
ANDed together.
BITMAP
AND
MERGE 1
MERGE
MERGE n
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Phase 2
Hash Join
Dimension n
Table
Access
Hash Join
Dimension i
Table
Access
Hash Join
Dimension 1
Table
Access
Fact Table
Access
From IRS
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
filter("C"."CUST_STATE_PROVINCE"='CA')
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
SORT GROUP BY
HASH JOIN
HASH JOIN
TABLE ACCESS BY INDEX ROWID SALES
BITMAP CONVERSION TO ROWIDS
BITMAP AND
BITMAP MERGE
BITMAP KEY ITERATION
BUFFER SORT
TABLE ACCESS FULL CHANNELS
BITMAP INDEX RANGE SCAN SALES_CHANNELS_BX
BITMAP OR
BITMAP INDEX SINGLE VALUE SALES_Q_BJX
BITMAP INDEX SINGLE VALUE SALES_Q_BJX
TABLE ACCESS FULL CHANNELS
TABLE ACCESS FULL TIMES
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The STAR_TRANSFORMATION hint makes the optimizer use the best plan in which the
transformation has been used. Without the hint, the optimizer could make a cost-based
decision to use the best plan generated without the transformation, instead of the best
plan for the transformed query. Even if the hint is given, there is no guarantee that the
transformation takes place. The optimizer only generates the subqueries if it seems
reasonable to do so. If no subqueries are generated, there is no transformed query, and
the best plan for the untransformed query is used, regardless of the hint.
The FACT hint is used in the context of the star transformation to indicate to the
transformation that the hinted table should be considered as a fact table and all other
tables regardless of their size are considered as dimensions.
The NO_FACT hint is used in the context of the star transformation to indicate to the
transformation that the hinted table should not be considered as a fact table.
Note: The FACT and NO_FACT hints might be useful only in case there are more than one fact
table accessed in the star query.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
pk
fk
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
pk
fk
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
pk
fk1
d1
fk2
pk
c1
d2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
pk
c2
d1
pk
fk
d2
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
If the star_transformation_enabled parameter is set to
true, the optimizer will:
a. Always use a star transformation
b. Always use a temporary table
c. Always consider a star transformation
d. Never use a temporary table
e. Always use a hash join
Answer: c
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Which two of the following properties of the schema structure
are required by the optimizer to consider using the star
transformation?
a. At least one fact table
b. At least one bitmap join index
c. At least two dimension tables
d. At least one bind variable
e. At least one histogram on a join column
Answer: a, c
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Assuming that the START_TRANSFORMATION_ENABLED
parameter is set to TRUE, the star transformation is chosen by
the optimizer when:
a. All the conditions are met
b. The cost is lower than a tradition access path
c. The bitmap join indexes eliminate additional joins
d. Temporary tables can be used to reduce table accesses
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
Define a star schema
Show a star query plan without transformation
Define the star transformation requirements
Show a star query plan after transformation
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
Practice 9: Overview
This practice covers using the star transformation technique to
optimize your query.
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Practice 9: Overview
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 10
Optimizer Statistics
Chapter 10 - Page 1
Optimizer Statistics
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Statistics
Optimizer Statistics
Chapter 10 - Page 2
Optimizer Statistics
Objectives
After completing this lesson, you should be able to do the
following:
Gather optimizer statistics
Gather system statistics
Set statistic preferences
Use dynamic sampling
Manipulate optimizer statistics
Optimizer Statistics
Chapter 10 - Page 3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Optimizer Statistics
Selectivity of predicates
Cost of each execution plan
Access method, join order, and join method
CPU and input/output (I/O) costs
Optimizer Statistics
Optimizer statistics describe details about the database and the objects in the database.
These statistics are used by the query optimizer to select the best execution plan for each
SQL statement.
Because the objects in a database change constantly, statistics must be regularly updated so
that they accurately describe these database objects. Statistics are maintained automatically
by Oracle Database, or you can maintain the optimizer statistics manually using the
DBMS_STATS package.
Optimizer Statistics
Chapter 10 - Page 4
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Statistics
Table statistics:
Number of rows
Number of blocks
Average row length
Index Statistics:
B*-tree level
Distinct keys
Number of leaf blocks
Clustering factor
Column statistics
Basic: Number of distinct
values, number of nulls,
average length, min, max
Histograms (data
distribution
when the column data is
skewed)
Extended statistics
System statistics
I/O performance and utilization
CPU performance and utilization
Optimizer Statistics
Chapter 10 - Page 5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Statistics
Chapter 10 - Page 6
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Used to decide:
Full table scan versus index scan
Optimizer Statistics
Chapter 10 - Page 7
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
This tells you if the statistics are valid in the corresponding index.
DISTINCT_KEYS
This is the number of distinct indexed values. For indexes that enforce UNIQUE and PRIMARY
KEY constraints, this value is the same as the number of rows in the table.
AVG_LEAF_BLOCKS_PER_KEY
This is the average number of leaf blocks in which each distinct value in the index appears,
rounded to the nearest integer. For indexes that enforce UNIQUE and PRIMARY KEY
constraints, this value is always 1 (one).
AVG_DATA_BLOCKS_PER_KEY
This is the average number of data blocks in the table that are pointed to by a distinct value in
the index rounded to the nearest integer. This statistic is the average number of data blocks
that contain rows that contain a given value for the indexed columns.
NUM_ROWS
It is the number of rows in the index.
Optimizer Statistics
Chapter 10 - Page 8
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
STALE_STATS
Block 2
Block 3
A B C
A B C
A B C
C B A
DBA_IND_STATISTICS.CLUSTERING_FACTOR
A B C
A A A
B B B
C C C
Block 1
Block 2
Block 3
Optimizer Statistics
Chapter 10 - Page 9
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The example in the slide shows how the clustering factor can affect cost. Assume the
following situation: There is a table with 9 rows, there is a nonunique index on col1 for table,
the c1 column currently stores the values A, B, and C, and the table only has three data
blocks.
Case 1: If the same rows in the table are arranged so that the index values are scattered
across the table blocks (rather than collocated), the index clustering factor is high.
Case 2: The index clustering factor is low for the rows as they are collocated in the
same block for the same value.
Note: For bitmap indexes, the clustering factor is not applicable and is not used.
Optimizer Statistics
Chapter 10 - Page 10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The clustering factor is computed and stored in the CLUSTERING_FACTOR column of the
DBA_INDEXES view when you gather statistics on the index. The way it is computed is
relatively easy. You read the index from left to right, and for each indexed entry, you add one
to the clustering factor if the corresponding row is located in a different block than the one
from the previous row. Based on this algorithm, the smallest possible value for the clustering
factor is the number of blocks, and the highest possible value is the number of rows.
Optimizer Statistics
Chapter 10 - Page 11
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Histograms
Histograms
A histogram captures the distribution of different values in a column, so it yields better
selectivity estimates. Having histograms on columns that contain skewed data or values with
large variations in the number of duplicates help the query optimizer generate good selectivity
estimates and make better decisions regarding index usage, join orders, and join methods.
Without histograms, a uniform distribution is assumed. If a histogram is available on a column,
the estimator uses it instead of the number of distinct values.
When creating histograms, Oracle Database uses two different types of histogram
representations depending on the number of distinct values found in the corresponding
column. When you have a data set with less than 254 distinct values, and the number of
histogram buckets is not specified, the system creates a frequency histogram. If the number of
distinct values is greater than the required number of histogram buckets, the system creates a
height-balanced histogram.
You can find information about histograms in these dictionary views: DBA_TAB_HISTOGRAMS,
DBA_PART_HISTOGRAMS, and DBA_SUBPART_HISTOGRAMS
Note: Gathering histogram statistics is the most resource-consuming operation in gathering
statistics.
Optimizer Statistics
Chapter 10 - Page 12
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Histograms
Frequency Histograms
10 buckets, 10 distinct values
Cumulative cardinality
40000
ENDPOINT
30000
NUMBER 20000
10000
0
10
16 27
32
39 49
Frequency Histograms
For the example in the slide, assume that you have a column that is populated with 40,001
numbers. You only have ten distinct values: 1, 3, 5, 7, 10, 16, 27, 32, 39, and 49. Value 10 is
the most popular value with 16,293 occurrences.
When the requested number of buckets equals (or is greater than) the number of distinct
values, you can store each different value and record exact cardinality statistics. In this case,
in DBA_TAB_HISTOGRAMS, the ENDPOINT_VALUE column stores the column value and the
ENDPOINT_NUMBER column stores the cumulative row count including that column value,
because this can avoid some calculation for range scans. The actual row counts are derived
from the endpoint values if needed. The actual number of row counts is shown by the curve in
the slide for clarity; only the ENDPOINT_VALUE and ENDPOINT_NUMBER columns are stored
in the data dictionary.
Optimizer Statistics
Chapter 10 - Page 13
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Frequency Histograms
Optimizer Statistics
Chapter 10 - Page 14
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Height-Balanced Histograms
5 buckets, 10 distinct values
(8000 rows per bucket)
Popular value
10
10
32
49
ENDPOINT VALUE
Same number
of rows per bucket
Height-Balanced Histograms
In a height-balanced histogram, the ordered column values are divided into bands so that
each band contains approximately the same number of rows. The histogram tells you values
of the endpoints of each band. In the example in the slide, assume that you have a column
that is populated with 40,001 numbers. There will be 8,000 values in each band. You only
have ten distinct values: 1, 3, 5, 7, 10, 16, 27, 32, 39, and 49. Value 10 is the most popular
value with 16,293 occurrences. When the number of buckets is less than the number of
distinct values, ENDPOINT_NUMBER records the bucket number and ENDPOINT_VALUE
records the column value that corresponds to this endpoint. In the example, the number of
rows per bucket is one-fifth of the total number of rows, that is 8000. Based on this
assumption, value 10 appears between 8000 and 24000 times. So you are sure that value 10
is a popular value.
This type of histogram is good for equality predicates on popular value, and range predicates.
The number of rows per bucket is not recorded because this can be derived from the total
number of values and the fact that all the buckets contain an equal number of values. In this
example, value 10 is a popular value because it spans multiple endpoint values. To save
space, the histogram does not actually store duplicated buckets. In the example in the slide,
bucket 2 (with endpoint value 10) would not be recorded in DBA_TAB_HISTOGRAMS for that
reason.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Optimizer Statistics
Chapter 10 - Page 15
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Height-Balanced Histograms
Optimizer Statistics
Chapter 10 - Page 16
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Histogram Considerations
Histogram Considerations
Histograms are useful only when they reflect the current data distribution of a given column.
The data in the column can change as long as the distribution remains constant. If the data
distribution of a column changes frequently, you must recompute its histogram frequently.
Histograms are useful when you have a high degree of data skew in the columns for which
you want to create histograms.
However, there is no need to create histograms for columns which do not appear in a WHERE
clause of a SQL statement. Similarly, there is no need to create histograms for columns with
uniform distribution.
In addition, for columns declared as UNIQUE, histograms are useless because the selectivity
is obvious. Also, the maximum number of buckets is 254, which can be lower depending on
the actual number of distinct column values. Histograms can affect performance and should
be used only when they substantially improve query plans. For uniformly distributed data, the
optimizer can make fairly accurate guesses about the cost of executing a particular statement
without the use of histograms.
Note: Character columns have some exceptional behavior as histogram data is stored only for
the first 32 bytes of any string.
Optimizer Statistics
Chapter 10 - Page 17
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Histogram Considerations
MODEL
S(MAKE MODEL)=S(MAKE)xS(MODEL)
select
dbms_stats.create_extended_stats('jfv','vehicle','(make,model)')
from dual;
exec dbms_stats.gather_table_stats('jfv','vehicle',method_opt=>'for all columns size 1 for columns (make,model) size 3');
2
3
SYS_STUF3GLKIOP5F4B0BTTCFTMX0W
DBA_STAT_EXTENSIONS
VEHICLE
MAKE
MODEL
S(MAKE MODEL)=S(MAKE,MODEL)
If all the columns of a conjunctive predicate match all the columns of a concatenated
index key, and the predicates are equalities used in equijoins, then the optimizer uses
the number of distinct keys (NDK) in the index for estimating selectivity, as 1/NDK.
When DYNAMIC_SAMPLING is set to level 4, the query optimizer uses dynamic sampling
to estimate the selectivity of complex predicates involving several columns from the
same table. However, the sample size is very small and increases parsing time. As a
result, the sample is likely to be statistically inaccurate and may cause more harm than
good.
In all other cases, the optimizer assumes that the values of columns used in a complex
predicate are independent of each other. It estimates the selectivity of a conjunctive predicate
by multiplying the selectivity of individual predicates. This approach results in underestimation
of the selectivity if there is a correlation between the columns. To circumvent this issue,
Oracle Database 11g allows you to collect, store, and use the following statistics to capture
functional dependency between two or more columns (also called groups of columns): number
of distinct values, number of nulls, frequency histograms, and density.
Optimizer Statistics
Chapter 10 - Page 18
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Based on the example in the slide, the name can be determined by using the following
SQL:
select
dbms_stats.show_extended_stats_name('jfv','vehicle','(make,model)
') from dual
After you create the statistics extensions, you can retrieve them by using the
ALL|DBA|USER_STAT_EXTENSIONS views.
Optimizer Statistics
Chapter 10 - Page 19
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
For example, consider a VEHICLE table in which you store information about cars. The MAKE
and MODEL columns are highly correlated, in that MODEL determines MAKE. This is a strong
dependency, and both columns should be considered by the optimizer as highly correlated.
You can signal that correlation to the optimizer by using the CREATE_EXTENDED_STATS
function as shown in the example in the slide, and then compute the statistics for all columns
(including the ones for the correlated groups that you created).
VEHICLE
VEHICLE
Still possible
MODEL
MODEL
Recommended
S(upper( MODEL))=0.01
DBA_STAT_EXTENSIONS
VEHICLE
select
dbms_stats.create_extended_stats(
'jfv','vehicle','(upper(model))')
from dual;
MODEL
SYS_STU3FOQ$BDH0S_14NGXFJ3TQ50
exec dbms_stats.gather_table_stats('jfv','vehicle',method_opt=>'for all columns size 1 for columns (upper(model)) size 3');
Optimizer Statistics
Chapter 10 - Page 20
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
GATHERING_MODE:
NOWORKLOAD|INTERVAL
START|STOP
Optimizer Statistics
Chapter 10 - Page 21
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
NOWORKLOAD: This is the default. This mode captures characteristics of the I/O system.
Gathering may take a few minutes and depends on the size of the database. During this
period the system estimates the average read seek time and transfer speed for the I/O
system. This mode is suitable for all workloads. It is recommended that you run
GATHER_SYSTEM_STATS ('noworkload') after you create the database and
tablespaces.
INTERVAL: Captures system activity during a specified interval. This works in
combination with the interval parameter that specifies the amount of time for the
capture. You should provide an interval value in minutes, after which system statistics
are created or updated in the dictionary or a staging table. You can use
GATHER_SYSTEM_STATS (gathering_mode=>'STOP') to stop gathering earlier
than scheduled.
START | STOP: Captures system activity during specified start and stop times, and
refreshes the dictionary or a staging table with statistics for the elapsed period.
Note: Since Oracle Database 10g, Release 2, the system automatically gathers essential
parts of system statistics at startup.
Optimizer Statistics
Chapter 10 - Page 22
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
When you use the GATHER_SYSTEM_STATS procedure, you should specify the
GATHERING_MODE parameter:
First day
EXECUTE DBMS_STATS.GATHER_SYSTEM_STATS(
interval => 120,
stattab => 'mystats', statid => 'OLTP');
First night
EXECUTE DBMS_STATS.GATHER_SYSTEM_STATS(
interval => 120,
stattab => 'mystats', statid => 'OLAP');
Next days
EXECUTE DBMS_STATS.IMPORT_SYSTEM_STATS(
stattab => 'mystats', statid => 'OLTP');
EXECUTE DBMS_STATS.IMPORT_SYSTEM_STATS(
Optimizer Statistics
Chapter 10 - Page 23
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Statistics
Chapter 10 - Page 24
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Dynamic sampling
When statistics are missing:
Selectivity:
Equality
1%
Inequality
5%
Other predicates
5%
20
25
# of distinct values
100
Table cardinality
100
2000
Optimizer Statistics
Chapter 10 - Page 25
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Statement level
Table level
DBA_TAB_STAT_PREFS
Schema level
Database level
Global level
CASCADE
DEGREE
ESTIMATE_PERCENT METHOD_OPT
GRANULARITY
NO_INVALIDATE
INCREMENTAL
PUBLISH
STALE_PERCENT
set_global_prefs
set_database_prefs
set_schema_prefs
set_table_prefs
gather_*_stats
exec dbms_stats.set_table_prefs('SH','SALES','STALE_PERCENT','13');
Optimizer Statistics
Chapter 10 - Page 26
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
In the graphic in the slide, the last three highlighted options are new in Oracle Database 11g,
Release 1:
CASCADE gathers statistics on the indexes as well. Index statistics gathering is not
parallelized.
ESTIMATE_PERCENT is the estimated percentage of rows used to compute statistics
(Null means all rows): The valid range is [0.000001,100]. Use the constant
DBMS_STATS.AUTO_SAMPLE_SIZE to have the system determine the appropriate
sample size for good statistics. This is the recommended default.
NO_INVALIDATE controls the invalidation of dependent cursors of the tables for which
statistics are being gathered. It does not invalidate the dependent cursors if set to TRUE.
The procedure invalidates the dependent cursors immediately if set to FALSE. Use
DBMS_STATS.AUTO_INVALIDATE to have the system decide when to invalidate
dependent cursors. This is the default.
PUBLISH is used to decide whether to publish the statistics to the dictionary or to store
them in a pending area before.
STALE_PERCENT is used to determine the threshold level at which an object is
considered to have stale statistics. The value is a percentage of rows modified since the
last statistics gathering. The example changes the 10 percent default to 13 percent for
SH.SALES only.
DEGREE determines the degree of parallelism used to compute statistics. The default for
degree is null, which means use the table default value specified by the DEGREE clause
in the CREATE TABLE or ALTER TABLE statement. Use the constant
DBMS_STATS.DEFAULT_DEGREE to specify the default value based on the initialization
parameters. The AUTO_DEGREE value determines the degree of parallelism
automatically. This is either 1 (serial execution) or DEFAULT_DEGREE (the system
default value based on the number of CPUs and initialization parameters), depending on
the size of the object.
METHOD_OPT is a SQL string used to collect histogram statistics. The default value is
FOR ALL COLUMNS SIZE AUTO.
GRANULARITY is the granularity of statistics to collect for partitioned tables.
INCREMENTAL is used to gather global statistics on partitioned tables in an incremental
way.
It is important to note that you can change default values for the above parameters using the
DBMS_STATS.SET_GLOBAL_PREFS procedure.
Note: You can describe all the effective statistics preference settings for all relevant tables by
using the DBA_TAB_STAT_PREFS view.
Optimizer Statistics
Chapter 10 - Page 27
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
whereas database preferences are used to set preferences on all tables. The preference
values that are specified in various ways take precedence from the outer circles to the inner
ones (as shown in the slide).
Volatile tables that are modified significantly during the course of the day
Objects that are the target of large bulk loads that add 10% or more to the objects total
size between statistics-gathering intervals
For external tables, statistics are only collected manually using GATHER_TABLE_STATS.
Sampling on external tables is not supported, so the ESTIMATE_PERCENT option should be
explicitly set to null. Because data manipulation is not allowed against external tables, it is
sufficient to analyze external tables when the corresponding file changes. Other areas in
which statistics need to be manually gathered are the system statistics and fixed objects, such
as the dynamic performance tables. These statistics are not automatically gathered.
Optimizer Statistics
Chapter 10 - Page 28
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Gather/Modify
View/Name
Export/Import
Delete/Lock
Optimizer Statistics
Chapter 10 - Page 29
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
GATHER_INDEX_STATS
GATHER_TABLE_STATS
GATHER_SCHEMA_STATS
GATHER_DICTIONARY_STATS
GATHER_DATABASE_STATS
GATHER_SYSTEM_STATS
Monitoring objects for mass data manipulation language (DML) operations and gathering
statistics if necessary
Optimizer Statistics
Chapter 10 - Page 30
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
,'default'
-- granularity
, true );
-- cascade to indexes
dbms_stats.set_param('CASCADE',
'DBMS_STATS.AUTO_CASCADE');
dbms_stats.set_param('ESTIMATE_PERCENT','5');
dbms_stats.set_param('DEGREE','NULL');
Optimizer Statistics
Chapter 10 - Page 31
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Estimate table cardinality for tables and relevant indexes without statistics or for tables
whose statistics are too outdated to be reliable
Optimizer Statistics
Chapter 10 - Page 32
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The sampling time is a small fraction of total execution time for the query.
Note: Dynamic sampling can be applied to a subset of a single tables predicates and
combined with standard selectivity estimates of predicates for which dynamic sampling is not
done.
Optimizer Statistics
Chapter 10 - Page 33
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
OPTIMIZER_DYNAMIC_SAMPLING
OPTIMIZER_DYNAMIC_SAMPLING
You control dynamic sampling with the OPTIMIZER_DYNAMIC_SAMPLING parameter, which can
be set to a value from "0" to "10." A value of "0" means dynamic sampling is not done.
A value of "1" means dynamic sampling is performed on all unanalyzed tables if the following
criteria are met:
This unanalyzed table has more blocks than the default number of blocks that would be
used for dynamic sampling of this table. This default number is 32.
Optimizer Statistics
Chapter 10 - Page 34
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
OPTIMIZER_DYNAMIC_SAMPLING
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: Dynamic sampling is repeatable if no rows have been inserted, deleted, or updated in
the table being sampled since the previous sample operation.
Optimizer Statistics
Chapter 10 - Page 35
Locking Statistics
Locking Statistics
Starting with Oracle Database 10g, you can lock statistics on a specified table with the
LOCK_TABLE_STATS procedure of the DBMS_STATS package. You can lock statistics on a
table without statistics or set them to NULL using the DELETE_*_STATS procedures to
prevent automatic statistics collection so that you can use dynamic sampling on a volatile
table with no statistic. You can also lock statistics on a volatile table at a point when it is fully
populated so that the table statistics are more representative of the table population.
You can also lock statistics at the schema level by using the LOCK_SCHEMA_STATS
procedure. You can query the STATTYPE_LOCKED column in the {USER | ALL |
DBA}_TAB_STATISTICS view to determine whether the statistics on the table are locked.
You can use the UNLOCK_TABLE_STATS procedure to unlock the statistics on a specified
table.
You can set the value of the FORCE parameter to TRUE to overwrite the statistics even if they
are locked. The FORCE argument is found in the following DBMS_STATS procedures:
DELETE_*_STATS, IMPORT_*_STATS, RESTORE_*_STATS, and SET_*_STATS.
Note: When you lock the statistics on a table, all the dependent statistics are considered
locked. This includes table statistics, column statistics, histograms, and dependent index
statistics.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
Optimizer Statistics
Chapter 10 - Page 36
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Locking Statistics
Restoring Statistics
BEGIN
DBMS_STATS.RESTORE_TABLE_STATS(
OWNNAME=>'OE', TABNAME=>'INVENTORIES',
AS_OF_TIMESTAMP=>'15-JUL-10 09.28.01.597526000 AM -05:00');
END;
Restoring Statistics
Old versions of statistics are saved automatically whenever statistics in dictionary are modified
with the DBMS_STATS procedures. You can restore statistics using RESTORE procedures of
DBMS_STATS package. These procedures use a time stamp as an argument and restore
statistics as of that time stamp. This is useful when newly collected statistics lead to suboptimal execution plans and the administrator wants to revert to the previous set of statistics.
Note: the ANALYZE command does not store old statistics.
There are dictionary views that can be used to determine the time stamp for restoration of
statistics. The views *_TAB_STATS_HISTORY views (ALL, DBA, or USER) contain a history of
table statistics modifications. For the example in the slide the timestamp was determined by:
select stats_update_time from dba_tab_stats_history
where table_name = 'INVENTORIES'
The database purges old statistics automatically at regular intervals based on the statistics
history retention setting and the time of the recent analysis of the system. You can configure
retention using the DBMS_STATS .ALTER_STATS_HISTORY_RETENTION procedure. The
default value is 31 days, which means that you would be able to restore the optimizer
statistics to any time in last 31 days.
Optimizer Statistics
Chapter 10 - Page 37
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Restoring Statistics
EXPORT_*_STATS
IMPORT_*_STATS
Optimizer Statistics
Chapter 10 - Page 38
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
When there are no statistics for an object being used in a SQL
statement, the optimizer uses:
a. Rule-based optimization
b. Dynamic sampling
c. Fixed values
d. Statistics gathered during parse phase
e. Random values
Answer: b, c
Optimizer Statistics
Chapter 10 - Page 39
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The optimizer depends on accurate statistics to produce the
best execution plans. The automatic statistics gathering (AGS)
task does not gather statistics on everything. Which objects
require you to gather statistics manually?
a. External tables
b. Data dictionary
c. Fixed objects
d. Volatile tables
e. System statistics
Answer: a, c, e
Optimizer Statistics
Chapter 10 - Page 40
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
There is a very volatile table in the database. The size of the
table changes by more than 50% daily. What steps are part of
the procedure to force dynamic sampling?
a. Delete statistics.
b. Lock statistics.
c. Gather statistics when the table is at its largest.
d. Set DYNAMIC_SAMPLING=9.
e. Set DYNAMIC_SAMPLING=0.
f. Allow the DYNAMIC_SAMPLING parameter to default.
Answer: a, b, f
Optimizer Statistics
Chapter 10 - Page 41
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
Collect optimizer statistics
Collect system statistics
Set statistic preferences
Use dynamic sampling
Manipulate optimizer statistics
Optimizer Statistics
Chapter 10 - Page 42
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Statistics
Chapter 10 - Page 43
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Optimizer Statistics
Chapter 10 - Page 44
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 11
Chapter 11 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 11 - Page 2
Objectives
After completing this lesson, you should be able to:
List the benefits of using bind variables
Use bind peeking
Use adaptive cursor sharing
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Cursor sharing
Library cache
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: In the case of the example in the slide, V$SQL.PLAN_HASH_VALUE is identical for the
first and third query.
18000
17500
Cursor sharing
Library cache
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
12000
First time
you execute
Plan A
min_sal=12000
Next time
you execute
18000
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
min_sal=12000
min_sal=18000
min_sal=7500
Plan A
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The substitution of any value would produce the same execution plan. It would, therefore, be
safe for the optimizer to generate only one plan for different occurrences of the same
statement executed with different literal values.
On the other hand, assume that the same EMPLOYEES table has a wide range of values in its
DEPARTMENT_ID column. For example, department 50 could contain over one third of all
employees and department 70 could contain just one or two.
See the two queries:
SQL> SELECT * FROM employees WHERE department_id = 50;
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Using only one execution plan for sharing the same cursor would not be safe if you have
histogram statistics (and there is skew in the data) on the DEPARTMENT_ID column. In this
case, depending on which statement was executed first, the execution plan could contain a
full table (or fast full index) scan, or it could use a simple index range scan.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
In earlier releases, you could select only the EXACT or the FORCE option. Setting the value to
SIMILAR causes the optimizer to examine the statement to ensure that replacement occurs
only for safe literals. It can then use information about the nature of any available index
(unique or nonunique) and statistics collected on the index or underlying table, including
histograms.
The value of CURSOR_SHARING in the initialization file can be overridden with an ALTER
SYSTEM SET CURSOR_SHARING or an ALTER SESSION SET CURSOR_SHARING
command.
The CURSOR_SHARING_EXACT hint causes the system to execute the SQL statement without
any attempt to replace literals by bind variables.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
System-generated
bind variable
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
System
observes
statement
for a while.
Bind-aware cursor
Initial selectivity cube
Initial plan
GB
0.0025
HJ
P
a
r
s
e
GB
HJ
0.003
0.15
P
a
r
s
e
0.004
HJ
0.18
H
a
r
d
No need
for new plan
HJ
11
No need
for new plan
GB
GB
HJ
HJ
HJ
HJ
Cubes merged
0.009
GB
GB
HJ
HJ
HJ
P
a
r
s
e
0.28
HJ
0.3
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
3. On the next soft parse of this query, suppose that the selectivity of the predicate with the
new set of bind values is now (0.3,0.009). Because that selectivity is not within an
existing cube, no child cursor match is found. So the system does a hard parse, which
generates a new child cursor with a second execution plan in that case. In addition, the
new selectivity cube is stored as part of the new child cursor. After the new child cursor
executes, the system stores the bind values and execution statistics in the cursor.
4. On the next soft parse of this query, suppose the selectivity of the predicate with the new
set of bind values is now (0.28,0.004). Because that selectivity is not within one of the
existing cubes, the system does a hard parse. Suppose that this time, the hard parse
generates the same execution plan as the first one. Because the plan is the same as the
first child cursor, both child cursors are merged. That is, both cubes are merged into a
new bigger cube, and one of the child cursors is deleted. The next time there is a soft
parse, if the selectivity falls within the new cube, the child cursor matches.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
matching, and because the selectivity is within an existing cube, the statement uses the
existing child cursors execution plan to run.
V$SQL_CS_HISTOGRAM
V$SQL_CS_SELECTIVITY
V$SQL_CS_STATISTICS
IS_BIND_SENSITIVE: Indicates if a cursor is bind sensitive; value YES | NO. A query for
which the optimizer peeked at bind variable values when computing predicate
selectivities and where a change in a bind variable value may lead to a different plan is
called bind sensitive.
IS_BIND_AWARE: Indicates if a cursor is bind aware; value YES | NO. A cursor in the
cursor cache that has been marked to use bind-aware cursor sharing is called bind
aware.
V$SQL_CS_HISTOGRAM: Shows the distribution of the execution count across a threebucket execution history histogram.
V$SQL_CS_SELECTIVITY: Shows the selectivity cubes or ranges stored in a cursor for
every predicate containing a bind variable and whose selectivity is used in the cursor
sharing checks. It contains the text of the predicates and the selectivity range low and
high values.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Plan A
'SA_REP'
Plan B
'AD_ASST'
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
CURSOR_SHARING:
If CURSOR_SHARING <> EXACT, statements containing
literals may be rewritten using bind variables.
If statements are rewritten, adaptive cursor sharing may
apply to them.
When using the SPM automatic plan capture, the first plan captured for a SQL statement
with bind variables is marked as the corresponding SQL plan baseline. If another plan is
found for that same SQL statement (which maybe the case with adaptive cursor
sharing), it is added to the SQL statements plan history and marked for verification. It will
not be used immediately. So even though adaptive cursor sharing has come up with a
new plan based on a new set of bind values, SPM does not let it be used until the plan
has been verified. Thus reverting to10g behavior, only the plan generated based on the
first set of bind values is used by all subsequent executions of the statement. One
possible workaround is to run the system for some time with automatic plan capture set
to False, and after the cursor cache has been populated with all the plans a SQL
statement with bind has, load the entire plan directly from the cursor cache into the
corresponding SQL plan baseline. By doing this, all the plans for a single SQL statement
are marked as SQL baseline plans by default. Refer to the lesson titled "SQL Plan
Management" for more information.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Which three statements are true about applications that are
coded with literals in the SQL statements rather than bind
variables?
a. More shared pool space is required for cursors.
b. Less shared pool space is required for cursors.
c. Histograms are used if available.
d. Histograms are not used.
e. No parsing is required for literal values.
f. Every different literal value requires parsing.
Answer: a, c, f
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The CURSOR_SHARING parameter should be set to ________
for systems with large tables and long-running queries such as
a data warehouse.
a. Similar
b. Force
c. Exact
d. Literal
e. True
f. False
Answer: c
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
Adaptive Cursor Sharing can be turned off by setting the
CURSOR_SHARING parameter to FALSE.
a. True
b. False
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Answer: b
Summary
In this lesson, you should have learned how to:
List the benefits of using bind variables
Use bind peeking
Use adaptive cursor sharing
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 11 - Page 28
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 12
Chapter 12 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 12 - Page 2
Objectives
After completing this lesson, you should be able to do the
following:
Describe statement profiling
Use SQL Tuning Advisor
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
In the normal mode, the optimizer compiles SQL and generates an execution plan. The
normal mode of the optimizer generates a reasonable execution plan for the vast
majority of SQL statements. In the normal mode, the optimizer operates with very strict
time constraints, usually a fraction of a second, during which it must find a good
execution plan.
In the tuning mode, the optimizer performs additional analysis to check whether the
execution plan produced under the normal mode can be further improved. The output of
the query optimizer in the tuning mode is not an execution plan, but a series of actions,
along with their rationale and expected benefit (for producing a significantly superior
plan). When called under tuning mode, the optimizer is referred to as Automatic Tuning
Optimizer (ATO). The tuning performed by ATO is called system SQL tuning.
Under the tuning mode, the optimizer can take several minutes to tune a single statement.
ATO is meant to be used for complex and high-load SQL statements that have a nontrivial
impact on the entire system.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
How can I
tune my
high-load
SQL?
I can do
it for you!
SQL workload
ADDM
High-load
SQL
SQL Tuning
Advisor
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Statistics Check
optimization
mode
Detect stale or
missing statistics.
Plan Tuning
optimization
mode
Plan tuning
(SQL Profile).
Access Analysis
optimization
mode
SQL Analysis
optimization
mode
SQL Tuning
Advisor
Automatic Tuning
Optimizer
Restructure SQL.
Comprehensive
SQL tuning
Statistics Analysis: ATO checks each query object for missing or stale statistics and
makes a recommendation to gather relevant statistics. It also collects auxiliary
information to supply missing statistics or correct stale statistics in case
recommendations are not implemented.
SQL Profiling: ATO verifies its own estimates and collects auxiliary information to
remove estimation errors. It also collects auxiliary information in the form of customized
optimizer settings, such as first rows and all rows, based on the past execution history of
the SQL statement. It builds a SQL Profile using the auxiliary information and makes a
recommendation to create it. When a SQL Profile is created, the profile enables the
query optimizer, under normal mode, to generate a well-tuned plan.
Access Path Analysis: ATO explores whether a new index can be used to significantly
improve access to each table in the query, and when appropriate makes
recommendations to create such indexes.
SQL Structure Analysis: Here, ATO tries to identify SQL statements that lend
themselves to bad plans, and makes relevant suggestions to restructure them. The
suggested restructuring can be syntactic as well as semantic changes to the SQL code.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Auxiliary information in the form of statistics for objects with no statistics, and statistic
adjustment factor for objects with stale statistics
For optimal results, you gather statistics when recommended and then rerun Automatic
Tuning Optimizer. However, you may be hesitant to accept this recommendation immediately
because of the impact it could have on other queries in the system.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Submit
Optimizer
Create
(Tuning mode)
SQL Tuning
Advisor
SQL
Profile
Use
No application
code change Optimizer
Output
(Normal mode)
Database
users
Well-tuned
plan
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Workload
Generate
profiles
High load
SQL Tuning
Advisor
ADDM
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Significant
performance
gain
SQL
Access
Advisor
Workload
Comprehensive
index
analysis
Indexes
Indexes
CREATE INDEX JFV.IDX$_00002 on JFV.TEST("C");
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Poorly written
SQL statement
How can I
rewrite it?
Restructured
SQL statement
SQL constructs
Type mismatch and
indexes
SQL Tuning
Advisor
Design mistakes
Use of SQL constructors such as NOT IN instead of NOT EXISTS, or UNION instead of
UNION ALL
Use of predicates involving indexed columns with data-type mismatch that prevents the
use of the index
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
ADDM
High-load SQL
Sources
AWR
Manual Selection
SQL
Tuning
Advisor
Cursor cache
Filter
Custom
SQL statements from Automatic Workload Repository (AWR): A user can select any set
of SQL statements captured by AWR. This can be done using snapshots or baselines.
SQL statements from cursor cache, AWR, and custom workload can be filtered and ranked
before they are input to SQL Tuning Advisor.
For a multistatement input, an object called SQL Tuning Set (STS) is provided. An STS stores
multiple SQL statements along with their execution information:
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Tuning ADDM-identified SQL statements: The ADDM Finding Details page shows
high-load SQL statements identified by ADDM. Each of these high-load SQL statements
is known to consume a significant proportion of one or more system resources. You can
use this page to launch SQL Tuning Advisor on a selected high-load SQL statement.
Tuning top SQL statements: Another SQL source is the list of top SQL statements.
This is shown in the slide. You can identify the list of top SQL statements by looking at
their cumulative execution statistics based on a selected time window. The user can
select one or more top SQL statements identified by their SQL IDs, and then click
Schedule SQL Tuning Advisor.
Tuning a SQL Tuning Set: It is also possible to look at various STSs created by
different users. An STS could have been created from a list of top SQL statements, by
selecting SQL statements from a range of snapshots created by AWR, or by selecting
customized SQL statements.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Implementing Recommendations
Implementing Recommendations
On the recommendations page, you can view the various recommendations. For each
recommendation, as shown, a SQL Profile has been created; you can implement it if you
want, after you view the new plan. Click the eyeglass icon to view the Compare Explain Plan
page.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Implementing Recommendations
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
SQL Tuning Advisor will recommend:
a. SQL Profiles
b. Additional Indexes
c. Deleting Indexes
d. Rewriting SQL Statements
e. All of the above
Answer: a, b, d
SQL Tuning Advisor in comprehensive mode recommends all except deleting indexes. SQL
Tuning Advisor focuses on one SQL statement at a time. An entire workload must be
considered to determine if deleting an index will help performance.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
The SQL Profile will force the best execution plan even when
the data in the table changes.
a. True
b. False
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned the following:
Statement profiling
SQL Tuning Advisor
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 13
Chapter 13 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 13 - Page 2
Objectives
After completing this lesson, you should be able to use SQL
Access Advisor.
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Solution
SQL
Access
Advisor
No expertise
required
Workload
Component
of CBO
Provides
implementation
script
Bases decision making on rules that actually reside in the cost-based optimizer (CBO)
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Hypothetical
STS
Filter
Options
Indexes
Materialized
views
Materialized Partitioned
views log
objects
Hypothetical, to generate a likely workload from your dimensional model. This option is
interesting when your system is being initially designed.
SQL Access Advisor also provides powerful workload filters that you can use to target the
tuning. For example, a user can specify that the advisor should look at only the 30 most
resource-intensive statements in the workload, based on optimizer cost. For the given
workload, the advisor then does the following:
Optimizes materialized views for maximum query rewrite usage and fast refresh
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Possible Recommendations
Recommendation
Comprehensive
Limited
YES
YES
YES
NO
YES
NO
YES
YES
YES
YES
YES
NO
YES
YES
YES
YES
YES
YES
Possible Recommendations
SQL Access Advisor carefully considers the overall impact of recommendations and makes
recommendations by using only the known workload and supplied information. Two workload
analysis methods are available:
Comprehensive: With this approach, SQL Access Advisor addresses all aspects of
tuning partitions, materialized views, indexes, and materialized view logs. It assumes
that the workload contains a complete and representative set of application SQL
statements.
When comprehensive workload analysis is chosen, SQL Access Advisor forms a better set of
global tuning adjustments, but the effect may be a longer analysis time. As shown in the table,
the chosen workload approach determines the type of recommendations made by the advisor.
Note: Partition recommendations can work on only those tables that have at least 10,000
rows, and workloads that have some predicates and joins on columns of the NUMBER or DATE
type. Partitioning recommendations can be generated only on these types of columns. In
addition, partitioning recommendations can be generated only for single-column interval and
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Possible Recommendations
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
hash partitions. Interval partitioning recommendations can be output as range syntax, but
interval is the default. Hash partitioning is done to leverage only partitionwise joins.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Current and Recent SQL Activity: This source corresponds to SQL statements that
are still cached in your System Global Area (SGA).
Use an existing SQL Tuning Set: You also have the possibility of creating and using a
SQL Tuning Set that holds your statements.
Hypothetical Workload: This option provides a schema that allows the advisor to
search for dimension tables and produce a workload. This is very useful to initially
design your schema.
Using the Filter Options section, you can further filter your workload source. Filter options are:
Users
Tables
SQL Text
Module IDs
Actions
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
You can also schedule the implementation of the recommendations by clicking the Schedule
Implementation button.
Quiz
Identify two available workload analysis methods.
a. Comprehensive
b. Complete
c. Partial
d. Limited
Answer: a, d
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Quiz
SQL Access Advisor identifies but cannot help resolve
performance problems relating to the execution of SQL
statements.
a. True
b. False
Answer: b
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned to use SQL Access
Advisor.
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 13 - Page 22
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 14
Chapter 14 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 14 - Page 2
Objectives
After completing this lesson, you should be able to use
Automatic SQL Tuning.
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
Automatic
High load
SQL Tuning
Advisor
4
Generate
SQL profiles.
ADDM
3
Run SQL Tuning Advisor.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Top SQL
Auto matic
Workload
3
1
SQL Tuning
Reports
Step 1: Based on the AWR Top SQL identification (SQLs that were top in four different
time periods: the past week, any day in the past week, any hour in the past week, or
single response time), Automatic SQL Tuning targets for automatic tuning.
Steps 2 and 3: While the Automatic SQL Tuning task executes during the maintenance
window, the previously identified SQL statements are automatically tuned by invoking
SQL Tuning Advisor. As a result, SQL profiles are created for them if needed. However,
before making any decision, the new profile is carefully tested.
Step 4: At any point in time, you can request a report about these automatic tuning
activities. You then have the option of checking the tuned SQL statements to validate or
remove the automatic SQL profiles that were generated.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Considered for
auto implementation
New
SQL profile
Restructure
SQL.
Existing
profile?
Indexes
3X
benefit?
Accept profile
N
Y
3X
benefit?
Stale
stats
Replace profile.
GATHER_STATS_JOB
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
B. When a SQL profile is generated and it causes the optimizer to pick a different
execution plan for the statement, the advisor must decide whether to implement the
SQL profile. It makes its decision according to the flowchart in the slide. Although
the benefit thresholds here apply to the sum of CPU and input/output (I/O) time, SQL
profiles are not accepted when there is degradation in either statistic. So the
requirement is that there is a three-time improvement in the sum of CPU and I/O
time, with neither statistic becoming worse. In this way, the statement runs faster
than it would without the profile, even with contention in CPU or I/O.
3. If stale or missing statistics are found, make this information available to
GATHER_STATS_JOB.
Automatic implementation of tuning recommendations is limited to SQL profiles because they
have fewer risks. It is easy for you to reverse the implementation.
Note: All SQL profiles are created in the standard EXACT mode. They are matched and
tracked according to the current value of the CURSOR_SHARING parameter. You are
responsible for setting CURSOR_SHARING appropriately for your workload.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
A. Test the new SQL profile by executing the statement with and without it.
Autotask configuration:
On/off switch
Maintenance windows running tuning task
CPU resource consumption of tuning task
Task parameters:
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Ad hoc or rarely repeated SQL statements: If a SQL statement is not executed multiple
times in the same form, the advisor ignores it. SQL statements that do not repeat within
a week are also not considered.
Parallel queries
Long-running queries (after creating a profile): If a query takes too long to run after being
SQL profiled, it is not practical to test-execute and, therefore, it is ignored by the advisor.
Note that this does not mean that the advisor ignores all long-running queries. If the
advisor can find a SQL profile that causes a query that once took hours to run in
minutes, it could be accepted because test-execution is still possible. The advisor would
execute the old plan just long enough to determine that it is worse than the new one, and
then would terminate test-execution without waiting for the old plan to finish, thereby
switching the order of execution.
With the exception of truly ad hoc SQL, these limitations apply to Automatic SQL Tuning only.
Such statements can still be tuned by manually running SQL Tuning Advisor.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
In the maintenance window, an Automatic SQL Tuning task will
run by default. Which two actions will this task perform by
default?
a. Prioritizes and tunes the SQL statements with the top
resource consumption
b. Works on each statement for a maximum of 30 minutes
c. Stops when all SQL statements are tuned, or when the
window closes
d. Automatically implements any recommended SQL profiles
Answer: a, c
The default settings for Automatic SQL Tuning task is to tune the top SQL statements after
prioritizing them based on the AWR Top SQL identification (SQLs that were top in four
different time periods: the past week, any day in the past week, any hour in the past week, or
single response time).
The time limit is 1200 seconds per statement by default (20 minutes).
Work must stop when the window closes. If any SQL statements remain, they must wait for
the next maintenance window.
Any SQL profiles that are generated are not implemented by default, but you can change the
configuration so that they are automatically implemented.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned to use Automatic SQL
Tuning
Oracle University and InfoTech (Pvt.) Ltd use only
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 14 - Page 18
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 15
Chapter 15 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 15 - Page 2
Objectives
After completing this lesson, you should be able to:
Manage SQL performance through changes
Set up SQL Plan Management
Set up various SQL Plan Management scenarios
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The plan baseline can be seeded for critical SQL with SQL
tuning set (STS) from SQL Performance Analyzer.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The main benefit of the SQL Plan Management feature is performance stability of the system
by avoiding plan regressions. In addition, it saves the DBA time that is often spent in
identifying and analyzing SQL performance regressions and finding workable solutions.
Plan history
Repeatable
SQL
statement
SQL
profile
Plan
baseline
GB
GB
HJ
HJ
HJ
HJ
GB
HJ
HJ
Automatic
SQL tuning
task
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The statement log, plan history, and plan baselines are stored in the SQL management base
(SMB), which also contains SQL profiles. The SMB is part of the database dictionary and is
stored in the SYSAUX tablespace. The SMB has automatic space management (for example,
periodic purging of unused plans). You can configure the SMB to change the plan retention
policy and set space size limits.
Note: With Oracle Database 11g, if the database instance is up but the SYSAUX tablespace is
OFFLINE, the optimizer is unable to access SQL management objects. This can affect
performance on some of the SQL workload.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
plan. A set of acceptable plans constitutes a SQL plan baseline. The very first plan generated
for a SQL statement is obviously acceptable for use; therefore, it forms the original plan
baseline. Any new plans subsequently found by the optimizer are part of the plan history but
not part of the plan baseline initially.
dbms_spm
Plan history
Plan history
GB
HJ
HJ
GB
HJ
HJ
GB
HJ
HJ
GB
HJ
HJ
Plan history
Cursor
cache
GB
HJ
HJ
Staging
table
DBA
Bulk loading: Uses the DBMS_SPM package, which enables you to manually manage
SQL plan baselines. With procedures from this package, you can load SQL plans into a
SQL plan baseline directly from the cursor cache ( A ) using
LOAD_PLANS_FROM_CURSOR_CACHE or from an existing SQL tuning set (STS) (B)
using LOAD_PLANS_FROM_SQLSET. For a SQL statement to be loaded into a SQL plan
baseline from an STS, the plan for the SQL statement needs to be stored in the STS.
DBMS_SPM.ALTER_SQL_PLAN_BASELINE enables you to enable and disable a
baseline plan and change other plan attributes. To move baselines between databases,
use the DBMS_SPM.*_STGTAB_BASELINE procedures to create a staging table, and to
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
export and import baseline plans from a staging table. The staging table can be moved
between databases using the Data Pump Export and Import utilities.
Plan history
Automatic
SQL Tuning
GB
HJ
HJ
DBA
GB
HJ
HJ
>?
SQL
Tuning
Advisor
By running SQL Tuning Advisor: SQL plan baselines can be evolved by manually or
automatically tuning SQL statements using SQL Tuning Advisor. When SQL Tuning
Advisor finds a tuned plan and verifies its performance to be better than a plan chosen
from the corresponding SQL plan baseline, it makes a recommendation to accept a SQL
profile. When the SQL profile is accepted, the tuned plan is added to the corresponding
SQL plan baseline.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Enabled but
not accepted
GB
GB
HJ
HJ
HJ
HJ
Enabled and
accepted
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: The DBA_SQL_PLAN_BASELINES view contains additional attributes that enable you to
determine when each plan was last used and whether a plan should be automatically purged.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
optimizer uses only the best plan from these three, ignoring all the others. A SQL plan
baseline is said to be FIXED if it contains at least one enabled fixed plan. If new plans
are added to a fixed SQL plan baseline, these new plans cannot be used until they are
manually declared as FIXED. You can look at each plans attributes by using the
DBA_SQL_PLAN_BASELINES view, as shown in the slide. You can then use the
DBMS_SPM.ALTER_SQL_PLAN_BASELINE function to change some of them. You can
also remove plans or a complete plan history by using the
DBMS_SPM.DROP_SQL_PLAN_BASELINE function. The example shown in the slide
changes the ENABLED attribute of SQL_PLAN_6zsnd8f6zsd9g54bc8843 to NO.
optimizer_use_sql_
plan_baselines=true?
HJ
Yes
Plan part
of history?
No
Plan history
Yes
No
GB
GB
HJ
HJ
HJ
Plan part
of baseline?
Yes
HJ
Plan
baseline
GB
HJ
HJ
GB
HJ
HJ
No
Select baseline plan
with lowest best cost.
GB
HJ
Yes
HJ
GB
HJ
GB
<
HJ
HJ
HJ
No
GB
HJ
HJ
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Production database
Plan history
Plan history
GB
GB
GB
GB
HJ
HJ
HJ
HJ
HJ
HJ
HJ
HJ
No plan
regressions
No plan
regressions
DBA
DBA
Plan history
Well- GB
tuned HJ
plan
HJ
GB
GB
HJ
HJ
HJ
HJ
Well-tuned
plan
Baseline
plans
staging table
Development database
Database upgrade: Bulk SQL plan loading is especially useful when the system is
being upgraded from an earlier version to Oracle Database 11g. For this, you can
capture plans for a SQL workload into a SQL tuning set (STS) before the upgrade, and
then load these plans from the STS into the SQL plan baseline immediately after the
upgrade. This strategy can minimize plan regressions resulting from the use of the new
optimizer version.
New application deployment: The deployment of a new application module means the
introduction of new SQL statements into the system. The software vendor can ship the
application software along with the appropriate SQL plan baselines for the new SQL
being introduced. Because of the plan baselines, the new SQL statements will initially
run with the plans that are known to give good performance under a standard test
configuration. However, if the customer system configuration is very different from the
test configuration, the plan baselines can be evolved over time to produce better
performance.
In both scenarios, you can use the automatic SQL plan capture after manual loading to make
sure that only better plans will be used for your applications in the future.
Note: In all scenarios in this lesson, assume that OPTIMIZER_USE_SQL_PLAN_BASELINES
is set to TRUE.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
O_F_E=10
GB
HJ
HJ
HJ
Regressing
statements
HJ
No plan
regressions
After O_F_E=11
change
optimizer_features_enable
GB
GB
GB
HJ
HJ
HJ
HJ
HJ
HJ
Well-tuned
plans
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
No plan
regressions
Plan history
Plan
baseline
GB
GB
HJ
HJ
HJ
HJ
Plan history
Plan
baseline
GB
GB
HJ
HJ
GB
HJ
HJ
HJ
HJ
optimizer_features_enable=10.2.0.2
optimizer_capture_sql_plan_baselines=true
No plan
regressions
optimizer_features_enable=11.1.0.1
optimizer_capture_sql_plan_baselines=true
Better
plans
Plan history
Plan baseline
GB
HJ
HJ
GB
HJ
HJ
Welltuned
plans
GB
GB
GB
HJ
HJ
HJ
HJ
HJ
HJ
optimizer_features_enable=11.1.0.1
optimizer_capture_sql_plan_baselines=true
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
DBA_SQL_MANAGEMENT_CONFIG
time
105
Alert log
SQL Management
Base
SYSAUX
53
1%
10%
20%
50%
space
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
When the OPTIMIZER_USE_SQL_PLAN_BASELINES
parameter is set to TRUE, the optimizer:
a. Does not develop an execution plan; it uses an accepted
plan in the baselines
b. Compares the plan it develops with accepted plans in the
baselines
c. Compares the plan it develops with enabled plans in the
baselines
d. Does not develop an execution plan; it uses enabled plans
in the baselines
e. Develops plans and adds them to the baselines as verified
Answer: b
The optimizer always develops an execution plan. Then it compares the plan with accepted
plans in the SQL baseline. If an accepted baseline exists, the baseline is used. If the plan
developed by the optimizer is different, it is stored in the plan history, but it is not part of the
baseline until it is verified and marked as accepted.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Quiz
Summary
In this lesson, you should have learned how to:
Manage SQL performance through changes
Set up SQL Plan Management
Set up various SQL Plan Management scenarios
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 15 - Page 24
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 16
Chapter 16 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 16 - Page 2
Objectives
After completing this lesson, you should be able to :
Use hints when appropriate
Specify hints for:
Optimizer mode
Query transformation
Access path
Join orders
Join methods
Views
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Types of Hints
Single-table hints
Multitable hints
Statement hints
Types of Hints
Single-table: Single-table hints are specified on one table or view. INDEX and USE_NL are
examples of single-table hints.
Multitable: Multitable hints are like single-table hints, except that the hint can specify one or
more tables or views. LEADING is an example of a multitable hint.
Query block: Query block hints operate on single query blocks. STAR_TRANSFORMATION
and UNNEST are examples of query block hints.
Statement: Statement hints apply to the entire SQL statement. ALL_ROWS is an example of a
statement hint.
Note: USE_NL(table1 table2) is not considered a multitable hint because it is actually a
shortcut for USE_NL(table1) and USE_NL(table2).
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Types of Hints
Specifying Hints
Hints apply to the optimization of only one statement block:
A self-contained DML statement against a table
A top-level DML or a subquery
MERGE
SELECT
INSERT
/*+
hint
*/
comment
text
UPDATE
DELETE
MERGE
SELECT
INSERT
UPDATE
--+
hint
comment
text
DELETE
Specifying Hints
Hints apply to the optimization of only the block of the statement in which they appear. A
statement block is:
For example, a compound query consisting of two component queries combined by the
UNION operator has two blocks, one for each component query. For this reason, hints in the
first component query apply only to its optimization, not to the optimization of the second
component query.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Specifying Hints
You must place the hint comment immediately after the first keyword (MERGE, SELECT,
INSERT, DELETE, or UPDATE) of a SQL statement block.
A statement block can have only one comment containing hints, but it can contain many
hints inside that comment separated by spaces.
Hints apply to only the statement block in which they appear and override instance- or
session-level parameters.
If a SQL statement uses aliases, hints must reference the aliases rather than the table
names.
The Oracle optimizer ignores incorrectly specified hints. However, be aware of the following
situations:
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Hint Recommendations
Hint Recommendations
Hints may prevent the optimizer from using better execution plans.
Hints may become less valid (or even invalid) when the database structure or contents
change.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Hint Recommendations
UPDATE OF 'PRODUCTS'
TABLE ACCESS (BY INDEX ROWID) OF 'PRODUCTS' (TABLE) (Cost)
INDEX (RANGE SCAN) OF 'PRODUCTS_PROD_CAT_IX' (INDEX)
(cost)
4
5
1
4
The hint shown in the example works only if an index called PRODUCTS_PROD_CAT_IX exists
on the PRODUCTS table in the PROD_CATEGORY column.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Hint Categories
There are hints for:
Optimization approaches and goals
Access paths
Query transformations
Join orders
Join operation
Parallel execution
Additional hints
Hint Categories
Most of these hints are discussed in the following slides. Many of these hints accept the table
and index names as arguments.
Note: Hints for parallel execution is not covered in this course.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Hint Categories
ALL_ROWS
FIRST_ROWS(n)
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Note: The FIRST_ROWS hints are probably the most useful hints.
Chapter 16 - Page 12
FULL
CLUSTER
HASH
ROWID
INDEX
INDEX_ASC
INDEX_COMBINE
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
INDEX: The INDEX hint explicitly chooses an index scan for the specified table. You can use
the INDEX hint for domain, B*-tree, bitmap, and bitmap join indexes. However, it is better if
you use INDEX_COMBINE rather than INDEX for bitmap indexes because it is a more versatile
hint. This hint can optionally specify one or more indexes.
If this hint specifies a single available index, the optimizer performs a scan on this index. The
optimizer does not consider a full table scan or a scan on another index on the table.
If this hint specifies a list of available indexes, the optimizer considers the cost of a scan on
each index in the list and then performs the index scan with the lowest cost. The optimizer can
also choose to scan multiple indexes from this list and merge the results, if such an access
path has the lowest cost. The optimizer does not consider a full table scan or a scan on an
index not listed in the hint.
If this hint specifies no indexes, the optimizer considers the cost of a scan on each available
index on the table and then performs the index scan with the lowest cost. The optimizer can
also choose to scan multiple indexes and merge the results, if such an access path has the
lowest cost. The optimizer does not consider a full table scan.
INDEX_ASC: The INDEX_ASC hint explicitly chooses an index scan for the specified table. If
the statement uses an index range scan, the Oracle server scans the index entries in
ascending order of their indexed values. Because the servers default behavior for a range
scan is to scan index entries in the ascending order of their indexed values, this hint does not
specify anything more than the INDEX hint. However, you might want to use the INDEX_ASC
hint to specify ascending range scans explicitly, should the default behavior change.
INDEX_COMBINE: The INDEX_COMBINE hint explicitly chooses a bitmap access path for the
table. If no indexes are given as arguments for the INDEX_COMBINE hint, the optimizer uses a
Boolean combination of bitmap indexes that has the best cost estimate for the table. If certain
indexes are given as arguments, the optimizer tries to use some Boolean combination of
those particular bitmap indexes.
For example:
SELECT /*+INDEX_COMBINE(customers cust_gender_bix cust_yob_bix)*/ *
FROM customers WHERE cust_year_of_birth < 70 AND cust_gender = 'M';
Note: For INDEX, INDEX_FFS, and INDEX_SS, there are counter hints, NO_INDEX,
NO_INDEX_FFS, and NO_INDEX_SS, respectively to avoid using those paths.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
ROWID: The ROWID hint explicitly chooses a table scan by ROWID for the specified table.
INDEX_JOIN
INDEX_DESC
INDEX_FFS
INDEX_SS
NO_INDEX
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
INDEX_FFS: The INDEX_FFS hint causes a fast-full index scan to be performed rather than a
full table scan.
For example:
SELECT /*+ INDEX_FFS ( o order_pk ) */ COUNT(*)
FROM order_items l, orders o
WHERE l.order_id > 50 AND l.order_id = o.order_id;
INDEX_SS: The INDEX_SS hint instructs the optimizer to perform an index skip scan for the
specified indexes of the specified table. If the statement uses an index range scan, the system
scans the index entries in the ascending order of their indexed values. In a partitioned index,
the results are in the ascending order within each partition. There are also INDEX_SS_ASC
and INDEX_SS_DESC hints.
NO_INDEX: The NO_INDEX hint explicitly disallows a set of indexes for the specified table.
If this hint specifies a single available index, the optimizer does not consider a scan on
this index. Other indexes that are not specified are still considered.
If this hint specifies a list of available indexes, the optimizer does not consider a scan on
any of the specified indexes. Other indexes that are not specified in the list are still
considered.
If this hint specifies no indexes, the optimizer does not consider a scan on any index on
the table. This behavior is the same as a NO_INDEX hint that specifies a list of all
available indexes for the table.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
SELECT /*+INDEX_COMBINE(CUSTOMERS)*/
cust_last_name
FROM SH.CUSTOMERS
WHERE ( CUST_GENDER= 'F' AND
CUST_MARITAL_STATUS = 'single')
OR
CUST_YEAR_OF_BIRTH BETWEEN '1917'
AND '1920';
If certain indexes are given as arguments for the hint, the optimizer tries to use some
combination of those particular bitmap indexes.
If no indexes are named in the hint, all indexes are considered to be hinted.
The optimizer always tries to use hinted indexes, whether or not it considers them to be
cost effective.
In the example in the slide, suppose that all the three columns that are referenced in the
WHERE predicate of the statement in the slide (CUST_MARITAL_STATUS, CUST_GENDER, and
CUST_YEAR_OF_BIRTH) have a bitmap index. When you enable AUTOTRACE, the execution
plan of the statement might appear as shown in the next slide.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Execution Plan
--------------------------------------------------|
0 | SELECT STATEMENT
|
|
1 | TABLE ACCESS BY INDEX ROWID | CUSTOMERS
|
2 |
BITMAP CONVERSION TO ROWIDS |
|
3 |
BITMAP OR
|
|
4 |
BITMAP MERGE
|
|
5 |
BITMAP INDEX RANGE SCAN | CUST_YOB_BIX
|
6 |
BITMAP AND
|
|
7 |
BITMAP INDEX SINGLE VALUE| CUST_MARITAL_BIX
|
8 |
BITMAP INDEX SINGLE VALUE| CUST_GENDER_BIX
COUNT: Returns the number of entries if the actual values are not needed
BITMAP INDEX SINGLE VALUE: Looks up the bitmap for a single key
BITMAP MERGE: Merges several bitmaps resulting from a range scan into one (using a bitwise
AND operator)
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
USE_CONCAT
NO_EXPAND
Prevents OR expansions
REWRITE
NO_REWRITE
UNNEST
NO_UNNEST
NO_QUERY_TRANSFORMATION
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
MERGE
NO_MERGE
STAR_TRANSFORMATION
FACT
NO_FACT
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
FACT: The FACT hint is used in the context of the star transformation to indicate to the
transformation that the hinted table should be considered as a fact table.
NO_FACT: The NO_FACT hint is used in the context of the star transformation to indicate to the
transformation that the hinted table should not be considered as a fact table.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Even if the hint is given, there is no guarantee that the transformation will take place. The
optimizer generates the subqueries only if it seems reasonable to do so. If no subqueries are
generated, there is no transformed query, and the best plan for the untransformed query is
used regardless of the hint.
ORDERED
LEADING
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
NO_USE_NL
DRIVING_SITE
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
In many cases, a nested loop join returns the first row faster than a sort-merge join does. A
nested loop join can return the first row after reading the first selected row from one table and
the first matching row from the other and combining them. But a sort-merge join cannot return
the first row until after reading and sorting all selected rows of both tables and then combining
the first rows of each sorted row source.
In the following statement in which a nested loop is forced through a hint, orders is accessed
through a full table scan and the l.order_id = h.order_id filter condition is applied to
every row. For every row that meets the filter condition, order_items is accessed through
the index order_id.
SELECT /*+ USE_NL(l h) */ h.customer_id, l.unit_price * l.quantity
FROM oe.orders h ,oe.order_items l
WHERE l.order_id = h.order_id;
Adding an INDEX hint to the query could avoid the full table scan on orders, resulting in an
execution plan similar to one that is used on larger systems, even though it might not be
particularly efficient here.
USE_MERGE: The USE_MERGE hint causes the Oracle server to join each specified table with
another row source by using a sort-merge join, as in the following example:
SELECT /*+USE_MERGE(employees departments)*/ * FROM employees,
departments WHERE employees.department_id =
departments.department_id;
NO_USE_MERGE: The NO_USE_MERGE hint causes the optimizer to exclude the sort-merge
join to join each specified table to another row source using the specified table as the inner
table.
USE_HASH: The USE_HASH hint causes the Oracle server to join each specified table with
another row source using a hash join, as in the following example:
SELECT /*+USE_HASH(l l2) */ l.order_date, l.order_id,
l2.product_id, SUM(l2.unit_price*quantity)
FROM oe.orders l, oe.order_items l2
WHERE l.order_id = l2.order_id
GROUP BY l2.product_id, l.order_date, l.order_id;
Here is another example:
SELECT /*+use_hash(employees departments)*/ *
FROM hr.employees, hr.departments
WHERE employees.department_id = departments.department_id;
NO_USE_HASH: The NO_USE_HASH hint causes the optimizer to exclude the hash join to join
each specified table to another row source using the specified table as the inner table.
DRIVING_SITE: This hint instructs the optimizer to execute the query at a different site than
that selected by the database. This hint is useful if you are using distributed query optimization
to decide on which site a join should be executed.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
However, in some cases tables can only be joined using nested loops. In such cases, the
optimizer ignores the hint for those tables.
Additional Hints
APPEND
NOAPPEND
CURSOR_SHARING_EXACT
CACHE
PUSH_PRED
PUSH_SUBQ
DYNAMIC_SAMPLING
Additional Hints
APPEND: The APPEND hint lets you enable direct-path INSERT if your database runs in serial
mode. Your database is in serial mode if you are not using Enterprise Edition. Conventional
INSERT is the default in serial mode, and direct-path INSERT is the default in parallel mode.
In direct-path INSERT, data is appended to the end of the table rather than using existing
space currently allocated to the table. As a result, direct-path INSERT can be considerably
faster than the conventional INSERT.
Note: In Enterprise Edition, a session must be placed in parallel mode for direct-path insert to
be the default.
NOAPPEND: The NOAPPEND hint disables direct-path INSERT by disabling parallel mode for
the duration of the INSERT statement. (Conventional INSERT is the default in serial mode,
and direct-path INSERT is the default in parallel mode.)
CURSOR_SHARING_EXACT: The Oracle server can replace literals in SQL statements with
bind variables if it is safe to do so. This is controlled with the CURSOR_SHARING startup
parameter. The CURSOR_SHARING_EXACT hint causes this behavior to be disabled. In other
words, the Oracle server executes the SQL statement without any attempt to replace literals
with bind variables.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Additional Hints
The CACHE and NOCACHE hints affect system statistics table scans (long tables) and table
scans (short tables), as shown in the V$SYSSTAT data dictionary view.
PUSH_PRED: The PUSH_PRED hint instructs the optimizer to push a join predicate into the
view.
PUSH_SUBQ: The PUSH_SUBQ hint instructs the optimizer to evaluate nonmerged subqueries
at the earliest possible step in the execution plan. Generally, subqueries that are not merged
are executed as the last step in the execution plan. If the subquery is relatively inexpensive
and reduces the number of rows significantly, evaluating the subquery earlier can improve
performance. This hint has no effect if the subquery is applied to a remote table or one that is
joined using a merge join.
DYNAMIC_SAMPLING: The DYNAMIC_SAMPLING hint lets you control dynamic sampling to
improve server performance by determining more accurate selectivity and cardinality
estimates. You can set the value of DYNAMIC_SAMPLING to a value from 0 to 10. The higher
the level, the more effort the compiler puts into dynamic sampling and the more broadly it is
applied. Sampling defaults to the cursor level unless you specify a table.
Consider the following example:
SELECT /*+ dynamic_sampling(1) */ * FROM ...
This example enables dynamic sampling if all the following conditions are true:
At least one table has not been analyzed and has no indexes.
The optimizer determines that a relatively expensive table scan is required for the table
that has not been analyzed.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
CACHE: The CACHE hint instructs the optimizer to place the blocks retrieved for the table in the
corresponding hot part of the buffer cache when a full table scan is performed. This hint is
useful for small lookup tables.
Additional Hints
MONITOR
NO_MONITOR
RESULT_CACHE
NO_RESULT_CACHE
OPT_PARAM
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Additional Hints
Merge the views query into the referencing query block in the accessing statement.
Push the predicate of the referencing query block inside the view.
When these transformations are impossible, the views query is executed and the result is
accessed as if it were a table. This appears as a VIEW step in execution plans.
Mergeable Views
The optimizer can merge a view into a referencing query block if the view definition does not
contain the following:
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Group functions (AVG, COUNT, MAX, MIN, SUM) in the select list
If there is such a hint in the top-level query, that hint is used regardless of any such hints
in the views.
If there is no top-level optimizer-mode hint, mode hints in referenced views are used as
long as all mode hints in the views are consistent.
If two or more mode hints in the referenced views conflict, all mode hints in the views are
discarded and the session mode is used, whether default or user specified.
Access-method and join hints on referenced views are ignored unless the view contains a
single table (or references another view with a single table). For such single-table views, an
access-method hint or a join hint on the view applies to the table in the view.
Access-method and join hints can also appear in a view definition:
If the view is a subquery (that is, if it appears in the FROM clause of a SELECT
statement), all access-method and join hints in the view are preserved when the view is
merged with the top-level query.
For views that are not subqueries, access-method and join hints in the view are
preserved only if the top-level query references no other tables or views (that is, if the
FROM clause of the SELECT statement contains only the view).
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
CREATE
SELECT
FROM
WHERE
view city_view AS
*
customers c
cust_city like 'S%';
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
In this lesson, you should have learned how to:
Use hints when appropriate
Specify hints for:
Optimizer mode
Query transformation
Access path
Join orders
Join methods
Views
Summary
In this lesson, you should have learned about additional optimizer settings and hints.
By using hints, you can influence the optimizer at the statement level. Use hints as a last
remedy when tuning SQL statements. There are several hint categories, one of which
includes hints for access-path methods.
To specify a hint, use the hint syntax in the SQL statement.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 17
Chapter 17 - Page 1
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Chapter 17 - Page 2
Objectives
After completing this appendix, you should be able to do the
following:
List the key features of Oracle SQL Developer
Identify menu items of Oracle SQL Developer
Create a database connection
Manage database objects
Use SQL Worksheet
Save and run SQL scripts
Create and save reports
Objectives
In this appendix, you are introduced to the graphical tool called SQL Developer. You learn
how to use SQL Developer for your database development tasks. You learn how to use SQL
Worksheet to execute SQL statements and SQL scripts.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Objectives
SQL Developer
Creating reports
You can connect to any target Oracle database schema by using standard Oracle database
authentication. When connected, you can perform operations on objects in the database.
The SQL Developer tightly integrates with Developer Migration Workbench that provides
users with a single point to browse database objects and data in third-party databases, and to
migrate from these databases to an Oracle database. You can also connect to schemas for
selected third-party (non-Oracle) databases such as MySQL, Microsoft SQL Server, and
Microsoft Access, and you can view metadata and data in these databases.
Additionally, SQL Developer includes support for Oracle Application Express 3.0.1 (Oracle
APEX).
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Reports
Files
Connections tab: By using this tab, you can browse database objects and users to
which you have access.
Files tab: Identified by the Files folder icon, this tab enables you to access files from
your local machine without having to use the File > Open menu. This tab does not
appear by default, Use the View > Files menu to activate it.
Reports tab: Identified by the Reports icon, this tab enables you to run predefined
reports or create and add your own reports.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
The following menus contain standard entries, plus entries for features specific to SQL
Developer:
View: Contains options that affect what is displayed in the SQL Developer interface
Navigate: Contains options for navigating to various panes and for executing
subprograms
Run: Contains the Run File and Execution Profile options that are relevant when a
function or procedure is selected, and also debugging options
Edit: Contains options for use when you edit functions and procedures
Versioning: Provides integrated support for the following versioning and source control
systems: Concurrent Versions System (CVS) and Subversion
Tools: Invokes SQL Developer tools such as SQL*Plus, Preferences, and SQL
Worksheet
Note: The Run menu also contains options that are relevant when a function or procedure is
selected for debugging.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Menus
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Basic: In this type, enter the host name and SID for the database you want to
connect to. Port is already set to 1521. Or you can also choose to enter the
Service name directly if you use a remote database connection.
TNS: You can select any one of the database aliases imported from the
tnsnames.ora file.
LDAP: You can look up database services in Oracle Internet Directory which
is a component of Oracle Identity Management.
Advanced: You can define a custom JDBC URL to connect to the database.
c) Click Test to ensure that the connection has been set correctly.
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
If you select the Save Password check box, the password is saved to an XML file. So,
after you close the SQL Developer connection and open it again, you are not prompted
for the password.
3. The connection gets added in the Connections Navigator. You can expand the
connection to view the database objects and view object definitionsfor example,
dependencies, details, statistics, and so on.
Note: From the same New/Select Database Connection window, You can also connect to
schemas for selected third-party (non-Oracle) databases, such as MySQL, Microsoft SQL
Server, Sybase Adaptive Server, Microsoft Access, and IBM DB2, and view metadata and
data. However, these connections are read-only connections that enable you to browse
objects and data in that data source.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
d) Click Connect
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Browsing Files
Use the File Navigator to explore the file system and open
system files.
To view the files navigator, click the Files tab, or select View > Files.
To view the contents of a file, double-click a file name to display its contents in the SQL
worksheet area.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Browsing Files
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Creating a table
Inserting data
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
10
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
9. Clear: Erases the statement or statements in the Enter SQL Statement box
10. SQL History: Displays a dialog box with information about SQL statements that you
have executed
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
8. Change Case: Step through: To Uppercase, and Lower Case, and Initial Capitalization
Enter SQL
statements.
Results are
shown here.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
F5
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Identify a location,
enter a file name,
and click Save.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
2
Select a connection from
the drop-down list.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
After
formatting
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Using Snippets
Snippets are code fragments that may be just syntax or
examples.
From the drop-down
list, you can select
the functions
category that you
want.
Using Snippets
You may want to use certain code fragments when you use the SQL Worksheet or create or
edit a PL/SQL function or procedure. SQL Developer has the feature called Snippets.
Snippets are code fragments such as SQL functions, Optimizer hints, and miscellaneous
PL/SQL programming techniques. You can drag snippets into the Editor window.
To display Snippets, select View > Snippets.
The Snippets window is displayed at the right side. You can use the drop-down list to select a
group.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Using Snippets
Inserting a
snippet
Editing the
snippet
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Step Over bypasses the next method and goes to the next statement after the method.
Step Out leaves the current method and goes to the next statement.
Step to End of Method goes to the last statement of the current method.
Pause halts execution but does not exit, thus allowing you to resume execution.
Terminate halts and exits the execution. You cannot resume execution from this point;
instead, to start running or debugging from the beginning of the function or procedure,
click the Run or Debug icon on the Source tab toolbar.
Garbage Collection removes invalid objects from the cache in favor of more frequently
accessed and more valid objects.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Database Reporting
SQL Developer provides a number of predefined reports about
the database and its objects.
Database Reporting
SQL Developer provides many reports about the database and its objects. These reports can
be grouped into the following categories:
Table reports
PL/SQL reports
Security reports
XML reports
Jobs reports
Streams reports
User-Defined reports
To display reports, click the Reports tab at the left side of the window. Individual reports are
displayed in tabbed panes at the right side of the window; and for each report, you can select
(using a drop-down list) the database connection for which to display the report. For reports
Copyright 2010, Oracle and/or its affiliates. All rights reserved.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Database Reporting
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
about objects, the objects shown are only those visible to the database user associated with
the selected database connection, and the rows are usually ordered by Owner. You can also
create your own user-defined reports.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
External Tools
Shortcuts to frequently
used tools
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
External Tools
Setting Preferences
Setting Preferences
You can customize many aspects of the SQL Developer interface and environment by
modifying SQL Developer preferences according to your preferences and needs. To modify
SQL Developer preferences, select Tools, then Preferences.
The preferences are grouped into the following categories:
Environment
Code Editors
Database
Debugger
Documentation
Extensions
File Types
Migration
PL/SQL Compilers
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Setting Preferences
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary
In this appendix, you should have learned how to use SQL
Developer to do the following:
Browse, create, and edit database objects
Execute SQL statements and scripts in SQL Worksheet
Create and save custom reports
Summary
SQL Developer is a free graphical tool to simplify database development tasks. Using SQL
Developer, you can browse, create, and edit database objects. You can use SQL Worksheet
to run SQL statements and scripts. SQL Developer enables you to create and save your own
special set of reports for repeated use.
THESE eKIT MATERIALS ARE FOR YOUR USE IN THIS CLASSROOM ONLY. COPYING eKIT MATERIALS FROM THIS COMPUTER IS STRICTLY PROHIBITED
Summary