SlideShare a Scribd company logo
1 of 98
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.1
2 Copyright © 2012, Oracle and/or its affiliates. All rights
reserved.
Insert Information Protection Policy Classification from Slide 8
Oracle Optimizer:
12c New Capabilities
Thomas Kyte
http://asktom.oracle.com/
ORACLE
PRODUCT
LOGO
Wifi sid: guest-access
Wifi username: Q7D3KcRn
Wifi password: 3dF2DneR
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.3
Oracle safe harbor statement
The following is intended to outline our general product direction. It is
intended for information purposes only, and may not be incorporated into
any contract. It is not a commitment to deliver any material, code, or
functionality, and should not be relied upon in making purchasing
decisions. The development, release, and timing of any features or
functionality described for Oracle's products remains at the sole
discretion of Oracle.
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.4
Optimizer evolution
In the beginning
there were rules
Optimizer evolved to
be cost based
CBO
CBO
Optimizer proactively adapts
to become self-learning
Rule are not enough
Databases became more
feature rich
Reactive tuning with
the use of advisors
and auto jobs
As environment changes
Potential for plan changes
Databases become
more real-time, ad-hoc
environments
Reactive tuning not enough
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.5
Agenda
 Adaptive Query Optimization
 Optimizer Statistics enhancements
 SQL Plan Management enhancements
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.6
Adaptive Plans
Join methods
Parallel distribution methods
Adaptive Statistics
Discovered at compile time
Discovered at run time
Adaptive Query Optimization
Overview
Adaptive Query
Optimization
Adaptive Plans
Adaptive
Statistics
Join
Methods
Parallel
distribution
Methods
At compile
time
At run
time
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.7
Query: Find all of the
products with a unit price of
15 that we have sold more
that 1 of
Two possible join methods
for this query
Nested Loops
Hash Join
Adaptive Execution Plans
Adapt join methods
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.8
Alternative sub-plans are
pre-computed
Sub-plans stored in the
cursor
Stats collect inserted before
join
Rows buffered until final
decision is made
Adaptive Execution Plans
Adapt join methods
Table scan
Order _items
NESTED LOOPS
Index Scan
Prod_info_ind
Statistics
Collector
Default Plan is a nested loops join
HASH JOIN
Table scan
Prod_info
Rows coming out of order_items table are buffered up
to a point If row count is less than the threshold use
nested Loops otherwise switch to hash join
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.9
Number of rows seen in
statistics collector exceeds
threshold
Plan switches to hash join
Statistics collect disabled
Plan resolved on first
execution & remains the
same for subsequent
executions
Adaptive Execution Plans
Adapt join methods
Final Plan is a hash join
Statistics collector disabled after decision is
made and becomes a pass through operation
Table scan
Order _items
NESTED LOOPS
Index Scan
Prod_info_ind
HASH JOIN
Table scan
Prod_info
Statistics
Collector
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.10
Explain plan command
always shows default plan
Example shows a nested
loops join as default plan
No statistics collector shown
in plan
Adaptive Execution Plans
Displaying the default plan
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.11
After the statement has
completed use
DBMS_XPLAN.DISPLAY_CURSOR
to see the final plan selected
Example shows that hash
join picked at execution time
Again the statistics collector
is not visible in the plan
Adaptive Execution Plans
Displaying the final plan
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.12
Full adaptive plan displayed
when format parameter
‘+adaptive’ is set
Example shows both the
nested loops and hash join
in the plan
Adaptive Execution Plans
Displaying the full adaptive plan
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.13
Additional information
displayed on why operations
are inactive can be seen
with format parameter
‘+report’
Adaptive Execution Plans
Displaying plan with +adaptive & +report formats
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.14
New column in V$SQL
IS_RESOLVED_ADAPTIVE_PLAN
Indicates statement had an
adaptive plan which was
resolved on first execution
Resolved plan is used for
subsequent executions
Statistics collectors and
buffering is disabled
Adaptive Execution Plans
Indicator in V$SQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.15
Adaptive plans are enabled by
default
Can be put in reporting mode
OPTIMIZER_ADAPTIVE_REPORTING_ONLY
Reporting mode shows what
would have happened during
execution in the plan
Adaptive Execution Plans
Reporting mode
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.16
Adaptive Execution Plans
 Join method decision deferred until runtime
– Default plan is computed using available statistics
– Alternate sub-plans are pre-computed and stored in the cursor
– Statistic collectors are inserted at key points in the plan
 Final decision is based on statistics collected during execution
– Default plan and sub-plans have a valid range for statistics collected
– If statistics prove to be out of range, the sub-plans will be swapped
– Requires buffering near the swap point to avoid returning rows to user
 Possible sub-plans are nested loop joins or hash joins and vice versa
Adaptive join methods
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.17
Adaptive Plans
Join methods
Parallel distribution methods
Adaptive Statistics
Discovered at compile time
Discovered at run time
Adaptive Query Optimization
Overview
Adaptive Query
Optimization
Adaptive Plans
Adaptive
Statistics
Join
Methods
Parallel
distribution
Methods
At
compile
time
At run
time
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.18
Dynamic Statistics
 During compilation optimizer decides if statistics are sufficient to
generate a good plan or not
 Dynamic statistics are used to compensate for missing, stale, or
incomplete statistics
 They can be used for table scans, index access, joins and group bys
 One type of dynamic statistics is dynamic sampling
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.19
Dynamic sampling has a
new level 11(AUTO)
Decision to use dynamic
sampling depends on the
complexity of predicate,
existing statistics and
total execution time
Dynamic statistics shared
among queries
Dynamic Statistics
Dynamic Sampling
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.20
Dynamic Statistics SGA
SHARED_POOL
Select *
From product_information
Where list_price-min_price=29
And category_id not in (11,22)
And prod_name like ‘Smart%’;
Optimizer checks
for existing statistics
in data dictionary
2
SHARED DYNAMIC STATISTICS
DATA DICTIONARY
SQL statement
is submitted
1
Optimizer determines
plan using dynamic
statistics
5
Cursor 0: Select * from product_information …
Dynamic sampling
occurs on small number of
blocks from table
Resulting dynamic statistics
are stored in cache
4
Statistics found but need to be
augmented due to complex predicates
3
Table cardinality estimate for prod_info
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.21
Dynamic Statistics SGA
SHARED_POOL
Select supplier_id, prod_name
From product_information
Where list_price-min_price=29
And category_id not in (11,22)
And prod_name like ‘Smart%’;
Optimizer checks
for existing statistics
in data dictionary
7
SHARED DYNAMIC STATISTICS
DATA DICTIONARY
Different SQL
statement is
submitted with
same predicates
6
Optimizer determines
plan using dynamic
statistics
10
Cursor 0: Select supplier_id, prod_name …
Necessary Dynamic
statistics found in shared
cache
9
Statistics found but need to be
augmented due to complex predicates
8
Table cardinality estimate for prod_info
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.22
Adaptive Statistics
 During execution optimizer estimates are compared to execution statistics
 If statistics vary significantly then a new plan will be chosen for
subsequent executions based on execution statistics
 Re-optimization uses statistics gathered from previous executions
 First introduced as Cardinality Feedback in 11.2
Re-optimization
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.23
Adaptive Statistics
 Statistics gathered about data volume and data type seen during execution
 If execution statistics vary significantly statement will be hard parsed on
the next execution using the execution statistics instead
 Statements are only monitored once if they don’t show significant
differences initially they won’t change in the future
 Only individual table cardinalities and group by estimates examined
 Information is stored in the cursor only and is lost if cursor ages out
Cardinality Feedback pre 12c
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.24
Initial execution of a query
is monitored
Example shows initial plan
is hash join between sales
and customers
Cardinality estimates 8X off
Adaptive Statistics
Cardinality Feedback pre 12c
Initial Cardinality estimates are more than 8X off
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.25
Execution statistics used to
reparse the statement on
the second execution
New plan shows correct
cardinality estimates and a
new join order
Information learnt is stored
in the cursor only and is lost
if cursor ages out
Adaptive Statistics
Cardinality Feedback pre 12c
Execution Plan after the second execution
Estimates
are now
correct
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.26
Adaptive Statistics
 Join statistics are also monitored
 Works with adaptive cursor sharing for statement with binds
 New Column in V$SQL IS_REOPTIMIZABLE
 Information found at execution time is persisted as SQL Plan Directives
Re-optimization in 12c
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27
New column in V$SQL
IS_REOPTIMIZABLE
Indicates that the statement
will be re-parsed on the next
execution
Adaptive Statistics
Re-optimization – indicator in V$SQL
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28
Adapt join method example
showed the join change from
nested loops to hash join
But cursor is also marked
IS_REOPTIMIZABLE
Why?
Re-optimization will occur on
second execution because
cardinality estimates off
Adaptive Statistics
Adaptive Plans & Re-optimization working together
Initial Cardinality estimates are off
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29
On second execution
statement is re-parsed
using execution statistics
New child cursor created
with new plan
New plan changes the join
order
Adaptive Statistics
Adaptive Plans & Re-optimization working together
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30
Adaptive Statistics
 Directives are additional information used during optimization to
generate a better plan
– For example, when table T1 is joined to T2 use dynamic statistics to get
accurate cardinality estimate
– Directives are collected on query expressions not at a statement level
 Allows for directives to be used for multiple statements
