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)
Ad

Recommended

Why & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to query
Antonios Chatzipavlis
 
SQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database Performance
Mark Ginnebaugh
 
Sql Server Performance Tuning
Sql Server Performance Tuning
Bala Subra
 
Sql server performance tuning
Sql server performance tuning
ngupt28
 
Performance tuning in sql server
Performance tuning in sql server
Antonios Chatzipavlis
 
Query Optimization in SQL Server
Query Optimization in SQL Server
Rajesh Gunasundaram
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First Time
Dean Richards
 
Sql server performance tuning and optimization
Sql server performance tuning and optimization
Manish Rawat
 
Uncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony Davis
Red Gate Software
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
Kevin Kline
 
Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline
► Supreme Mandal ◄
 
SQL Server Optimization Checklist
SQL Server Optimization Checklist
Grant Fritchey
 
Sql server performance tuning
Sql server performance tuning
Jugal Shah
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsf
Mao Geng
 
Database performance tuning and query optimization
Database performance tuning and query optimization
Dhani Ahmad
 
Oracle db performance tuning
Oracle db performance tuning
Simon Huang
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
nitin anjankar
 
Before you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution Plans
Timothy Corey
 
Advanced t sql - querying and programming inside sql server
Advanced t sql - querying and programming inside sql server
Vinod Kumar
 
The Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL Server
Jason Strate
 
Oracle database performance tuning
Oracle database performance tuning
Yogiji Creations
 
Oracle Performance Tuning Training | Oracle Performance Tuning
Oracle Performance Tuning Training | Oracle Performance Tuning
OracleTrainings
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
Tung Nguyen Thanh
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
Guy Harrison
 
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
oramanc
 
Proactive performance monitoring with adaptive thresholds
Proactive performance monitoring with adaptive thresholds
John Beresniewicz
 
Sql architecture
Sql architecture
rchakra
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)
Harish Chand
 

More Related Content

What's hot (20)

Uncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony Davis
Red Gate Software
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
Kevin Kline
 
Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline
► Supreme Mandal ◄
 
SQL Server Optimization Checklist
SQL Server Optimization Checklist
Grant Fritchey
 
Sql server performance tuning
Sql server performance tuning
Jugal Shah
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsf
Mao Geng
 
Database performance tuning and query optimization
Database performance tuning and query optimization
Dhani Ahmad
 
Oracle db performance tuning
Oracle db performance tuning
Simon Huang
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
nitin anjankar
 
Before you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution Plans
Timothy Corey
 
Advanced t sql - querying and programming inside sql server
Advanced t sql - querying and programming inside sql server
Vinod Kumar
 
The Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL Server
Jason Strate
 
Oracle database performance tuning
Oracle database performance tuning
Yogiji Creations
 
Oracle Performance Tuning Training | Oracle Performance Tuning
Oracle Performance Tuning Training | Oracle Performance Tuning
OracleTrainings
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
Tung Nguyen Thanh
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
Guy Harrison
 
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
oramanc
 
Proactive performance monitoring with adaptive thresholds
Proactive performance monitoring with adaptive thresholds
John Beresniewicz
 
Sql architecture
Sql architecture
rchakra
 
Uncovering SQL Server query problems with execution plans - Tony Davis
Uncovering SQL Server query problems with execution plans - Tony Davis
Red Gate Software
 
Ten query tuning techniques every SQL Server programmer should know
Ten query tuning techniques every SQL Server programmer should know
Kevin Kline
 
Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline
► Supreme Mandal ◄
 
SQL Server Optimization Checklist
SQL Server Optimization Checklist
Grant Fritchey
 
Sql server performance tuning
Sql server performance tuning
Jugal Shah
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsf
Mao Geng
 
Database performance tuning and query optimization
Database performance tuning and query optimization
Dhani Ahmad
 
Oracle db performance tuning
Oracle db performance tuning
Simon Huang
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basics
nitin anjankar
 
