Top tips for Oracle SQL tuning Guy Harrison Senior Software Architect, Quest Software BUY QUEST PRODUCTS BUY GUY’S BOOK BUY QUEST PRODUCTS.

Slides:



Advertisements
Similar presentations
Tuning Oracle SQL The Basics of Efficient SQLThe Basics of Efficient SQL Common Sense Indexing The Optimizer –Making SQL Efficient Finding Problem Queries.
Advertisements

Copyright © 2007 Ramez Elmasri and Shamkant B. Navathe Slide
Tuning: overview Rewrite SQL (Leccotech)Leccotech Create Index Redefine Main memory structures (SGA in Oracle) Change the Block Size Materialized Views,
Understanding SQL Server Query Execution Plans
Chapter 9. Performance Management Enterprise wide endeavor Research and ascertain all performance problems – not just DBMS Five factors influence DB performance.
Module 13: Performance Tuning. Overview Performance tuning methodologies Instance level Database level Application level Overview of tools and techniques.
Overview of performance tuning strategies Oracle Performance Tuning Allan Young June 2008.
© Bharati Vidyapeeths Institute of Computer Applications and Management, New Delhi © Bharati Vidyapeeths Institute of Computer Applications and.
What Happens when a SQL statement is issued?
1 Copyright © 2011, Oracle and/or its affiliates. All rights reserved.
Copyright © 200\8 Quest Software High Performance PL/SQL Guy Harrison Chief Architect, Database Solutions.
INTRODUCTION TO ORACLE Lynnwood Brown System Managers LLC Performance And Tuning – Lecture 7 Copyright System Managers LLC 2007 all rights reserved.
Agenda Overview of the optimizer How SQL is executed Identifying statements that need tuning Explain Plan Modifying the plan.
David Konopnicki Choosing Access Path ä The basic methods. ä The access paths and when they are available. ä How the optimizer chooses among the.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 11 Database Performance Tuning and Query Optimization.
Database Systems More SQL Database Design -- More SQL1.
Optimization Exercises. Question 1 How do you think the following query should be computed? What indexes would you suggest to use? SELECT E.ename, D.mgr.
Architecting a Large-Scale Data Warehouse with SQL Server 2005 Mark Morton Senior Technical Consultant IT Training Solutions DAT313.
AN INTRODUCTION TO EXECUTION PLAN OF QUERIES These slides have been adapted from a presentation originally made by ORACLE. The full set of original slides.
ORACLE ONLINE TRAINING Contact our Support Team : SOFTNSOL India: Skype id : softnsoltrainings id:
Relational Database Performance CSCI 6442 Copyright 2013, David C. Roberts, all rights reserved.
Executing Explain Plans and Explaining Execution Plans Craig Martin 01/20/2011.
Database Systems: Design, Implementation, and Management Tenth Edition Chapter 11 Database Performance Tuning and Query Optimization.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Database Systems: Design, Implementation, and Management Eighth Edition Chapter 10 Database Performance Tuning and Query Optimization.
Oracle Database Administration Lecture 6 Indexes, Optimizer, Hints.
1 Robert Wijnbelt Health Check your Database A Performance Tuning Methodology.
Physical Database Design & Performance. Optimizing for Query Performance For DBs with high retrieval traffic as compared to maintenance traffic, optimizing.
Module 7 Reading SQL Server® 2008 R2 Execution Plans.
Ashwani Roy Understanding Graphical Execution Plans Level 200.
Chapter 7 © 2013 Pearson Education, Inc. Publishing as Prentice Hall 1 Modern Database Management 11 th Edition Jeffrey A. Hoffer, V. Ramesh, Heikki Topi.
RBO RIP George Lumpkin Director Product Management Oracle Corporation Session id:
1 Optimizing Your ColdFusion Applications for Oracle Justin Fidler, CNA, CPS, CCFD Chief Technology Officer Bantu, Inc. 8 May 2001.
Basic Optimization DB Workshop for LHC online/offline developers CERN January
11-1 Improve response time of interactive programs. Improve batch throughput. To ensure scalability of applications load vs. performance. Reduce system.
Star Transformations Tony Hasler, UKOUG Birmingham 2012 Tony Hasler, Anvil Computer Services Ltd.
SQL Performance and Optimization l SQL Overview l Performance Tuning Process l SQL-Tuning –EXPLAIN PLANs –Tuning Tools –Optimizing Table Scans –Optimizing.
1 Chapter 10 Joins and Subqueries. 2 Joins & Subqueries Joins – Methods to combine data from multiple tables – Optimizer information can be limited based.
Database Systems Design, Implementation, and Management Coronel | Morris 11e ©2015 Cengage Learning. All Rights Reserved. May not be scanned, copied or.
Oracle tuning: a tutorial Saikat Chakraborty. Introduction In this session we will try to learn how to write optimized SQL statements in Oracle 8i We.
Module 4 Database SQL Tuning Section 3 Application Performance.
1 Chapter 13 Parallel SQL. 2 Understanding Parallel SQL Enables a SQL statement to be: – Split into multiple threads – Each thread processed simultaneously.
Physical Database Design Purpose- translate the logical description of data into the technical specifications for storing and retrieving data Goal - create.
Chapter 8 Physical Database Design. Outline Overview of Physical Database Design Inputs of Physical Database Design File Structures Query Optimization.
Chapter 5 Index and Clustering
NSF DUE ; Wen M. Andrews J. Sargeant Reynolds Community College Richmond, Virginia.
1 Copyright © 2005, Oracle. All rights reserved. Following a Tuning Methodology.
Last Updated : 27 th April 2004 Center of Excellence Data Warehousing Group Teradata Performance Optimization.
1 Chapter 9 Tuning Table Access. 2 Overview Improve performance of access to single table Explain access methods – Full Table Scan – Index – Partition-level.
Sorting and Joining.
Query Processing – Implementing Set Operations and Joins Chap. 19.
Oracle9i Developer: PL/SQL Programming Chapter 11 Performance Tuning.
Database Systems, 8 th Edition SQL Performance Tuning Evaluated from client perspective –Most current relational DBMSs perform automatic query optimization.
Dynamicpartnerconnections.com Development for performance Oleksandr Katrusha, Program manager
 CONACT UC:  Magnific training   
