SlideShare ist ein Scribd-Unternehmen logo
1 von 28
SQL Server Query Optimization, Execution and Debugging Query Performance Vinod Kumar M Technology Evangelist – Microsoft @vinodk_sql www.ExtremeExperts.com http://blogs.sqlxml.org/vinodkumar
Session Objectives And Takeaways Takeaways (Learn…):   why estimated row counts affect plan selection how to find out “estimated” and “actual” row counts in the query plans challenges of parameterized queries  how to influence query plan choice tips on design and testing of parameterized queries and stored procedures bunch of useful demos you can try on your own
Agenda	 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
Agenda	 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
SQL Server Relational ServerHigh-Level Architecture  Language Processing (Parse/Bind) Query Optimization  (Plan Generation, View Matching, Statistics, Costing) Statement/Batch Execution Query Execution (Query Operators, Memory Grants, Parallelism) Metadata, Type system, Expression Services Utilities (DBCC,  Backup / Restore, BCP, …) Plan Cache Management Storage Engine (Access Methods, Database Page Cache, Locking, Transactions, …) SQL-OS (Schedulers, Buffer Pool, Memory Management, Synchronization Primitives, …) SQL Relational Engine
Query Optimization Query Optimization is cost based selection of good enough (potentially not the best) Query Plan Input to Query Optimization is Operator Tree produced by Parsing 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.ProductID FROM [Order Details] od WHERE od.ProductID IN (9,15) SELECT od.OrderID,od.ProductID FROM [Order Details] od WHERE od.ProductID IN (59,31) Conclusions SQL Server is using cardinality estimates to derive cost of operators Cardinality estimates are derived from the statistics
Agenda	 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
Query Debugging Tools SSMS – Management Studio Showplan DMVs – Dynamic Management Views Trace Perfmon counters
Optimizer Perfmon Counters ,[object Object]
Auto-Param Attempts/sec
Forced Parameterizations/sec
Guided Plan Executions/sec
SQL Compilations/sec
SQL Re-Compilations/sec ,[object Object]
DMVs sys.dm_exec_query_stats - returns performance statistics and SQL handle for each query plan in cache sys.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 handle sys.dm_exec_plan_attributes – TVF returns one row per plan attribute for the plan specified by the plan handle.
Agenda	 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
Demo – Stored Procedure CREATE PROCEDURE myp @ShipRegion NVARCHAR(15) as SELECT o.Orderid,c.CompanyName,od.Quantity FROM Orders o, [Order Details] od,Customers c  WHERE  o.Orderid=od.Orderid AND o.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 information Actual Number of Rows Actual Rebinds and Rewinds Number of Executions Parameter values (compile time and runtime) Estimated rowcount is per single execution When comparing the estimated and actual rowcounts multiply the estimated rowcountby estimated number of executions Sometimes (rarely!) the shape of the Actual Query Plan may differ  from the Estimated
How to Obtain Actual Plan? SSMS (as it was shown) SQLTRACE Showplan XML Statistics Profile event SET STATISTICS XML ON Returns the Actual Plan in XML format following the result SET STATISTICS PROFILE ON Returns text format of the query plan with two leading columns: ROWS and EXECUTES Using DMV But does not contain “actual” row counts or “actual parameter values”
Agenda	 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
Two Different Days… -- Day One – NULL query comes first DBCC FREEPROCCACHE EXECUTE myp NULL EXECUTE myp 'BC' -- Day Two – a BC query comes first DBCC FREEPROCCACHE EXECUTE myp 'BC' EXECUTE myp NULL Observe: Query plan is reused for all parameter values if found in the cache If used for “different” value the discrepancies between “estimated” and “actual” row counts are higher
Agenda	 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
One Testing Scenario A story… Developer created parameterized stored proc Tester developed a driver Tests were successful and sp moved to production  After 4 weeks w/out any problems the sp now takes forever to finish and blocks the production Disaster 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 Results If 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	 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
One Query Plan is Goodbut some parameter values may generate different plan Workarounds  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 plan Rewrite the sp and “hide” the passed in parameter (example follows)

Weitere ähnliche Inhalte

Was ist angesagt?

Oracle performance tuning_sfsf
Oracle performance tuning_sfsfOracle performance tuning_sfsf
Oracle performance tuning_sfsf
Mao Geng
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
Simon Huang
 
Oracle database performance tuning
Oracle database performance tuningOracle database performance tuning
Oracle database performance tuning
Yogiji Creations
 
Oracle Performance Tuning Training | Oracle Performance Tuning
Oracle Performance Tuning Training | Oracle Performance TuningOracle Performance Tuning Training | Oracle Performance Tuning
Oracle Performance Tuning Training | Oracle Performance Tuning
OracleTrainings
 
Sql architecture
Sql architectureSql architecture
Sql architecture
rchakra
 

Was ist angesagt? (20)

Uncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony DavisUncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony Davis
 
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
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning BaselineSQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline
 
SQL Server Optimization Checklist
SQL Server Optimization ChecklistSQL Server Optimization Checklist
SQL Server Optimization Checklist
 
Sql server performance tuning
Sql server performance tuningSql server performance tuning
Sql server performance tuning
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsfOracle performance tuning_sfsf
Oracle performance tuning_sfsf
 
Database performance tuning and query optimization
Database performance tuning and query optimizationDatabase performance tuning and query optimization
Database performance tuning and query optimization
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
 
Before you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution PlansBefore you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution Plans
 
Advanced t sql - querying and programming inside sql server
Advanced t sql - querying and programming inside sql serverAdvanced t sql - querying and programming inside sql server
Advanced t sql - querying and programming inside sql server
 
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
 
Oracle database performance tuning
Oracle database performance tuningOracle database performance tuning
Oracle database performance tuning
 
Oracle Performance Tuning Training | Oracle Performance Tuning
Oracle Performance Tuning Training | Oracle Performance TuningOracle Performance Tuning Training | Oracle Performance Tuning
Oracle Performance Tuning Training | Oracle Performance Tuning
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL DatabasePerformance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
 
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR usesEarl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
 
Proactive performance monitoring with adaptive thresholds
Proactive performance monitoring with adaptive thresholdsProactive performance monitoring with adaptive thresholds
Proactive performance monitoring with adaptive thresholds
 
Sql architecture
Sql architectureSql architecture
Sql architecture
 

Andere mochten auch

Microsoft sql server architecture
Microsoft sql server architectureMicrosoft sql server architecture
Microsoft sql server architecture
Naveen Boda
 

Andere mochten auch (13)

Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)
 
Master tuning
Master   tuningMaster   tuning
Master tuning
 
Sql server performance Tuning
Sql server performance TuningSql server performance Tuning
Sql server performance Tuning
 
SQL Server
SQL ServerSQL Server
SQL Server
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL ServerEnd-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
 
Microsoft sql server architecture
Microsoft sql server architectureMicrosoft sql server architecture
Microsoft sql server architecture
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql server
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTUREMS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
 
Sql server basics
Sql server basicsSql server basics
Sql server basics
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database ConceptsMS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
 
SQL Server 2012 Best Practices
SQL Server 2012 Best PracticesSQL Server 2012 Best Practices
SQL Server 2012 Best Practices
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architecture
 

Ähnlich wie SQL Server Query Optimization, Execution and Debugging Query Performance

Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And WhatPerformance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
udaymoogala
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
avniS
 
Data Mining for Developers
Data Mining for DevelopersData Mining for Developers
Data Mining for Developers
llangit
 

Ähnlich wie SQL Server Query Optimization, Execution and Debugging Query Performance (20)

05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
 
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
 
SQL Server 2008 Development for Programmers
SQL Server 2008 Development for ProgrammersSQL Server 2008 Development for Programmers
SQL Server 2008 Development for Programmers
 
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And WhatPerformance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
 
Sql query analyzer & maintenance
Sql query analyzer & maintenanceSql query analyzer & maintenance
Sql query analyzer & maintenance
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_plan
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimizationPractical SQL query monitoring and optimization
Practical SQL query monitoring and optimization
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluation
 
Oracle Sql Tuning
Oracle Sql TuningOracle Sql Tuning
Oracle Sql Tuning
 
Understanding DB2 Optimizer
Understanding DB2 OptimizerUnderstanding DB2 Optimizer
Understanding DB2 Optimizer
 
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
 
BI 2008 Simple
BI 2008 SimpleBI 2008 Simple
BI 2008 Simple
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesSQL Server 2008 Integration Services
SQL Server 2008 Integration Services
 
Modernizing SQL Server the Right Way
Modernizing SQL Server the Right WayModernizing SQL Server the Right Way
Modernizing SQL Server the Right Way
 
Modeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDrawModeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDraw
 
Test automation process
Test automation processTest automation process
Test automation process
 
Test automation process _ QTP
Test automation process _ QTPTest automation process _ QTP
Test automation process _ QTP
 
Skills Portfolio
Skills PortfolioSkills Portfolio
Skills Portfolio
 
SQL_Tuning_Oracle_10g.pdf
SQL_Tuning_Oracle_10g.pdfSQL_Tuning_Oracle_10g.pdf
SQL_Tuning_Oracle_10g.pdf
 
Data Mining for Developers
Data Mining for DevelopersData Mining for Developers
Data Mining for Developers
 

Mehr von Vinod Kumar (6)

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

Kürzlich hochgeladen

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
panagenda
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 

Kürzlich hochgeladen (20)

Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
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
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
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...
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
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
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Why Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire businessWhy Teams call analytics are critical to your entire business
Why Teams call analytics are critical to your entire business
 
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
 
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
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 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...
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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, ...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 