Before you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution Plans
Timothy Corey
 
Advanced t sql - querying and programming inside sql server
Advanced t sql - querying and programming inside sql server
Vinod Kumar
 
The Plan Cache Whisperer - Performance Tuning SQL Server
The Plan Cache Whisperer - Performance Tuning SQL Server
Jason Strate
 
Oracle database performance tuning
Oracle database performance tuning
Yogiji Creations
 
Oracle Performance Tuning Training | Oracle Performance Tuning
Oracle Performance Tuning Training | Oracle Performance Tuning
OracleTrainings
 
Performance Tuning And Optimization Microsoft SQL Database
Performance Tuning And Optimization Microsoft SQL Database
Tung Nguyen Thanh
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
Guy Harrison
 
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
Earl Shaffer Oracle Performance Tuning pre12c 11g AWR uses
oramanc
 
Proactive performance monitoring with adaptive thresholds
Proactive performance monitoring with adaptive thresholds
John Beresniewicz
 
Sql architecture
Sql architecture
rchakra
 

Viewers also liked (13)

Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)
Harish Chand
 
Master tuning
Master tuning
Thomas Kejser
 
Sql server performance Tuning
Sql server performance Tuning
Simon Huang
 
SQL Server
SQL Server
webhostingguy
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
Kevin Kline
 
Microsoft sql server architecture
Microsoft sql server architecture
Naveen Boda
 
Physical architecture of sql server
Physical architecture of sql server
Divya Sharma
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
Douglas Bernardini
 
Sql server basics
Sql server basics
VishalJharwade
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
DataminingTools Inc
 
SQL Server 2012 Best Practices
SQL Server 2012 Best Practices
Microsoft TechNet - Belgium and Luxembourg
 
Ms sql server architecture
Ms sql server architecture
Ajeet Singh
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)
Harish Chand
 
Sql server performance Tuning
Sql server performance Tuning
Simon Huang
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
Kevin Kline
 
Microsoft sql server architecture
Microsoft sql server architecture
Naveen Boda
 
Physical architecture of sql server
Physical architecture of sql server
Divya Sharma
 
MS Sql Server: Introduction To Database Concepts
MS Sql Server: Introduction To Database Concepts
DataminingTools Inc
 
Ms sql server architecture
Ms sql server architecture
Ajeet Singh
 
Ad

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

05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
KareemBullard1
 
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Ronald Francisco Vargas Quesada
 
SQL Server 2008 Development for Programmers
SQL Server 2008 Development for Programmers
Adam Hutson
 
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
udaymoogala
 
Sql query analyzer & maintenance
Sql query analyzer & maintenance
nspyrenet
 
Explain the explain_plan
Explain the explain_plan
Maria Colgan
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimization
Ivo Andreev
 
Overview of query evaluation
Overview of query evaluation
avniS
 
Oracle Sql Tuning
Oracle Sql Tuning
Chris Adkin
 
Understanding DB2 Optimizer
Understanding DB2 Optimizer
terraborealis
 
Maximizing Database Tuning in SAP SQL Anywhere
Maximizing Database Tuning in SAP SQL Anywhere
SAP Technology
 
BI 2008 Simple
BI 2008 Simple
llangit
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration Services
Eduardo Castro
 
Modernizing SQL Server the Right Way
Modernizing SQL Server the Right Way
Juan Fabian
 
Modeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDraw
Gregory Solovey
 
Test automation process _ QTP
Test automation process _ QTP
Bharathi Krishnamurthi
 
Test automation process
Test automation process
Bharathi Krishnamurthi
 
Skills Portfolio
Skills Portfolio
rolee23
 
SQL_Tuning_Oracle_10g.pdf
SQL_Tuning_Oracle_10g.pdf
NareshKumar729083
 
Mathematical Modeling using MATLAB, by U.M. Sundar Senior Application Enginee...
Mathematical Modeling using MATLAB, by U.M. Sundar Senior Application Enginee...
CdactX Technologies, Ltd.
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
KareemBullard1
 
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Ronald Francisco Vargas Quesada
 