Scott Fallen Sales Engineer, SQL Sentry Blog: scottfallen.blogspot.com.
Diving into Query Execution Plans ED POLLACK AUTOTASK CORPORATION DATABASE OPTIMIZATION ENGINEER.
3 Copyright © 2006, Oracle. All rights reserved. Designing and Developing for Performance.
11 Copyright © 2009, Oracle. All rights reserved. Enhancing ETL Performance.
Tuning Oracle SQL The Basics of Efficient SQL Common Sense Indexing
More SQL: Complex Queries, Triggers, Views, and Schema Modification
SQL Trace and TKPROF.
Indexes By Adrienne Watt.
Database Performance Tuning &
Database Performance Tuning and Query Optimization
Practical Database Design and Tuning
Chapter 11 Database Performance Tuning and Query Optimization
Diving into Query Execution Plans
Introduction to the Optimizer
Performance Tuning ETL Process
Presentation transcript:

Top tips for Oracle SQL tuning Guy Harrison Senior Software Architect, Quest Software BUY QUEST PRODUCTS BUY GUY’S BOOK BUY QUEST PRODUCTS

Top 10 Oracle SQL tuning tips 1.Design and develop with performance in mind 2.Establish a tuning environment 3.Index wisely 4.Reduce parsing 5.Take advantage of Cost Based Optimizer 6.Avoid accidental table scans 7.Optimize necessary table scans 8.Optimize joins 9.Use array processing 10.Consider PL/SQL for “tricky” SQL

Hint #1: Design and develop with performance in mind  Explicitly identify performance targets  Focus on critical transactions –Test the SQL for these transactions against simulations of production data  Measure performance as early as possible  Consider prototyping critical portions of the applications  Consider de-normalization and other performance by design features early on

Hint #2: Establish a tuning and development environment  A significant portion of SQL that performs poorly in production was originally crafted against empty or nearly empty tables.  Make sure you establish a reasonable sub-set of production data that is used during development and tuning of SQL  Make sure your developers understand EXPLAIN PLAN and tkprof, or equip them with commercial tuning tools.

Understanding SQL tuning tools  The foundation tools for SQL tuning are: –The EXPLAIN PLAN command –The SQL Trace facility –The tkprof trace file formatter  Effective SQL tuning requires either familiarity with these tools or the use of commercial alternatives such as SQLab

EXPLAIN PLAN  The EXPLAIN PLAN reveals the execution plan for an SQL statement.  The execution plan reveals the exact sequence of steps that the Oracle optimizer has chosen to employ to process the SQL.  The execution plan is stored in an Oracle table called the “plan table”  Suitably formatted queries can be used to extract the execution plan from the plan table.

A simple EXPLAIN PLAN SQL> EXPLAIN PLAN FOR select count(*) from sales where product_id=1; Explained. SQL> SELECT RTRIM (LPAD (' ', 2 * LEVEL) || RTRIM (operation) ||' '||RTRIM (options) || ' ' || object_name) query_plan 2 FROM plan_table 3 CONNECT BY PRIOR id = parent_id 4* START WITH id = 0 QUERY_PLAN SELECT STATEMENT SORT AGGREGATE TABLE ACCESS FULL SALES

Interpreting EXPLAIN PLAN  The more heavily indented an access path is, the earlier it is executed.  If two steps are indented at the same level, the uppermost statement is executed first.  Some access paths are “joined” – such as an index access that is followed by a table lookup.

