SlideShare a Scribd company logo
Performance Tuning with
Execution Plans
GOAL
• Show where, how and why
performance issues appear within
execution plans in order to better
understand how to use execution
plans to troubleshoot SQL Server
query performance
Let’s Talk
scarydba.com
grant@scarydba.com
@gfritchey
Grant Fritchey
Today’s Agenda
• Introduction to Execution Plans
• Common T-SQL Code Smells
• Worked Examples
• Querying the Plan Cache
• More Worked Examples
• Parameter Sniffing
• Additional Tools
Introduction to Execution
Plans
Performance Tuning with Execution Plans
Execution Plans
• Execution plans are a representation
of the processes used by the query
engine to perform the query
submitted to SQL Server.
Relational Engine
QUERY
RESULT
Relational
Engine
Query
Parsor
Syntax
Check
Parse
Tree
Algebrizer
Resolves
Objects
Query
Processor
Tree
Optimizer
Execution
Plan
Query
Processor
QUERY OPTIMIZER
Optimizer
• Cost-Based
– Just an estimate
– Not based on your computer
• Statistics
– Defined in indexes and tables
– Must be maintained to ensure a good execution
plan
• Cache
– Every query goes to cache (almost)
Generating a Plan
• SQL Server Management Studio
– Estimated
– Actual
• Procedure Cache
– Estimated (sort of)
• Extended Events
– Estimated
– Actual
• Trace Events (not recommended)
– Estimated
– Actual
Tune the Query
Small to medium, look at the query first
Medium to large, go straight to the execution plan
Very large and insane, query the execution plan
Watch for low-hanging fruit
Fix syntax over stats
Stats over indexing
Indexing over restructuring
Restructuring
Read the execution plan
Understand the business needs
Where To Start?
Where To Start?
First Operator
• Plan size
• Compile time
• Memory grant
• Missing Indexes
• Optimization level
• Parameter
– Compiled value
– Runtime Value
• Query hash
• Reason for early termination
• ANSI settings
Right to Left or Left to Right?
• A clue: English
• Another clue: These things
Left to Right or Right to Left
• Answer: Both
• Logical processing order:
– Represents how the optimizer sees the query
– Reading it from Left to Right
• Physical processing order
– Represents the flow of data
– Follow the arrows/pipes from Right to Left
• Both are necessary to understand certain plans
What Else to Look For
• Warnings
• Most Costly Operations
• Fat Pipes
• Extra Operations
• Scans
• Estimated vs. Actual
Demo
Summary
• Execution plans are your view into the optimizer
• You can capture plans multiple ways
• You start with the first operator
• Additional things to look for include:
– Warnings
– Most costly operations
– Fat pipes
– Extra operations
– Scans
– Estimated vs. Actual
• Remember that these are just representations
Common T-SQL Code
Smells
Performance Tuning with Execution Plans
Code Smells
• A code smell is a piece of code that
functions, but doesn’t function in the
best possible way within a given set
of circumstances
T-SQL Code Smells
• Functions on Predicates
• Data Conversion (Implicit & Explicit)
• Cursors
• Nested Views
• IF Logic
• Multi-Statement Table-Valued User
Defined Functions
Demo
Worked Examples
Demo
Querying the Plan
Performance Tuning with Execution Plans
Execution Plans From
CacheSELECT TOP 10
SUBSTRING(dest.text, (deqs.statement_start_offset / 2) + 1,
(CASE deqs.statement_end_offset
WHEN -1 THEN DATALENGTH(dest.text)
ELSE deqs.statement_end_offset
- deqs.statement_start_offset
END) / 2 + 1) AS querystatement,
deqp.query_plan,
deqs.query_hash,
deqs.execution_count
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_query_plan(deqs.plan_handle) AS deqp
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
ORDER BY deqs.total_elapsed_time DESC;
Inside Execution Plans
SELECT DB_NAME(deqp.dbid),
SUBSTRING(dest.text, (deqs.statement_start_offset / 2) + 1,
(CASE deqs.statement_end_offset
WHEN -1 THEN DATALENGTH(dest.text)
ELSE deqs.statement_end_offset
END - deqs.statement_start_offset) / 2 + 1) AS StatementText,
deqs.statement_end_offset,
deqs.statement_start_offset,
deqp.query_plan,
deqs.execution_count,
deqs.total_elapsed_time,
deqs.total_logical_reads,
deqs.total_logical_writes
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_query_plan(deqs.plan_handle) AS deqp
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE CAST(deqp.query_plan AS NVARCHAR(MAX)) LIKE '%StatementOptmEarlyAbortReason="TimeOut"%';
Interesting Dynamic
Management Objects
• Sys.dm_exec_query_plan
• sys.dm_exec_query_profiles
• Sys.dm_exec_text_query_plan
Demo
Additional Resources
• Sp_whoisactive – Adam Machanic
• Diagnostic Queries – Glen Berry
• Performance Tuning with SQL Server
Dynamic Management Views – Louis
Davidson and Tim Ford
More Worked Examples
Demo
Parameter Sniffing
http://download.red-
gate.com/ebooks/SQL/eBook_Perform
ance_Tuning_Davidson_Ford.pdf
Parameter Sniffing
• It’s a good thing… except when it
isn’t
• Automatic
• Only works on parameters (with an
exception)
• It’s all about statistics
– Average vs. Specific
Bad Parameter Sniffing
• Differentiate from parameter sniffing
• Still about statistics
• Intermittent
• Different plans
• Focus on the compiled value
• Compare to runtime
• When it’s bad, it’s very bad
Local Variables
• Eliminate parameters
• Turn parameters into local variables
• Produces “generic” plan
Variable Sniffing
• The exception to parameters
• Same process
• Only works in a recompile situation
• Invisible killer or guardian angel
OPTIMIZE FOR <value>
• Specific and accurate
• Changes over time
• Produces “precise” plan
OPTIMIZE FOR
UNKNOWN
• For when you’re not sure
• Changes over time
• Produces “generic” plan
WITH RECOMPILE
• Specific every time
• Increases overhead
• May be more costly than
Statistics
• After all, it’s all about the statistics
• Stats can age w/o updating
• You may have auto-update turned
off
• Sampled updates may be
inadequate
• Filtered statistics may help
Plan Guides
• Just a different way to use hints
• Produces whatever plan you define
Turn Sniffing Off
• Dangerous choice
• Last for a reason
• Very dangerous
• Turns it all off
• Everywhere
• Did I mention it’s dangerous?
Demo
Additional Tools
Performance Tuning with Execution Plans
Supratimas
• Web based
• Free
• Easy to use
• Limited Functionality
SQL Sentry Plan Explorer
• Application
• Free and Paid Version
• Easy to Use
• Extensive Funtionality
Query Store
• Azure SQL Database
• SQL Server 2016
• Guaranteed to change how you
monitor and tune queries
Demo
Conclusion
Tune the Query
• Small to medium, look at the query first
• Medium to large, go straight to the execution plan
• Very large and insane, query the execution plan
• Watch for low-hanging fruit
• Fix syntax over stats
– Stats over indexing
• Indexing over restructuring
– Restructuring
• Read the execution plan
• Understand the business needs
56
Performance Tuning with Execution Plans
Resources
• Scarydba.com/resources
• SQL Server Execution Plans
• SQL Server Query Performance
Tuning
Rate This Session Now!
Rate with Mobile App:
• Select the session from the
Agenda or Speakers menus
• Select the Actions tab
• Click Rate Session
Rate with Website:
Register at www.devconnections.com/logintoratesession
Go to www.devconnections.com/ratesession
Select this session from the list and rate it
Tell Us
What
You
Thought
of This
Session
Be Entered to
WINPrizes!
#ITDEVCON
Let’s Talk
scarydba.com
grant@scarydba.com
@gfritchey
Grant Fritchey