SQL Server 2008 Development for Programmers
SQL Server 2008 Development for Programmers
Adam Hutson
 
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
Performance Tuning With Oracle ASH and AWR. Part 1 How And What
udaymoogala
 
Sql query analyzer & maintenance
Sql query analyzer & maintenance
nspyrenet
 
Explain the explain_plan
Explain the explain_plan
Maria Colgan
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimization
Ivo Andreev
 
Overview of query evaluation
Overview of query evaluation
avniS
 
Oracle Sql Tuning
Oracle Sql Tuning
Chris Adkin
 
Understanding DB2 Optimizer
Understanding DB2 Optimizer
terraborealis
 
Maximizing Database Tuning in SAP SQL Anywhere
Maximizing Database Tuning in SAP SQL Anywhere
SAP Technology
 
BI 2008 Simple
BI 2008 Simple
llangit
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration Services
Eduardo Castro
 
Modernizing SQL Server the Right Way
Modernizing SQL Server the Right Way
Juan Fabian
 
Modeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDraw
Gregory Solovey
 
Skills Portfolio
Skills Portfolio
rolee23
 
Mathematical Modeling using MATLAB, by U.M. Sundar Senior Application Enginee...
Mathematical Modeling using MATLAB, by U.M. Sundar Senior Application Enginee...
CdactX Technologies, Ltd.
 
Ad

More from Vinod Kumar (6)

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

Recently uploaded (20)

Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Using the SQLExecutor for Data Quality Management: aka One man's love for the...
Safe Software
 
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
War_And_Cyber_3_Years_Of_Struggle_And_Lessons_For_Global_Security.pdf
biswajitbanerjee38
 
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
Cluster-Based Multi-Objective Metamorphic Test Case Pair Selection for Deep N...
janeliewang985
 
MuleSoft for AgentForce : Topic Center and API Catalog
MuleSoft for AgentForce : Topic Center and API Catalog
shyamraj55
 
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
CapCut Pro Crack For PC Latest Version {Fully Unlocked} 2025
pcprocore
 
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Seminar: Evolving Landscape of Post-Quantum Cryptography.pptx
FIDO Alliance
 
Connecting Data and Intelligence: The Role of FME in Machine Learning
Connecting Data and Intelligence: The Role of FME in Machine Learning
Safe Software
 
Security Tips for Enterprise Azure Solutions
Security Tips for Enterprise Azure Solutions
Michele Leroux Bustamante
 
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Seminar: Authentication for a Billion Consumers - Amazon.pptx
FIDO Alliance
 
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC and Open Hackathons Monthly Highlights June 2025
OpenACC
 
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Smarter Aviation Data Management: Lessons from Swedavia Airports and Sweco
Safe Software
 
OpenPOWER Foundation & Open-Source Core Innovations
OpenPOWER Foundation & Open-Source Core Innovations
IBM
 
PyCon SG 25 - Firecracker Made Easy with Python.pdf
PyCon SG 25 - Firecracker Made Easy with Python.pdf
Muhammad Yuga Nugraha
 
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Seminar: New Data: Passkey Adoption in the Workforce.pptx
FIDO Alliance
 
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance Seminar State of Passkeys.pptx
FIDO Alliance
 
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Seminar: Targeting Trust: The Future of Identity in the Workforce.pptx
FIDO Alliance
 
Cyber Defense Matrix Workshop - RSA Conference
Cyber Defense Matrix Workshop - RSA Conference
Priyanka Aash
 
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
ReSTIR [DI]: Spatiotemporal reservoir resampling for real-time ray tracing ...
revolcs10
 
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
"How to survive Black Friday: preparing e-commerce for a peak season", Yurii ...
Fwdays
 
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Enhance GitHub Copilot using MCP - Enterprise version.pdf
Nilesh Gule
 

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.