– Persisted on disk in the SYSAUX tablespace
– Directives will be automatically maintained
– Managed using the new package DBMS_SPD
SQL Plan Directives
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31
SQL Plan Directives SGA
SHARED_POOL
Select *
FROM customers
where state =‘CA’
AND country=‘USA’;
SQL statement
is submitted
Cursor 0: Select * from customers
……..
Optimizer determines
plan
2
DIRECTIVE CACHE
During execution
cardinality estimate
discovered to be wrong
and directive created
3
IS_REOPTIMIZABLE = Y
Directive: Use DS for customers table
when column city, country are used
1
Sysaux Tablespace
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32
SQL Plan Directives
Select *
FROM customers
where state=‘CA’
AND country=‘USA’;
SQL Directives
Sysaux Tablespace
SGA
This execution and
subsequent execution
use child cursor 1
6
Directive: Use DS for customer table
when column city, country are used
SHARED_POOL
Cursor 0: Select * from customers …..
IS_REOPTIMIZABLE = Y
Optimizer determines
new plan using
execution statistics
5
Cursor 1: Select * from customers …..
IS_REOPTIMIZABLE = N
Directives periodically
persisted to disk in the
sysaux tablespace
Extension Binds Stats Sqlid
SQL Directives
DIRECTIVE CACHEDIRECTIVE CACHE
Same SQL
statement is
submitted
again
4
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33
SQL Plan Directives
Select email
FROM customers
where state=‘MA’
AND country=‘USA’;
New SQL
statement is
submitted on
customers table
7
Optimizer
checks for
directives on
customers table
and finds one on
the columns state
and country
8
Cursor 0: Select email from customers
Optimizer determines
plan with help of
directive
9
Optimizer adds
column group creation
for state & country
columns to next statistics
gather on customer table
10
SGA
DIRECTIVE CACHE
SHARED_POOL
Sysaux Tablespace
Extension Binds Stats Sqlid
SQL Directives
DIRECTIVE CACHE
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34
Number of SQL Plan
Directives used for a
statement is displayed in
the notes section of the
execution plan
In this case one SQL
Plan Directive was used
SQL Plan Directives
In use
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35
SQL Plan Directives
Monitoring
Auto flushed every 15 minutes
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.36
SQL Plan Directives
Monitoring
Auto flushed every 15 minutes
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.37
SQL Plan Directive state
was “MISSING_STATS”
Indicates Oracle can
automatically gather
statistics to improve the
original mis-estimation
In this case a column
group on STATE and
COUNTRY will address
the problem
SQL Plan Directives
Gather statistics to allow automatic creation of missing statistics
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38
SQL Plan Directives
Monitoring
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.39
Correct statistics in place
Optimizer uses statistics
instead of directives
Accurate cardinality
estimate seen in the plan
Statement not marked for
re-optimization
SQL Plan Directives
Final plan no longer needs the directive
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.40
Adaptive Plans
Join methods
Parallel distribution methods
Adaptive Statistics
Discovered at compile time
Discovered at run time
Adaptive Query Optimization
Overview
Adaptive Query
Optimization
Adaptive Plans
Adaptive
Statistics
Join
Methods
Parallel
distribution
Methods
At
compile
time
At run
time
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.41
Summary
 Optimizer begins to learn from its mistakes
– Adaptive Plans
 Adapt join methods
 Adapt parallel distribution methods
– Adaptive Statistics
 Dynamic statistics
 Re-optimization
 SQL Plan Directives
 And lots of other great features!
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.42
Agenda
 Adaptive Query Optimization
 Optimizer Statistics enhancements
 SQL Plan Management enhancements
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.43
Statistics
Enhancements
 New types of histograms
 Online statistics gathering
 Session level statistics for GTTs
 Enhanced incremental statistics
 Concurrent statistics gathering
 Automatic detection of column groups
 Statistic gathering reporting
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.44
Histograms
 Histograms tell Optimizer about the data distribution in a Column
 Creation controlled by METHOD_OPT parameter
 Default create histogram on any column that has been used in the
WHERE clause or GROUP BY of a statement AND has a data skew
 Relies on column usage information gathered at compilation time and
stored in SYS.COL_USAGE$
 Four types of histograms
– Frequency
– Top-Frequency
Oracle Confidential
– Height balanced
– Hybrid
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.45
Histograms
 A frequency histogram is only created if the number of distinct values in
a column (NDV) is less than 254 values
Frequency Histograms (FREQUENCY)
Frequency histogram
Oracle Confidential
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.46
Histograms
 A height balanced histogram is created if the number of distinct values
in a column (NDV) is greater than 254 values
Height Balanced Histograms (HEIGHT BALANCED)
Height balanced histogram
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.47
Histograms
 Traditionally a frequency histogram is only created if NDV < 254
 But if a small number of values occupies most of the rows (>99% rows)
 Creating a frequency histograms on that small set of values is very
useful even though NDV is greater than 254
• Ignores the unpopular values to create a better quality histogram for
popular values
 Built using the same technique used for frequency histograms
 Only created with AUTO_SAMPLE_SIZE
Top Frequency (TOP-FREQUENCY)
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.48
Histograms
 A Hybrid histogram is created if the number of distinct values in a column
(NDV) is greater than 254 values and Top Frequency requirements are not met
Hybrid Histograms (HYBRID)
Hybrid histogram
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.49
Histograms
 Similar to height balanced histogram as created if the NDV >254
 Store the actual frequencies of bucket endpoints in histograms
 No values are allowed to spill over multiple buckets
 More endpoint values can be squeezed in a histogram
 Achieves the same effect as increasing the # of buckets
 Only created with AUTO_SAMPLE_SIZE
Hybrid Histograms (HYBRID)
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.50
Statistics
Enhancements
 New types of histograms
 Online statistics gathering
 Session level statistics for GTTs
 Enhanced incremental statistics
 Concurrent statistics gathering
 Automatic detection of column groups
 Statistic gathering reporting
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.51
Online Statistics Gathering
 Statistics gathered as part of the direct path load operations
– Create Table As Select or Insert As Select commands
 Statistics available directly after load
 No additional table scan required to gather statistics
 All internal maintenance operations that use CTAS benefit from this
 Note only occurs on IAS if table is empty
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.52
New table SALES2 is
created using a CTAS
command
Both table and column
level statistics are
available immediately
after table has been
created
Online Statistics Gathering Example
Statistics immediately available
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.53
Histogram & index
statistics not gathered
To gather these statistics
without re-gathering
basic statistics set option
parameter of
GATHER_TABLE_STATS
to GATHER AUTO
Online Statistics Gathering Example
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.54
Histogram & index
statistics gathered using
new GATHER AUTO
option without
regathering base column
statistics
Online Statistics Gathering Example
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.55
Statistics
Enhancements
 New types of histograms
 Online statistics gathering
 Session level statistics for GTTs
 Enhanced incremental statistics
 Concurrent statistics gathering
 Automatic detection of column groups
 Statistic gathering reporting
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.56
Session private statistics for GTT
 Traditionally statistics gathered on GTT were shared by all sessions
 Share statistics are not always optimal
 Now each session can have its own version of statistics for GTT
 Controlled by new preference GLOBAL_TEMP_TABLE_STATS
 Default value is SESSION (non shared)
 To force sharing (as in 11g) set table preference to SHARED
Overview
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.57
Statistics gathered on a
GTT are no longer
shared by all sessions
To restore shared
statistics change the
table preference
GLOBAL_TEMP_TABLE_STATS
to SHARED
Session private statistics for GTT
By default statistics on GTT are session-private
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.58
Statistics
Enhancements
 New types of histograms
 Online statistics gathering
 Session level statistics for GTTs
 Enhanced incremental statistics
 Concurrent statistics gathering
 Automatic detection of column groups
 Statistic gathering reporting
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.59
Enhanced Incremental Statistics
 Incremental statistics allows global level statistics to accurately
generated from partition level statistics
 NDV statistics can now be accurately aggregated by the introduction of
