SlideShare a Scribd company logo
1 of 21
Before You Optimize:
Understanding Execution Plans




                        @IAmTimCorey
About Me
•   Worked with Microsoft SQL since 6.5
•   Started my career in VB6
•   Moved to .NET when it came out
•   Consultant, Adjunct Professor, Trainer, and
    Speaker
Agenda
•   Introduction to Execution Plans
•   Reading Execution Plans
•   Limitations
•   Additional Tools
•   Next Steps
What Are Execution Plans?
Basic Execution Plan
Types of Execution Plans
           Estimated           Actual
Graphical Ctrl + L        Ctrl + M
Text      SHOWPLAN_ALL    STATISTICS PROFILE
          SHOWPLAN_TEXT
XML       SHOWPLAN_XML    STATISTICS_XML
Estimated vs. Actual Details
List of Existing Plans
SELECT [cp].[refcounts]
 ,[cp].[usecounts]
 ,[cp].[objtype]
 ,[st].[dbid]
 ,[st].[objectid]
 ,[st].[text]
 ,[qp].[query_plan]
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle)
qp;

* From SQL Server Execution Plans by Grant Fritchey – p. 23
Execution Plan Aging
Formula: Cost to compile * # of calls
Lazywriter: scans cache and decrements by one
each scan
Clear Cache: DBCC FREEPROCCACHE

Items are removed when:
• Memory is needed
• The age of the item is zero
• The plan is not currently in use
How Do You Read an Execution
           Plan?
Rebind and Rewind
Occur on certain loop joins. They represent
each time the system has to look through the
inner table again for more data.

Rebind – when the outer data changes
Rewind – when the outer data remains the same

More info: http://bit.ly/P7EUv3
Limitations
Ad Hoc Query Plans
Ad hoc plans will use the cache as long as:
• The schema is specified throughout
• The text doesn’t change (at all*)

* For queries with one table only, simple
parameterization will allow the parameters to
change while still reusing the cached plan. To
expand this to more complex queries, see this
reference: http://bit.ly/Oi3FDH
Parameter Sniffing
SQL Server designs execution plans based upon the
first set of parameters passed in. This can have
adverse effects. To get around it, you can:
• Use WITH RECOMPILE
• Use tailored stored procs
• Set a trace flag to disable parameter sniffing
• Use the OPTIMIZE FOR query hint
• Use sp_recompile to clear cache for stored proc
   or those that use a particular table

Read more here: http://bit.ly/MqNVOG
Additional Tools
SQL Sentry Plan Explorer




http://bit.ly/NDwBqh
AutoEPLoader




http://bit.ly/StcFVu
SQL Server Profiler
How Do I Learn More?
Further Resources
•   Book by Grant Fritchey - http://bit.ly/MtL0a2
•   Index Statistics - http://bit.ly/NTArHo
•   Query Parallelism - http://bit.ly/NlcS0s
•   Query Hints - http://bit.ly/N6YMKo
For questions, comments, and
 further information, catch me on
Twitter at @IAmTimCorey or email
      me@timothycorey.com

More Related Content

What's hot

Module Owb Execute Mappings
Module Owb Execute MappingsModule Owb Execute Mappings
Module Owb Execute Mappings
Nicholas Goodman
 
Exciting Features for SQL Devs in SQL 2012
Exciting Features for SQL Devs in SQL 2012Exciting Features for SQL Devs in SQL 2012
Exciting Features for SQL Devs in SQL 2012
Brij Mishra
 
