SlideShare a Scribd company logo
1 of 49
SQL Tuning 101
The three pillars of SQL Tuning:
Diagnostics Collection, Root Cause Analysis and
Remediation
Carlos Sierra
Agenda
• Motivation
• Methodology
– Diagnostics Collection
– Root Cause Analysis
– Remediation
• Some Important Topics
– Execution Plan
– Cost-based Optimizer
– Plan Stability
• Free Tools
Motivation
• One bad SQL can degrade overall DB performance!
• SQL Tuning is:
– A Complex Task
– Part Science and part Art
– The Responsibility of WHO?
• DBA?
• Developer?
• Oracle?
• Application Vendor?
Methodology
The three pillars of SQL Tuning
1. Good Practices
2. Diagnostics Collection
3. Root Cause Analysis (RCA)
4. Remediation
I. Good Practices
• The forgotten pillar of SQL Tuning
• Quid pro Quo (e.g. This for That or Give and Take)
– Be nice to the CBO and the CBO will be nice to you
• A healthy environment requires less SQL Tuning
• A win-win!
• Except for Consultants like myself!
Some Good Practices
• Start with a modern and solid database release
• Reset all CBO related parameters (and some more)
• Gather CBO Statistics as per Application or Product
– Automatic task does a decent job on 11.2.0.4+
• Write reasonable SQL
– Use the product as designed and avoid weird SQL
– If SQL is too long or too complex the CBO will struggle
Partial list of Parameters to Reset
• optimizer_features_enable
• optimizer_index_cost_adj
• optimizer_index_caching
• db_file_multiblock_read_count (not CBO exclusive)
• cursor_sharing (not an optimizer parameter)
• optimizer_dynamic_sampling
• optimizer_mode
II. Diagnostics Collection
a) Identify SQL_ID
b) Use Oracle-product base Tools
c) Supplement with specialized Tools
II.a Identify SQL_ID
• Oracle Enterprise Manager (OEM)
– [ OEM] [ Database | Grid | Cloud ] Control
• Automatic Workload Repository (AWR)
• Statspack (SP)
• SQL Trace (and TKPROF)
• V$ dynamic views (e.g. V$SQL and V$SESSION)
II.b Oracle-product base Tools
• SQL Trace (and TKPROF)
• Active Session History (ASH)
• EXPLAIN PLAN FOR
• AUTOTRACE
• SQL Developer
• DBMS_XPLAN
• SQL Monitor
SQL Trace
• ALTER SESSION SET
– SQL_TRACE = [ TRUE | FALSE ]
– EVENTS ‘10046 trace name context forever, level N’
• N = 1: all executions (10g-) or 1st execution (11g+)
• N = 4: Binds
• N = 8: Waits
• N = 12 = 4 + 8
• N = 16: each execution (11g+)
• N = 64: 1st + each where DB time > 1min (11.2.0.2+)
Where is my Trace?
• V$DIAG_INFO (11.1+)
• USER_DUMP_DEST (deprecated 12c)
TKPROF: SQL Text and DB Calls
TKPROF: Execution Plan and Wait Events
Active Session History (ASH)
• 1 sec snapshots of V$SESSION
• Every 10 ASH samples into AWR (10 sec granularity)
• Sessions “ON CPU” or “WAITING” (non-idle)
• Multiple Dimensions
• Excellent repository for performance data mining
• Requires Oracle Diagnostics Pack!
SQL Trace vs. ASH
Pros
• Precise
• Free
Pros
• Always available
• Multi-dimensional repository
• Plan line granularity (11g+)
Cons
• Re-execute transaction
• Waits per cursor
– No plan line granularity
Cons
• Requires Diagnostics Pack
EXPLAIN PLAN FOR
• Actual SQL is not executed
• Blind to Bind Peeking, thus unreliable with Binds
SET AUTOTRACE ON
• Actual SQL is executed
• Includes small subset of Session Statistics
Query Output and Execution Plan
Predicate Information and Session Stats
SQL Developer
DBMS_XPLAN
• DISPLAY (from PLAN_TABLE)
• DISPLAY_CURSOR
• DISPLAY_AWR
• DISPLAY_SQL_PLAN_BASELINE
• DISPLAY_SQL_SET
• SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY%());
DBMS_XPLAN.DISPLAY_CURSOR
• SQL_ID
• CURSOR_CHILD_NO (defaults to 0!)
• FORMAT
– TYPICAL = DEFAULT
– ALL = TYPICAL + QB + PROJECTION + ALIAS + REMOTE
– ADVANCED = ALL + OUTLINE + BINDS
– ALLSTATS = IOSTATS + MEMSTATS (all executions)
– ALLSTATS LAST (last execution)
– ADAPTIVE (12c)
Sample query with hints and binds
SQL Monitor
• Part of the Oracle Tuning Pack
• Tabular and Graphical Execution Plan
• Timeline per Plan Line
• Binds and Predicates
• Nice and intuitive
• Executed from OEM or SQL*Plus
II.c Specialized Tools
• SQLTXPLAIN (a.k.a. SQLT)
– My Oracle Support (MOS) 215187.1
• SQLHC
– MOS 1366133.1
• SQLd360
– By Mauro Pagano
• Others?
III. Root Cause Analysis
• This is where you want to spend your time!
• Go over all the output of your specialized tool
• Look for correlations and possible causation
• Put yourself in the shoes of the Optimizer
• Question everything (is there a better way?)
• Ask for help after you have done your homework
• Enjoy the ride!
Typical Steps
1. Find where the time is spent (plan line)
– Too many executions or too much time per exec?
2. Validate estimated rows versus actual rows
– If off determine why (deficient statistics maybe?)
3. What is the history of this SQL?
– Can you find a better performing plan?
4. Can you make perfect sense of the SQL and plan?
IV. Remediation
• Explore multiple possibilities
– And try to prove yourself wrong!
• Implement the smallest-scope fix
– Avoid system-wide changes unless you are rock solid!
• Avoid guesses and assumptions (piñata method)
– Too many people out there are “tuning” blind-folded!
• Trust nobody! (be skeptic and test thoroughly)
Three Important Topics
1. Execution Plan
2. Cost-based Optimizer
3. Plan Stability
1. Execution Plan
• If you do not understand the SQL or the Execution
Plan stop right there!
• From SQL text you can draw a diagram if that helps
• To understand the Execution Plan start small
– Review a two-tables query and review plan
– Move to a three-tables query and review plan
– Introduce subqueries and more complex constructions
2. Cost-based Optimizer
• CBO was released on 7.3 (circa February 1996)
• A large and complex piece of software enhanced
for two decades
• By design the CBO produces an optimal execution
plan according to some representation of the data
– This means: execution plans are expected to change!
– Breathe deep and embrace the change!
3. Plan Stability
• Most DBAs hate Execution Plan changes
– They never hear of changes for the better!
• To remediate undesired plan changes we do have
several Plan Stability techniques
– SQL Plan Management (Baselines) from 11g
– SQL Profiles from 10g
– Deprecated Stored Outlines from 9i
– And then some others (SQL Patches and CBO Hints)
Popular Free Diagnostics Tools
• SQLTXPLAIN
• SQLHC
• SQLd360
• Stand-alone scripts
SQLTXPLAIN
SQLd360
SQLd360 Plan Tree
SQLT XPLAIN vs. SQLd360
Pros
• Oracle Support Standard
• Free (requires MOS account)
• Comprehensive and mature
Pros
• Free Software (no strings)
• Installs nothing on database
• Graphical visualization of data
Cons
• Requires installation
• HTML Tables (no charts)
Cons
• Still young (frequent releases)
SQL Tuning Road Map
1. Start with a clean and healthy environment
2. Identify SQL_ID
3. Collect diagnostics using comprehensive tools
4. Spend time analyzing diagnostics collected
5. Determine root cause
6. Explore remediation actions
7. Test and implement solution
Questions
The End
• http://carlos-sierra.net/
– Blog and downloads
• carlos.sierra.usa@gmail.com
– Questions and follow-up
• SQL Tuning is more about understanding
what your eyes see at first