the synopsis
 The synopses are stored in the Sysaux tablespace
 In 12c reduced the space required to store synopses on disk
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.60
NDV statistics can now
be accurately aggregated
The synopses are stored
in the Sysaux tablespace
12c reduces the space
required to store
synopses on disk
Enhanced Incremental Statistics
Sales Table
May 22nd 2012
May 23rd 2012
May 18th 2012
May 19th 2012
May 20th 2012
May 21st 2012
Sysaux Tablespace
1. Partition level stats are
gathered & synopsis created
2. Global stats
generated by
aggregating partition
level statistics and
synopsis
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.61
Enhanced Incremental Statistics for Partition
Exchange
DBA
1. Create external table for flat files
3. Set INCREMENTAL to true &
INCREMENTAL_LEVEL to TABLE
4. Gather Statistics
Sales Table
May 22nd 2012
May 23rd 2012
May 18th 2012
May 19th 2012
May 20th 2012
May 21st 2012
2. Use CTAS command to create non-partitioned
table TMP_SALES
TMP_SALES
May 24th 2012
Sysaux Tablespace
6. Global stats generated
by aggregating partition
level statistics for existing
partition with stats on new
partition
5. Alter table Sales exchange partition May_24_2012 with
table tmp_sales
May 24th 2012
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.62
During data load some rows
going to the older partitions
In 11g any DML on older
partitions triggered partition
statistics to be re-gathered
New DBMS_STATS preference
INCREMENTAL_STALENESS
When set to
USE_STALE_PERCENT DML on less
than 10% of rows in older
partitions will not trigger re-
gather
Enhanced Incremental Statistics Staleness
Tolerance
Sales Table
May 22nd 2012
May 23rd 2012
May 18th 2012
May 19th 2012
May 20th 2012
May 21st 2012
Sysaux Tablespace
1. Partition level stats are
gathered & synopsis created
2. Global stats
generated by
aggregating partition
level statistics and
synopsis
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.63
Statistics
Enhancements
 New types of histograms
 Online statistics gathering
 Session level statistics for GTTs
 Enhanced incremental statistics
 Concurrent statistics gathering
 Automatic detection of column groups
 Statistic gathering reporting
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.64
Statistics Enhancements
• Gather statistics on multiple objects at the same time
• Controlled by DBMS_STATS preference, CONCURRENT
• Uses Database Scheduler and Advanced Queuing
• Number of concurrent gather operations controlled by
job_queue_processes parameter
• Each gather operation can still operate in parallel
Concurrent Statistics Gathering – Originally introduced in 11.2
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.65
A statistics gathering job is
created for each table and
partition in the schema
Level 1 contain statistics
gathering jobs for all non-
partitioned tables and a
coordinating job for each
partitioned table
Level 2 contain statistics
gathering jobs for each
partition in the partitioned
tables
Concurrent Statistics Gathering for SH Schema
Exec DBMS_STATS.GATHER_SCHEMA_STATS(‘SH’);
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.66
The number of concurrent
gathers is controlled by the
parameter
job_queue_processes
In this example it is set to 3
Remember each concurrent
gather operates in parallel
In this example parallel
degree is 4
Concurrent Statistics Gathering on Partition
Table
Exec DBMS_STATS.GATHER_TABLE_STATS(‘SH’,’SALES);
Sales Table
Partition 1
May 18th 2012
Partition 2
May 19th 2012
Partition 3
May 20th 2012
Job1
Job2
Job3
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.67
Statistics Enhancements
 Batch manager to batch smaller jobs together to reduce scheduling
over head
 Auto statistics gather job can now use concurrency
 Cap to limit the resource available to the job via resource manager
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.68
Statistics
Enhancements
 New types of histograms
 Online statistics gathering
 Session level statistics for GTTs
 Enhanced incremental statistics
 Concurrent statistics gathering
 Automatic detection of column groups
 Statistic gathering reporting
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.69
Extended Statistics
 Two types of Extended Statistics
– Column groups statistics
 Column group statistics useful when multiple column from the same table are
used in where clause predicates or group by clause
– Expression statistics
 Expression statistics useful when a column is used as part of a complex
expression in where clause predicate
 Automatically maintained when statistics are gathered on the table
 Candidates for columns groups can be manually or automatically
determined
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.70
Oracle can automatically
detect column group
candidates based on an
STS or by monitoring a
workload
Uses DBMS_STATS procedure
SEED_COL_USAGE
If the first two arguments are
set to NULL the current
workload will be monitored
The third argument is the
time limit in seconds
Automatic Column Group Detection
1. Start column group usage capture
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.71
Actual number of rows
returned by this query is 932
Optimizer under-estimates
the cardinality as it assumes
each where clause
predicate will reduce
number of rows returned
Optimizer is not aware of
real-world relations between
city, state, & country
Automatic Column Group Detection
2. Run your workload
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.72
Actual number of rows
returned by this query is 145
Optimizer over-estimates
the cardinality as it is not
aware of the real-world
relations between state &
country
Automatic Column Group Detection
2. Run your workload
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.73
Automatic Column Group Detection
3. Check column usage information recorded for our table
COLUMN USAGE REPORT FOR SH.CUSTOMERS
1. COUNTRY_ID : EQ
2. CUST_CITY : EQ
3. CUST_STATE_PROVINCE : EQ
4. (CUST_CITY, CUST_STATE_PROVINCE, COUNTRY_ID) : FILTER
5. (CUST_STATE_PROVINCE, COUNTRY_ID) : GROUP_BY
SELECT dbms_stats.report_col_usage(user, 'customers') FROM dual;
EQ means column was used in
equality predicate in query 1
GROUP_BY columns used in group
by expression in query 2
FILTER means columns used together
as filter predicates rather than join etc.
Comes from query 1
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.74
Automatic Column Group Detection
4. Create extended stats for customers based on usage
EXTENSIONS FOR SH.CUSTOMERS
1. (CUST_CITY, CUST_STATE_PROVINCE, COUNTRY_ID):
SYS_STUMZ$C3AIHLPBROI#SKA58H_N created
2. (CUST_STATE_PROVINCE, COUNTRY_ID) :
SYS_STU#S#WF25Z#QAHIHE#MOFFMM_ created
Column group statistics will now be automatically maintained
every time you gather statistics on this table
SELECT dbms_stats.create_extended_stats(user, 'customers') FROM dual;
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.75
Statistics
Enhancements
 New types of histograms
 Online statistics gathering
 Session level statistics for GTTs
 Enhanced incremental statistics
 Concurrent statistics gathering
 Automatic detection of column groups
 Statistic gathering reporting
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.76
DBMS_STATS.REPORT_STATS_OPERATIONS
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.77
DBMS_STATS.REPORT_GATHER_SCHEMA_STATS
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.78
Agenda
 Adaptive Query Optimization
 Optimizer Statistics enhancements
 SQL Plan Management enhancements
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.79
SQL Plan Management
How it works
Parse
HJ
HJ
GB
Plan history
Plan baseline
Execute
Plan Acceptable
HJ
HJ
GB
Users
Actual execution plans stored in SQL
plan baseline in Oracle Database 12c
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.80
SQL Plan Management
How it works
Parse
NL
NL
GB
Plan history
Plan baseline
HJ
HJ
GB
Users
NL
NL
GB
Note you do not need to be in auto-
capture mode to have a new plan
added to an existing SQL plan baseline
Note additional fields such as fetches,
row processed etc. are not populated
because new plan never executed
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.81
SQL Plan Management
How it works
Parse
Plan history
Plan baseline
Execute
Plan Acceptable
HJ
HJ
GB
Users
NL
NL
GB
HJ
HJ
GB
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.82
Adaptive SQL Plan Management
 New evolve auto task running in the maintenance window
– Ranks all non-accepted plans and runs evolve process for them
 Newly found plans are ranked the highest
– If new plan performs better than existing plan it is automatically accepted
– If new plan performs worse than existing plan it will remain unaccepted
– Poor performing plans will not be retried for 30 days and then only if the
statement is active
SPM Evolve Advisor
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.83
Automatic Plan Evolution
Plan history
Plan baseline
NL
NL
GB
HJ
HJ
GB
Nightly verification task checks for
unaccepted plans
It then test execute
to check if new plan is
as good as or better
than old plan
1
2
Plan history
HJ
HJ
GB
Plan baseline
NL
NL
GB
Plans which perform better than
original plan are recommended
to be added to the plan baseline
3
L
Plans which don’t perform as good
as the original plan stay in the
plan history & are marked
unaccepted but last_verified updated
NL
NL
GB
4
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.84
SPM Evolve Advisor
New nightly auto task
called
SYS_AUTO_SPM_EVOLVE_TASK
Information on task found
in DBA_ADVISOR_TASKS
Adaptive SQL Plan Management
You can review what happening during
the task using DBMS_SPM.
REPORT_AUTO_EVOLVE_TASK
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.85
Reports are persisted
and can be review any
time
Clearer findings section
summaries the results of
the evolve task
New recommendation
section that clearly states
how to implement the
recommendations
proposed
Reviewing the evolve report
Same
comparison
criteria as in 11g
If you can hint it, baseline it
• It is not always possible to add hints to third party applications
• Hints can be extremely difficult to manage over time
• Once added never removed
Alternative approach to hints
Solution
 Use SQL Plan Management (SPM)
Influencing plan without adding hints
• Simple two table join between the SALES and PRODUCTS
Example Overview
Group By
HASH JOIN
TABLE ACCESS
SALES
TABLE ACCESS
PRODUCTS
Group By
HASH JOIN
TABLE ACCESS
SALESINDEX RANGE SCAN
PROD_SUPP_ID_INDX
Current Plan Desired Plan
Influencing plan without adding hints
Step 1. Execute the non-hinted SQL statement
Influencing plan without adding hints
Default plan uses full table scans followed by a hash join
Influencing plan without adding hints
Step 2. Find the SQL_ID for the non-hinted statement in V$SQL
Influencing plan without adding hints
Step 3. Create a SQL plan baseline for the non-hinted SQL statement
Influencing plan without adding hints
Step 4. Captured Plan is not our desired plan so it should be disabled
Influencing plan without adding hints
Step 5. Modify the SQL statement to use the hint(s) & execute it
Influencing plan without adding hints
Step 6. Find SQL_ID & PLAN_HASH_VALUE for hinted SQL stmt
Influencing plan without adding hints
Step 7. Associate hinted plan with original SQL stmt’s SQL HANDLE
Sql_id & plan_hash_value
belong to hinted statement
sql_handle is for
the non-hinted
statement
Influencing plan without adding hints
Step 8. Confirm SQL statement has two plans in its SQL plan baseline
Hinted plan only enabled plan for
non-hinted SQL statement
Influencing plan without adding hints
Step 9. Confirm hinted plan is being used
Non-hinted SQL text but
it is using the plan hash
value for the hinted
statement
Note section also
confirms SQL plan
baseline used for
statement
Copyright © 2012, Oracle and/or its affiliates. All rights reserved.98

More Related Content

What's hot

