SlideShare a Scribd company logo
SQL Server Query Optimization, Execution and Debugging Query Performance
SQL Server Query Optimization, Execution and Debugging Query PerformanceVinod Kumar MTechnology Evangelist – Microsoft@vinodk_sqlwww.ExtremeExperts.comhttp://blogs.sqlxml.org/vinodkumar
Session Objectives And TakeawaysTakeaways (Learn…):  why estimated row counts affect plan selectionhow to find out “estimated” and “actual” row counts in the query planschallenges of parameterized queries how to influence query plan choicetips on design and testing of parameterized queries and stored proceduresbunch of useful demos you can try on your own
Agenda	IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
Agenda	IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
SQL Server Relational ServerHigh-Level Architecture Language Processing (Parse/Bind)Query Optimization (Plan Generation, View Matching, Statistics, Costing)Statement/Batch ExecutionQuery Execution(Query Operators, Memory Grants, Parallelism)Metadata, Type system, Expression ServicesUtilities (DBCC, Backup / Restore, BCP, …)Plan Cache ManagementStorage Engine (Access Methods, Database Page Cache, Locking, Transactions, …)SQL-OS (Schedulers, Buffer Pool, Memory Management, Synchronization Primitives, …)SQL Relational Engine
Query OptimizationQuery Optimization is cost based selection of good enough (potentially not the best) Query PlanInput to Query Optimization is Operator Tree produced byParsing SQL statement (Syntax)Semantic analysis and checking (Algebrizing – this includes type derivation, type checking, binding variables, table and column names, etc.)Output is Query Plan
How is the plan cost determined?Demo – watch query plan costs for two similar queries…selectod.OrderID,od.ProductIDFROM [Order Details] odWHERE od.ProductID IN (9,15)SELECT od.OrderID,od.ProductIDFROM [Order Details] odWHERE od.ProductID IN (59,31)ConclusionsSQL Server is using cardinality estimates to derive cost of operatorsCardinality estimates are derived from the statistics
Agenda	IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
Query Debugging ToolsSSMS – Management StudioShowplanDMVs – Dynamic Management ViewsTracePerfmon counters
Optimizer Perfmon CountersUse “SQL Server:SQL Statistics” object counters:
Auto-Param Attempts/sec
Forced Parameterizations/sec
Guided Plan Executions/sec
SQL Compilations/sec
SQL Re-Compilations/sec TraceExecution events may be result of query plan selectionThe most useful execution event categories 	Errors and Warnings (e.g. Exchange Spill or Sort Warning)Performance (e.g. Plan Guide Successful or Performance Statistics)Query OptimizationErrors and Warnings – Missing Column Statistics and Missing Join PredicatePerformance - 8 different Showplan Events; the most useful areShowplan XML for Query Compile – with each compileShowplan XML Statistics Profile – with each execution
DMVssys.dm_exec_query_stats- returns performance statistics and SQL handle for each query plan in cachesys.dm_exec_sql_text- Returns the text of the sql statement based on the SQL handle sys.dm_exec_query_plan- Returns the showplan in XML format for a batch or module based on the SQL handlesys.dm_exec_plan_attributes– TVF returns one row per plan attribute for the plan specified by the plan handle.
Agenda	IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
Demo – Stored ProcedureCREATE PROCEDURE myp @ShipRegion NVARCHAR(15)asSELECT o.Orderid,c.CompanyName,od.QuantityFROM Orders o, [Order Details] od,Customers c WHERE o.Orderid=od.Orderid ANDo.CustomerID=c.CustomerID AND	((o.ShipRegion=@ShipRegion) OR 	(@ShipRegion is NULL) AND 	(o.ShipRegion is NULL))
Estimated and Actual Query Plan Actual Query Plan contains additional informationActual Number of RowsActual Rebinds and RewindsNumber of ExecutionsParameter values (compile time and runtime)Estimated rowcount is per single executionWhen comparing the estimated and actual rowcounts multiply the estimated rowcountby estimated number of executionsSometimes (rarely!) the shape of the Actual Query Plan may differ  from the Estimated
How to Obtain Actual Plan?SSMS (as it was shown)SQLTRACEShowplan XML Statistics Profile eventSET STATISTICS XML ONReturns the Actual Plan in XML format following the resultSET STATISTICS PROFILE ONReturns text format of the query plan with two leading columns: ROWS and EXECUTESUsing DMVBut does not contain “actual” row counts or “actual parameter values”
Agenda	IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
Two Different Days…-- Day One – NULL query comes firstDBCC FREEPROCCACHEEXECUTE myp NULLEXECUTE myp 'BC'-- Day Two – a BC query comes firstDBCC FREEPROCCACHEEXECUTE myp 'BC'EXECUTE myp NULLObserve:Query plan is reused for all parameter values if found in the cacheIf used for “different” value the discrepancies between “estimated” and “actual” row counts are higher
Agenda	IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
One Testing ScenarioA story…Developer created parameterized stored procTester developed a driverTests were successful and sp moved to production After 4 weeks w/out any problems the sp now takes forever to finish and blocks the productionDisaster declared, all hands…A likely cause:The tests were run always with the same query plan created for the first set of parameter values
Test ResultsIf the plans are equal (watch for plan reuse! Run DBCC FREEPROCCACHE) you are ok (most likely)Else it still may be ok to use one of the generated plans for all parameter values (even those that would not pick the plan)Else you need to use more than one plan to get desirable performance…
Agenda	IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
One Query Plan is Goodbut some parameter values may generate different planWorkarounds If optimize for “unknown” gives desired plan -> use OPTION (OPTIMIZE FOR UNKNOWN)If optimization for a specific value produces the plan -> use OPTION (OPTIMIZE FOR (@ShipRegion=‘BC’))Use Plan Guides to enforce the same planRewrite the sp and “hide” the passed in parameter (example follows)