More Related Content

What's hot

Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsZohar Elkayam
 
SQL Plan Directives explained
SQL Plan Directives explainedSQL Plan Directives explained
SQL Plan Directives explainedMauro Pagano
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuningGuy Harrison
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptChien Chung Shen
 
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...Carlos Sierra
 
Troubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel PoderTroubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel PoderTanel Poder
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Aaron Shilo
 
Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360Carlos Sierra
 
Oracle database performance tuning
Oracle database performance tuningOracle database performance tuning
Oracle database performance tuningYogiji Creations
 
SQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12cSQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12cTanel Poder
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsEnkitec
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder
 
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentalsDB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentalsJohn Beresniewicz
 
Chasing the optimizer
Chasing the optimizerChasing the optimizer
Chasing the optimizerMauro Pagano
 
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdfOracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdfSrirakshaSrinivasan2
 
Oracle statistics by example
Oracle statistics by exampleOracle statistics by example
Oracle statistics by exampleMauro Pagano
 
Troubleshooting Complex Performance issues - Oracle SEG$ contention
Troubleshooting Complex Performance issues - Oracle SEG$ contentionTroubleshooting Complex Performance issues - Oracle SEG$ contention
Troubleshooting Complex Performance issues - Oracle SEG$ contentionTanel Poder
 