SQL Server Query Optimization, Execution and Debugging Query Performance

  • 1.
  • 2. SQL Server Query Optimization, Execution and Debugging Query Performance Vinod Kumar M Technology Evangelist – Microsoft @vinodk_sql www.ExtremeExperts.com http://blogs.sqlxml.org/vinodkumar
  • 3. Session Objectives And Takeaways Takeaways (Learn…): why estimated row counts affect plan selection how to find out “estimated” and “actual” row counts in the query plans challenges of parameterized queries how to influence query plan choice tips on design and testing of parameterized queries and stored procedures bunch of useful demos you can try on your own
  • 4. Agenda Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
  • 5. Agenda Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
  • 6. SQL Server Relational ServerHigh-Level Architecture Language Processing (Parse/Bind) Query Optimization (Plan Generation, View Matching, Statistics, Costing) Statement/Batch Execution Query Execution (Query Operators, Memory Grants, Parallelism) Metadata, Type system, Expression Services Utilities (DBCC, Backup / Restore, BCP, …) Plan Cache Management Storage Engine (Access Methods, Database Page Cache, Locking, Transactions, …) SQL-OS (Schedulers, Buffer Pool, Memory Management, Synchronization Primitives, …) SQL Relational Engine
  • 7. Query Optimization Query Optimization is cost based selection of good enough (potentially not the best) Query Plan Input to Query Optimization is Operator Tree produced by Parsing 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.ProductID FROM [Order Details] od WHERE od.ProductID IN (9,15) SELECT od.OrderID,od.ProductID FROM [Order Details] od WHERE od.ProductID IN (59,31) Conclusions SQL Server is using cardinality estimates to derive cost of operators Cardinality estimates are derived from the statistics
  • 9. Agenda Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
  • 10. Query Debugging Tools SSMS – Management Studio Showplan DMVs – Dynamic Management Views Trace Perfmon counters
  • 11.
  • 16.
  • 17. DMVs sys.dm_exec_query_stats - returns performance statistics and SQL handle for each query plan in cache sys.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 handle sys.dm_exec_plan_attributes – TVF returns one row per plan attribute for the plan specified by the plan handle.
  • 18. Agenda Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
  • 19. Demo – Stored Procedure CREATE PROCEDURE myp @ShipRegion NVARCHAR(15) as SELECT o.Orderid,c.CompanyName,od.Quantity FROM Orders o, [Order Details] od,Customers c WHERE o.Orderid=od.Orderid AND o.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 information Actual Number of Rows Actual Rebinds and Rewinds Number of Executions Parameter values (compile time and runtime) Estimated rowcount is per single execution When comparing the estimated and actual rowcounts multiply the estimated rowcountby estimated number of executions Sometimes (rarely!) the shape of the Actual Query Plan may differ from the Estimated
  • 21. How to Obtain Actual Plan? SSMS (as it was shown) SQLTRACE Showplan XML Statistics Profile event SET STATISTICS XML ON Returns the Actual Plan in XML format following the result SET STATISTICS PROFILE ON Returns text format of the query plan with two leading columns: ROWS and EXECUTES Using DMV But does not contain “actual” row counts or “actual parameter values”
  • 22. Agenda Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
  • 23. Two Different Days… -- Day One – NULL query comes first DBCC FREEPROCCACHE EXECUTE myp NULL EXECUTE myp 'BC' -- Day Two – a BC query comes first DBCC FREEPROCCACHE EXECUTE myp 'BC' EXECUTE myp NULL Observe: Query plan is reused for all parameter values if found in the cache If used for “different” value the discrepancies between “estimated” and “actual” row counts are higher
  • 24. Agenda Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
  • 25. One Testing Scenario A story… Developer created parameterized stored proc Tester developed a driver Tests were successful and sp moved to production After 4 weeks w/out any problems the sp now takes forever to finish and blocks the production Disaster 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 Results If 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 Introduction SQL Server Optimizer Query Debugging Tools Estimated and Actual Query Plan Parameters and Query Plan Testing Considerations Hints and Other Workarounds
  • 28. One Query Plan is Goodbut some parameter values may generate different plan Workarounds 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 plan Rewrite the sp and “hide” the passed in parameter (example follows)
  • 29. Hiding Parameter Value ALTER PROCEDURE myp @ShipRegion NVARCHAR(15) as DECLARE @LocalShipRegion NVARCHAR (15) SET @LocalShipRegion=@ShipRegion SELECT o.Orderid,c.CompanyName,od.Quantity FROM Orders o, [Order Details] od,Customers c WHERE o.Orderid=od.Orderid AND o.CustomerID=c.CustomerID AND ((o.ShipRegion=@LocalShipRegion) OR (@LocalShipRegionis NULL) and (o.ShipRegion is NULL))
  • 30. Session Takeaways Takeaways (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. References http://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.