More Related Content

PDF
Why & how to optimize sql server for performance from design to query
PDF
SQL Server Tuning to Improve Database Performance
PPT
Sql Server Performance Tuning
PPT
Sql server performance tuning
PDF
Performance tuning in sql server
PPTX
Query Optimization in SQL Server
PDF
SQL Server Query Tuning Tips - Get it Right the First Time
PPT
Sql server performance tuning and optimization
Why & how to optimize sql server for performance from design to query
SQL Server Tuning to Improve Database Performance
Sql Server Performance Tuning
Sql server performance tuning
Performance tuning in sql server
Query Optimization in SQL Server
SQL Server Query Tuning Tips - Get it Right the First Time
Sql server performance tuning and optimization

What's hot (20)

PDF
Uncovering SQL Server query problems with execution plans - Tony Davis
PPTX
Ten query tuning techniques every SQL Server programmer should know
PPTX
Database Performance Tuning
PDF
SQL Server Performance Tuning Baseline
PPTX
Sql server performance tuning
PPTX
Oracle performance tuning_sfsf
PPT
Database performance tuning and query optimization
PDF
Oracle db performance tuning
PPTX
Oracle Database Performance Tuning Basics
PPTX
Before you optimize: Understanding Execution Plans
PPT
Advanced t sql - querying and programming inside sql server
PPTX
The Plan Cache Whisperer - Performance Tuning SQL Server
PPTX
Oracle database performance tuning
PPTX
Oracle Performance Tuning Training | Oracle Performance Tuning
PPT
Performance Tuning And Optimization Microsoft SQL Database
PPTX
Top 10 tips for Oracle performance (Updated April 2015)
PPT
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
PDF
Proactive performance monitoring with adaptive thresholds
PPT
Sql architecture
PPTX
Oracle Oracle Performance Tuning
Uncovering SQL Server query problems with execution plans - Tony Davis
Ten query tuning techniques every SQL Server programmer should know
Database Performance Tuning
SQL Server Performance Tuning Baseline
Sql server performance tuning
Oracle performance tuning_sfsf
Database performance tuning and query optimization
Oracle db performance tuning
Oracle Database Performance Tuning Basics
Before you optimize: Understanding Execution Plans
Advanced t sql - querying and programming inside sql server
The Plan Cache Whisperer - Performance Tuning SQL Server
Oracle database performance tuning
Oracle Performance Tuning Training | Oracle Performance Tuning
Performance Tuning And Optimization Microsoft SQL Database
Top 10 tips for Oracle performance (Updated April 2015)
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Proactive performance monitoring with adaptive thresholds
Sql architecture
Oracle Oracle Performance Tuning
Ad

Viewers also liked (13)

