Beruflich Dokumente
Kultur Dokumente
List of discussion
Query execution overview Optimizer basics Understanding RBO Understanding CBO Understanding Hints Best practices
1. Create a cursor 2. Parse a statement <<< sql optimization 3. Describe query results 4. Define query output 5. Bind variables <<< after sql optimization 6. Parallelize the statement 7. Execute the statement 8. Fetch rows of a query 9. Close the cursor
8
SGA
Shared Pool
Log buffer
Shared pool maintains shareable parts of the cursor: query text Execution plan Bind variable data types and lengths Shareable cursors saves resources from unnecessary parsing.
10
Parse stage has determined if the SQL can be parallized, and parallel plan already built.
11
Steps 7 through 9
Execute:
Puts values into all bind variables Drives the SQL statement to produce the desired results
12
To remember .
Query optimization is in parsing stage, which is before binding variables. Cost of Non-sharable SQL, out of scope Next what is query optimization ...
Optimizer Basic
13
14
Optimizer Basic
It is an Oracle engine that would choose the most efficient method on retrieving data on a given query. The steps chosen is called execution plan. Two kind of Optimizer on Oracle:
RBO or Rule Based Optimizer since v6 CBO or Cost Based Optimizer since v7
15
Parse
Query rewrite
Result
Query Execution
QEP Generation
16
17
18
View Merging
View merging rewrites queries containing views so that only base tables remain. It is only done when a correct results is guaranteed. Either view is pushed out to query, or query is pushed into the view. If it cannot be merged, then view must be executed separately. (VIEW and FILTER operator on explain plan)
19
Non-merge-able Views
Group by clause All aggregate functions Rownum reference Start with / connect by clause All set operation (union, minus, ) Distinct (unless query also has distinct) Has join with tables in original query
20
Sub-query Merging
Merging sub-query to open up new access path and new join order
Single row subqueries. (Oracle will evaluate subquery and store the result) IN or subqueries might be converted into EXISTS or NOT EXISTS or in line view
21
22
Transitivity
CBO performs transitivity as the first step in optimization. It generates additional predicates based on existing predicates. This would open more access paths. Transitivity is NOT done for join predicates.
23
Transitivity Example
A=5, A=B then it is concluded that B=5
A=B , B=C then oracle would NOT conclude that A=C
Understanding RBO
24
25
Understanding RBO
Released with Oracle 6. Using an ordered list of access methods and join methods on relative cost or each operation. Has a very limited input in determining access paths. Will be removed from the Oracle database Server Normally, it chooses the path from right to left in the from clause. If hint (except RULE hint) is supplied, then it will run under CBO. On some complex queries, it outperforms CBO
RBO ranking
1. Single row by ROWID 2. Single row by cluster join. 3. Single row by hash cluster key with unique key. 4. Single row by unique index. 5. Cluster join. 6. Hash Cluster key. 7. Indexed cluster key. 8. Composite key. 9. Single-column non-unique index. 10. Bounded range search on indexed columns 11. Unbounded range search on indexed columns 12. Sort-merge join 13. Max or Min of indexed columns 14. Order by on indexed columns 15. Full table-scan. (cluster)
26
(cluster)
(cluster) (cluster) (cluster)
27
Not so good things about RBO... method. RBO has a small number of possible access
28
(it does not recognize IOT, bitmap index, hash join, ) It will process the tables based on how they are ordered on the query. (can be good and most of the time is not so good) Always ranks execution plan based on relative cost in the list, regardless of the data stored in the table. Index scan will always better than table scan, which is not true. Coding for the RBO is halted. All new features require implementation of CBO. RBO uses poor information to break frequently occurring ties.
Understanding CBO
29
30
Understanding CBO
It uses all available information. Dictionary , statistics, histogram, supplied parameter setting. CBO uses Oracle intelligent formula to calculate the COST of a SQL statement. Constantly improving from version to version. It examines all possible access methods (defaulted to 80,000 permutations) Evaluate the costs for each access plan, then simple choose the lowest one
31
Database statistics (partial list ) DBA_TABLES (num_rows, blocks, empty_blocks, avg_space, chain_cnt, avg_row_len, last_analyzed, sample_size, avg_space_freelist_blocks) DBA_TAB_COLUMNS or DBA_TAB_COL_STATISTICS (num_distinct, low_value, high_value, density, num_nulls, num_buckets) DBA_INDEXES (blevel, leaf_blocks, distinct_keys, clustering_factor, num_rows, avg_leaf_block_per_key)
32
selectivity for relations on indexed columns .009 selectivity for = on indexed columns .004 multiblock read factor 8 remote table average row length 100 # of blocks 100 Scan cost 13 Index levels 1 number leaf blocks/key 1
33
34
First_row applies a heuristic bias to the cost model to promote the use of indexes and nested loop)
35
Cost is the estimated number of I/O, CPU, Network operations that a statement requires. CPU cost (parse) has little impact on a SQL tuning on most cases. While I/O is the most. Difference between logical and physical I/O It is affected by some parameters:
36
Example
37
Index access
number or levels in the B*-tree number of leaf blocks to examine
38
Cost of Sorting
Data may need to be sorted for:
Sorts are typically CPU intensive, and can be I/O bound if the sort can not fit in memory. Cost depends on sort_area_size and # rows.
39
MERGE
Sort
Sort
Row source 1
Row source 2
40
Nested Loop
Access A (Full)
41
Output rows
DISK
42
43
Using HINT
44
45
The optimization approach (RULE, ALL_ROWS, FIRST_ROWS) The access path for a table accessed (FULL , INDEX,HASH, ...) The join order and method (ordered, leading, star, use_nl, use_merge, use_hash ...)
46
47
48
49
50
51
52
53
Best Practices
54
55
View / subquery merging, transitivity FIRST_ROWS vs ALL_ROWS vs RULE Different logic from version to version. Dynamic plan based on statistics
CBO behavior changes from version to version. Set by optimizer_features_enable Know the impact of using bind variables
Do not compare with using literals Oracle 9i, peeking bind variables before generating explain plan
56
57
Nested views and multi view joins. Unnecessarily using views. ( as select * from snp_)
Drop bad indexes , low ratio for distinct values / num rows For composite index, start with column that has more distinct values. Unique scan for unique index, use all index columns Generate Histogram for skewwed indexes
58
Up-to-date statistics High water mark of a table Optimal setting for init.ora parameter Use Histogram if necessary for skewed data Bind variables Missing object statistics on some tables Remotely join tables
Statistics can be exported to different environment Use DBMS_STATS instead of analyze command
59
Guide optimizer to start with the most selective predicates. Ordered hint might prevent CBO to find an alternative plan as data distribution change. Cautious with parallel degree. Make sure the load is no contention, and not overloading DB servers.
Use RULE hint on complex query if it performs better. Understand the impact of putting HINT inside a view. Syntax error will be ignored. /*+ <HINT> */ Multiple HINTS can be applied, separate with space
60
Most cases, order on from and where clause don't matter. In some complex query, it may influence CBO access path. CBO evaluates list of predicates (where) clause to start evaluating explain plan By default it is 80,000 permutation generated Index scan is NOT always outperform Full table scan Join involves more than 5 table often confuse CBO.
61
References
Oracle SQL Tuning: Pocket Reference, by Mark Gurry. Everything You Always wanted to know about optimizer: Student guide, by Oracle University. The Search for Intelligent Life in The Cost-Based Optimizer, Tim Gorman, Database Technologies, Inc Cost Based Optimizer (CBO)- A Technology Change or a New Feature?, Muthu Ramaswamy, GERS Inc. Inside the Oracle Cost Based Optimizer, Richard M. Slavik, S&P Solutions Note:35934.1: Cost Based Optimizer - Common Misconception and Issues, Metalink.oracle.com Sources from Oracle 8.1.7 documentation, performance tuning guide.
Q&A
Thank you
62