Professional Documents
Culture Documents
SQL Tuning PDF
SQL Tuning PDF
Workshop
Electronic Presentation
D17265GC10
Edition 1.0
November 2004
D40051
Author
Priya Vennapusa
Course Overview
Objectives
After completing this lesson, you should be able to do
the following:
Describe course objectives
Describe course schedule
I-2
Course Objectives
Proactive Tuning:
Describe the basic steps in processing SQL
statements
Describe the causes of performance problems
Understand where SQL tuning fits in an overall
tuning methodology
Influence the physical data model so as to avoid
performance problems
Understand query optimizer behavior
Influence the optimizer behavior
I-3
Course Objectives
Reactive Tuning:
Use the diagnostic tools to gather information
about SQL statement processing
Describe Automatic SQL Tuning
Describe alternative methods of accessing data
I-4
Course Schedule
Day
Lesson
I-5
Course Schedule
Day
Lesson
I-6
Summary
In this lesson, you should have learned to:
Describe course objectives
Describe course schedule
I-7
Objectives
After completing this lesson, you should be able to:
Describe the Oracle Database architecture and
components
Make qualified decisions about your tuning
actions
1-2
1-3
Streams pool
Large pool
Java pool
Database
buffer cache
Redo log
buffer
System
Monitor
SMON
Check
point
CKPT
1-4
Process
Monitor
PMON
Control
file
Database
Writer
DBW0
Data
files
Log
Writer
LGWR
Redo log
files
Archived
redo log
files
Archiver
ARC0
Control files
Data files
Parameter file
1-5
Password file
PGA
PGA
Server
process 1
Server
process 2
Server
process 3
SGA
1-6
Shared pool
Streams pool
Large pool
Java Pool
Database
buffer cache
Redo log
buffer
Fixed SGA
Large pool
Java pool
Database
buffer cache
Redo log
buffer
1-8
Shared Pool
The shared pool consists of:
Data dictionary cache containing information on
objects, storage, and privileges
Library cache containing information such as SQL
statements, parsed or compiled PL/SQL blocks, and
Java classes
Appropriate sizing of the shared pool affects performance
by:
Reducing disk reads
Allowing shareable SQL code
Reducing parsing, thereby saving CPU resources
Reducing latching overhead, thereby improving
scalability
1-9
SGA
1-10
Cursor for
SELECT statement 1
Shared SQL
SELECT
statement 1
SELECT
statement 2
SELECT
statement 1
User A
User B
User C
1-11
1-13
Connecting to an Instance
User
Server
Oracle database
User
Server
Client
Application server
User
Browser
1-14
Server
Server
Open
Parse
1-16
Close
Bind
Execute
Fetch
Parse phase:
1-17
Bind phase:
Checks the statement for bind variables
Assigns or reassigns a value to the bind variable
1-19
Execute phase:
Executes the SQL statement
Performs necessary I/O and sorts for data
manipulation language (DML) statements
Fetch phase:
Retrieves rows for a query
Sorts for queries when needed
Uses an array fetch mechanism
1-20
1
Server
process
SGA
Database
buffer cache
Redo log
buffer
Shared pool
Control
files
Redo
log files
1-21
UPDATE
employees ...
4
User
process
COMMIT Processing
Instance
Database
Data
files
SGA
Database
buffer cache
Redo log
buffer
Server
process
Shared pool
Control
files
Redo
log files
1-23
User
process
LGWR
1-25
1-26
Summary
In this lesson, you should have learned about the
Oracle Database architecture and various components
that require tuning.
1-28
Objectives
After completing this lesson, you should be able to do
the following:
Determine performance problems
Manage performance
Describe tuning methodologies
Identify goals for tuning
Describe automatic SQL tuning features
List manual SQL tuning steps
2-2
Performance Problems
2-3
CPU
I/O
Memory (may be detected as an I/O problem)
Data communications resources
High-load SQL
Contention
Factors to Be Managed
Schema
Data design
Indexes
Application
SQL statements
Procedural code
2-4
Instance
Database
User expectations
Hardware and network tuning
Tuning Goals
2-6
Manual tuning
Automatic SQL tuning
2-8
Identify high-load or
problematic SQL
ADDM
Top SQL report
2-9
Manual Tuning
1.
2.
3.
4.
5.
6.
2-10
2-11
SQL text
Structure of tables and indexes
Optimizer statistics
Views
Optimizer plan: current and prior
2-12
2-14
2-16
2-18
B*tree
Bitmap
Bitmap join
Concatenated
2-19
Stored outlines
Stored statistics
Locking statistics
2-20
Statistics analysis
SQL profiling
Access path analysis
SQL structure analysis
Copyright 2004, Oracle. All rights reserved.
2-22
Provides:
2-23
Cursor cache
Automatic Workload Repository (AWR)
User-defined workload
Hypothetical workload if a schema contains
dimensions or primary/foreign key relationships
2-24
Summary
In this lesson, you should have learned how to:
Manage performance
2-25
Summary
In this lesson, you should have learned how to:
Tune SQL statements
2-26
Objectives
After completing this lesson, you should be able to
describe the basic steps involved in designing and
developing for performance.
3-2
Understanding Scalability
3-3
3-4
3-5
3-6
Simple design
Data modeling
Tables and indexes
Using views
Writing efficient SQL
Cursor sharing
Using bind variables
SQL versus PL/SQL
Dynamic SQL
3-7
Simple tables
Well-written SQL
Indexing only as required
Retrieving only required information
Data Modeling
3-8
Table Design
3-9
Default values
Check constraints
Materialized views
Clusters
Index Design
Index keys
Primary key
Unique key
Foreign keys
3-10
Using Views
3-12
3-13
3-14
Reduces parsing
Dynamically adjusts memory
Improves memory usage
3-15
Case
White space
Comments
Object references
Bind variables
3-16
Performance Checklist
3-17
Summary
In this lesson, you should have learned the basic steps
that are involved in designing and developing for
performance.
3-18
Objectives
After completing this lesson, you should be able to do
the following:
Describe the functions of the Oracle optimizer
Identify the factors influencing the optimizer
Set the optimizer approach at the instance and
session level
4-2
Oracle Optimizer
The optimizer creates an execution plan for every SQL
statement by:
Evaluating expressions and conditions
Using object and system statistics
Deciding how to access the data
Deciding how to join tables
Deciding which path is most efficient
Comparing the cost for execution of different
plans
Determining the least-cost plan
4-3
Query
transformer
Transformed query
Estimator
Statistics
Query + estimates
Plan
generator
Query plan
4-5
Dictionary
Selectivity
4-7
4-8
4-9
4-10
4-11
4-13
{FIRST_ROWS(_n)|ALL_ROWS}
4-14
4-15
Fast response
Time for retrieving the first rows
Suitable for:
Interactive applications
Web-based or GUI applications
4-17
4-18
Access Paths
4-19
Full-table scans
Row ID scans
Index scans
Cluster scans
Hash scans
Join Orders
A join order is the order in which different join items
(such as tables) are accessed and joined together.
4-20
Join Methods
The different join methods considered by the optimizer
are:
Nested-loop join
Hash join
Sort-merge join
Cartesian join
4-21
Summary
In this lesson, you should have learned about:
Functions of the optimizer
Cost factors that are considered by the optimizer
Setting the optimizer approach
4-22
Optimizer Operations
Objectives
After completing this lesson, you should be able to do
the following:
Describe different access paths
Optimize sort performance
Describe different join techniques
Explain join optimization
Find optimal join execution plans
5-2
5-3
Access Paths
5-4
5-5
5-6
Lack of index
Large amount of data
Small table
Row ID Scans
5-8
Index Scans
Types of index scans:
Index unique scan
Index range scan
Index range scan descending
Index skip scan
5-9
Index Scans
Types of index scans:
Full scan
Fast-full index scan
Index join
Bitmap join
5-11
5-13
Join Terminology
Join statement
Join predicate, nonjoin predicate
Single-row predicate
SELECT c.cust_last_name,c.cust_first_name,
co.country_id, co.country_name
FROM
customers c JOIN countries co
ON
(c.country_id = co.country_id)
AND
( co.country_id = '52790'
OR
c.cust_id = 205);
Join predicate
Nonjoin predicate
Single-row predicate
5-14
Join Terminology
Natural join
Cross join
SELECT *
FROM
customers c CROSS JOIN countries co;
5-15
5-16
5-17
5-18
c.cust_id, c.cust_last_name
co.country_name
customers c
OUTER JOIN countries co
(c.country_id = co.country_id);
5-19
5-20
Join Optimization
5-21
Join Orders
----------2! = 2
3! = 6
4! = 24
Join Methods
5-22
5-23
5-24
Table access
(Outer/driving table)
Table access
(Inner table)
5-25
Hash Joins
A hash join is executed as follows:
Both tables are split into as many partitions as
required, using a full table scan.
For each partition pair, a hash table is built in
memory on the smallest partition.
The other partition is used to probe the hash table.
5-26
2
Table access
5-27
3
Table access
5-28
Sort-Merge Joins
A sort-merge join is executed as follows:
1. The rows from each row source are sorted
on the join predicate columns.
2. The two sorted row sources are then merged
and returned as the resulting row source.
5-29
Table access
Table access
Sort
5-30
Sort
5-31
Star Joins
Dimension
tables
PRODUCTS
CUSTOMERS
SALES
Facts
table
5-32
CHANNELS
PROMOTIONS
TIMES
5-33
Hints specified
5-35
Noncorrelated subquery
Correlated subquery
NOT IN subquery (antijoin)
EXISTS subquery (semijoin)
Sort Operations
5-38
SORT
SORT
SORT
SORT
SORT
UNIQUE
AGGREGATE
GROUP BY
JOIN
ORDER BY
5-39
Top-N SQL
SELECT *
FROM (SELECT prod_id
,
prod_name
,
prod_list_price
,
prod_min_price
FROM products
ORDER BY prod_list_price DESC)
WHERE ROWNUM <= 5;
5-40
5-41
Summary
In this lesson, you should have learned how to:
Describe available join operations
Optimize join performance against different
requirements
Influence the join order
Explain why tuning joins is more complicated than
tuning single table statements
5-42
Execution Plans
Objectives
After completing this lesson, you should be able to do
the following:
Use the EXPLAIN PLAN command to show how a
statement is processed
Use the DBMS_XPLAN package
6-2
6-3
6-4
EXPLAIN PLAN
SQL Trace
Statspack
Automatic Workload Repository
V$SQL_PLAN
SQL*Plus AUTOTRACE
6-6
6-7
6-9
FOR statement
6-10
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.
6-11
6-12
Parse Tree
SELECT STATEMENT
0
MERGE JOIN
SORT JOIN
TABLE ACCESS BY
INDEX ROWID
of DEPARTMENTS
INDEX FULL SCAN
DEPT_ID_PK
6-13
6-14
V$SQL_PLAN Columns
HASH_VALUE
ADDRESS
PARENT_ID
ID
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
| Rows | Bytes | Cost (%CPU|
| Name
-------------------------------------------------------------------------------|
0 | SELECT STATEMENT
|
|
|
|
6 (100|
|
|
1 | MERGE JOIN
106 | 2862 |
6 (17|
|
|
2 |
27 |
TABLE ACCESS BY INDEX ROWID| DEPARTMENTS |
432 |
2
(0|
|
3 |
INDEX FULL SCAN
27 |
| DEPT_ID_PK |
|
1
(0|
|* 4 |
SORT JOIN
|
107 | 1177 |
|
4 (25|
|
5 |
107 | 1177 |
TABLE ACCESS FULL
3
(0|
| EMPLOYEES
|
-------------------------------------------------------------------------------Predicate Information (identified by operation id):
--------------------------------------------------4 - access("E"."DEPARTMENT_ID"="D"."DEPARTMENT_ID")
filter("E"."DEPARTMENT_ID"="D"."DEPARTMENT_ID")
24 rows selected.
6-16
V$SQL_PLAN_STATISTICS View
6-17
6-18
Object statistics
Time-model statistics
Some system and session statistics
Active Session History (ASH) statistics
6-20
Creating snapshots
Dropping snapshots
Managing snapshot settings
AWR Views
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
6-22
PLAN_TABLE_OUTPUT
-------------------------------------------------------------------------------------SQL_ID 454rug2yva18w
-------------------select /* example */ * from hr.employees natural join hr.departments
Plan hash value: 4179021502
---------------------------------------------------------------------------------| Id | Operation
| Rows | Bytes | Cost (%CPU)| Time
| Name
|
---------------------------------------------------------------------------------|
0 | SELECT STATEMENT
|
|
6 (100)|
|
|
|
11 |
|
|
968 |
1 | HASH JOIN
|
6 (17)| 00:00:01 |
|
2 |
TABLE ACCESS FULL| DEPARTMENTS |
11 |
220 |
2
(0)| 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 |
----------------------------------------------------------------------------------
6-23
SQL*Plus AUTOTRACE
OFF
SET AUTOTRACE
ON
TRACE[ONLY]
EXPLAIN
STATISTICS
SHOW AUTOTRACE
6-25
set autotrace on
6-26
6-27
Summary
In this lesson, you should have learned how to:
Use EXPLAIN PLAN to view execution plans
Query V$SQL_PLAN to see the execution plan for
cursors that were recently executed
Use the Automatic Workload Repository
Use SQL*Plus AUTOTRACE to run statements
and display execution plans and statistics
6-28
Practice 6: Overview
This practice covers the following topics:
Using AUTOTRACE
Using EXPLAIN PLAN
6-29
Using AWR
Retrieving the execution plan using DBMS_XPLAN
Gathering Statistics
Objectives
After completing this lesson, you should be able to do
the following:
Identify table, index, and column statistics
Describe the Automatic Statistics Gathering
mechanism
Use the DBMS_STATS package to collect statistics
manually
Identify predicate selectivity calculations
7-2
7-3
Selectivity of predicates
Cost of each execution plan
Access method and join method
CPU and I/O costs
Object statistics
Table statistics
Column statistics
Index statistics
System statistics
I/O performance and utilization
CPU performance and utilization
7-4
7-6
Dynamic sampling
7-7
7-8
7-9
7-10
WEEKNIGHT_WINDOW
WEEKEND_WINDOW
EXECUTE DBMS_SCHEDULER.SET_ATTRIBUTE(
'WEEKNIGHT_WINDOW',
'repeat_interval',
'freq=daily; byday= MON, TUE, WED, THU, FRI;
byhour=0; byminute=0; bysecond=0');
7-12
7-13
7-14
DML monitoring
Sampling
Degree of parallelism
Histograms
Cascade
DML Monitoring
You can:
View the information on DML changes in the
USER_TAB_MODIFICATIONS view
Use DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO
to update the view with current information
Use GATHER_DATABASE_STATS or
GATHER_SCHEMA_STATS for manual statistics gathering
for tables with stale statistics when OPTIONS is set to
GATHER STALE or GATHER AUTO
7-15
Sampling
7-17
Degree of Parallelism
7-18
Histograms
Influence optimizer decisions on selecting the
optimal execution plan
Provide improved selectivity estimates in the
presence of data skew
Enable optimal execution plans with nonuniform
data distributions
7-19
Column
Value
Count of
Rows
10
10
20
1050
30
126
40
567
50
248
Number of
buckets = 5
10
20
30
40
50
10
20
30
40
50
Creating Histograms
7-20
7-22
Histogram Tips
7-23
Histogram Tips
7-24
7-25
Cascading to Indexes
7-26
,'default'
-- granularity
7-28
Dynamic sampling:
BEGIN
DBMS_STATS.DELETE_TABLE_STATS('OE','ORDERS');
DBMS_STATS.LOCK_TABLE_STATS('OE','ORDERS');
END;
BEGIN
DBMS_STATS.GATHER_TABLE_STATS('OE','ORDERS');
DBMS_STATS.LOCK_TABLE_STATS('OE','ORDERS');
END;
7-29
Dynamic Sampling
Dynamic sampling is used to automatically collect
statistics when:
The cost of collecting the statistics is minimal
compared to the execution time
The query is executed many times
7-30
Locking Statistics
7-31
7-32
7-33
HISTOGRAM
NUM_BUCKETS DENSITY
ANALYZED
----------- ----------- ---------- --------NONE
1 .000278862 09-FEB-04
NONE
1
.25 09-FEB-04
NONE
1 .000141663 09-FEB-04
72 5.4416E-07 09-FEB-04
FREQUENCY
NONE
1
.25 09-FEB-04
NONE
1
1 09-FEB-04
1 .000684932 09-FEB-04
NONE
7-34
IMPORT_STATS
New
statistics
SET_STATS
RESTORE_TABLE_STATS
DBA_OPTSTATS_OPERATIONS
Old
statistics
Operation
date
31
days
DBA_TAB_STATS_HISTORY
7-36
7-37
RESTORE_*_STATS()
PURGE_STATS()
ALTER_STATS_HISTORY_RETENTION()
I/O
CPU
BEGIN
dbms_stats.gather_system_stats(
gathering_mode => 'interval',
interval => 720,
stattab => 'mystats',
statid => 'oltp');
END;
/
7-39
Dictionary tables
Fixed tables
GATHER_DATABASE_STATS
GATHER_DICTIONARY_STATS
7-41
GATHER_FIXED_OBJECTS_STATS
Workload
CREATE
ALTER
DROP
DDLs
GATHER_DATABASE_STATS(OPTIONS=>'GATHER AUTO')
7-42
Summary
In this lesson, you should have learned how to:
Use the Automatic Statistics Gathering
mechanism
Use the DBMS_STATS package for manual statistics
gathering
Determine selectivity for predicates with and
without bind variables
7-43
Practice 7: Overview
This practice covers the following topics:
Using DBMS_STATS to gather manual statistics
Verifying the existence of the gather_stats_job
7-44
Application Tracing
Objectives
After completing this lesson, you should be able to do
the following:
Configure the SQL Trace facility to collect session
statistics
Enable SQL Trace and locate your trace files
Format trace files using the TKPROF utility
Interpret the output of the TKPROF command
8-2
8-3
trcsess utility
SQL Trace and TKPROF
8-4
8-5
Using DBMS_MONITOR
EXECUTE DBMS_MONITOR.CLIENT_ID_STAT_ENABLE(
client_id => 'OE.OE',
1
8-6
8-8
trcsess Utility
Client
Client
Client
Dedicated
server
Dedicated
server
Dedicated
server
Trace
file
Trace
file
Trace
file
Clients
Shared
server
Shared
server
Shared
server
Trace
file
Trace
file
Trace
file
TRCSESS
Trace file
for one service
TRCSESS
TKPROF
Report
file
8-9
Trace file
for one client
trcsess Utility
SQL>
2 from v$session
3
SID||'.'||SERIAL#
'SH');
USERNAME
------------------- -------------------------236.57
HR
245.49845
SH
8-10
Server process
Trace
file
TKPROF
Database
8-12
Report
file
8-13
Trace
file
TKPROF
Database
8-14
Report
file
Initialization Parameters
TIMED_STATISTICS = {false|true}
MAX_DUMP_FILE_SIZE = {n|unlimited}
USER_DUMP_DEST = directory_path
STATISTICS_LEVEL = {BASIC|TYPICAL|ALL}
8-15
SQL_TRACE = TRUE
8-17
8-19
8-20
8-22
PARSE
EXECUTE
FETCH
8-23
Count
CPU
Elapsed
Disk
Query
Current
Rows
...
Misses in library cache during parse: 1
Optimizer mode: ALL_ROWS
Parsing user id: 61
Rows
------24
24
8-25
cpu
elapsed
disk
query
current
-------- ---------- ---------- ---------- ---------0.02
0
0.02
0
0
0.00
0
0.00
0
0
0.09
1459
0.10
1408
0
-------- ---------- ---------- ---------- ---------0.11
1459
1408
0
0.12
rows
------0
0
1
------1
8-27
cpu
elapsed
disk
query
current
--------0
0
1
--------1
55097)
8-28
Summary
In this lesson, you should have learned how to:
Set SQL Trace initialization parameters
SQL_TRACE, TIMED_STATISTICS
USER_DUMP_DEST, MAX_DUMP_FILE_SIZE
8-29
Practice 8: Overview
This practice covers the following topics:
Using TKPROF
Using DBMS_MONITOR
8-30
Objectives
After completing this lesson, you should understand
the different methods of identifying high-load SQL:
ADDM
Top SQL
Dynamic performance views
Statspack
9-2
Analyze SQL
Take
corrective
action
9-3
SQL
workload
Automatic
(ADDM)
Manual
(Top SQL)
9-4
High-load
SQL
MMON
EM
ADDM
results
60
minutes
Snapshots
ADDM
ADDM
results
AWR
9-6
ADDM Output
ADDM
results
ADDM
EM
Recommendations
Findings
with impact
9-7
Invoke
advisors
AWR
SQL
workload
Top SQL
9-8
High-load
SQL
SQL Tuning
Advisor
Spot SQL
9-9
Period SQL
9-10
9-11
9-12
V$SQLAREA View
9-13
Column
Description
SQL_TEXT
SORTS
EXECUTIONS
DISK_READS
CPU_TIME
ELAPSED_TIME
9-14
9-15
Summary
In this lesson, you should have learned about the
different methods of identifying high-load SQL:
ADDM
Top SQL
Statspack
Dynamic performance views
9-16
Objectives
After completing this lesson, you should be able to do
the following:
Describe automatic SQL tuning
Describe the Automatic Workload Repository
Use Automatic Database Diagnostic Monitor
View the cursor cache
Perform automatic SQL tuning
Use the SQL Tuning Advisor
Use the SQL Access Advisor
10-2
Analyze
SQL
Take
corrective
action
10-3
ADDM
High-load
SQL
SQL
workload
10-4
DBA
10-5
SQL
workload
ADDM
High-load
SQL
10-7
SQL Tuning
Advisor
Comprehensive
SQL tuning
Detect stale or missing
statistics
SQL profiling
Access path
analysis
SQL structure
analysis
10-8
Restructure SQL
Statistics Analysis
Automatic
Statistics Gathering
disabled
Stale or missing
statistics
SQL Tuning
Advisor
DBMS_STATS.GATHER_TABLE_STATS(
ownname=>'SH', tabname=>'CUSTOMERS',
estimate_percent=>
DBMS_STATS.AUTO_SAMPLE_SIZE);
10-9
SQL Profiling
Submit
Optimizer Create
(Tuning mode)
SQL Profile
SQL Tuning
Advisor
Use
Database
users
10-10
SQL statements
SQL Tuning
Advisor
Significant
performance gain
Indexes
10-12
Poorly written
SQL statement
Restructured
SQL statement
SQL constructs
Type mismatch
and indexes
SQL Tuning
Advisor
10-13
Design mistakes
AWR
Sources
ADDM
High-load SQL
Manual selection
AWR
STS
Filter/rank
Cursor cache
Custom
10-14
DBA
Copyright 2004, Oracle. All rights reserved.
SQL
Tuning
Advisor
Manual selection
AWR
Filter/rank
STS
Cursor cache
Custom
10-16
DBA
SQL
Tuning
Advisor
10-19
DBA_ADVISOR_TASKS
DBA_ADVISOR_FINDINGS
DBA_ADVISOR_RECOMMENDATIONS
DBA_ADVISOR_RATIONALE
DBA_SQLTUNE_STATISTICS
DBA_SQLTUNE_BINDS
DBA_SQLTUNE_PLANS
DBA_SQLSET, DBA_SQLSET_BINDS
DBA_SQLSET_STATEMENTS
DBA_SQLSET_REFERENCES
View recommendations
Implement recommendations
10-20
SQL workload
Recommendations
Select
Select
Select
Create index
Drop index
Create materialized view
SQL Access
Advisor
10-21
10-23
Cursor cache
User-defined
Workload
Hypothetical
STS
Filter options
10-24
SQL Access
Advisor
10-25
Advisor
Statistics
SQL Profile
SQL Structure
SQL Tuning/Access
Advisor
10-26
Summary
In this lesson, you should have learned how to:
Describe the Automatic Workload Repository
Use Automatic Database Diagnostic Monitor
View the cursor cache
Perform automatic SQL tuning
Use the SQL Tuning Advisor
Use the SQL Access Advisor
10-27
Index Usage
Objectives
After completing this lesson, you should be able to do
the following:
Identify index types
Identify basic access methods
Monitor index usage
11-2
Indexing Guidelines
11-3
Types of Indexes
11-4
When to Index
11-6
Index
Do Not Index
High-selectivity keys
Foreign keys
11-8
11-9
CHANNELS
#channel_id
11-10
SALES
PRODUCTS
#prod_id
Index scans:
Allow index access only
Are followed by access by ROWID
11-11
11-12
11-13
11-14
Summary
In this lesson, you should have learned about the
following:
Indexes
Index types
DML operations and indexes
Indexes and constraints
Monitoring indexes
Index usage monitoring
11-15
Objectives
After completing this lesson, you should be able to do
the following:
Use composite indexes
Use bitmap indexes
Use bitmap join indexes
Identify bitmap index operations
Create function-based indexes
Use index-organized tables
12-2
Composite Indexes
Here are some features of the index displayed below.
cust_last_name
cust_last_name cust_first_name
cust_last_name cust_first_name cust_gender
12-4
12-5
Bitmap Index
12-6
12-7
12-8
12-9
Customers
CREATE
ON
FROM
WHERE
12-10
12-11
Advantages
Good performance for join queries; space-efficient
Especially useful for large-dimension tables in star
schemas
Disadvantages
More indexes are required: Up to one index per
dimension-table column rather than one index per
dimension table is required.
Maintenance costs are higher: Building or
refreshing a bitmap join index requires a join.
12-12
Function-Based Index
12-14
12-15
Accessing
index-organized table
ROWID
Non-key columns
Key column
Row header
12-16
12-17
Can be rebuilt
Can be accessed by either primary key or leading
columns
Advantages
IOTs provide fast key-based access for queries
involving exact match and range searches.
DML causes only updates to index structure.
Storage requirements are reduced.
IOTs are useful in:
Applications that retrieve data based on a primary
key
Applications that involve content-based
information
Disadvantages
Not suitable for queries that do not use the primary
key in a predicate
12-18
Summary
In this lesson, you should have learned about:
Composite indexes
Bitmap indexes
Bitmap join indexes
Function-based indexes
Index-organized tables
12-19
Optimizer Hints
Objectives
After completing this lesson, you should be able to
specify hints for:
Optimizer mode
Query transformation
Access path
Join orders
Join methods
13-2
13-3
Types of Hints
13-4
Single-table hints
Multitable hints
Statement hints
Specifying Hints
MERGE
SELECT
INSERT
/*+
hint
comment
text
UPDATE
DELETE
MERGE
SELECT
INSERT
UPDATE
--+
hint
comment
text
DELETE
13-5
*/
13-6
Hint Recommendations
13-7
13-8
Hint Categories
There are hints for:
Optimization approaches and goals
Access paths
Query transformations
Join orders
Join operation
Parallel execution
13-9
13-10
13-11
FULL
ROWID
INDEX
INDEX_ASC
INDEX_COMBINE
13-13
INDEX_JOIN
INDEX_DESC
INDEX_FFS
NO_INDEX
AND_EQUAL
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';
13-15
13-16
13-17
USE_CONCAT
NO_EXPAND
Prevents OR expansions
13-18
MERGE
NO_MERGE
STAR_
TRANSFORMATION
FACT
NO_FACT
13-20
ORDERED
LEADING
USE_NL
NO_USE_NL
USE_MERGE
13-22
Other Hints
13-24
APPEND
NOAPPEND
ORDERED_PREDICATES
CURSOR_SHARING_EXACT
DYNAMIC_SAMPLING
13-26
Hint
NO_INDEX
Description
FULL
INDEX or
INDEX_COMBINE
13-27
13-29
MERGE
NO_MERGE
CREATE
SELECT
FROM
WHERE
view city_view AS
*
customers c
cust_city like 'S%';
13-30
SELECT PLAN_TABLE_OUTPUT
FROM TABLE(DBMS_XPLAN.DISPLAY(NULL, NULL,
'ALL'));
SELECT /*+ QB_NAME(qb) FULL(@qb e) */
employee_id, last_name
FROM hr.employees e
WHERE employee_id = 100;
13-31
13-33
Summary
In this lesson, you should have learned how to:
Set the optimizer mode
Use optimizer hint syntax
Determine access-path hints
Analyze hints and their impact on views
13-34
Materialized Views
Objectives
After completing this lesson, you should be able to do
the following:
Identify the characteristics and benefits of
materialized views
Use materialized views to enable query rewrites
Verify the properties of materialized views
Perform refreshes on materialized views
14-2
Materialized Views
A materialized view:
Is a precomputed set of results
Has its own data segment and offers:
Space management options
Use of its own indexes
Is useful for:
Expensive and complex joins
Summary and aggregate data
14-3
14-5
14-6
14-7
14-9
Refresh Methods
14-10
COMPLETE
FAST
FORCE
NEVER
Refresh Modes
Manual refresh
14-12
REFRESH_MODE in ALL_MVIEWS
14-14
14-15
Query Rewrites
14-16
Query Rewrites
14-17
REWRITE_OR_ERROR
14-18
14-20
14-21
SELECT
,
,
,
FROM
WHERE
AND
AND
GROUP BY
,
HAVING
t.week_ending_day
t.calendar_year
p.prod_subcategory
sum(c.unit_cost) AS dollars
costs c, times t, products p
c.time_id = t.time_id
c.prod_id = p.prod_id
t.calendar_year = '1999'
t.week_ending_day, t.calendar_year
p.prod_subcategory
sum(c.unit_cost) > 10000;
SELECT
,
,
FROM
WHERE
AND
week_ending_day
prod_subcategory
dollars
cost_per_year_mv
calendar_year = '1999'
dollars > 10000;
Copyright 2004, Oracle. All rights reserved.
Can be run:
From Oracle Enterprise Manager by using the SQL
Access Advisor Wizard
By invoking the DBMS_ADVISOR package
14-23
14-24
14-25
Results of Tune_MVIEW
IMPLEMENTATION recommendations
CREATE MATERIALIZED VIEW LOG statements
ALTER MATERIALIZED VIEW LOG FORCE
statements
One or more CREATE MATERIALIZED VIEW
statements
UNDO recommendations
14-26
DBMS_MVIEW.EXPLAIN_MVIEW Procedure
Accepts:
Materialized view name
SQL statement
14-28
P RELATED_TE MSGTXT
- ---------- --------------------
PCT_TABLE
N CUSTOMERS
Y
N
N
N SALES
no partition key or
PMARKER in select
list
relation is not a
partitioned
table
...
14-29
14-30
14-32
REWRITE
REWRITE_OR_ERROR
NO_REWRITE
Summary
In this lesson, you should have learned how to:
Create materialized views
Enable query rewrites using materialized views
14-33
Objectives
After completing this lesson, you should understand
the following:
Star transformations
Basics of parallel execution
Types of parallelism
Parallel query
Parallelizing SQL statements
Viewing parallel queries with EXPLAIN PLAN
D-2
Star Transformation
With the star transformation, you can:
Execute star queries efficiently, especially in the
following cases:
D-3
D-4
Steps in Execution
The Oracle Server processes the query by carrying out
the following steps:
1. Use a bitmap index to identify row sets for sales in
channels I, P, or S. Combine these with a bitmap
OR operation.
2. Use a bitmap for rows corresponding to sales in
the city of Asten.
3. Use a bitmap for rows with product ID greater than
40,000.
4. Combine these three bitmaps into a single bitmap
with the bitmap AND operation.
5. Use this final bitmap to access rows that satisfy all
the conditions from the fact table.
6. Join these rows from the fact table to the
dimension tables.
D-5
D-7
D-8
D-9
Access methods
Join methods
DDL
DML
Miscellaneous SQL operations
Query
SQL*Loader
D-11
Degree of Parallelism
User
process
Server
processes
D-12
D-14
A parallel hint
The query includes a parallel hint specification.
The schema objects have a PARALLEL declaration.
D-15
Parallel DML
D-16
Parallel DDL
Use default DOP
ALTER TABLE employees PARALLEL;
Use DOP of 4
ALTER TABLE employees PARALLEL 4;
Session override
ALTER SESSION FORCE PARALLEL DDL
D-18
Parallelization Rules
D-20
----------------------------------------------------------------------------------------|Id | Operation
TQ |IN-OUT|PQ Distrib|
|Name
|Rows |Bytes |Cost |
----------------------------------------------------------------------------------------| 0 | SELECT STATEMENT
|
|
|
|
|
41 | 1066 |
4 |
| 1 | PX COORDINATOR
|
|
|
|
|
|
|
|
| 2 |
PX SEND QC (RANDOM)
|:TQ10001 |
41 | 1066 |
4 |Q1,01 | P->S |QC (RAND) |
| 3 |
SORT GROUP BY
|
|
41 | 1066 |
4 |Q1,01 | PCWP |
|
| 4 |
PX RECEIVE
|
|
41 | 1066 |
4 |Q1,01 | PCWP |
|
| 5 |
PX SEND HASH
|:TQ10000 |
41 | 1066 |
4 |Q1,00 | P->P | HASH
|
| 6 |
SORT GROUP BY
|
|
41 | 1066 |
4 |Q1,00 | PCWP |
|
| 7 |
PX BLOCK ITERATOR |
|
41 | 1066 |
1 |Q1,00 | PCWC |
|
| 8 |
TABLE ACCESS FULL|EMP2
|
41 | 1066 |
1 |Q1,00 | PCWP |
|
-----------------------------------------------------------------------------------------
D-21
D-23
D-24
PARALLEL
NO_PARALLEL
PQ_DISTRIBUTE
PARALLEL_INDEX
NO_PARALLEL_INDEX
Summary
In this lesson, you should have learned how to do the
following:
Describe parallel execution
Describe the types of parallelism
Use parallel query
Parallelize SQL statements
View parallel queries with EXPLAIN PLAN
D-25
Objectives
After completing this lesson, you should be able to do
the following:
Identify the purpose and benefits of optimizer plan
stability
Create stored outlines
Use stored outlines
Edit stored outlines
Maintain stored outlines
E-2
E-3
Plan Equivalence
E-4
SQL>
2
SQL>
SQL>
ALTER SESSION
SET create_stored_outlines = OTLN1;
SELECT ... ;
SELECT ... ;
E-6
E-7
In
shared
pool?
Same
outline
category?
Execute
outline plan
Query DD for
matching outline
Regular
execute
E-9
Found?
Integrate outline
and generate plan
E-10
Rename an outline
Rebuild an outline
Change the category of an outline
SQL> BEGIN
2
dbms_outln.drop_unused;
3
dbms_outln.update_by_cat
4
('default','otln1');
5
dbms_outln.drop_by_cat('otln1');
6 END;
E-11
Public outlines
Default setting when creating outlines
Stored in the OUTLN schema
Used when USE_STORED_OUTLINES is set to TRUE
or a category
Private outlines
Stored in the users schema for the duration of the
session
Can be edited
Used when USE_PRIVATE_OUTLINES is set to TRUE
or a category
Changes can be saved as public outlines.
E-12
E-13
E-14
Editable Attributes
E-15
Join order
Join methods
Access methods
Distributed execution plans
Distribution methods for parallel query execution
Query rewrite
View and subquery merging
E-16
SELECT_CATALOG_ROLE
CREATE ANY OUTLINE
EXECUTE privilege on DBMS_OUTLN_EDIT
DBMS_OUTLN_EDIT.CREATE_EDIT_TABLES
Creates required temporary tables in users schema
for cloning and editing outlines
E-18
E-19
Configuration Parameters
USE_PRIVATE_OUTLINES is a session parameter that
controls the use of private outlines instead of public
outlines.
ALTER SESSION SET use_private_outlines =
[TRUE | FALSE | category_name ];
E-20
Cloning Outlines
The CREATE OUTLINE command can be used to clone
outlines:
CREATE [OR REPLACE]
[PUBLIC | PRIVATE] OUTLINE [outline_name]
[FROM [PUBLIC | PRIVATE] source_outline_name]
[FOR CATEGORY category_name] [ON statement]
Example
CREATE OR REPLACE OUTLINE public_outline2
FROM public_outline1 FOR CATEGORY cat2;
E-21
SQL Profiles
SQL Profiles
Are an alternative to using hints
Consist of auxiliary stored statistics that are
specific to a statement
Contain execution history information about the
SQL statement that the Automatic Tuning Optimizer
uses to set optimizer parameter settings
E-22
Summary
In this lesson, you should have learned how to:
Use stored outlines to ensure execution-plan
consistency
Create outlines for a session or a single statement
Organize outlines in categories
Enable or disable using outlines or categories of
outlines
Maintain outlines with the DBMS_OUTLN package or
the ALTER OUTLINE command
E-23
Statspack
Objectives
After completing this lesson, you should be able to do
the following Use Statspack.
F-2
Overview of Statspack
Statspack
collects data about high-resource SQL.
precalculates many useful data
F-3
Statspack Mechanism
F-4
F-5
F-6
SPREPSQL.SQL
Displays statistics, the complete SQL text, and
information on any SQL plans associated with that
statement.
F-7
Snapshot Levels
F-8
Level
Description
>= 0
>= 5
>= 6
>= 7
>= 10
Snapshot Levels
F-9
Level
Description
>= 0
>= 5
>= 6
>= 7
>= 10
F-10
F-12
Summary
In this lesson, you should have learned about the use
of Statspack in statistics gathering.
F-13