Performance Tuning
Performance Tuning
SAURABH MEHTA
Date: 1-August-2011
Contact :
[email protected]
Discussion Objectives
Day1:
Basics of Performance Tuning
Understanding oracle Optimizer
Tools for performance Tuning
Q&A
Day2:
Identifying performance bottlenecks
How to Approach Performance Issue?
Writing SQL for performance
Understanding Analytic Functions
Q&A
Day3:
Understanding Materialized Views
Understanding Partitions
Understanding Hints
Q&A
Basics of Performance Tuning
Performance??
SQL statements
Performance Tuning Roles
Generate plan
description
Execute the
plan
Transform plan
into “executable”
How Does Oracle Process SQL?
[1] Syntactic - checks the syntax of the query
[2] Semantic- checks that all objects exist and are accessible
Plan 1 cost=1000
How accurate is
Plan 2 cost=3000 the cost estimation?
Plan 3 cost=4000
Plan 4 cost= 500 Execution
Limitations Of Optimizer
• EXPLAIN PLAN
• SQL trace and TKPROF
• SQL*Plus autotrace feature
• SQL Advisor
Explain Plan
•Tool that describes the algorithm the database will use to run a SQL statement.
• With Oracle, there are a number of ways of running Explain Plan.
Assumption: You have access to PLAN_TABLE
• Option 1: SQL*PLUS EXPLAIN
This is the low-tech method for those with no access to a nice GUI tool. This is a two
step process:
Add the following line BEFORE your SQL statement
EXPLAIN PLAN SET STATEMENT_ID = ‘S314000011’ FOR
SELECT * FROM emp;
SELECT STATEMENT
MERGE JOIN
SORT JOIN
NESTED LOOPS
TABLE ACCESS FULL TELLER
TABLE ACCESS BY ROWID BRANCH
INDEX UNIQUE SCAN IBRANCH
SORT JOIN
TABLE ACCESS FULL ACCOUNT
• SQL row source execution starts from the TOP RIGHTMOST INDENTED operation.
• Next stages in plan execution use row sources from previous operations
Reading Query Plan
Sorted rows from step 6,7 are then
RESULT merged together
4 5
NESTED LOOP Table Access ACCOUNT (Full)
1
FULL table scan scans all rows in
the table.
Index Unique-Scan IBRANCH
Data is accessed by looking up key values in
an index and returning rowids.
SQL Trace & TKPROF
SQL TRACE is the main method for collecting SQL Execution information in Oracle, it
collects a wide range of information and statistics that can be used to tune SQL
operations.
The SQL Trace facility can be enabled/disabled for an individual session or at the
instance level.
Enabling SQL tracing for an entire instance
> SQL_TRACE = TRUE (INIT.ORA)
Syntax:
tkprof tracefile outpufile explain=user/passwd sys=no waits=yes sort=exeela,fchela
Here exeela = elapsed time executing and fchela = elapsed time fetching
d
ows P rocesse
R
SQL Tuning Advisor: Overview
Statistics check
optimization mode Detect stale or missing
statistics
SQL Tuning
SQL analysis
optimization mode Advisor Restructure SQL
Using the SQL Tuning Advisor
In this case
Row source 1 is outer table
Row source 2 is inner table
Sort Merge
When to Use Any Join Equi Joins only Equi Joins Only
Features Works with any join Better than NL when index Better than NL when
are missing or search not index are missing not
No sorting required restrictive restrictive
Drawbacks Very inefficient when index Must perform sort before rows Can require lot of
are missing or search in not are returned. Expensive operation memory
restrictive
Indexes
•Indexed retrieval is almost always faster (not 100% true) than full-
table scans
•In general, index
• Primary key columns (By default)
• Foreign key columns
• Columns used frequently in WHERE and ORDER BY clauses
• Know your Indexes and use them to your advantage
Comparison Operators that will use an index Comparison Operators that will not use an index
= col = :a != col != :a
NOT anything col NOT <:a
>[=] col >= :a
NOT col <:a
<[=] col < :a col NOT LIKE 'ABC%'
BETWEEN col BETWEEN :a AND :b LIKE '%...' col LIKE '%ABC%'
LIKE '_...' col LIKE '_ABC%'
LIKE col LIKE 'ABC%'
IS NULL col IS NULL
IN (list) col IN (1, 2, 3) IS NOT NULL col IS NOT NULL
B*Tree Index
A composite index contains more than one key column. Composite indexes can
provide additional advantages over single column indexes.
Better Selectivity :Sometimes two or more columns, each with poor selectivity,
can be combined to form a composite index with good selectivity.
Adding Data Storage: If all the columns selected by the query are in the composite
index, Oracle can return these values from the index without accessing the table.
CREATE INDEX idx_composite ON mytab (x, y, z);
These combinations of columns are leading portions of the index: X, XY, and XYZ.
These combinations of columns are not leading portions of the index: YZ and Z.
Operations & Options
Other Issues
• Are any of the tables remote?
• Is Parallel execution involved? (Example)
Writing SQL for performance
EXISTS vs IN
• Use NOT EXISTS in place of NOT IN.
In sub-query statement such as the following NOT IN clause causes an
internal Sort/Merge.
SELECT *
FROM emp e
WHERE e.deptno NOT IN ( SELECT d.deptno
FROM dept d
WHERE d.dname like %S% ) ;
To improve performance use the following code.
SELECT *
FROM emp e
WHERE NOT EXISTS ( SELECT d.deptno
FROM dept d
WHERE d.deptno = e.deptno
AND d.dname LIKE '%S%' ) ;
This would allow such statements to use an index, if one exists.
EXISTS vs JOIN
•Use Joins in place of EXISTS.
In general, join tables rather than specifying sub-queries.
SELECT * FROM emp e WHERE EXISTS ( SELECT d.deptno FROM dept d WHERE e.deptno = d.deptno AND
d.dname = 'RESEARCH') ;
To improve performance use the following:
SELECT * FROM emp e, dept d WHERE e.deptno = d.deptno AND d.dname = 'RESEARCH' ; .
•EXISTS in place of DISTINCT.
Use EXISTS in place of DISTINCT if you want the result set to contain distinct values while joining tables.
SELECT DISTINCT d.deptno ,d.dname ,
FROM dept d , emp e
WHERE d.deptno = e.deptno ;
SELECT *
FROM emp
WHERE NOT deptno = 0;
SELECT *
FROM emp
WHERE deptno > 0;
Index Usage
/** Do Not use **/ /** Suggested Alternative **/
SELECT * SELECT *
FROM emp FROM emp
WHERE sal != 0 ; WHERE sal > 0 ;
Note: Index can tell you what is there in a table but not what is not in a table.
•ORDER BY clause
Required Output select count(case when sal between 1001 and 2000 then
empno end) Sal_1k_2k ,
count(case when sal between 2001 and 3000 then empno
Sal_1K_2K Sal_2K_3K Sal_3K_4K end) Sal_2k_3k ,
count(case when sal between 3001 and 4000 then empno
6 5 0 end) Sal_3k_4K
from scott.emp
Working with Date
Find all objects created on a particular DATE?
name varchar2(30)
type varchar2(18)
referenced_owner varchar2(30)
referenced_name varchar2(64)
referenced_link_name varchar2(128)
dependency_type varchar2(4)
Issue: The delete below takes long time and sometime hangs.
delete from my_uobject where object_name='DUAL‘;
Union vs Union All
UNION will eliminate any duplicate rows returned by the various select
statements being unioned whereas UNION ALL will not. It will return all
records even duplicates.
• When? – Starting 8i
Features/Capabilities
• Can be partitioned and indexed
• Can be queried directly
• Can have DML applied against it
• Several refresh options are available
• Best in read-intensive environments
Materialized Views
Advantages
• Useful for summarizing, pre-computing, replicating and distributing data
• Faster access for expensive and complex joins
• Transparent to end-users(MVs can be added/dropped without invalidating
coded SQL)
Disdvantages
• Storage costs of maintaining the views
• Maintenance overhead for Support team
Materialized Views
Materialized View Syntax
CREATE MATERIALIZED VIEW <name>
TABLESPACE <tbs name> {<storage parameters>}
<build option>
REFRESH <refresh option> <refresh mode>
[ENABLE|DISABLE] QUERY REWRITE
AS
SELECT <select clause>;
• Local
• A local index is equi-partitioned with the underlying table, so
each index partition has entries for rows in a single table
partition. The partition bounds will be the same as for the table
itself.
Understanding Hints
External Links:
http://www.datadisk.co.uk/html_docs/oracle/sql_optimization.htm
http://www.akadia.com/services/ora_interpreting_explain_plan.html
http://www.adp-gmbh.ch/ora/sql/join/join_methods.html