A more complex EXPLAIN PLAN SELECT STATEMENT VIEW SYS_DBA_SEGS UNION-ALL NESTED LOOPS VIEW SYS_OBJECTS UNION-ALL TABLE ACCESS FULL TAB$ TABLE ACCESS FULL TABPART$ TABLE ACCESS FULL CLU$ TABLE ACCESS FULL IND$ TABLE ACCESS FULL INDPART$ TABLE ACCESS FULL LOB$ TABLE ACCESS FULL TABSUBPART$ TABLE ACCESS FULL INDSUBPART$ TABLE ACCESS FULL LOBFRAG$ TABLE ACCESS BY INDEX ROWID OBJ$ INDEX UNIQUE SCAN I_OBJ1 TABLE ACCESS CLUSTER SEG$ INDEX UNIQUE SCAN I_FILE#_BLOCK# TABLE ACCESS BY INDEX ROWID FILE$ INDEX UNIQUE SCAN I_FILE2 TABLE ACCESS CLUSTER TS$ INDEX UNIQUE SCAN I_TS# TABLE ACCESS CLUSTER USER$ INDEX UNIQUE SCAN I_USER# NESTED LOOPS TABLE ACCESS FULL UNDO$ TABLE ACCESS BY INDEX ROWID FILE$ INDEX UNIQUE SCAN I_FILE2 TABLE ACCESS CLUSTER SEG$ INDEX UNIQUE SCAN I_FILE#_BLOCK# TABLE ACCESS CLUSTER TS$ INDEX UNIQUE SCAN I_TS# TABLE ACCESS CLUSTER USER$ INDEX UNIQUE SCAN I_USER# NESTED LOOPS TABLE ACCESS FULL FILE$ TABLE ACCESS CLUSTER SEG$ INDEX RANGE SCAN I_FILE#_BLOCK# TABLE ACCESS CLUSTER TS$ INDEX UNIQUE SCAN I_TS# TABLE ACCESS CLUSTER USER$ INDEX UNIQUE SCAN I_USER#

SQL_TRACE and tkprof  ALTER SESSION SET SQL_TRACE TRUE causes a trace of SQL execution to be generated.  The TKPROF utility formats the resulting output.  Tkprof output contains breakdown of execution statistics, execution plan and rows returned for each step. These stats are not available from any other source.  Tkprof is the most powerful tool, but requires a significant learning curve.

Tkprof output count 2 cpu 3 elapsed 4 disk 5 query 6 current 7 rows Parse a 1 d Execute b 1 e Fetch c 20 j i total k f g 99 h Rows l Execution Plan m SELECT STATEMENT GOAL: CHOOSE 99 FILTER TABLE ACCESS GOAL: ANALYZED (FULL) OF 'CUSTOMERS' TABLE ACCESS GOAL: ANALYZED (FULL) OF 'EMPLOYEES'

Using SQLab  Because EXPLAIN PLAN and tkprof are unwieldy and hard to interpret, third party tools that automate the process and provide expert advice improve SQL tuning efficiency.  The Quest SQLab product: –Identifies SQL your database that could benefit from tuning –Provides a sophisticated tuning environment to examine, compare and evaluate execution plans. –Incorporates an expert system to advise on indexing and SQL statement changes

SQLab SQL tuning lab –Display execution plan in a variety of intuitive ways –Provide easy access to statistics and other useful data –Model changes to SQL and immediately see the results

SQLab Expert Advice –SQLab provides specific advice on how to tune an SQL statement

SQLab SQL trace integration –SQLab can also retrieve the execution statistics that are otherwise only available through tkprof

Hint #3: Index wisely  Index to support selective WHERE clauses and join conditions  Use concatenated indexes where appropriate  Consider overindexing to avoid table lookups  Consider advanced indexing options –Hash Clusters –Bit mapped indexes –Index only tables

Effect of adding columns to a concatenated index –Novice SQL programmers often are satisfied if the execution plan shows an index –Make sure the index has all the columns required

Bit-map indexes –Contrary to widespread belief, can be effective when there are many distinct column values –Not suitable for OLTP however

Hint #4: Reduce parsing  Use bind variables –Bind variables are key to application scalability –If necessary in , set cursor CURSOR_SHARING to FORCE  Reuse cursors in your application code –How to do this depends on your development language  Use a cursor cache –Setting SESSION_CACHED_CURSORS (to 20 or so) can help applications that are not re-using cursors

Hint #5: Take advantage of the Cost Based Optimizer  The older rule based optimizer is inferior in almost every respect to the modern cost based optimizer  Using the cost based optimizer effectively involves: –Regular collection of table statistics using the ANALYZE or DBMS_STATS command –Understand hints and how they can be used to influence SQL statement execution –Choose the appropriate optimizer mode: FIRST_ROWS is best for OLTP applications; ALL_ROWS suits reporting and OLAP jobs