All of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL DeveloperAll of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL DeveloperJeff Smith
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptChien Chung Shen
 

What's hot (20)

Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
 
SQL Plan Directives explained
SQL Plan Directives explainedSQL Plan Directives explained
SQL Plan Directives explained
 
Oracle sql high performance tuning
Oracle sql high performance tuningOracle sql high performance tuning
Oracle sql high performance tuning
 
Oracle Database SQL Tuning Concept
Oracle Database SQL Tuning ConceptOracle Database SQL Tuning Concept
Oracle Database SQL Tuning Concept
 
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...
Understanding How is that Adaptive Cursor Sharing (ACS) produces multiple Opt...
 
Troubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel PoderTroubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel Poder
 
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
Exploring Oracle Database Performance Tuning Best Practices for DBAs and Deve...
 
Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360Understanding my database through SQL*Plus using the free tool eDB360
Understanding my database through SQL*Plus using the free tool eDB360
 
Oracle database performance tuning
Oracle database performance tuningOracle database performance tuning
Oracle database performance tuning
 
SQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12cSQL Monitoring in Oracle Database 12c
SQL Monitoring in Oracle Database 12c
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning FundamentalsOracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
 
Tanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools shortTanel Poder - Scripts and Tools short
Tanel Poder - Scripts and Tools short
 
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentalsDB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
DB Time, Average Active Sessions, and ASH Math - Oracle performance fundamentals
 
Chasing the optimizer
Chasing the optimizerChasing the optimizer
Chasing the optimizer
 
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdfOracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
Oracle_Multitenant_19c_-_All_About_Pluggable_D.pdf
 
Oracle statistics by example
Oracle statistics by exampleOracle statistics by example
Oracle statistics by example
 
Troubleshooting Complex Performance issues - Oracle SEG$ contention
Troubleshooting Complex Performance issues - Oracle SEG$ contentionTroubleshooting Complex Performance issues - Oracle SEG$ contention
Troubleshooting Complex Performance issues - Oracle SEG$ contention
 
AWR and ASH Deep Dive
AWR and ASH Deep DiveAWR and ASH Deep Dive
AWR and ASH Deep Dive
 
All of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL DeveloperAll of the Performance Tuning Features in Oracle SQL Developer
All of the Performance Tuning Features in Oracle SQL Developer
 
Oracle Database Performance Tuning Concept
Oracle Database Performance Tuning ConceptOracle Database Performance Tuning Concept
Oracle Database Performance Tuning Concept
 

Similar to SQL Tuning 101

An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1Navneet Upneja
 
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse SupportOracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse Supportnkarag
 
Database Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance AnalysisDatabase Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance AnalysisDAGEOP LTD
 
Embarcadero In Search of Plan Stability Part 1 Webinar Slides
Embarcadero In Search of Plan Stability Part 1 Webinar SlidesEmbarcadero In Search of Plan Stability Part 1 Webinar Slides
Embarcadero In Search of Plan Stability Part 1 Webinar SlidesEmbarcadero Technologies
 
Oracle Database : Addressing a performance issue the drilldown approach
Oracle Database : Addressing a performance issue the drilldown approachOracle Database : Addressing a performance issue the drilldown approach
Oracle Database : Addressing a performance issue the drilldown approachLaurent Leturgez
 
261197832 8-performance-tuning-part i
261197832 8-performance-tuning-part i261197832 8-performance-tuning-part i
261197832 8-performance-tuning-part iNaviSoft
 
Winning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editionsWinning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editionsPini Dibask
 
Collaborate 2019 - How to Understand an AWR Report
Collaborate 2019 - How to Understand an AWR ReportCollaborate 2019 - How to Understand an AWR Report
Collaborate 2019 - How to Understand an AWR ReportAlfredo Krieg
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basicsnitin anjankar
 