PPTX
Microsoft SQL Server internals & architecture
PDF
Performance tuning and optimization (ppt)
PPTX
Master tuning
PDF
Sql server performance Tuning
PDF
SQL Server
PPTX
End-to-end Troubleshooting Checklist for Microsoft SQL Server
PPTX
Microsoft sql server architecture
PPTX
Physical architecture of sql server
PDF
MS-SQL SERVER ARCHITECTURE
PPTX
Sql server basics
PPTX
MS Sql Server: Introduction To Database Concepts
PPTX
SQL Server 2012 Best Practices
PPT
Ms sql server architecture
Microsoft SQL Server internals & architecture
Performance tuning and optimization (ppt)
Master tuning
Sql server performance Tuning
SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
Microsoft sql server architecture
Physical architecture of sql server
MS-SQL SERVER ARCHITECTURE
Sql server basics
MS Sql Server: Introduction To Database Concepts
SQL Server 2012 Best Practices
Ms sql server architecture
Ad

Similar to SQL Server Query Optimization, Execution and Debugging Query Performance (20)

PPTX
05_DP_300T00A_Optimize.pptx
PPTX
Presentación Oracle Database Migración consideraciones 10g/11g/12c
PPTX
SQL Server 2008 Development for Programmers
PPT
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
PPTX
Sql query analyzer & maintenance
PPTX
Explain the explain_plan
PDF
Practical SQL query monitoring and optimization
PPT
Overview of query evaluation
PPT
Oracle Sql Tuning
PPTX
Understanding DB2 Optimizer
PDF
Maximizing Database Tuning in SAP SQL Anywhere
PPT
BI 2008 Simple
PPT
SQL Server 2008 Integration Services
PDF
Modernizing SQL Server the Right Way
PPTX
Modeling and Testing Dovetail in MagicDraw
PPT
Test automation process _ QTP
PPT
Test automation process
PPT
Skills Portfolio
PDF
SQL_Tuning_Oracle_10g.pdf
PDF
Mathematical Modeling using MATLAB, by U.M. Sundar Senior Application Enginee...
05_DP_300T00A_Optimize.pptx
Presentación Oracle Database Migración consideraciones 10g/11g/12c
SQL Server 2008 Development for Programmers
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Sql query analyzer & maintenance
Explain the explain_plan
Practical SQL query monitoring and optimization
Overview of query evaluation
Oracle Sql Tuning
Understanding DB2 Optimizer
Maximizing Database Tuning in SAP SQL Anywhere
BI 2008 Simple
SQL Server 2008 Integration Services
Modernizing SQL Server the Right Way
Modeling and Testing Dovetail in MagicDraw
Test automation process _ QTP
Test automation process
Skills Portfolio
SQL_Tuning_Oracle_10g.pdf
Mathematical Modeling using MATLAB, by U.M. Sundar Senior Application Enginee...

More from Vinod Kumar (6)

PPTX
Backup beyond just a strategy with SQL Server
PPT
Choosing a concurrency model, optimistic or pessimistic
PPTX
Choosing A Concurrency Model, Optimistic Or Pessimistic
PPT
Sql Server Security
PPT
Windows Mobile 5.0 Data Access And Storage Webcast
PPT
Protecting Your Key Asset – Data Protection Best Practices V2.0 Final
Backup beyond just a strategy with SQL Server
Choosing a concurrency model, optimistic or pessimistic
Choosing A Concurrency Model, Optimistic Or Pessimistic
Sql Server Security
Windows Mobile 5.0 Data Access And Storage Webcast
Protecting Your Key Asset – Data Protection Best Practices V2.0 Final

Recently uploaded (20)