Independent models validation and automation
Independent models validation and automationIndependent models validation and automation
Independent models validation and automationSohail_farooq
 
IFRS 9 Impairment Analyzer - Brochure
IFRS 9 Impairment Analyzer - BrochureIFRS 9 Impairment Analyzer - Brochure
IFRS 9 Impairment Analyzer - BrochureSohail_farooq
 
Risk listening: monitoring for profitable growth
Risk listening: monitoring for profitable growthRisk listening: monitoring for profitable growth
Risk listening: monitoring for profitable growthDataWorks Summit
 
Soa12c launch 5 event processing shmakov eng cr
Soa12c launch 5 event processing shmakov eng crSoa12c launch 5 event processing shmakov eng cr
Soa12c launch 5 event processing shmakov eng crVasily Demin
 
But I Did What I’ve Always Done and Ended Up Over Budget and Under Expectations
But I Did What I’ve Always Done and Ended Up Over Budget and Under ExpectationsBut I Did What I’ve Always Done and Ended Up Over Budget and Under Expectations
But I Did What I’ve Always Done and Ended Up Over Budget and Under Expectationseprentise
 
Data meets AI - AICUG - Santa Clara
Data meets AI  - AICUG - Santa ClaraData meets AI  - AICUG - Santa Clara
Data meets AI - AICUG - Santa ClaraSandesh Rao
 
Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...
Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...
Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...DataWorks Summit
 
Introduction to Machine Learning - From DBA's to Data Scientists - OGBEMEA
Introduction to Machine Learning - From DBA's to Data Scientists - OGBEMEAIntroduction to Machine Learning - From DBA's to Data Scientists - OGBEMEA
Introduction to Machine Learning - From DBA's to Data Scientists - OGBEMEASandesh Rao
 
Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...
Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...
Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...eprentise
 
Cdcr oracle exadata case study
Cdcr oracle exadata case  studyCdcr oracle exadata case  study
Cdcr oracle exadata case studyjoepanora
 
IaaS strategy evaluation
IaaS strategy evaluation IaaS strategy evaluation
IaaS strategy evaluation WGroup
 
How Arbys Restructured their GL Chart of Accounts
How Arbys Restructured their GL Chart of AccountsHow Arbys Restructured their GL Chart of Accounts
How Arbys Restructured their GL Chart of Accountseprentise
 
Machine Learning trading bots
Machine Learning trading botsMachine Learning trading bots
Machine Learning trading botsDataWorks Summit
 

What's hot (13)

Independent models validation and automation
Independent models validation and automationIndependent models validation and automation
Independent models validation and automation
 
IFRS 9 Impairment Analyzer - Brochure
IFRS 9 Impairment Analyzer - BrochureIFRS 9 Impairment Analyzer - Brochure
IFRS 9 Impairment Analyzer - Brochure
 
Risk listening: monitoring for profitable growth
Risk listening: monitoring for profitable growthRisk listening: monitoring for profitable growth
Risk listening: monitoring for profitable growth
 
Soa12c launch 5 event processing shmakov eng cr
Soa12c launch 5 event processing shmakov eng crSoa12c launch 5 event processing shmakov eng cr
Soa12c launch 5 event processing shmakov eng cr
 
But I Did What I’ve Always Done and Ended Up Over Budget and Under Expectations
But I Did What I’ve Always Done and Ended Up Over Budget and Under ExpectationsBut I Did What I’ve Always Done and Ended Up Over Budget and Under Expectations
But I Did What I’ve Always Done and Ended Up Over Budget and Under Expectations
 
Data meets AI - AICUG - Santa Clara
Data meets AI  - AICUG - Santa ClaraData meets AI  - AICUG - Santa Clara
Data meets AI - AICUG - Santa Clara
 
Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...
Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...
Connecting Home/Building, Life and Car..The Importance of Insurance Risk Moni...
 
Introduction to Machine Learning - From DBA's to Data Scientists - OGBEMEA
Introduction to Machine Learning - From DBA's to Data Scientists - OGBEMEAIntroduction to Machine Learning - From DBA's to Data Scientists - OGBEMEA
Introduction to Machine Learning - From DBA's to Data Scientists - OGBEMEA
 
Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...
Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...
Secondary Ledgers: The Benefits of Adjustment Ledgers for GAAP Reporting and ...
 
Cdcr oracle exadata case study
Cdcr oracle exadata case  studyCdcr oracle exadata case  study
Cdcr oracle exadata case study
 
IaaS strategy evaluation
IaaS strategy evaluation IaaS strategy evaluation
IaaS strategy evaluation
 
How Arbys Restructured their GL Chart of Accounts
How Arbys Restructured their GL Chart of AccountsHow Arbys Restructured their GL Chart of Accounts
How Arbys Restructured their GL Chart of Accounts
 
Machine Learning trading bots
Machine Learning trading botsMachine Learning trading bots
Machine Learning trading bots
 

Similar to Oracle 12c Optimizer IOUG

Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14
Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14
Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14p6academy
 
Setting up the Oracle Optimizer for Proof of Concept Testing
Setting up the Oracle Optimizer for Proof of Concept TestingSetting up the Oracle Optimizer for Proof of Concept Testing
Setting up the Oracle Optimizer for Proof of Concept TestingNigel Bayliss
 
Con9534 fusion financials
Con9534 fusion financialsCon9534 fusion financials
Con9534 fusion financialsBerry Clemens
 
Oracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdf
Oracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdfOracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdf
Oracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdfDetchDuvanGaelaCamar
 
4.0 integrated solution_roadmap_yuchang_su
4.0 integrated solution_roadmap_yuchang_su4.0 integrated solution_roadmap_yuchang_su
4.0 integrated solution_roadmap_yuchang_suningunoreconocido
 
Conociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big data
Conociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big dataConociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big data
Conociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big dataMundo Contact
 
Continuous Performance Monitoring of a Distributed Application [CON4730]
Continuous Performance Monitoring of a Distributed Application [CON4730]Continuous Performance Monitoring of a Distributed Application [CON4730]
Continuous Performance Monitoring of a Distributed Application [CON4730]Ashish Srivastava
 
Twp optimizer-with-oracledb-12c-1963236
Twp optimizer-with-oracledb-12c-1963236Twp optimizer-with-oracledb-12c-1963236
Twp optimizer-with-oracledb-12c-1963236Santosh Kumar
 
Step-by-Step Cookbook for Identifying and Tuning SQL Problems
Step-by-Step Cookbook for Identifying and Tuning SQL ProblemsStep-by-Step Cookbook for Identifying and Tuning SQL Problems
Step-by-Step Cookbook for Identifying and Tuning SQL ProblemsMinh237839
 
Using Change Management in Primavera Contract Management
Using Change Management in Primavera Contract ManagementUsing Change Management in Primavera Contract Management
Using Change Management in Primavera Contract Managementp6academy
 
Collaborate 2012-business data transformation and consolidation
Collaborate 2012-business data transformation and consolidationCollaborate 2012-business data transformation and consolidation
Collaborate 2012-business data transformation and consolidationChain Sys Corporation
 
Collaborate 2012-business data transformation and consolidation for a global ...
Collaborate 2012-business data transformation and consolidation for a global ...Collaborate 2012-business data transformation and consolidation for a global ...
Collaborate 2012-business data transformation and consolidation for a global ...Chain Sys Corporation
 
PaaSing a Java EE Application
PaaSing a Java EE ApplicationPaaSing a Java EE Application
PaaSing a Java EE ApplicationJagadish Prasath
 
HBaseCon 2013: Being Smarter Than the Smart Meter
HBaseCon 2013: Being Smarter Than the Smart MeterHBaseCon 2013: Being Smarter Than the Smart Meter
HBaseCon 2013: Being Smarter Than the Smart MeterCloudera, Inc.
 
A6 harnessing the power of big data and business analytics to transform bus...
A6   harnessing the power of big data and business analytics to transform bus...A6   harnessing the power of big data and business analytics to transform bus...
A6 harnessing the power of big data and business analytics to transform bus...Dr. Wilfred Lin (Ph.D.)
 
206610 instantis for the enterprise
206610 instantis for the enterprise206610 instantis for the enterprise
206610 instantis for the enterprisep6academy
 
Primavera Cost Unifier cost controls and project delivery modules tips and tr...
Primavera Cost Unifier cost controls and project delivery modules tips and tr...Primavera Cost Unifier cost controls and project delivery modules tips and tr...
Primavera Cost Unifier cost controls and project delivery modules tips and tr...p6academy
 
IBM Insight 2014 - Advanced Warehouse Analytics in the Cloud
IBM Insight 2014 - Advanced Warehouse Analytics in the CloudIBM Insight 2014 - Advanced Warehouse Analytics in the Cloud
IBM Insight 2014 - Advanced Warehouse Analytics in the CloudTorsten Steinbach
 

Similar to Oracle 12c Optimizer IOUG (20)

Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14
Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14
Whats new in primavera unifier - Oracle Primavera P6 Collaborate 14
 
Setting up the Oracle Optimizer for Proof of Concept Testing
Setting up the Oracle Optimizer for Proof of Concept TestingSetting up the Oracle Optimizer for Proof of Concept Testing
Setting up the Oracle Optimizer for Proof of Concept Testing
 
Con9534 fusion financials
Con9534 fusion financialsCon9534 fusion financials
Con9534 fusion financials
 
Oracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdf
Oracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdfOracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdf
Oracle-Whitepaper-Optimizer-with-Oracle-Database-12c.pdf
 