Winning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editionsWinning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editionsPini Dibask
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresJitendra Singh
 
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12cPresentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12cRonald Francisco Vargas Quesada
 
In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1Enkitec
 
collab2011-tuning-ebusiness-421966.pdf
collab2011-tuning-ebusiness-421966.pdfcollab2011-tuning-ebusiness-421966.pdf
collab2011-tuning-ebusiness-421966.pdfElboulmaniMohamed
 
Getting optimal performance from oracle e business suite
Getting optimal performance from oracle e business suiteGetting optimal performance from oracle e business suite
Getting optimal performance from oracle e business suiteaioughydchapter
 
Getting optimal performance from oracle e business suite(aioug aug2015)
Getting optimal performance from oracle e business suite(aioug aug2015)Getting optimal performance from oracle e business suite(aioug aug2015)
Getting optimal performance from oracle e business suite(aioug aug2015)pasalapudi123
 
A data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonA data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonTerry Bunio
 
Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502kaziul Islam Bulbul
 

Similar to SQL Tuning 101 (20)

An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1An Approach to Sql tuning - Part 1
An Approach to Sql tuning - Part 1
 
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse SupportOracle SQL Tuning for Day-to-Day Data Warehouse Support
Oracle SQL Tuning for Day-to-Day Data Warehouse Support
 
Database Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance AnalysisDatabase Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance Analysis
 
Embarcadero In Search of Plan Stability Part 1 Webinar Slides
Embarcadero In Search of Plan Stability Part 1 Webinar SlidesEmbarcadero In Search of Plan Stability Part 1 Webinar Slides
Embarcadero In Search of Plan Stability Part 1 Webinar Slides
 
Free oracle performance tools
Free oracle performance toolsFree oracle performance tools
Free oracle performance tools
 
Oracle Database : Addressing a performance issue the drilldown approach
Oracle Database : Addressing a performance issue the drilldown approachOracle Database : Addressing a performance issue the drilldown approach
Oracle Database : Addressing a performance issue the drilldown approach
 
261197832 8-performance-tuning-part i
261197832 8-performance-tuning-part i261197832 8-performance-tuning-part i
261197832 8-performance-tuning-part i
 
Breaking data
Breaking dataBreaking data
Breaking data
 
Winning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editionsWinning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editions
 
Collaborate 2019 - How to Understand an AWR Report
Collaborate 2019 - How to Understand an AWR ReportCollaborate 2019 - How to Understand an AWR Report
Collaborate 2019 - How to Understand an AWR Report
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
 
Winning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editionsWinning performance challenges in oracle standard editions
Winning performance challenges in oracle standard editions
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
 
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12cPresentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12c
 
In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1In Search of Plan Stability - Part 1
In Search of Plan Stability - Part 1
 
collab2011-tuning-ebusiness-421966.pdf
collab2011-tuning-ebusiness-421966.pdfcollab2011-tuning-ebusiness-421966.pdf
collab2011-tuning-ebusiness-421966.pdf
 
Getting optimal performance from oracle e business suite
Getting optimal performance from oracle e business suiteGetting optimal performance from oracle e business suite
Getting optimal performance from oracle e business suite
 
Getting optimal performance from oracle e business suite(aioug aug2015)
Getting optimal performance from oracle e business suite(aioug aug2015)Getting optimal performance from oracle e business suite(aioug aug2015)
Getting optimal performance from oracle e business suite(aioug aug2015)
 
A data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madisonA data driven etl test framework sqlsat madison
A data driven etl test framework sqlsat madison
 
Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502Collaborate 2011-tuning-ebusiness-416502
Collaborate 2011-tuning-ebusiness-416502
 

More from Carlos Sierra

How a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DBHow a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DBCarlos Sierra
 
Oracle Performance Tools of the Trade
Oracle Performance Tools of the TradeOracle Performance Tools of the Trade
Oracle Performance Tools of the TradeCarlos Sierra
 
Introducing the eDB360 Tool
Introducing the eDB360 ToolIntroducing the eDB360 Tool
Introducing the eDB360 ToolCarlos Sierra
 
Introducing the eDB360 Tool
Introducing the eDB360 ToolIntroducing the eDB360 Tool
Introducing the eDB360 ToolCarlos Sierra
 