PDF
Diabetes mellitus diagnosis method based random forest with bat algorithm
PDF
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
PDF
Approach and Philosophy of On baking technology
PDF
NewMind AI Monthly Chronicles - July 2025
PDF
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
PPTX
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
PPTX
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
PDF
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PPTX
Big Data Technologies - Introduction.pptx
PDF
Electronic commerce courselecture one. Pdf
PDF
Spectral efficient network and resource selection model in 5G networks
PDF
Advanced methodologies resolving dimensionality complications for autism neur...
PDF
Dropbox Q2 2025 Financial Results & Investor Presentation
PPT
Teaching material agriculture food technology
PPT
“AI and Expert System Decision Support & Business Intelligence Systems”
PDF
NewMind AI Weekly Chronicles - August'25 Week I
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
Encapsulation_ Review paper, used for researhc scholars
PPTX
Cloud computing and distributed systems.
Diabetes mellitus diagnosis method based random forest with bat algorithm
Blue Purple Modern Animated Computer Science Presentation.pdf.pdf
Approach and Philosophy of On baking technology
NewMind AI Monthly Chronicles - July 2025
7 ChatGPT Prompts to Help You Define Your Ideal Customer Profile.pdf
Detection-First SIEM: Rule Types, Dashboards, and Threat-Informed Strategy
KOM of Painting work and Equipment Insulation REV00 update 25-dec.pptx
Bridging biosciences and deep learning for revolutionary discoveries: a compr...
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Big Data Technologies - Introduction.pptx
Electronic commerce courselecture one. Pdf
Spectral efficient network and resource selection model in 5G networks
Advanced methodologies resolving dimensionality complications for autism neur...
Dropbox Q2 2025 Financial Results & Investor Presentation
Teaching material agriculture food technology
“AI and Expert System Decision Support & Business Intelligence Systems”
NewMind AI Weekly Chronicles - August'25 Week I
The AUB Centre for AI in Media Proposal.docx
Encapsulation_ Review paper, used for researhc scholars
Cloud computing and distributed systems.

