SlideShare ist ein Scribd-Unternehmen logo
1 von 29
Amit Bansal
CTO
eDominer Systems P Ltd |
Peopleware India
Who is Amit Bansal?
 CTO, eDominer Systems & Peopleware India
 Conducted more than 200 workshops on SQL Server &
 BI for top notch IT companies world wide
 Microsoft MVP for SQL Server
 Microsoft Certified Trainer Advisory Council member
 Speaker at TechED India, TechED US & TechED Europe
 Technical Reviewer – MSL courses on SQL Server
 SME – SQL Server 2008 certifications
 UG Lead (Delhi NCR) – Culminis
 Manager – www.WeTogether.in, www.DelhiDevs.com,
 www.BlogBoard.in
Agenda & Session takeaways
 Query Optimizer characteristics
 Using Query & Table Hints
 Plan Freezing concept
 Scenarios from the wild
 What are Plan Guides & different types
 Implementing Plan Guides
 Managing & Validating Plan Guides
 Plan Guide considerations
 Summary
Query Optimizer characteristics
 Cost based optimization
 Does the Query Optimizer always do a fine job?
    Does it always select the best query plan?
 Use Hints to affect the query plan selection
    Use Hints as a last resort, Use with caution
    To be used only by experienced DBDs & DBAs
 Is there really a problem?
    Check if there are other issues
    Identify the real cause of a poor plan
    What if SQL Server fails to generate a valid plan?
    (error 8622 is raised)
Join, Query & Table Hints
   FAST N Hint                 Functionality
   RECOMPILE
                               Index Hints
   OPTIMIZE FOR Hint
   OPTIMIZE FOR UNKNOWN Hint   Join Hints
   JOIN Hints                  Parallelism
   FORCE ORDER Hint            Locking
   INDEX Hint
                               Compilation
   FORCESEEK Hint
   READPAST Hint               Table Hints
   USE PLAN Hint               ….
Plan Freezing concepts
 Forcing / Locking down a query plan
 Provides greater query performance stability &
 predictability
 Enables organizations to promote stable query plans
    Hardware Server replacements
    Server upgrades
    Production Deployments
 Plan Freezing can
    Optimize query performance
    Copy query plans between servers
    Prevent the plan cache from growing excessively with large
    compiled plans that are not reused
Scenarios from the wild…
 A query started mis-behaving after SQL Server upgrade
 Query text cannot be modified to use hints
     Eg: Application/vendor code, ISV, etc
 Query performance degraded after hardware upgrade
 You need to copy plans from one server to the other
 Overcoming ‘Parameter Sniffing’ issues
 After a service pack upgrade – “my query just starting
 running 4 times slower today and the plan is different
 from yesterday” ……sigh 
What are Plan Guides?
 Plan Freezing concept is implemented with Plan Guides
 A DB object that associates a set of query hints with
 the query
 Can be created using:
     sp_create_plan_guide
     sp_create_plan_guide_from_handle
 Fixed query plan (XML Showplan output) can be also
 be applied
 Available in Standard, Enterprise, Evaluation &
 Developer edition
Types of Plan Guides
 Object Plan Guides
    matches queries that execute in the context of a SQL Server
    object (SP, UDF, DML triggers etc)
 SQL Plan Guides
    matches queries that execute in the context of stand-alone
    Transact-SQL statements and batches ( not part of a
    database object)
 Template Plan Guides
    matches stand-alone queries that parameterize to a
    specified form
    To override the current PARAMETERIZATION setting
Object Plan Guides
 You are interested in a T-SQL statement appearing in
 the context of a SQL Server object
 SQL Server object can be:
    Stored Procedure
    User Defined Function (Scalar)
    Multi-statement table-valued user-defined
    functions
    DML Triggers
Object Plan Guides
sp_create_plan_guide
@name = N'Guide1',
@stmt = N'SELECT *FROM Sales.SalesOrderHeader AS
h,
        Sales.Customer AS c,
        Sales.SalesTerritory AS t
        WHERE h.CustomerID = c.CustomerID
             AND c.TerritoryID = t.TerritoryID
             AND CountryRegionCode =
@Country_region',
@type = N'OBJECT',
@module_or_batch =
N'Sales.GetSalesOrderByCountry',
@params = NULL,
@hints = N'OPTION (OPTIMIZE FOR (@Country_region
= N''US''))'
Implementing Object Plan Guides
Name
Title
Company
SQL Plan Guides
 You are interested in a particular T-SQL statement
    Stand-alone
    Or part of a batch
 T-SQL statements sent by CLR objects, extended SPs &
 Dynamic SQL (EXEC (sql_string)) are processed as
 batches
 The text has to be exactly the same:
    Case, whitespace, etc.