Using SQL Plan Management (SPM) to balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to balance Plan Flexibility and Plan StabilityUsing SQL Plan Management (SPM) to balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to balance Plan Flexibility and Plan StabilityCarlos Sierra
 
SQL Tuning made easier with SQLTXPLAIN (SQLT)
SQL Tuning made easier with SQLTXPLAIN (SQLT)SQL Tuning made easier with SQLTXPLAIN (SQLT)
SQL Tuning made easier with SQLTXPLAIN (SQLT)Carlos Sierra
 
SQLT XPLORE: The SQLT XPLAIN hidden child
SQLT XPLORE: The SQLT XPLAIN hidden childSQLT XPLORE: The SQLT XPLAIN hidden child
SQLT XPLORE: The SQLT XPLAIN hidden childCarlos Sierra
 

More from Carlos Sierra (7)

How a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DBHow a Developer can Troubleshoot a SQL performing poorly on a Production DB
How a Developer can Troubleshoot a SQL performing poorly on a Production DB
 
Oracle Performance Tools of the Trade
Oracle Performance Tools of the TradeOracle Performance Tools of the Trade
Oracle Performance Tools of the Trade
 
Introducing the eDB360 Tool
Introducing the eDB360 ToolIntroducing the eDB360 Tool
Introducing the eDB360 Tool
 
Introducing the eDB360 Tool
Introducing the eDB360 ToolIntroducing the eDB360 Tool
Introducing the eDB360 Tool
 
Using SQL Plan Management (SPM) to balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to balance Plan Flexibility and Plan StabilityUsing SQL Plan Management (SPM) to balance Plan Flexibility and Plan Stability
Using SQL Plan Management (SPM) to balance Plan Flexibility and Plan Stability
 
SQL Tuning made easier with SQLTXPLAIN (SQLT)
SQL Tuning made easier with SQLTXPLAIN (SQLT)SQL Tuning made easier with SQLTXPLAIN (SQLT)
SQL Tuning made easier with SQLTXPLAIN (SQLT)
 
SQLT XPLORE: The SQLT XPLAIN hidden child
SQLT XPLORE: The SQLT XPLAIN hidden childSQLT XPLORE: The SQLT XPLAIN hidden child
SQLT XPLORE: The SQLT XPLAIN hidden child
 

Recently uploaded

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsAhmed Mohamed
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...confluent
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Mater
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmSujith Sukumaran
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...OnePlan Solutions
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Developmentvyaparkranti
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commercemanigoyal112
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odishasmiwainfosol
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanyChristoph Pohl
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZABSYZ Inc
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprisepreethippts
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Matt Ray
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsSafe Software
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024StefanoLambiase
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringHironori Washizaki
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based projectAnoyGreter
 

Recently uploaded (20)

Unveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML DiagramsUnveiling Design Patterns: A Visual Guide with UML Diagrams
Unveiling Design Patterns: A Visual Guide with UML Diagrams
 
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
Catch the Wave: SAP Event-Driven and Data Streaming for the Intelligence Ente...
 
Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)Ahmed Motair CV April 2024 (Senior SW Developer)
Ahmed Motair CV April 2024 (Senior SW Developer)
 
Intelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalmIntelligent Home Wi-Fi Solutions | ThinkPalm
Intelligent Home Wi-Fi Solutions | ThinkPalm
 
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
Maximizing Efficiency and Profitability with OnePlan’s Professional Service A...
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
VK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web DevelopmentVK Business Profile - provides IT solutions and Web Development
VK Business Profile - provides IT solutions and Web Development
 
Cyber security and its impact on E commerce
Cyber security and its impact on E commerceCyber security and its impact on E commerce
Cyber security and its impact on E commerce
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company OdishaBalasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
Balasore Best It Company|| Top 10 IT Company || Balasore Software company Odisha
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte GermanySuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
SuccessFactors 1H 2024 Release - Sneak-Peek by Deloitte Germany
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
Salesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZSalesforce Implementation Services PPT By ABSYZ
Salesforce Implementation Services PPT By ABSYZ
 
Odoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 EnterpriseOdoo 14 - eLearning Module In Odoo 14 Enterprise
Odoo 14 - eLearning Module In Odoo 14 Enterprise
 
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
Open Source Summit NA 2024: Open Source Cloud Costs - OpenCost's Impact on En...
 