Discovering the Plan Cache (#SQLSat 206)
Discovering the Plan Cache (#SQLSat 206)Discovering the Plan Cache (#SQLSat 206)
Discovering the Plan Cache (#SQLSat 206)
Jason Strate
 
Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)
Jason Strate
 
Discovering the plan cache (#SQLSat211)
Discovering the plan cache (#SQLSat211)Discovering the plan cache (#SQLSat211)
Discovering the plan cache (#SQLSat211)
Jason Strate
 

What's hot (20)

Batch Apex in Salesforce
Batch Apex in SalesforceBatch Apex in Salesforce
Batch Apex in Salesforce
 
The Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL ServerThe Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL Server
 
Module Owb Execute Mappings
Module Owb Execute MappingsModule Owb Execute Mappings
Module Owb Execute Mappings
 
Module Owb Mappings
Module Owb MappingsModule Owb Mappings
Module Owb Mappings
 
Exciting Features for SQL Devs in SQL 2012
Exciting Features for SQL Devs in SQL 2012Exciting Features for SQL Devs in SQL 2012
Exciting Features for SQL Devs in SQL 2012
 
Discovering the Plan Cache (#SQLSat 206)
Discovering the Plan Cache (#SQLSat 206)Discovering the Plan Cache (#SQLSat 206)
Discovering the Plan Cache (#SQLSat 206)
 
Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)
 
SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...
SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...
SQL Pass Summit Presentations from Datavail - Optimize SQL Server: Query Tuni...
 
Discovering the plan cache (#SQLSat211)
Discovering the plan cache (#SQLSat211)Discovering the plan cache (#SQLSat211)
Discovering the plan cache (#SQLSat211)
 
Batchable vs @future vs Queueable
Batchable vs @future vs QueueableBatchable vs @future vs Queueable
Batchable vs @future vs Queueable
 
Query optimization
Query optimizationQuery optimization
Query optimization
 
Build Reliable Asynchronous Code with Queueable Apex
Build Reliable Asynchronous Code with Queueable ApexBuild Reliable Asynchronous Code with Queueable Apex
Build Reliable Asynchronous Code with Queueable Apex
 
SFDC Batch Apex
SFDC Batch ApexSFDC Batch Apex
SFDC Batch Apex
 
SQL Saturday - Twelve Trace Flags In Twelve Minutes
SQL Saturday - Twelve Trace Flags In Twelve MinutesSQL Saturday - Twelve Trace Flags In Twelve Minutes
SQL Saturday - Twelve Trace Flags In Twelve Minutes
 
MySQL optimisations of Docplanner services
MySQL optimisations of Docplanner servicesMySQL optimisations of Docplanner services
MySQL optimisations of Docplanner services
 
Salesforce Apex Ten Commandments
Salesforce Apex Ten CommandmentsSalesforce Apex Ten Commandments
Salesforce Apex Ten Commandments
 
Module Owb Tuning
Module Owb TuningModule Owb Tuning
Module Owb Tuning
 
Gatling overview
Gatling overviewGatling overview
Gatling overview
 
Siebel test automation enchancements by areon consulting
Siebel test automation enchancements by areon consultingSiebel test automation enchancements by areon consulting
Siebel test automation enchancements by areon consulting
 
Part5 sql tune
Part5 sql tunePart5 sql tune
Part5 sql tune
 

Viewers also liked

Hacking Windows IPC
Hacking Windows IPCHacking Windows IPC
Hacking Windows IPC
gueste041bc
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
avniS
 

Viewers also liked (12)

Hacking Windows IPC
Hacking Windows IPCHacking Windows IPC
Hacking Windows IPC
 
Index in sql server
Index in sql serverIndex in sql server
Index in sql server
 
Strategies for SQL Server Index Analysis
Strategies for SQL Server Index AnalysisStrategies for SQL Server Index Analysis
Strategies for SQL Server Index Analysis
 
Presentation interpreting execution plans for sql statements
Presentation    interpreting execution plans for sql statementsPresentation    interpreting execution plans for sql statements
Presentation interpreting execution plans for sql statements
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
 
Introduction of sql server indexing
Introduction of sql server indexingIntroduction of sql server indexing
Introduction of sql server indexing
 
Social Media Strategy Execution
Social Media Strategy ExecutionSocial Media Strategy Execution
Social Media Strategy Execution
 
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1 "Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
"Using Indexes in SQL Server 2008" by Alexander Korotkiy, part 1
 
Columnstore indexes in sql server 2014
Columnstore indexes in sql server 2014Columnstore indexes in sql server 2014
Columnstore indexes in sql server 2014
 
Database index(sql server)
Database index(sql server)Database index(sql server)
Database index(sql server)
 
MySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 TipsMySQL Performance Tuning: Top 10 Tips
MySQL Performance Tuning: Top 10 Tips
 
How to Design Indexes, Really
How to Design Indexes, ReallyHow to Design Indexes, Really
How to Design Indexes, Really
 

Similar to Before you optimize: Understanding Execution Plans

Similar to Before you optimize: Understanding Execution Plans (20)

Beginners guide to_optimizer
Beginners guide to_optimizerBeginners guide to_optimizer
Beginners guide to_optimizer
 
Structured Streaming in Spark
Structured Streaming in SparkStructured Streaming in Spark
Structured Streaming in Spark
 
Fast federated SQL with Apache Calcite
Fast federated SQL with Apache CalciteFast federated SQL with Apache Calcite
Fast federated SQL with Apache Calcite
 
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
Peeking into the Black Hole Called PL/PGSQL - the New PL Profiler / Jan Wieck...
 
Maximizing Database Tuning in SAP SQL Anywhere
Maximizing Database Tuning in SAP SQL AnywhereMaximizing Database Tuning in SAP SQL Anywhere
Maximizing Database Tuning in SAP SQL Anywhere
 
Data Engineer's Lunch 89: Machine Learning Orchestration with AirflowMachine ...
Data Engineer's Lunch 89: Machine Learning Orchestration with AirflowMachine ...Data Engineer's Lunch 89: Machine Learning Orchestration with AirflowMachine ...
Data Engineer's Lunch 89: Machine Learning Orchestration with AirflowMachine ...
 
Introduction to PowerShell for SharePoint - SharePointFest 2014 workshop
Introduction to PowerShell for SharePoint - SharePointFest 2014 workshopIntroduction to PowerShell for SharePoint - SharePointFest 2014 workshop
Introduction to PowerShell for SharePoint - SharePointFest 2014 workshop
 
Machine Learning Orchestration with Airflow
Machine Learning Orchestration with AirflowMachine Learning Orchestration with Airflow
Machine Learning Orchestration with Airflow
 
XStream: stream processing platform at facebook
XStream:  stream processing platform at facebookXStream:  stream processing platform at facebook
XStream: stream processing platform at facebook
 
3 query tuning techniques every sql server programmer should know
3 query tuning techniques every sql server programmer should know3 query tuning techniques every sql server programmer should know
3 query tuning techniques every sql server programmer should know
 
LVOUG meetup #2 - Forcing SQL Execution Plan Instability
LVOUG meetup #2 - Forcing SQL Execution Plan InstabilityLVOUG meetup #2 - Forcing SQL Execution Plan Instability
LVOUG meetup #2 - Forcing SQL Execution Plan Instability
 
Optimising Queries - Series 1 Query Optimiser Architecture
Optimising Queries - Series 1 Query Optimiser ArchitectureOptimising Queries - Series 1 Query Optimiser Architecture
Optimising Queries - Series 1 Query Optimiser Architecture
 
Understanding DB2 Optimizer
Understanding DB2 OptimizerUnderstanding DB2 Optimizer
Understanding DB2 Optimizer
 
Trenowanie i wdrażanie modeli uczenia maszynowego z wykorzystaniem Google Clo...
Trenowanie i wdrażanie modeli uczenia maszynowego z wykorzystaniem Google Clo...Trenowanie i wdrażanie modeli uczenia maszynowego z wykorzystaniem Google Clo...
Trenowanie i wdrażanie modeli uczenia maszynowego z wykorzystaniem Google Clo...
 
Open Data Science Conference Big Data Infrastructure – Introduction to Hadoop...
Open Data Science Conference Big Data Infrastructure – Introduction to Hadoop...Open Data Science Conference Big Data Infrastructure – Introduction to Hadoop...
Open Data Science Conference Big Data Infrastructure – Introduction to Hadoop...
 
Bootstrapping state in Apache Flink
Bootstrapping state in Apache FlinkBootstrapping state in Apache Flink
Bootstrapping state in Apache Flink
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should knowTen query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
 
Tuning for Systematic Trading: Talk 2: Deep Learning
Tuning for Systematic Trading: Talk 2: Deep LearningTuning for Systematic Trading: Talk 2: Deep Learning
Tuning for Systematic Trading: Talk 2: Deep Learning
 
DevOps: Automate all the things
DevOps: Automate all the thingsDevOps: Automate all the things
DevOps: Automate all the things
 
Big Data, Bigger Analytics
Big Data, Bigger AnalyticsBig Data, Bigger Analytics
Big Data, Bigger Analytics
 

Recently uploaded

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...2024: Domino Containers - The Next Step. News from the Domino Container commu...
2024: Domino Containers - The Next Step. News from the Domino Container commu...
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024AXA XL - Insurer Innovation Award Americas 2024
AXA XL - Insurer Innovation Award Americas 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Cyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdfCyberprint. Dark Pink Apt Group [EN].pdf
Cyberprint. Dark Pink Apt Group [EN].pdf
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
ICT role in 21st century education and its challenges
ICT role in 21st century education and its challengesICT role in 21st century education and its challenges
ICT role in 21st century education and its challenges
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 

Before you optimize: Understanding Execution Plans

  • 1. Before You Optimize: Understanding Execution Plans @IAmTimCorey
  • 2. About Me • Worked with Microsoft SQL since 6.5 • Started my career in VB6 • Moved to .NET when it came out • Consultant, Adjunct Professor, Trainer, and Speaker
  • 3. Agenda • Introduction to Execution Plans • Reading Execution Plans • Limitations • Additional Tools • Next Steps
  • 6. Types of Execution Plans Estimated Actual Graphical Ctrl + L Ctrl + M Text SHOWPLAN_ALL STATISTICS PROFILE SHOWPLAN_TEXT XML SHOWPLAN_XML STATISTICS_XML
  • 8. List of Existing Plans SELECT [cp].[refcounts] ,[cp].[usecounts] ,[cp].[objtype] ,[st].[dbid] ,[st].[objectid] ,[st].[text] ,[qp].[query_plan] FROM sys.dm_exec_cached_plans cp CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp; * From SQL Server Execution Plans by Grant Fritchey – p. 23
  • 9. Execution Plan Aging Formula: Cost to compile * # of calls Lazywriter: scans cache and decrements by one each scan Clear Cache: DBCC FREEPROCCACHE Items are removed when: • Memory is needed • The age of the item is zero • The plan is not currently in use
  • 10. How Do You Read an Execution Plan?
  • 11. Rebind and Rewind Occur on certain loop joins. They represent each time the system has to look through the inner table again for more data. Rebind – when the outer data changes Rewind – when the outer data remains the same More info: http://bit.ly/P7EUv3
  • 13. Ad Hoc Query Plans Ad hoc plans will use the cache as long as: • The schema is specified throughout • The text doesn’t change (at all*) * For queries with one table only, simple parameterization will allow the parameters to change while still reusing the cached plan. To expand this to more complex queries, see this reference: http://bit.ly/Oi3FDH
  • 14. Parameter Sniffing SQL Server designs execution plans based upon the first set of parameters passed in. This can have adverse effects. To get around it, you can: • Use WITH RECOMPILE • Use tailored stored procs • Set a trace flag to disable parameter sniffing • Use the OPTIMIZE FOR query hint • Use sp_recompile to clear cache for stored proc or those that use a particular table Read more here: http://bit.ly/MqNVOG
  • 16. SQL Sentry Plan Explorer http://bit.ly/NDwBqh
  • 19. How Do I Learn More?
  • 20. Further Resources • Book by Grant Fritchey - http://bit.ly/MtL0a2 • Index Statistics - http://bit.ly/NTArHo • Query Parallelism - http://bit.ly/NlcS0s • Query Hints - http://bit.ly/N6YMKo
  • 21. For questions, comments, and further information, catch me on Twitter at @IAmTimCorey or email me@timothycorey.com

Editor's Notes

  1. What this presentation is NOT: Not about optimization. Use car illustration – check engine light is on. What does it mean? We will read the diagnostic information. We aren’t going to cover how to fix the problems we find. Identification is the step we are covering.
  2. Roadmap the database uses to get the data most efficiently.Why is this important? We need to know if our assumptions are rightDiscuss cached plans / plan creation costPermissions needed to view plan: GRANT SHOWPLAN TO <user>SQL determines most efficient or “close enough” for simple plansOnly DML (not DDL) gets a plan cache (only one way to do DDL)
  3. Demo #1
  4. Demo #1
  5. Demo #1
  6. Demo #2
  7. Invalidate cache by redoing indexes and other operations that would alter the plan’s effectiveness
  8. Demo #1Query cost (relative to the batch)Right to LeftDemo #3Type of operation (scan, seek, etc.) – pragmatic approach to getting dataCost of operation (relative to query)Details ViewTable scan(heap) vs. Index scan
  9. Demo #4
  10. Ad hoc also get a value of zero in the cache (easily wiped out)
  11. For example, if the parameter first used to call the query is on an indexed list and the value is found in five entries out of a thousand, the index will be used for the lookup. However, if the next time you pass in a value that can be found in 800 of the thousand records, a table scan would be a better option.
  12. Size (of the arrow) matters