SQL Plan Guides
sp_create_plan_guide
@name = N'Guide2',
@stmt = N'SELECT TOP 1 * FROM
Sales.SalesOrderHeader ORDER BY OrderDate DESC',
@type = N'SQL',
@module_or_batch = NULL,
@params = NULL,
@hints = N'OPTION (MAXDOP 1)';
Implementing SQL Plan Guides
Name
Title
Company
Template Plan Guides
 To override PARAMETERIZATION database setting
 Can only use the following hints:
      PARAMETERIZATION FORCED
      PARAMETERIZATION SIMPLE
 Little tricky
      SQL Server has to construct a template of the query
      in the same format that it will be in once it is
      parameterized
      Special stored procedure: sp_get_query_template
      @params is only used for TEMPLATE plan guide
Template Plan Guides
EXEC sp_create_plan_guide
    @name = N'TemplateGuide1',
    @stmt = N'SELECT * FROM
AdventureWorks.Sales.SalesOrderHeader AS h
               INNER JOIN
AdventureWorks.Sales.SalesOrderDetail AS d
                   ON h.SalesOrderID =
d.SalesOrderID
               WHERE h.SalesOrderID = @0',
    @type = N'TEMPLATE',
    @module_or_batch = NULL,
    @params = N'@0 int',
    @hints = N'OPTION(PARAMETERIZATION FORCED)';
Implementing Template Plan Guides
Name
Title
Company
Applying a Fixed Query Plan to a Plan
Guide
  Useful when you know about an existing
  execution plan that performs better than the
  one selected by the optimizer for a particular
  query
  Can be applied to OBJECT or SQL plan guides
  Extract the XML Showplan from the cache and
  supply it to the sp_create_plan_guide
Applying a Fixed Query Plan to a Plan
Guide
Creating Plan Guides directly from
the plan cache
  Creates one or more plan guides from a query
  plan in the plan cache
  Can be applied to OBJECT or SQL plan guides
  Extract the plan handle from the cache and
  supply it to the
  sp_create_plan_guide_from_handle
Creating Plan Guides directly from the
plan cache
Managing & Validating Plan Guides
 Managing Plan Guides
     sp_control_plan_guide
       ENABLE, DISABLE, DROP
 Validating Plan guides
     sys.fn_validate_plan_guide
Plan Guides considerations
 The statement text in the plan guide must exactly
 match the query text
 To verify that your plan guide was used, see for specific
 elements in XML Showplan output
     PlanGuideDB & PlanGuideName (or)
     TemplatePlanGuideDB & TemplatePlanGuideName
     Query Plan (properties window)
Summary
 There are many scenarios where you cannot use hints
 Plan Guides come to rescue
 Three different types (OBJECT, SQL, TEMPLATE)
 SQL Server 2008 enhancements
    Applying a fixed query to a plan guide using XML
    Showplan
    Creating a plan directly from a plan in the plan
    cache
    Validating Plan Guides
 Plan Guide Considerations
© 2009 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.

Weitere ähnliche Inhalte

Ähnlich wie Admin Guiding Query Plans

Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)
Jason Strate
 
Advance Data Analysis & Database
Advance Data Analysis & DatabaseAdvance Data Analysis & Database
Advance Data Analysis & Database
Ahmed Yasir Khan
 
Sql server 2008_replication_technical_case_study
Sql server 2008_replication_technical_case_studySql server 2008_replication_technical_case_study
Sql server 2008_replication_technical_case_study
Klaudiia Jacome
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
Doug Armantrout
 

Ähnlich wie Admin Guiding Query Plans (20)

Beginners guide to_optimizer
Beginners guide to_optimizerBeginners guide to_optimizer
Beginners guide to_optimizer
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_plan
 
PASSMN Summit 2009 Upgrade to SSAS 2008
PASSMN Summit 2009 Upgrade to SSAS 2008PASSMN Summit 2009 Upgrade to SSAS 2008
PASSMN Summit 2009 Upgrade to SSAS 2008
 
Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)Discovering the plan cache (sql sat175)
Discovering the plan cache (sql sat175)
 
Understanding performance bottlenecks using performance dashboard
Understanding performance bottlenecks using performance dashboardUnderstanding performance bottlenecks using performance dashboard
Understanding performance bottlenecks using performance dashboard
 
