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?

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 DavisRed Gate Software
 
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 knowKevin Kline
 
Database Performance Tuning
Database Performance Tuning Database Performance Tuning
Database Performance Tuning Arno Huetter
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning BaselineSQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline► Supreme Mandal ◄
 
SQL Server Optimization Checklist
SQL Server Optimization ChecklistSQL Server Optimization Checklist
SQL Server Optimization ChecklistGrant Fritchey
 
Sql server performance tuning
Sql server performance tuningSql server performance tuning
Sql server performance tuningJugal Shah
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsfOracle performance tuning_sfsf
Oracle performance tuning_sfsfMao Geng
 
Database performance tuning and query optimization
Database performance tuning and query optimizationDatabase performance tuning and query optimization
Database performance tuning and query optimizationDhani Ahmad
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuningSimon Huang
 
Oracle Database Performance Tuning Basics
Oracle Database Performance Tuning BasicsOracle Database Performance Tuning Basics
Oracle Database Performance Tuning Basicsnitin anjankar
 
Before you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution PlansBefore you optimize: Understanding Execution Plans
Before you optimize: Understanding Execution PlansTimothy Corey
 
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 serverVinod Kumar
 
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 ServerJason Strate
 
Oracle database performance tuning
Oracle database performance tuningOracle database performance tuning
Oracle database performance tuningYogiji 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 TuningOracleTrainings
 
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 DatabaseTung Nguyen Thanh
 
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)Guy Harrison
 
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 usesoramanc
 
Proactive performance monitoring with adaptive thresholds
Proactive performance monitoring with adaptive thresholdsProactive performance monitoring with adaptive thresholds
Proactive performance monitoring with adaptive thresholdsJohn Beresniewicz
 
Sql architecture
Sql architectureSql architecture
Sql architecturerchakra
 

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 internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureKevin Kline
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)Harish Chand
 
Sql server performance Tuning
Sql server performance TuningSql server performance Tuning
Sql server performance TuningSimon Huang
 
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 ServerKevin Kline
 
Microsoft sql server architecture
Microsoft sql server architectureMicrosoft sql server architecture
Microsoft sql server architectureNaveen Boda
 
Physical architecture of sql server
Physical architecture of sql serverPhysical architecture of sql server
Physical architecture of sql serverDivya Sharma
 
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 ConceptsDataminingTools Inc
 
Ms sql server architecture
Ms sql server architectureMs sql server architecture
Ms sql server architectureAjeet Singh
 

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

05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptxKareemBullard1
 
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/12cRonald Francisco Vargas Quesada
 
SQL Server 2008 Development for Programmers
SQL Server 2008 Development for ProgrammersSQL Server 2008 Development for Programmers
SQL Server 2008 Development for ProgrammersAdam Hutson
 
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 Whatudaymoogala
 
Sql query analyzer & maintenance
Sql query analyzer & maintenanceSql query analyzer & maintenance
Sql query analyzer & maintenancenspyrenet
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_planMaria Colgan
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimizationPractical SQL query monitoring and optimization
Practical SQL query monitoring and optimizationIvo Andreev
 
Overview of query evaluation
Overview of query evaluationOverview of query evaluation
Overview of query evaluationavniS
 
Oracle Sql Tuning
Oracle Sql TuningOracle Sql Tuning
Oracle Sql TuningChris Adkin
 
Understanding DB2 Optimizer
Understanding DB2 OptimizerUnderstanding DB2 Optimizer
Understanding DB2 Optimizerterraborealis
 
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 AnywhereSAP Technology
 
BI 2008 Simple
BI 2008 SimpleBI 2008 Simple
BI 2008 Simplellangit
 
SQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesSQL Server 2008 Integration Services
SQL Server 2008 Integration ServicesEduardo Castro
 
Modernizing SQL Server the Right Way
Modernizing SQL Server the Right WayModernizing SQL Server the Right Way
Modernizing SQL Server the Right WayJuan Fabian
 
Modeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDrawModeling and Testing Dovetail in MagicDraw
Modeling and Testing Dovetail in MagicDrawGregory Solovey
 
Skills Portfolio
Skills PortfolioSkills Portfolio
Skills Portfoliorolee23
 
Data Mining for Developers
Data Mining for DevelopersData Mining for Developers
Data Mining for Developersllangit
 

Ä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

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 ServerVinod Kumar
 
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 pessimisticVinod Kumar
 
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 PessimisticVinod Kumar
 
Sql Server Security
Sql Server SecuritySql Server Security
Sql Server SecurityVinod Kumar
 
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 WebcastVinod Kumar
 
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 FinalVinod Kumar
 

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

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clashcharlottematthew16
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsMiki Katsuragi
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenHervé Boutemy
 

Kürzlich hochgeladen (20)

Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Powerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time ClashPowerpoint exploring the locations used in television show Time Clash
Powerpoint exploring the locations used in television show Time Clash
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Vertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering TipsVertex AI Gemini Prompt Engineering Tips
Vertex AI Gemini Prompt Engineering Tips
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
DevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache MavenDevoxxFR 2024 Reproducible Builds with Apache Maven
DevoxxFR 2024 Reproducible Builds with Apache Maven
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 

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.