4.0 integrated solution_roadmap_yuchang_su
4.0 integrated solution_roadmap_yuchang_su4.0 integrated solution_roadmap_yuchang_su
4.0 integrated solution_roadmap_yuchang_su
 
Six Sigma Project
Six Sigma ProjectSix Sigma Project
Six Sigma Project
 
CMDB Building Blocks
CMDB Building BlocksCMDB Building Blocks
CMDB Building Blocks
 
Conociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big data
Conociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big dataConociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big data
Conociendo y entendiendo a tu cliente mediante monitoreo, analíticos y big data
 
Continuous Performance Monitoring of a Distributed Application [CON4730]
Continuous Performance Monitoring of a Distributed Application [CON4730]Continuous Performance Monitoring of a Distributed Application [CON4730]
Continuous Performance Monitoring of a Distributed Application [CON4730]
 
Twp optimizer-with-oracledb-12c-1963236
Twp optimizer-with-oracledb-12c-1963236Twp optimizer-with-oracledb-12c-1963236
Twp optimizer-with-oracledb-12c-1963236
 
Step-by-Step Cookbook for Identifying and Tuning SQL Problems
Step-by-Step Cookbook for Identifying and Tuning SQL ProblemsStep-by-Step Cookbook for Identifying and Tuning SQL Problems
Step-by-Step Cookbook for Identifying and Tuning SQL Problems
 
Using Change Management in Primavera Contract Management
Using Change Management in Primavera Contract ManagementUsing Change Management in Primavera Contract Management
Using Change Management in Primavera Contract Management
 
Collaborate 2012-business data transformation and consolidation
Collaborate 2012-business data transformation and consolidationCollaborate 2012-business data transformation and consolidation
Collaborate 2012-business data transformation and consolidation
 
Collaborate 2012-business data transformation and consolidation for a global ...
Collaborate 2012-business data transformation and consolidation for a global ...Collaborate 2012-business data transformation and consolidation for a global ...
Collaborate 2012-business data transformation and consolidation for a global ...
 
PaaSing a Java EE Application
PaaSing a Java EE ApplicationPaaSing a Java EE Application
PaaSing a Java EE Application
 
HBaseCon 2013: Being Smarter Than the Smart Meter
HBaseCon 2013: Being Smarter Than the Smart MeterHBaseCon 2013: Being Smarter Than the Smart Meter
HBaseCon 2013: Being Smarter Than the Smart Meter
 
A6 harnessing the power of big data and business analytics to transform bus...
A6   harnessing the power of big data and business analytics to transform bus...A6   harnessing the power of big data and business analytics to transform bus...
A6 harnessing the power of big data and business analytics to transform bus...
 
206610 instantis for the enterprise
206610 instantis for the enterprise206610 instantis for the enterprise
206610 instantis for the enterprise
 
Primavera Cost Unifier cost controls and project delivery modules tips and tr...
Primavera Cost Unifier cost controls and project delivery modules tips and tr...Primavera Cost Unifier cost controls and project delivery modules tips and tr...
Primavera Cost Unifier cost controls and project delivery modules tips and tr...
 
IBM Insight 2014 - Advanced Warehouse Analytics in the Cloud
IBM Insight 2014 - Advanced Warehouse Analytics in the CloudIBM Insight 2014 - Advanced Warehouse Analytics in the Cloud
IBM Insight 2014 - Advanced Warehouse Analytics in the Cloud
 

More from Connor McDonald

Sangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolestSangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolestConnor McDonald
 
Sangam 19 - Analytic SQL
Sangam 19 - Analytic SQLSangam 19 - Analytic SQL
Sangam 19 - Analytic SQLConnor McDonald
 
UKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tipsUKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tipsConnor McDonald
 
Sangam 19 - Successful Applications on Autonomous
Sangam 19 - Successful Applications on AutonomousSangam 19 - Successful Applications on Autonomous
Sangam 19 - Successful Applications on AutonomousConnor McDonald
 
Sangam 2019 - The Latest Features
Sangam 2019 - The Latest FeaturesSangam 2019 - The Latest Features
Sangam 2019 - The Latest FeaturesConnor McDonald
 
UKOUG 2019 - SQL features
UKOUG 2019 - SQL featuresUKOUG 2019 - SQL features
UKOUG 2019 - SQL featuresConnor McDonald
 
APEX tour 2019 - successful development with autonomous
APEX tour 2019 - successful development with autonomousAPEX tour 2019 - successful development with autonomous
APEX tour 2019 - successful development with autonomousConnor McDonald
 
APAC Groundbreakers 2019 - Perth/Melbourne
APAC Groundbreakers 2019 - Perth/Melbourne APAC Groundbreakers 2019 - Perth/Melbourne
APAC Groundbreakers 2019 - Perth/Melbourne Connor McDonald
 
OOW19 - Flashback, not just for DBAs
OOW19 - Flashback, not just for DBAsOOW19 - Flashback, not just for DBAs
OOW19 - Flashback, not just for DBAsConnor McDonald
 
OOW19 - Read consistency
OOW19 - Read consistencyOOW19 - Read consistency
OOW19 - Read consistencyConnor McDonald
 
OOW19 - Slower and less secure applications
OOW19 - Slower and less secure applicationsOOW19 - Slower and less secure applications
OOW19 - Slower and less secure applicationsConnor McDonald
 
OOW19 - Killing database sessions
OOW19 - Killing database sessionsOOW19 - Killing database sessions
OOW19 - Killing database sessionsConnor McDonald
 
OOW19 - Ten Amazing SQL features
OOW19 - Ten Amazing SQL featuresOOW19 - Ten Amazing SQL features
OOW19 - Ten Amazing SQL featuresConnor McDonald
 
Latin America Tour 2019 - 18c and 19c featues
Latin America Tour 2019   - 18c and 19c featuesLatin America Tour 2019   - 18c and 19c featues
Latin America Tour 2019 - 18c and 19c featuesConnor McDonald
 
Latin America tour 2019 - Flashback
Latin America tour 2019 -  FlashbackLatin America tour 2019 -  Flashback
Latin America tour 2019 - FlashbackConnor McDonald
 
Latin America Tour 2019 - 10 great sql features
Latin America Tour 2019  - 10 great sql featuresLatin America Tour 2019  - 10 great sql features
Latin America Tour 2019 - 10 great sql featuresConnor McDonald
 
Latin America Tour 2019 - pattern matching
Latin America Tour 2019 - pattern matchingLatin America Tour 2019 - pattern matching
Latin America Tour 2019 - pattern matchingConnor McDonald
 
Latin America Tour 2019 - slow data and sql processing
Latin America Tour 2019  - slow data and sql processingLatin America Tour 2019  - slow data and sql processing
Latin America Tour 2019 - slow data and sql processingConnor McDonald
 

More from Connor McDonald (20)

Flashback ITOUG
Flashback ITOUGFlashback ITOUG
Flashback ITOUG
 
Sangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolestSangam 19 - PLSQL still the coolest
Sangam 19 - PLSQL still the coolest
 
Sangam 19 - Analytic SQL
Sangam 19 - Analytic SQLSangam 19 - Analytic SQL
Sangam 19 - Analytic SQL
 
UKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tipsUKOUG - 25 years of hints and tips
UKOUG - 25 years of hints and tips
 
Sangam 19 - Successful Applications on Autonomous
Sangam 19 - Successful Applications on AutonomousSangam 19 - Successful Applications on Autonomous
Sangam 19 - Successful Applications on Autonomous
 
Sangam 2019 - The Latest Features
Sangam 2019 - The Latest FeaturesSangam 2019 - The Latest Features
Sangam 2019 - The Latest Features
 
UKOUG 2019 - SQL features
UKOUG 2019 - SQL featuresUKOUG 2019 - SQL features
UKOUG 2019 - SQL features
 
APEX tour 2019 - successful development with autonomous
APEX tour 2019 - successful development with autonomousAPEX tour 2019 - successful development with autonomous
APEX tour 2019 - successful development with autonomous
 
APAC Groundbreakers 2019 - Perth/Melbourne
APAC Groundbreakers 2019 - Perth/Melbourne APAC Groundbreakers 2019 - Perth/Melbourne
APAC Groundbreakers 2019 - Perth/Melbourne
 
OOW19 - Flashback, not just for DBAs
OOW19 - Flashback, not just for DBAsOOW19 - Flashback, not just for DBAs
OOW19 - Flashback, not just for DBAs
 
OOW19 - Read consistency
OOW19 - Read consistencyOOW19 - Read consistency
OOW19 - Read consistency
 
OOW19 - Slower and less secure applications
OOW19 - Slower and less secure applicationsOOW19 - Slower and less secure applications
OOW19 - Slower and less secure applications
 
OOW19 - Killing database sessions
OOW19 - Killing database sessionsOOW19 - Killing database sessions
OOW19 - Killing database sessions
 
OOW19 - Ten Amazing SQL features
OOW19 - Ten Amazing SQL featuresOOW19 - Ten Amazing SQL features
OOW19 - Ten Amazing SQL features
 
Latin America Tour 2019 - 18c and 19c featues
Latin America Tour 2019   - 18c and 19c featuesLatin America Tour 2019   - 18c and 19c featues
Latin America Tour 2019 - 18c and 19c featues
 
Latin America tour 2019 - Flashback
Latin America tour 2019 -  FlashbackLatin America tour 2019 -  Flashback
Latin America tour 2019 - Flashback
 