Dashboard Factory - most efficient way to develop with SAP Design Studio
Dashboard Factory - most efficient way to develop with SAP Design Studio Dashboard Factory - most efficient way to develop with SAP Design Studio
Dashboard Factory - most efficient way to develop with SAP Design Studio
 
Web Cloud Computing SQL Server - Ferrara University
Web Cloud Computing SQL Server  -  Ferrara UniversityWeb Cloud Computing SQL Server  -  Ferrara University
Web Cloud Computing SQL Server - Ferrara University
 
SQL Server Query Optimization, Execution and Debugging Query Performance
SQL Server Query Optimization, Execution and Debugging Query PerformanceSQL Server Query Optimization, Execution and Debugging Query Performance
SQL Server Query Optimization, Execution and Debugging Query Performance
 
STSADM Automating SharePoint Administration - Tech Ed South East Asia 2008 wi...
STSADM Automating SharePoint Administration - Tech Ed South East Asia 2008 wi...STSADM Automating SharePoint Administration - Tech Ed South East Asia 2008 wi...
STSADM Automating SharePoint Administration - Tech Ed South East Asia 2008 wi...
 
My sql udf,views
My sql udf,viewsMy sql udf,views
My sql udf,views
 
Part4 Influencing Execution Plans with Optimizer Hints
Part4 Influencing Execution Plans with Optimizer HintsPart4 Influencing Execution Plans with Optimizer Hints
Part4 Influencing Execution Plans with Optimizer Hints
 
Mstr meetup
Mstr meetupMstr meetup
Mstr meetup
 
Advance Data Analysis & Database
Advance Data Analysis & DatabaseAdvance Data Analysis & Database
Advance Data Analysis & Database
 
Business Intelligence Dev. Portfolio
Business Intelligence Dev. PortfolioBusiness Intelligence Dev. Portfolio
Business Intelligence Dev. Portfolio
 
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
 
Sql server 2008_replication_technical_case_study
Sql server 2008_replication_technical_case_studySql server 2008_replication_technical_case_study
Sql server 2008_replication_technical_case_study
 
Andy West – Director of Technology Architecture, Pearson
Andy West – Director of Technology Architecture, PearsonAndy West – Director of Technology Architecture, Pearson
Andy West – Director of Technology Architecture, Pearson
 
Udf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayiUdf&views in sql...by thanveer melayi
Udf&views in sql...by thanveer melayi
 
Business Intelligence Portfolio
Business Intelligence PortfolioBusiness Intelligence Portfolio
Business Intelligence Portfolio
 

Mehr von rsnarayanan

Kevin Ms Web Platform
Kevin Ms Web PlatformKevin Ms Web Platform
Kevin Ms Web Platform
rsnarayanan
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
rsnarayanan
 
Harish Aspnet Dynamic Data
Harish Aspnet Dynamic DataHarish Aspnet Dynamic Data
Harish Aspnet Dynamic Data
rsnarayanan
 
Harish Aspnet Deployment
Harish Aspnet DeploymentHarish Aspnet Deployment
Harish Aspnet Deployment
rsnarayanan
 
Whats New In Sl3
Whats New In Sl3Whats New In Sl3
Whats New In Sl3
rsnarayanan
 
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
rsnarayanan
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
rsnarayanan
 
Occasionally Connected Systems
Occasionally Connected SystemsOccasionally Connected Systems
Occasionally Connected Systems
rsnarayanan
 
Developing Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And ServicesDeveloping Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And Services
rsnarayanan
 
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
rsnarayanan
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
rsnarayanan
 
Ms Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My SqlMs Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My Sql
rsnarayanan
 
Windows 7 For Developers
Windows 7 For DevelopersWindows 7 For Developers
Windows 7 For Developers
rsnarayanan
 
What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1
rsnarayanan
 
Ux For Developers
Ux For DevelopersUx For Developers
Ux For Developers
rsnarayanan
 
A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8
rsnarayanan
 

Mehr von rsnarayanan (20)

Walther Aspnet4
Walther Aspnet4Walther Aspnet4
Walther Aspnet4
 
Walther Ajax4
Walther Ajax4Walther Ajax4
Walther Ajax4
 
Kevin Ms Web Platform
Kevin Ms Web PlatformKevin Ms Web Platform
Kevin Ms Web Platform
 
Harish Understanding Aspnet
Harish Understanding AspnetHarish Understanding Aspnet
Harish Understanding Aspnet
 
Walther Mvc
Walther MvcWalther Mvc
Walther Mvc
 
Harish Aspnet Dynamic Data
Harish Aspnet Dynamic DataHarish Aspnet Dynamic Data
Harish Aspnet Dynamic Data
 