More Related Content

What's hot (17)

PPTX
Episode 1 - PathToCode.com
Jitendra Zaa
 
PDF
Join 2017_Deep Dive_Table Calculations 101
Looker
 
PPTX
Map reduce
Somesh Maliye
 
PPTX
Moving advanced analytics to your sql server databases
Enrico van de Laar
 
PPTX
Episode 13 - Advanced Apex Triggers
Jitendra Zaa
 
PDF
Designing REST APIs
Srikanth Sombhatla
 
PPTX
Episode 5 - Writing unit tests in Salesforce
Jitendra Zaa
 
PPTX
Salesforce Apex Ten Commandments
NetStronghold
 
PDF
mabl's Machine Learning Implementation on Google Cloud Platform
Joseph Lust
 
PDF
Test Data - Food for your Test Automation Framework
Anand Bagmar
 
PPTX
Episode 18 - Asynchronous Apex
Jitendra Zaa
 
PDF
Build Reliable Asynchronous Code with Queueable Apex
Salesforce Developers
 
PPTX
Bogdan molocea scaling up using automation and performance testing
Codecamp Romania
 
PPTX
Batchable vs @future vs Queueable
Boris Bachovski
 
PPTX
Logic Apps Exception Management - Azure Lunchtime
Wagner Silveira
 