Hint #6: Avoid accidental tablescans  Tablescans that occur unintentionally are a major source of poorly performing SQL. Causes include: –Missing Index –Using “!=“, “<>” or NOT Use inclusive range conditions or IN lists –Looking for values that are NULL Use NOT NULL values with a default value –Using functions on indexed columns Use “functional” indexes in Oracle8i

Hint #7: Optimize necessary table scans  There are many occasions where a table scan is the only option. If so: –Consider parallel query option –Try to reduce size of the table Adjust PCTFREE and PCTUSED Relocate infrequently used long columns or BLOBs Rebuild when necessary to reduce the high water mark –Improve the caching of the table Use the CACHE hint or table property Implement KEEP and RECYCLE pools –Partition the table (if you really seek a large subset of data) –Consider the fast full index scan

Fast full index scan performance –Use when you must read every row, but not every column –Counting the rows in a table is a perfect example

Hint #8: Optimize joins  Pick the best join method –Nested loops joins are best for indexed joins of subsets –Hash joins are usually the best choice for “big” joins  Pick the best join order –Pick the best “driving” table –Eliminate rows as early as possible in the join order  Optimize “special” joins when appropriate –STAR joins for data-warehousing applications –STAR_TRANSFORMATION if you have bitmap indexes –ANTI-JOIN methods for NOT IN sub-queries –SEMI-JOIN methods for EXISTS sub-queries –Properly index CONNECT BY hierarchical queries

 Optimizes queries using EXISTS where there is no supporting index select * from customers c where exists (select 1 from employees e where e.surname=c.contact_surname and e.firstname=c.contact_firstname and e.date_of_birth=c.date_of_birth) Oracle 8 semi-joins No index on employees

Oracle 8 semi-joins  Without the semi-join or supporting index, queries like the one on the preceding slide will perform very badly.  Oracle will perform a tablescan of the inner table for each row retrieved by the outer table  If customers has 100,000 rows, and employees 800 rows then 80 MILLION rows will be processed!  In Oracle7, you should create the index or use an IN- based subquery  In Oracle8, the semi-join facility allows the query to be resolved by a sort-merge or hash join.

To Use semi-joins  Set ALWAYS_SEMI_JOIN=HASH or MERGE in INIT.ORA, OR  Use a MERGE_SJ or HASH_SJ hint in the subquery of the SQL statement SELECT * FROM customers c WHERE exists (select /*+merge_sj*/ 1 from employees e where ….)

Oracle8 semi-joins  The performance improvements are impressive (note the logarithmic scale)

Star Join improvements  A STAR join involves a large “FACT” table being joined to a number of smaller “dimension” tables

Star Join improvements  The Oracle7 Star join algorithm works well when there is a concatenated index on all the FACT table columns  But when there are a large number of dimensions, creating concatenated indexes for all possible queries is impossible.  Oracle8’s “Star transformation” involves re-wording the query so that it can be supported by combinations of bitmap indexes.  Since bitmap indexes can be efficiently combined, a single bitmap index on each column can support all possible queries.

To enable the star transformation  Create bitmap indexes on each of the FACT table columns which are used in star queries  Make sure that STAR_TRANSFORMATION_ENABLED is TRUE, either by changing init.ora or using an ALTER SESSION statement.  Use the STAR_TRANSFORMATION hint if necessary.

Drawback of Star transformation  Bitmap indexes reduce concurrency (row-level locking may break down).  But remember that large number of distinct column values may not matter

Star transformation performance  When there is no suitable concatenated index, the Star transformation results in a significant improvement

Hint #9: Use ARRAY processing –Retrieve or insert rows in batches, rather than one at a time. –Methods of doing this are language specific

Hint #10: Consider PL/SQL for “tricky” SQL  With SQL you specify the data you want, not how to get it. Sometime you need to specifically dictate your retrieval algorithms.  For example: –Getting the second highest value –Doing lookups on a low-high lookup table –Correlated updates –SQL with multiple complex correlated subqueries –SQL that seems to hard to optimize unless it is broken into multiple queries linked in PL/SQL

Oracle8i PL/SQL Improvements –Array processing –NOCOPY –Temporary tables –The profiler –Dynamic SQL

Bonus hint: When your SQL is tuned, look to your Oracle configuration  When SQL is inefficient there is limited benefit in investing in Oracle server or operating system tuning.  However, once SQL is tuned, the limiting factor for performance will be Oracle and operating system configuration.  In particular, check for internal Oracle contention that typically shows up as latch contention or unusual wait conditions (buffer busy, free buffer, etc)  Third party tools – such as Quest’s Spotlight on Oracle product – can be invaluable

w w w. q u e s t. c o m