Harish Aspnet Deployment
Harish Aspnet DeploymentHarish Aspnet Deployment
Harish Aspnet Deployment
 
Whats New In Sl3
Whats New In Sl3Whats New In Sl3
Whats New In Sl3
 
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
Silverlight And .Net Ria Services – Building Lob And Business Applications Wi...
 
Advanced Silverlight
Advanced SilverlightAdvanced Silverlight
Advanced Silverlight
 
Netcf Gc
Netcf GcNetcf Gc
Netcf Gc
 
Occasionally Connected Systems
Occasionally Connected SystemsOccasionally Connected Systems
Occasionally Connected Systems
 
Developing Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And ServicesDeveloping Php Applications Using Microsoft Software And Services
Developing Php Applications Using Microsoft Software And Services
 
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
Build Mission Critical Applications On The Microsoft Platform Using Eclipse J...
 
J Query The Write Less Do More Javascript Library
J Query   The Write Less Do More Javascript LibraryJ Query   The Write Less Do More Javascript Library
J Query The Write Less Do More Javascript Library
 
Ms Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My SqlMs Sql Business Inteligence With My Sql
Ms Sql Business Inteligence With My Sql
 
Windows 7 For Developers
Windows 7 For DevelopersWindows 7 For Developers
Windows 7 For Developers
 
What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1What Is New In Wpf 3.5 Sp1
What Is New In Wpf 3.5 Sp1
 
Ux For Developers
Ux For DevelopersUx For Developers
Ux For Developers
 
A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8A Lap Around Internet Explorer 8
A Lap Around Internet Explorer 8
 

Kürzlich hochgeladen

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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Kürzlich hochgeladen (20)

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
 
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdfRising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
Rising Above_ Dubai Floods and the Fortitude of Dubai International Airport.pdf
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
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
 
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
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..Understanding the FAA Part 107 License ..
Understanding the FAA Part 107 License ..
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
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
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​Elevate Developer Efficiency & build GenAI Application with Amazon Q​
Elevate Developer Efficiency & build GenAI Application with Amazon Q​
 
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
 
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
 