SQL Server Query Optimization, Execution and Debugging Query Performance

  • 2. SQL Server Query Optimization, Execution and Debugging Query PerformanceVinod Kumar MTechnology Evangelist – Microsoft@vinodk_sqlwww.ExtremeExperts.comhttp://blogs.sqlxml.org/vinodkumar
  • 3. Session Objectives And TakeawaysTakeaways (Learn…): why estimated row counts affect plan selectionhow to find out “estimated” and “actual” row counts in the query planschallenges of parameterized queries how to influence query plan choicetips on design and testing of parameterized queries and stored proceduresbunch of useful demos you can try on your own
  • 4. Agenda IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
  • 5. Agenda IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
  • 6. SQL Server Relational ServerHigh-Level Architecture Language Processing (Parse/Bind)Query Optimization (Plan Generation, View Matching, Statistics, Costing)Statement/Batch ExecutionQuery Execution(Query Operators, Memory Grants, Parallelism)Metadata, Type system, Expression ServicesUtilities (DBCC, Backup / Restore, BCP, …)Plan Cache ManagementStorage Engine (Access Methods, Database Page Cache, Locking, Transactions, …)SQL-OS (Schedulers, Buffer Pool, Memory Management, Synchronization Primitives, …)SQL Relational Engine
  • 7. Query OptimizationQuery Optimization is cost based selection of good enough (potentially not the best) Query PlanInput to Query Optimization is Operator Tree produced byParsing SQL statement (Syntax)Semantic analysis and checking (Algebrizing – this includes type derivation, type checking, binding variables, table and column names, etc.)Output is Query Plan
  • 8. How is the plan cost determined?Demo – watch query plan costs for two similar queries…selectod.OrderID,od.ProductIDFROM [Order Details] odWHERE od.ProductID IN (9,15)SELECT od.OrderID,od.ProductIDFROM [Order Details] odWHERE od.ProductID IN (59,31)ConclusionsSQL Server is using cardinality estimates to derive cost of operatorsCardinality estimates are derived from the statistics
  • 9. Agenda IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
  • 10. Query Debugging ToolsSSMS – Management StudioShowplanDMVs – Dynamic Management ViewsTracePerfmon counters
  • 11. Optimizer Perfmon CountersUse “SQL Server:SQL Statistics” object counters:
  • 16. SQL Re-Compilations/sec TraceExecution events may be result of query plan selectionThe most useful execution event categories Errors and Warnings (e.g. Exchange Spill or Sort Warning)Performance (e.g. Plan Guide Successful or Performance Statistics)Query OptimizationErrors and Warnings – Missing Column Statistics and Missing Join PredicatePerformance - 8 different Showplan Events; the most useful areShowplan XML for Query Compile – with each compileShowplan XML Statistics Profile – with each execution
  • 17. DMVssys.dm_exec_query_stats- returns performance statistics and SQL handle for each query plan in cachesys.dm_exec_sql_text- Returns the text of the sql statement based on the SQL handle sys.dm_exec_query_plan- Returns the showplan in XML format for a batch or module based on the SQL handlesys.dm_exec_plan_attributes– TVF returns one row per plan attribute for the plan specified by the plan handle.
  • 18. Agenda IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
  • 19. Demo – Stored ProcedureCREATE PROCEDURE myp @ShipRegion NVARCHAR(15)asSELECT o.Orderid,c.CompanyName,od.QuantityFROM Orders o, [Order Details] od,Customers c WHERE o.Orderid=od.Orderid ANDo.CustomerID=c.CustomerID AND ((o.ShipRegion=@ShipRegion) OR (@ShipRegion is NULL) AND (o.ShipRegion is NULL))
  • 20. Estimated and Actual Query Plan Actual Query Plan contains additional informationActual Number of RowsActual Rebinds and RewindsNumber of ExecutionsParameter values (compile time and runtime)Estimated rowcount is per single executionWhen comparing the estimated and actual rowcounts multiply the estimated rowcountby estimated number of executionsSometimes (rarely!) the shape of the Actual Query Plan may differ from the Estimated
  • 21. How to Obtain Actual Plan?SSMS (as it was shown)SQLTRACEShowplan XML Statistics Profile eventSET STATISTICS XML ONReturns the Actual Plan in XML format following the resultSET STATISTICS PROFILE ONReturns text format of the query plan with two leading columns: ROWS and EXECUTESUsing DMVBut does not contain “actual” row counts or “actual parameter values”
  • 22. Agenda IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
  • 23. Two Different Days…-- Day One – NULL query comes firstDBCC FREEPROCCACHEEXECUTE myp NULLEXECUTE myp 'BC'-- Day Two – a BC query comes firstDBCC FREEPROCCACHEEXECUTE myp 'BC'EXECUTE myp NULLObserve:Query plan is reused for all parameter values if found in the cacheIf used for “different” value the discrepancies between “estimated” and “actual” row counts are higher
  • 24. Agenda IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
  • 25. One Testing ScenarioA story…Developer created parameterized stored procTester developed a driverTests were successful and sp moved to production After 4 weeks w/out any problems the sp now takes forever to finish and blocks the productionDisaster declared, all hands…A likely cause:The tests were run always with the same query plan created for the first set of parameter values
  • 26. Test ResultsIf the plans are equal (watch for plan reuse! Run DBCC FREEPROCCACHE) you are ok (most likely)Else it still may be ok to use one of the generated plans for all parameter values (even those that would not pick the plan)Else you need to use more than one plan to get desirable performance…
  • 27. Agenda IntroductionSQL Server OptimizerQuery Debugging ToolsEstimated and Actual Query PlanParameters and Query PlanTesting ConsiderationsHints and Other Workarounds
  • 28. One Query Plan is Goodbut some parameter values may generate different planWorkarounds If optimize for “unknown” gives desired plan -> use OPTION (OPTIMIZE FOR UNKNOWN)If optimization for a specific value produces the plan -> use OPTION (OPTIMIZE FOR (@ShipRegion=‘BC’))Use Plan Guides to enforce the same planRewrite the sp and “hide” the passed in parameter (example follows)
  • 29. Hiding Parameter ValueALTER PROCEDURE myp @ShipRegion NVARCHAR(15)asDECLARE @LocalShipRegion NVARCHAR (15)SET @LocalShipRegion=@ShipRegionSELECT o.Orderid,c.CompanyName,od.QuantityFROM Orders o, [Order Details] od,Customers c WHERE o.Orderid=od.Orderid ANDo.CustomerID=c.CustomerID AND ((o.ShipRegion=@LocalShipRegion) OR (@LocalShipRegionis NULL) and (o.ShipRegion is NULL))
  • 30. Session TakeawaysTakeaways (We have learned…): why estimated row counts affect plan selection (cost)how to find out “estimated” and “actual” row counts in the query plans (tools)challenges of parameterized queries (query plan reuse)how to influence query plan choice(sp rewrite, hints, plan guides)tips on design and testing of parameterized queries and stored procedures (several)
  • 31. Referenceshttp://blogs.msdn.com/sqltips/archive/2005/10/05/Top-N-costly-query-plans.aspxUmachandar’s blog “Find Top N costly query plans in adhoc batches or modules...” has some great DMV queries. You can track various times including cumulative time of many executions of the same statement or stored procedure. UC has example how to use the attributes in the XML showplan to correlate the plan costs with actual execution times. http://msdn.microsoft.com/en-us/library/dd672789.aspx Troubleshooting Performance Problems in SQL Server 2008 – white paper produced by MS developers and CSS. The paper is addressing most common performance problems as encountered by the CSS team and it is covering tools new in 2008.
  • 32. © 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries.The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.