Latin America Tour 2019 - 10 great sql features
Latin America Tour 2019  - 10 great sql featuresLatin America Tour 2019  - 10 great sql features
Latin America Tour 2019 - 10 great sql features
 
Latin America Tour 2019 - pattern matching
Latin America Tour 2019 - pattern matchingLatin America Tour 2019 - pattern matching
Latin America Tour 2019 - pattern matching
 
Latin America Tour 2019 - slow data and sql processing
Latin America Tour 2019  - slow data and sql processingLatin America Tour 2019  - slow data and sql processing
Latin America Tour 2019 - slow data and sql processing
 
ANSI vs Oracle language
ANSI vs Oracle languageANSI vs Oracle language
ANSI vs Oracle language
 

Recently uploaded

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAndikSusilo4
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking MenDelhi Call girls
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 

Recently uploaded (20)

Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Azure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & ApplicationAzure Monitor & Application Insight to monitor Infrastructure & Application
Azure Monitor & Application Insight to monitor Infrastructure & Application
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
08448380779 Call Girls In Diplomatic Enclave Women Seeking Men
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 

Oracle 12c Optimizer IOUG

  • 1. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.1
  • 2. 2 Copyright © 2012, Oracle and/or its affiliates. All rights reserved. Insert Information Protection Policy Classification from Slide 8 Oracle Optimizer: 12c New Capabilities Thomas Kyte http://asktom.oracle.com/ ORACLE PRODUCT LOGO Wifi sid: guest-access Wifi username: Q7D3KcRn Wifi password: 3dF2DneR
  • 3. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.3 Oracle safe harbor statement The following is intended to outline our general product direction. It is intended for information purposes only, and may not be incorporated into any contract. It is not a commitment to deliver any material, code, or functionality, and should not be relied upon in making purchasing decisions. The development, release, and timing of any features or functionality described for Oracle's products remains at the sole discretion of Oracle.
  • 4. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.4 Optimizer evolution In the beginning there were rules Optimizer evolved to be cost based CBO CBO Optimizer proactively adapts to become self-learning Rule are not enough Databases became more feature rich Reactive tuning with the use of advisors and auto jobs As environment changes Potential for plan changes Databases become more real-time, ad-hoc environments Reactive tuning not enough
  • 5. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.5 Agenda  Adaptive Query Optimization  Optimizer Statistics enhancements  SQL Plan Management enhancements
  • 6. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.6 Adaptive Plans Join methods Parallel distribution methods Adaptive Statistics Discovered at compile time Discovered at run time Adaptive Query Optimization Overview Adaptive Query Optimization Adaptive Plans Adaptive Statistics Join Methods Parallel distribution Methods At compile time At run time
  • 7. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.7 Query: Find all of the products with a unit price of 15 that we have sold more that 1 of Two possible join methods for this query Nested Loops Hash Join Adaptive Execution Plans Adapt join methods
  • 8. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.8 Alternative sub-plans are pre-computed Sub-plans stored in the cursor Stats collect inserted before join Rows buffered until final decision is made Adaptive Execution Plans Adapt join methods Table scan Order _items NESTED LOOPS Index Scan Prod_info_ind Statistics Collector Default Plan is a nested loops join HASH JOIN Table scan Prod_info Rows coming out of order_items table are buffered up to a point If row count is less than the threshold use nested Loops otherwise switch to hash join
  • 9. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.9 Number of rows seen in statistics collector exceeds threshold Plan switches to hash join Statistics collect disabled Plan resolved on first execution & remains the same for subsequent executions Adaptive Execution Plans Adapt join methods Final Plan is a hash join Statistics collector disabled after decision is made and becomes a pass through operation Table scan Order _items NESTED LOOPS Index Scan Prod_info_ind HASH JOIN Table scan Prod_info Statistics Collector
  • 10. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.10 Explain plan command always shows default plan Example shows a nested loops join as default plan No statistics collector shown in plan Adaptive Execution Plans Displaying the default plan
  • 11. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.11 After the statement has completed use DBMS_XPLAN.DISPLAY_CURSOR to see the final plan selected Example shows that hash join picked at execution time Again the statistics collector is not visible in the plan Adaptive Execution Plans Displaying the final plan
  • 12. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.12 Full adaptive plan displayed when format parameter ‘+adaptive’ is set Example shows both the nested loops and hash join in the plan Adaptive Execution Plans Displaying the full adaptive plan
  • 13. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.13 Additional information displayed on why operations are inactive can be seen with format parameter ‘+report’ Adaptive Execution Plans Displaying plan with +adaptive & +report formats
  • 14. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.14 New column in V$SQL IS_RESOLVED_ADAPTIVE_PLAN Indicates statement had an adaptive plan which was resolved on first execution Resolved plan is used for subsequent executions Statistics collectors and buffering is disabled Adaptive Execution Plans Indicator in V$SQL
  • 15. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.15 Adaptive plans are enabled by default Can be put in reporting mode OPTIMIZER_ADAPTIVE_REPORTING_ONLY Reporting mode shows what would have happened during execution in the plan Adaptive Execution Plans Reporting mode
  • 16. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.16 Adaptive Execution Plans  Join method decision deferred until runtime – Default plan is computed using available statistics – Alternate sub-plans are pre-computed and stored in the cursor – Statistic collectors are inserted at key points in the plan  Final decision is based on statistics collected during execution – Default plan and sub-plans have a valid range for statistics collected – If statistics prove to be out of range, the sub-plans will be swapped – Requires buffering near the swap point to avoid returning rows to user  Possible sub-plans are nested loop joins or hash joins and vice versa Adaptive join methods
  • 17. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.17 Adaptive Plans Join methods Parallel distribution methods Adaptive Statistics Discovered at compile time Discovered at run time Adaptive Query Optimization Overview Adaptive Query Optimization Adaptive Plans Adaptive Statistics Join Methods Parallel distribution Methods At compile time At run time
  • 18. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.18 Dynamic Statistics  During compilation optimizer decides if statistics are sufficient to generate a good plan or not  Dynamic statistics are used to compensate for missing, stale, or incomplete statistics  They can be used for table scans, index access, joins and group bys  One type of dynamic statistics is dynamic sampling
  • 19. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.19 Dynamic sampling has a new level 11(AUTO) Decision to use dynamic sampling depends on the complexity of predicate, existing statistics and total execution time Dynamic statistics shared among queries Dynamic Statistics Dynamic Sampling
  • 20. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.20 Dynamic Statistics SGA SHARED_POOL Select * From product_information Where list_price-min_price=29 And category_id not in (11,22) And prod_name like ‘Smart%’; Optimizer checks for existing statistics in data dictionary 2 SHARED DYNAMIC STATISTICS DATA DICTIONARY SQL statement is submitted 1 Optimizer determines plan using dynamic statistics 5 Cursor 0: Select * from product_information … Dynamic sampling occurs on small number of blocks from table Resulting dynamic statistics are stored in cache 4 Statistics found but need to be augmented due to complex predicates 3 Table cardinality estimate for prod_info
  • 21. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.21 Dynamic Statistics SGA SHARED_POOL Select supplier_id, prod_name From product_information Where list_price-min_price=29 And category_id not in (11,22) And prod_name like ‘Smart%’; Optimizer checks for existing statistics in data dictionary 7 SHARED DYNAMIC STATISTICS DATA DICTIONARY Different SQL statement is submitted with same predicates 6 Optimizer determines plan using dynamic statistics 10 Cursor 0: Select supplier_id, prod_name … Necessary Dynamic statistics found in shared cache 9 Statistics found but need to be augmented due to complex predicates 8 Table cardinality estimate for prod_info
  • 22. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.22 Adaptive Statistics  During execution optimizer estimates are compared to execution statistics  If statistics vary significantly then a new plan will be chosen for subsequent executions based on execution statistics  Re-optimization uses statistics gathered from previous executions  First introduced as Cardinality Feedback in 11.2 Re-optimization
  • 23. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.23 Adaptive Statistics  Statistics gathered about data volume and data type seen during execution  If execution statistics vary significantly statement will be hard parsed on the next execution using the execution statistics instead  Statements are only monitored once if they don’t show significant differences initially they won’t change in the future  Only individual table cardinalities and group by estimates examined  Information is stored in the cursor only and is lost if cursor ages out Cardinality Feedback pre 12c
  • 24. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.24 Initial execution of a query is monitored Example shows initial plan is hash join between sales and customers Cardinality estimates 8X off Adaptive Statistics Cardinality Feedback pre 12c Initial Cardinality estimates are more than 8X off
  • 25. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.25 Execution statistics used to reparse the statement on the second execution New plan shows correct cardinality estimates and a new join order Information learnt is stored in the cursor only and is lost if cursor ages out Adaptive Statistics Cardinality Feedback pre 12c Execution Plan after the second execution Estimates are now correct
  • 26. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.26 Adaptive Statistics  Join statistics are also monitored  Works with adaptive cursor sharing for statement with binds  New Column in V$SQL IS_REOPTIMIZABLE  Information found at execution time is persisted as SQL Plan Directives Re-optimization in 12c
  • 27. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.27 New column in V$SQL IS_REOPTIMIZABLE Indicates that the statement will be re-parsed on the next execution Adaptive Statistics Re-optimization – indicator in V$SQL
  • 28. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.28 Adapt join method example showed the join change from nested loops to hash join But cursor is also marked IS_REOPTIMIZABLE Why? Re-optimization will occur on second execution because cardinality estimates off Adaptive Statistics Adaptive Plans & Re-optimization working together Initial Cardinality estimates are off
  • 29. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.29 On second execution statement is re-parsed using execution statistics New child cursor created with new plan New plan changes the join order Adaptive Statistics Adaptive Plans & Re-optimization working together
  • 30. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.30 Adaptive Statistics  Directives are additional information used during optimization to generate a better plan – For example, when table T1 is joined to T2 use dynamic statistics to get accurate cardinality estimate – Directives are collected on query expressions not at a statement level  Allows for directives to be used for multiple statements – Persisted on disk in the SYSAUX tablespace – Directives will be automatically maintained – Managed using the new package DBMS_SPD SQL Plan Directives
  • 31. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.31 SQL Plan Directives SGA SHARED_POOL Select * FROM customers where state =‘CA’ AND country=‘USA’; SQL statement is submitted Cursor 0: Select * from customers …….. Optimizer determines plan 2 DIRECTIVE CACHE During execution cardinality estimate discovered to be wrong and directive created 3 IS_REOPTIMIZABLE = Y Directive: Use DS for customers table when column city, country are used 1 Sysaux Tablespace
  • 32. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.32 SQL Plan Directives Select * FROM customers where state=‘CA’ AND country=‘USA’; SQL Directives Sysaux Tablespace SGA This execution and subsequent execution use child cursor 1 6 Directive: Use DS for customer table when column city, country are used SHARED_POOL Cursor 0: Select * from customers ….. IS_REOPTIMIZABLE = Y Optimizer determines new plan using execution statistics 5 Cursor 1: Select * from customers ….. IS_REOPTIMIZABLE = N Directives periodically persisted to disk in the sysaux tablespace Extension Binds Stats Sqlid SQL Directives DIRECTIVE CACHEDIRECTIVE CACHE Same SQL statement is submitted again 4
  • 33. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.33 SQL Plan Directives Select email FROM customers where state=‘MA’ AND country=‘USA’; New SQL statement is submitted on customers table 7 Optimizer checks for directives on customers table and finds one on the columns state and country 8 Cursor 0: Select email from customers Optimizer determines plan with help of directive 9 Optimizer adds column group creation for state & country columns to next statistics gather on customer table 10 SGA DIRECTIVE CACHE SHARED_POOL Sysaux Tablespace Extension Binds Stats Sqlid SQL Directives DIRECTIVE CACHE
  • 34. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.34 Number of SQL Plan Directives used for a statement is displayed in the notes section of the execution plan In this case one SQL Plan Directive was used SQL Plan Directives In use
  • 35. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.35 SQL Plan Directives Monitoring Auto flushed every 15 minutes
  • 36. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.36 SQL Plan Directives Monitoring Auto flushed every 15 minutes
  • 37. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.37 SQL Plan Directive state was “MISSING_STATS” Indicates Oracle can automatically gather statistics to improve the original mis-estimation In this case a column group on STATE and COUNTRY will address the problem SQL Plan Directives Gather statistics to allow automatic creation of missing statistics
  • 38. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.38 SQL Plan Directives Monitoring
  • 39. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.39 Correct statistics in place Optimizer uses statistics instead of directives Accurate cardinality estimate seen in the plan Statement not marked for re-optimization SQL Plan Directives Final plan no longer needs the directive
  • 40. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.40 Adaptive Plans Join methods Parallel distribution methods Adaptive Statistics Discovered at compile time Discovered at run time Adaptive Query Optimization Overview Adaptive Query Optimization Adaptive Plans Adaptive Statistics Join Methods Parallel distribution Methods At compile time At run time
  • 41. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.41 Summary  Optimizer begins to learn from its mistakes – Adaptive Plans  Adapt join methods  Adapt parallel distribution methods – Adaptive Statistics  Dynamic statistics  Re-optimization  SQL Plan Directives  And lots of other great features!
  • 42. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.42 Agenda  Adaptive Query Optimization  Optimizer Statistics enhancements  SQL Plan Management enhancements
  • 43. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.43 Statistics Enhancements  New types of histograms  Online statistics gathering  Session level statistics for GTTs  Enhanced incremental statistics  Concurrent statistics gathering  Automatic detection of column groups  Statistic gathering reporting
  • 44. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.44 Histograms  Histograms tell Optimizer about the data distribution in a Column  Creation controlled by METHOD_OPT parameter  Default create histogram on any column that has been used in the WHERE clause or GROUP BY of a statement AND has a data skew  Relies on column usage information gathered at compilation time and stored in SYS.COL_USAGE$  Four types of histograms – Frequency – Top-Frequency Oracle Confidential – Height balanced – Hybrid
  • 45. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.45 Histograms  A frequency histogram is only created if the number of distinct values in a column (NDV) is less than 254 values Frequency Histograms (FREQUENCY) Frequency histogram Oracle Confidential
  • 46. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.46 Histograms  A height balanced histogram is created if the number of distinct values in a column (NDV) is greater than 254 values Height Balanced Histograms (HEIGHT BALANCED) Height balanced histogram
  • 47. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.47 Histograms  Traditionally a frequency histogram is only created if NDV < 254  But if a small number of values occupies most of the rows (>99% rows)  Creating a frequency histograms on that small set of values is very useful even though NDV is greater than 254 • Ignores the unpopular values to create a better quality histogram for popular values  Built using the same technique used for frequency histograms  Only created with AUTO_SAMPLE_SIZE Top Frequency (TOP-FREQUENCY)
  • 48. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.48 Histograms  A Hybrid histogram is created if the number of distinct values in a column (NDV) is greater than 254 values and Top Frequency requirements are not met Hybrid Histograms (HYBRID) Hybrid histogram
  • 49. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.49 Histograms  Similar to height balanced histogram as created if the NDV >254  Store the actual frequencies of bucket endpoints in histograms  No values are allowed to spill over multiple buckets  More endpoint values can be squeezed in a histogram  Achieves the same effect as increasing the # of buckets  Only created with AUTO_SAMPLE_SIZE Hybrid Histograms (HYBRID)
  • 50. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.50 Statistics Enhancements  New types of histograms  Online statistics gathering  Session level statistics for GTTs  Enhanced incremental statistics  Concurrent statistics gathering  Automatic detection of column groups  Statistic gathering reporting
  • 51. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.51 Online Statistics Gathering  Statistics gathered as part of the direct path load operations – Create Table As Select or Insert As Select commands  Statistics available directly after load  No additional table scan required to gather statistics  All internal maintenance operations that use CTAS benefit from this  Note only occurs on IAS if table is empty
  • 52. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.52 New table SALES2 is created using a CTAS command Both table and column level statistics are available immediately after table has been created Online Statistics Gathering Example Statistics immediately available
  • 53. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.53 Histogram & index statistics not gathered To gather these statistics without re-gathering basic statistics set option parameter of GATHER_TABLE_STATS to GATHER AUTO Online Statistics Gathering Example
  • 54. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.54 Histogram & index statistics gathered using new GATHER AUTO option without regathering base column statistics Online Statistics Gathering Example
  • 55. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.55 Statistics Enhancements  New types of histograms  Online statistics gathering  Session level statistics for GTTs  Enhanced incremental statistics  Concurrent statistics gathering  Automatic detection of column groups  Statistic gathering reporting
  • 56. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.56 Session private statistics for GTT  Traditionally statistics gathered on GTT were shared by all sessions  Share statistics are not always optimal  Now each session can have its own version of statistics for GTT  Controlled by new preference GLOBAL_TEMP_TABLE_STATS  Default value is SESSION (non shared)  To force sharing (as in 11g) set table preference to SHARED Overview
  • 57. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.57 Statistics gathered on a GTT are no longer shared by all sessions To restore shared statistics change the table preference GLOBAL_TEMP_TABLE_STATS to SHARED Session private statistics for GTT By default statistics on GTT are session-private
  • 58. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.58 Statistics Enhancements  New types of histograms  Online statistics gathering  Session level statistics for GTTs  Enhanced incremental statistics  Concurrent statistics gathering  Automatic detection of column groups  Statistic gathering reporting
  • 59. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.59 Enhanced Incremental Statistics  Incremental statistics allows global level statistics to accurately generated from partition level statistics  NDV statistics can now be accurately aggregated by the introduction of the synopsis  The synopses are stored in the Sysaux tablespace  In 12c reduced the space required to store synopses on disk
  • 60. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.60 NDV statistics can now be accurately aggregated The synopses are stored in the Sysaux tablespace 12c reduces the space required to store synopses on disk Enhanced Incremental Statistics Sales Table May 22nd 2012 May 23rd 2012 May 18th 2012 May 19th 2012 May 20th 2012 May 21st 2012 Sysaux Tablespace 1. Partition level stats are gathered & synopsis created 2. Global stats generated by aggregating partition level statistics and synopsis
  • 61. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.61 Enhanced Incremental Statistics for Partition Exchange DBA 1. Create external table for flat files 3. Set INCREMENTAL to true & INCREMENTAL_LEVEL to TABLE 4. Gather Statistics Sales Table May 22nd 2012 May 23rd 2012 May 18th 2012 May 19th 2012 May 20th 2012 May 21st 2012 2. Use CTAS command to create non-partitioned table TMP_SALES TMP_SALES May 24th 2012 Sysaux Tablespace 6. Global stats generated by aggregating partition level statistics for existing partition with stats on new partition 5. Alter table Sales exchange partition May_24_2012 with table tmp_sales May 24th 2012
  • 62. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.62 During data load some rows going to the older partitions In 11g any DML on older partitions triggered partition statistics to be re-gathered New DBMS_STATS preference INCREMENTAL_STALENESS When set to USE_STALE_PERCENT DML on less than 10% of rows in older partitions will not trigger re- gather Enhanced Incremental Statistics Staleness Tolerance Sales Table May 22nd 2012 May 23rd 2012 May 18th 2012 May 19th 2012 May 20th 2012 May 21st 2012 Sysaux Tablespace 1. Partition level stats are gathered & synopsis created 2. Global stats generated by aggregating partition level statistics and synopsis
  • 63. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.63 Statistics Enhancements  New types of histograms  Online statistics gathering  Session level statistics for GTTs  Enhanced incremental statistics  Concurrent statistics gathering  Automatic detection of column groups  Statistic gathering reporting
  • 64. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.64 Statistics Enhancements • Gather statistics on multiple objects at the same time • Controlled by DBMS_STATS preference, CONCURRENT • Uses Database Scheduler and Advanced Queuing • Number of concurrent gather operations controlled by job_queue_processes parameter • Each gather operation can still operate in parallel Concurrent Statistics Gathering – Originally introduced in 11.2
  • 65. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.65 A statistics gathering job is created for each table and partition in the schema Level 1 contain statistics gathering jobs for all non- partitioned tables and a coordinating job for each partitioned table Level 2 contain statistics gathering jobs for each partition in the partitioned tables Concurrent Statistics Gathering for SH Schema Exec DBMS_STATS.GATHER_SCHEMA_STATS(‘SH’);
  • 66. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.66 The number of concurrent gathers is controlled by the parameter job_queue_processes In this example it is set to 3 Remember each concurrent gather operates in parallel In this example parallel degree is 4 Concurrent Statistics Gathering on Partition Table Exec DBMS_STATS.GATHER_TABLE_STATS(‘SH’,’SALES); Sales Table Partition 1 May 18th 2012 Partition 2 May 19th 2012 Partition 3 May 20th 2012 Job1 Job2 Job3
  • 67. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.67 Statistics Enhancements  Batch manager to batch smaller jobs together to reduce scheduling over head  Auto statistics gather job can now use concurrency  Cap to limit the resource available to the job via resource manager
  • 68. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.68 Statistics Enhancements  New types of histograms  Online statistics gathering  Session level statistics for GTTs  Enhanced incremental statistics  Concurrent statistics gathering  Automatic detection of column groups  Statistic gathering reporting
  • 69. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.69 Extended Statistics  Two types of Extended Statistics – Column groups statistics  Column group statistics useful when multiple column from the same table are used in where clause predicates or group by clause – Expression statistics  Expression statistics useful when a column is used as part of a complex expression in where clause predicate  Automatically maintained when statistics are gathered on the table  Candidates for columns groups can be manually or automatically determined
  • 70. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.70 Oracle can automatically detect column group candidates based on an STS or by monitoring a workload Uses DBMS_STATS procedure SEED_COL_USAGE If the first two arguments are set to NULL the current workload will be monitored The third argument is the time limit in seconds Automatic Column Group Detection 1. Start column group usage capture
  • 71. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.71 Actual number of rows returned by this query is 932 Optimizer under-estimates the cardinality as it assumes each where clause predicate will reduce number of rows returned Optimizer is not aware of real-world relations between city, state, & country Automatic Column Group Detection 2. Run your workload
  • 72. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.72 Actual number of rows returned by this query is 145 Optimizer over-estimates the cardinality as it is not aware of the real-world relations between state & country Automatic Column Group Detection 2. Run your workload
  • 73. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.73 Automatic Column Group Detection 3. Check column usage information recorded for our table COLUMN USAGE REPORT FOR SH.CUSTOMERS 1. COUNTRY_ID : EQ 2. CUST_CITY : EQ 3. CUST_STATE_PROVINCE : EQ 4. (CUST_CITY, CUST_STATE_PROVINCE, COUNTRY_ID) : FILTER 5. (CUST_STATE_PROVINCE, COUNTRY_ID) : GROUP_BY SELECT dbms_stats.report_col_usage(user, 'customers') FROM dual; EQ means column was used in equality predicate in query 1 GROUP_BY columns used in group by expression in query 2 FILTER means columns used together as filter predicates rather than join etc. Comes from query 1
  • 74. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.74 Automatic Column Group Detection 4. Create extended stats for customers based on usage EXTENSIONS FOR SH.CUSTOMERS 1. (CUST_CITY, CUST_STATE_PROVINCE, COUNTRY_ID): SYS_STUMZ$C3AIHLPBROI#SKA58H_N created 2. (CUST_STATE_PROVINCE, COUNTRY_ID) : SYS_STU#S#WF25Z#QAHIHE#MOFFMM_ created Column group statistics will now be automatically maintained every time you gather statistics on this table SELECT dbms_stats.create_extended_stats(user, 'customers') FROM dual;
  • 75. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.75 Statistics Enhancements  New types of histograms  Online statistics gathering  Session level statistics for GTTs  Enhanced incremental statistics  Concurrent statistics gathering  Automatic detection of column groups  Statistic gathering reporting
  • 76. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.76 DBMS_STATS.REPORT_STATS_OPERATIONS
  • 77. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.77 DBMS_STATS.REPORT_GATHER_SCHEMA_STATS
  • 78. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.78 Agenda  Adaptive Query Optimization  Optimizer Statistics enhancements  SQL Plan Management enhancements
  • 79. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.79 SQL Plan Management How it works Parse HJ HJ GB Plan history Plan baseline Execute Plan Acceptable HJ HJ GB Users Actual execution plans stored in SQL plan baseline in Oracle Database 12c
  • 80. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.80 SQL Plan Management How it works Parse NL NL GB Plan history Plan baseline HJ HJ GB Users NL NL GB Note you do not need to be in auto- capture mode to have a new plan added to an existing SQL plan baseline Note additional fields such as fetches, row processed etc. are not populated because new plan never executed
  • 81. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.81 SQL Plan Management How it works Parse Plan history Plan baseline Execute Plan Acceptable HJ HJ GB Users NL NL GB HJ HJ GB
  • 82. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.82 Adaptive SQL Plan Management  New evolve auto task running in the maintenance window – Ranks all non-accepted plans and runs evolve process for them  Newly found plans are ranked the highest – If new plan performs better than existing plan it is automatically accepted – If new plan performs worse than existing plan it will remain unaccepted – Poor performing plans will not be retried for 30 days and then only if the statement is active SPM Evolve Advisor
  • 83. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.83 Automatic Plan Evolution Plan history Plan baseline NL NL GB HJ HJ GB Nightly verification task checks for unaccepted plans It then test execute to check if new plan is as good as or better than old plan 1 2 Plan history HJ HJ GB Plan baseline NL NL GB Plans which perform better than original plan are recommended to be added to the plan baseline 3 L Plans which don’t perform as good as the original plan stay in the plan history & are marked unaccepted but last_verified updated NL NL GB 4
  • 84. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.84 SPM Evolve Advisor New nightly auto task called SYS_AUTO_SPM_EVOLVE_TASK Information on task found in DBA_ADVISOR_TASKS Adaptive SQL Plan Management You can review what happening during the task using DBMS_SPM. REPORT_AUTO_EVOLVE_TASK
  • 85. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.85 Reports are persisted and can be review any time Clearer findings section summaries the results of the evolve task New recommendation section that clearly states how to implement the recommendations proposed Reviewing the evolve report Same comparison criteria as in 11g
  • 86. If you can hint it, baseline it • It is not always possible to add hints to third party applications • Hints can be extremely difficult to manage over time • Once added never removed Alternative approach to hints Solution  Use SQL Plan Management (SPM)
  • 87. Influencing plan without adding hints • Simple two table join between the SALES and PRODUCTS Example Overview Group By HASH JOIN TABLE ACCESS SALES TABLE ACCESS PRODUCTS Group By HASH JOIN TABLE ACCESS SALESINDEX RANGE SCAN PROD_SUPP_ID_INDX Current Plan Desired Plan
  • 88. Influencing plan without adding hints Step 1. Execute the non-hinted SQL statement
  • 89. Influencing plan without adding hints Default plan uses full table scans followed by a hash join
  • 90. Influencing plan without adding hints Step 2. Find the SQL_ID for the non-hinted statement in V$SQL
  • 91. Influencing plan without adding hints Step 3. Create a SQL plan baseline for the non-hinted SQL statement
  • 92. Influencing plan without adding hints Step 4. Captured Plan is not our desired plan so it should be disabled
  • 93. Influencing plan without adding hints Step 5. Modify the SQL statement to use the hint(s) & execute it
  • 94. Influencing plan without adding hints Step 6. Find SQL_ID & PLAN_HASH_VALUE for hinted SQL stmt
  • 95. Influencing plan without adding hints Step 7. Associate hinted plan with original SQL stmt’s SQL HANDLE Sql_id & plan_hash_value belong to hinted statement sql_handle is for the non-hinted statement
  • 96. Influencing plan without adding hints Step 8. Confirm SQL statement has two plans in its SQL plan baseline Hinted plan only enabled plan for non-hinted SQL statement
  • 97. Influencing plan without adding hints Step 9. Confirm hinted plan is being used Non-hinted SQL text but it is using the plan hash value for the hinted statement Note section also confirms SQL plan baseline used for statement
  • 98. Copyright © 2012, Oracle and/or its affiliates. All rights reserved.98