Admin Guiding Query Plans

  • 1.
  • 2. Amit Bansal CTO eDominer Systems P Ltd | Peopleware India
  • 3. Who is Amit Bansal? CTO, eDominer Systems & Peopleware India Conducted more than 200 workshops on SQL Server & BI for top notch IT companies world wide Microsoft MVP for SQL Server Microsoft Certified Trainer Advisory Council member Speaker at TechED India, TechED US & TechED Europe Technical Reviewer – MSL courses on SQL Server SME – SQL Server 2008 certifications UG Lead (Delhi NCR) – Culminis Manager – www.WeTogether.in, www.DelhiDevs.com, www.BlogBoard.in
  • 4. Agenda & Session takeaways Query Optimizer characteristics Using Query & Table Hints Plan Freezing concept Scenarios from the wild What are Plan Guides & different types Implementing Plan Guides Managing & Validating Plan Guides Plan Guide considerations Summary
  • 5. Query Optimizer characteristics Cost based optimization Does the Query Optimizer always do a fine job? Does it always select the best query plan? Use Hints to affect the query plan selection Use Hints as a last resort, Use with caution To be used only by experienced DBDs & DBAs Is there really a problem? Check if there are other issues Identify the real cause of a poor plan What if SQL Server fails to generate a valid plan? (error 8622 is raised)
  • 6. Join, Query & Table Hints FAST N Hint Functionality RECOMPILE Index Hints OPTIMIZE FOR Hint OPTIMIZE FOR UNKNOWN Hint Join Hints JOIN Hints Parallelism FORCE ORDER Hint Locking INDEX Hint Compilation FORCESEEK Hint READPAST Hint Table Hints USE PLAN Hint ….
  • 7. Plan Freezing concepts Forcing / Locking down a query plan Provides greater query performance stability & predictability Enables organizations to promote stable query plans Hardware Server replacements Server upgrades Production Deployments Plan Freezing can Optimize query performance Copy query plans between servers Prevent the plan cache from growing excessively with large compiled plans that are not reused
  • 8. Scenarios from the wild… A query started mis-behaving after SQL Server upgrade Query text cannot be modified to use hints Eg: Application/vendor code, ISV, etc Query performance degraded after hardware upgrade You need to copy plans from one server to the other Overcoming ‘Parameter Sniffing’ issues After a service pack upgrade – “my query just starting running 4 times slower today and the plan is different from yesterday” ……sigh 
  • 9. What are Plan Guides? Plan Freezing concept is implemented with Plan Guides A DB object that associates a set of query hints with the query Can be created using: sp_create_plan_guide sp_create_plan_guide_from_handle Fixed query plan (XML Showplan output) can be also be applied Available in Standard, Enterprise, Evaluation & Developer edition
  • 10. Types of Plan Guides Object Plan Guides matches queries that execute in the context of a SQL Server object (SP, UDF, DML triggers etc) SQL Plan Guides matches queries that execute in the context of stand-alone Transact-SQL statements and batches ( not part of a database object) Template Plan Guides matches stand-alone queries that parameterize to a specified form To override the current PARAMETERIZATION setting
  • 11. Object Plan Guides You are interested in a T-SQL statement appearing in the context of a SQL Server object SQL Server object can be: Stored Procedure User Defined Function (Scalar) Multi-statement table-valued user-defined functions DML Triggers
  • 12. Object Plan Guides sp_create_plan_guide @name = N'Guide1', @stmt = N'SELECT *FROM Sales.SalesOrderHeader AS h, Sales.Customer AS c, Sales.SalesTerritory AS t WHERE h.CustomerID = c.CustomerID AND c.TerritoryID = t.TerritoryID AND CountryRegionCode = @Country_region', @type = N'OBJECT', @module_or_batch = N'Sales.GetSalesOrderByCountry', @params = NULL, @hints = N'OPTION (OPTIMIZE FOR (@Country_region = N''US''))'
  • 13. Implementing Object Plan Guides Name Title Company
  • 14. SQL Plan Guides You are interested in a particular T-SQL statement Stand-alone Or part of a batch T-SQL statements sent by CLR objects, extended SPs & Dynamic SQL (EXEC (sql_string)) are processed as batches The text has to be exactly the same: Case, whitespace, etc.
  • 15. SQL Plan Guides sp_create_plan_guide @name = N'Guide2', @stmt = N'SELECT TOP 1 * FROM Sales.SalesOrderHeader ORDER BY OrderDate DESC', @type = N'SQL', @module_or_batch = NULL, @params = NULL, @hints = N'OPTION (MAXDOP 1)';
  • 16. Implementing SQL Plan Guides Name Title Company
  • 17. Template Plan Guides To override PARAMETERIZATION database setting Can only use the following hints: PARAMETERIZATION FORCED PARAMETERIZATION SIMPLE Little tricky SQL Server has to construct a template of the query in the same format that it will be in once it is parameterized Special stored procedure: sp_get_query_template @params is only used for TEMPLATE plan guide
  • 18. Template Plan Guides EXEC sp_create_plan_guide @name = N'TemplateGuide1', @stmt = N'SELECT * FROM AdventureWorks.Sales.SalesOrderHeader AS h INNER JOIN AdventureWorks.Sales.SalesOrderDetail AS d ON h.SalesOrderID = d.SalesOrderID WHERE h.SalesOrderID = @0', @type = N'TEMPLATE', @module_or_batch = NULL, @params = N'@0 int', @hints = N'OPTION(PARAMETERIZATION FORCED)';
  • 19. Implementing Template Plan Guides Name Title Company
  • 20. Applying a Fixed Query Plan to a Plan Guide Useful when you know about an existing execution plan that performs better than the one selected by the optimizer for a particular query Can be applied to OBJECT or SQL plan guides Extract the XML Showplan from the cache and supply it to the sp_create_plan_guide
  • 21. Applying a Fixed Query Plan to a Plan Guide
  • 22. Creating Plan Guides directly from the plan cache Creates one or more plan guides from a query plan in the plan cache Can be applied to OBJECT or SQL plan guides Extract the plan handle from the cache and supply it to the sp_create_plan_guide_from_handle
  • 23. Creating Plan Guides directly from the plan cache
  • 24. Managing & Validating Plan Guides Managing Plan Guides sp_control_plan_guide ENABLE, DISABLE, DROP Validating Plan guides sys.fn_validate_plan_guide
  • 25. Plan Guides considerations The statement text in the plan guide must exactly match the query text To verify that your plan guide was used, see for specific elements in XML Showplan output PlanGuideDB & PlanGuideName (or) TemplatePlanGuideDB & TemplatePlanGuideName Query Plan (properties window)
  • 26. Summary There are many scenarios where you cannot use hints Plan Guides come to rescue Three different types (OBJECT, SQL, TEMPLATE) SQL Server 2008 enhancements Applying a fixed query to a plan guide using XML Showplan Creating a plan directly from a plan in the plan cache Validating Plan Guides Plan Guide Considerations
  • 27.
  • 28.
  • 29. © 2009 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.