Powering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data StreamsPowering Real-Time Decisions with Continuous Data Streams
Powering Real-Time Decisions with Continuous Data Streams
 
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
Dealing with Cultural Dispersion — Stefano Lambiase — ICSE-SEIS 2024
 
Machine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their EngineeringMachine Learning Software Engineering Patterns and Their Engineering
Machine Learning Software Engineering Patterns and Their Engineering
 
MYjobs Presentation Django-based project
MYjobs Presentation Django-based projectMYjobs Presentation Django-based project
MYjobs Presentation Django-based project
 

SQL Tuning 101

  • 1. SQL Tuning 101 The three pillars of SQL Tuning: Diagnostics Collection, Root Cause Analysis and Remediation Carlos Sierra
  • 2. Agenda • Motivation • Methodology – Diagnostics Collection – Root Cause Analysis – Remediation • Some Important Topics – Execution Plan – Cost-based Optimizer – Plan Stability • Free Tools
  • 3. Motivation • One bad SQL can degrade overall DB performance! • SQL Tuning is: – A Complex Task – Part Science and part Art – The Responsibility of WHO? • DBA? • Developer? • Oracle? • Application Vendor?
  • 4. Methodology The three pillars of SQL Tuning 1. Good Practices 2. Diagnostics Collection 3. Root Cause Analysis (RCA) 4. Remediation
  • 5. I. Good Practices • The forgotten pillar of SQL Tuning • Quid pro Quo (e.g. This for That or Give and Take) – Be nice to the CBO and the CBO will be nice to you • A healthy environment requires less SQL Tuning • A win-win! • Except for Consultants like myself!
  • 6. Some Good Practices • Start with a modern and solid database release • Reset all CBO related parameters (and some more) • Gather CBO Statistics as per Application or Product – Automatic task does a decent job on 11.2.0.4+ • Write reasonable SQL – Use the product as designed and avoid weird SQL – If SQL is too long or too complex the CBO will struggle
  • 7. Partial list of Parameters to Reset • optimizer_features_enable • optimizer_index_cost_adj • optimizer_index_caching • db_file_multiblock_read_count (not CBO exclusive) • cursor_sharing (not an optimizer parameter) • optimizer_dynamic_sampling • optimizer_mode
  • 8. II. Diagnostics Collection a) Identify SQL_ID b) Use Oracle-product base Tools c) Supplement with specialized Tools
  • 9. II.a Identify SQL_ID • Oracle Enterprise Manager (OEM) – [ OEM] [ Database | Grid | Cloud ] Control • Automatic Workload Repository (AWR) • Statspack (SP) • SQL Trace (and TKPROF) • V$ dynamic views (e.g. V$SQL and V$SESSION)
  • 10. II.b Oracle-product base Tools • SQL Trace (and TKPROF) • Active Session History (ASH) • EXPLAIN PLAN FOR • AUTOTRACE • SQL Developer • DBMS_XPLAN • SQL Monitor
  • 11. SQL Trace • ALTER SESSION SET – SQL_TRACE = [ TRUE | FALSE ] – EVENTS ‘10046 trace name context forever, level N’ • N = 1: all executions (10g-) or 1st execution (11g+) • N = 4: Binds • N = 8: Waits • N = 12 = 4 + 8 • N = 16: each execution (11g+) • N = 64: 1st + each where DB time > 1min (11.2.0.2+)
  • 12. Where is my Trace? • V$DIAG_INFO (11.1+) • USER_DUMP_DEST (deprecated 12c)
  • 13. TKPROF: SQL Text and DB Calls
  • 14. TKPROF: Execution Plan and Wait Events
  • 15. Active Session History (ASH) • 1 sec snapshots of V$SESSION • Every 10 ASH samples into AWR (10 sec granularity) • Sessions “ON CPU” or “WAITING” (non-idle) • Multiple Dimensions • Excellent repository for performance data mining • Requires Oracle Diagnostics Pack!
  • 16. SQL Trace vs. ASH Pros • Precise • Free Pros • Always available • Multi-dimensional repository • Plan line granularity (11g+) Cons • Re-execute transaction • Waits per cursor – No plan line granularity Cons • Requires Diagnostics Pack
  • 17. EXPLAIN PLAN FOR • Actual SQL is not executed • Blind to Bind Peeking, thus unreliable with Binds
  • 18.
  • 19. SET AUTOTRACE ON • Actual SQL is executed • Includes small subset of Session Statistics
  • 20. Query Output and Execution Plan
  • 21. Predicate Information and Session Stats
  • 23.
  • 24. DBMS_XPLAN • DISPLAY (from PLAN_TABLE) • DISPLAY_CURSOR • DISPLAY_AWR • DISPLAY_SQL_PLAN_BASELINE • DISPLAY_SQL_SET • SELECT * FROM TABLE(DBMS_XPLAN.DISPLAY%());
  • 25. DBMS_XPLAN.DISPLAY_CURSOR • SQL_ID • CURSOR_CHILD_NO (defaults to 0!) • FORMAT – TYPICAL = DEFAULT – ALL = TYPICAL + QB + PROJECTION + ALIAS + REMOTE – ADVANCED = ALL + OUTLINE + BINDS – ALLSTATS = IOSTATS + MEMSTATS (all executions) – ALLSTATS LAST (last execution) – ADAPTIVE (12c)
  • 26. Sample query with hints and binds
  • 27.
  • 28. SQL Monitor • Part of the Oracle Tuning Pack • Tabular and Graphical Execution Plan • Timeline per Plan Line • Binds and Predicates • Nice and intuitive • Executed from OEM or SQL*Plus
  • 29.
  • 30.
  • 31. II.c Specialized Tools • SQLTXPLAIN (a.k.a. SQLT) – My Oracle Support (MOS) 215187.1 • SQLHC – MOS 1366133.1 • SQLd360 – By Mauro Pagano • Others?
  • 32. III. Root Cause Analysis • This is where you want to spend your time! • Go over all the output of your specialized tool • Look for correlations and possible causation • Put yourself in the shoes of the Optimizer • Question everything (is there a better way?) • Ask for help after you have done your homework • Enjoy the ride!
  • 33. Typical Steps 1. Find where the time is spent (plan line) – Too many executions or too much time per exec? 2. Validate estimated rows versus actual rows – If off determine why (deficient statistics maybe?) 3. What is the history of this SQL? – Can you find a better performing plan? 4. Can you make perfect sense of the SQL and plan?
  • 34. IV. Remediation • Explore multiple possibilities – And try to prove yourself wrong! • Implement the smallest-scope fix – Avoid system-wide changes unless you are rock solid! • Avoid guesses and assumptions (piñata method) – Too many people out there are “tuning” blind-folded! • Trust nobody! (be skeptic and test thoroughly)
  • 35. Three Important Topics 1. Execution Plan 2. Cost-based Optimizer 3. Plan Stability
  • 36. 1. Execution Plan • If you do not understand the SQL or the Execution Plan stop right there! • From SQL text you can draw a diagram if that helps • To understand the Execution Plan start small – Review a two-tables query and review plan – Move to a three-tables query and review plan – Introduce subqueries and more complex constructions
  • 37. 2. Cost-based Optimizer • CBO was released on 7.3 (circa February 1996) • A large and complex piece of software enhanced for two decades • By design the CBO produces an optimal execution plan according to some representation of the data – This means: execution plans are expected to change! – Breathe deep and embrace the change!
  • 38. 3. Plan Stability • Most DBAs hate Execution Plan changes – They never hear of changes for the better! • To remediate undesired plan changes we do have several Plan Stability techniques – SQL Plan Management (Baselines) from 11g – SQL Profiles from 10g – Deprecated Stored Outlines from 9i – And then some others (SQL Patches and CBO Hints)
  • 39. Popular Free Diagnostics Tools • SQLTXPLAIN • SQLHC • SQLd360 • Stand-alone scripts
  • 42.
  • 44.
  • 45.
  • 46. SQLT XPLAIN vs. SQLd360 Pros • Oracle Support Standard • Free (requires MOS account) • Comprehensive and mature Pros • Free Software (no strings) • Installs nothing on database • Graphical visualization of data Cons • Requires installation • HTML Tables (no charts) Cons • Still young (frequent releases)
  • 47. SQL Tuning Road Map 1. Start with a clean and healthy environment 2. Identify SQL_ID 3. Collect diagnostics using comprehensive tools 4. Spend time analyzing diagnostics collected 5. Determine root cause 6. Explore remediation actions 7. Test and implement solution
  • 49. The End • http://carlos-sierra.net/ – Blog and downloads • carlos.sierra.usa@gmail.com – Questions and follow-up • SQL Tuning is more about understanding what your eyes see at first