PPTX
Elm - never get a runtime error anymore. Almost.
Anton Astashov
 
PDF
What Your Tech Lead Thinks You Know (But Didn't Teach You)
Chris Riccomini
 
Episode 1 - PathToCode.com
Jitendra Zaa
 
Join 2017_Deep Dive_Table Calculations 101
Looker
 
Map reduce
Somesh Maliye
 
Moving advanced analytics to your sql server databases
Enrico van de Laar
 
Episode 13 - Advanced Apex Triggers
Jitendra Zaa
 
Designing REST APIs
Srikanth Sombhatla
 
Episode 5 - Writing unit tests in Salesforce
Jitendra Zaa
 
Salesforce Apex Ten Commandments
NetStronghold
 
mabl's Machine Learning Implementation on Google Cloud Platform
Joseph Lust
 
Test Data - Food for your Test Automation Framework
Anand Bagmar
 
Episode 18 - Asynchronous Apex
Jitendra Zaa
 
Build Reliable Asynchronous Code with Queueable Apex
Salesforce Developers
 
Bogdan molocea scaling up using automation and performance testing
Codecamp Romania
 
Batchable vs @future vs Queueable
Boris Bachovski
 
Logic Apps Exception Management - Azure Lunchtime
Wagner Silveira
 
Elm - never get a runtime error anymore. Almost.
Anton Astashov
 
What Your Tech Lead Thinks You Know (But Didn't Teach You)
Chris Riccomini
 

Similar to Performance Tuning with Execution Plans (20)

PPTX
Optimizing Application Performance - 2022.pptx
JasonTuran2
 
PPTX
SCRIMPS-STD: Test Automation Design Principles - and asking the right questions!
Richard Robinson
 
PPTX
Designing dashboards for performance shridhar wip 040613
Mrunal Shridhar
 
PPTX
Small is Beautiful- Fully Automate your Test Case Design
Georgina Tilby
 
PPTX
Using Metrics for Fun, Developing with the KV Store + Javascript & News from ...
Harry McLaren
 
PDF
PAC 2019 virtual Alexander Podelko
Neotys
 
PPTX
Testing for Logic App Solutions | Integration Monday
BizTalk360
 
PDF
A data driven etl test framework sqlsat madison
Terry Bunio
 
PPTX
Alexander Podelko - Context-Driven Performance Testing
Neotys_Partner
 
PPTX
The Plan Cache Whisperer - Performance Tuning SQL Server
Jason Strate
 
PDF
Breaking data
Terry Bunio
 
PDF
Performance tuning Grails applications
GR8Conf
 
PDF
Oracle SQL tuning with SQL Plan Management
Bjoern Rost
 
PDF
5 Steps on the Way to Continuous Delivery
XebiaLabs
 
PPTX
Load testing with Visual Studio and Azure - Andrew Siemer
Andrew Siemer
 
PPTX
Distributed query deep dive conor cunningham
Radityo Prasetianto Wibowo
 
PPTX
Database Fundamental Concepts- Series 1 - Performance Analysis
DAGEOP LTD
 
PDF
Exploring T-SQL Anti-Patterns
Antonios Chatzipavlis
 
PPTX
SQL Explore 2012: P&T Part 1
sqlserver.co.il
 
PPTX
Road to Continuous Delivery - Wix.com
Aviran Mordo
 
Optimizing Application Performance - 2022.pptx
JasonTuran2
 
SCRIMPS-STD: Test Automation Design Principles - and asking the right questions!
Richard Robinson
 
Designing dashboards for performance shridhar wip 040613
Mrunal Shridhar
 
Small is Beautiful- Fully Automate your Test Case Design
Georgina Tilby
 
Using Metrics for Fun, Developing with the KV Store + Javascript & News from ...
Harry McLaren
 
PAC 2019 virtual Alexander Podelko
Neotys
 
Testing for Logic App Solutions | Integration Monday
BizTalk360
 
A data driven etl test framework sqlsat madison
Terry Bunio
 
Alexander Podelko - Context-Driven Performance Testing
Neotys_Partner
 
The Plan Cache Whisperer - Performance Tuning SQL Server
Jason Strate
 
Breaking data
Terry Bunio
 
Performance tuning Grails applications
GR8Conf
 
Oracle SQL tuning with SQL Plan Management
Bjoern Rost
 
5 Steps on the Way to Continuous Delivery
XebiaLabs
 
Load testing with Visual Studio and Azure - Andrew Siemer
Andrew Siemer
 
Distributed query deep dive conor cunningham
Radityo Prasetianto Wibowo
 
Database Fundamental Concepts- Series 1 - Performance Analysis
DAGEOP LTD
 
Exploring T-SQL Anti-Patterns
Antonios Chatzipavlis
 
SQL Explore 2012: P&T Part 1
sqlserver.co.il
 
Road to Continuous Delivery - Wix.com
Aviran Mordo
 
Ad

More from Grant Fritchey (20)

PDF
You Need a PostgreSQL Restore Plan Presentation
Grant Fritchey
 
PDF
PostgreSQL Query Performance Monitoring for the Absolute Beginner
Grant Fritchey
 
PDF
Leveraging AI for the PostgreSQL DBA #pgconf.eu
Grant Fritchey
 
PDF
Exploring Execution Plans, Learning to Read SQL Server Execution Plans
Grant Fritchey
 
PPTX
SQL Server Performance Tuning: Common Problems, Possible Solutions
Grant Fritchey
 
PDF
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
PPTX
Migrating To PostgreSQL
Grant Fritchey
 
PPTX
PostgreSQL Performance Problems: Monitoring and Alerting
Grant Fritchey
 
PDF
Automating Database Deployments Using Azure DevOps
Grant Fritchey
 
PDF
Learn To Effectively Use Extended Events_Techorama.pdf
Grant Fritchey
 
PDF
Using Query Store to Understand and Control Query Performance
Grant Fritchey
 
PPTX
You Should Be Standing Here: Learn How To Present a Session
Grant Fritchey
 
PDF
Redgate Community Circle: Tools For SQL Server Performance Tuning
Grant Fritchey
 
PDF
10 Steps To Global Data Compliance
Grant Fritchey
 
PDF
Time to Use the Columnstore Index
Grant Fritchey
 
PDF
Introduction to SQL Server in Containers
Grant Fritchey
 
PDF
DevOps for the DBA
Grant Fritchey
 
PDF
SQL Injection: How It Works, How to Stop It
Grant Fritchey
 
PDF
Privacy and Protection in the World of Database DevOps
Grant Fritchey
 
PDF
SQL Server Tools for Query Tuning
Grant Fritchey
 
You Need a PostgreSQL Restore Plan Presentation
Grant Fritchey
 
PostgreSQL Query Performance Monitoring for the Absolute Beginner
Grant Fritchey
 
Leveraging AI for the PostgreSQL DBA #pgconf.eu
Grant Fritchey
 
Exploring Execution Plans, Learning to Read SQL Server Execution Plans
Grant Fritchey
 
SQL Server Performance Tuning: Common Problems, Possible Solutions
Grant Fritchey
 
Using Query Store in Azure PostgreSQL to Understand Query Performance
Grant Fritchey
 
Migrating To PostgreSQL
Grant Fritchey
 
PostgreSQL Performance Problems: Monitoring and Alerting
Grant Fritchey
 
Automating Database Deployments Using Azure DevOps
Grant Fritchey
 
Learn To Effectively Use Extended Events_Techorama.pdf
Grant Fritchey
 
Using Query Store to Understand and Control Query Performance
Grant Fritchey
 
You Should Be Standing Here: Learn How To Present a Session
Grant Fritchey
 
Redgate Community Circle: Tools For SQL Server Performance Tuning
Grant Fritchey
 
10 Steps To Global Data Compliance
Grant Fritchey
 
Time to Use the Columnstore Index
Grant Fritchey
 
Introduction to SQL Server in Containers
Grant Fritchey
 
DevOps for the DBA
Grant Fritchey
 
SQL Injection: How It Works, How to Stop It
Grant Fritchey
 
Privacy and Protection in the World of Database DevOps
Grant Fritchey
 
SQL Server Tools for Query Tuning
Grant Fritchey
 
Ad

Recently uploaded (20)

PPTX
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
PDF
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
PPTX
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
PDF
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
PDF
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
PDF
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
PDF
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
PPTX
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
PPTX
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
PDF
Laboratory Workflows Digitalized and live in 90 days with Scifeon´s SAPPA P...
info969686
 
PDF
Rewards and Recognition (2).pdf
ethan Talor
 
PDF
Dealing with JSON in the relational world
Andres Almiray
 
PDF
Code Once; Run Everywhere - A Beginner’s Journey with React Native
Hasitha Walpola
 
PDF
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
PDF
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
PPTX
Introduction to web development | MERN Stack
JosephLiyon
 
PDF
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
PPTX
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
 
PDF
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
 
PDF
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 
Iobit Driver Booster Pro 12 Crack Free Download
chaudhryakashoo065
 
The Rise of Sustainable Mobile App Solutions by New York Development Firms
ostechnologies16
 
IObit Driver Booster Pro 12.4-12.5 license keys 2025-2026
chaudhryakashoo065
 
>Nitro Pro Crack 14.36.1.0 + Keygen Free Download [Latest]
utfefguu
 
Writing Maintainable Playwright Tests with Ease
Shubham Joshi
 
AI Software Development Process, Strategies and Challenges
Net-Craft.com
 
IObit Uninstaller Pro 14.3.1.8 Crack for Windows Latest
utfefguu
 
CV-Project_2024 version 01222222222.pptx
MohammadSiddiqui70
 
ERP - FICO Presentation BY BSL BOKARO STEEL LIMITED.pptx
ravisranjan
 
Laboratory Workflows Digitalized and live in 90 days with Scifeon´s SAPPA P...
info969686
 
Rewards and Recognition (2).pdf
ethan Talor
 
Dealing with JSON in the relational world
Andres Almiray
 
Code Once; Run Everywhere - A Beginner’s Journey with React Native
Hasitha Walpola
 
WholeClear Split vCard Software for Split large vCard file
markwillsonmw004
 
capitulando la keynote de GrafanaCON 2025 - Madrid
Imma Valls Bernaus
 
Introduction to web development | MERN Stack
JosephLiyon
 
How DeepSeek Beats ChatGPT: Cost Comparison and Key Differences
sumitpurohit810
 
Quality on Autopilot: Scaling Testing in Uyuni
Oscar Barrios Torrero
 
Cloud computing Lec 02 - virtualization.pdf
asokawennawatte
 
Continouous failure - Why do we make our lives hard?
Papp Krisztián
 

Performance Tuning with Execution Plans