Plan Caching and Recompilation
Plan Caching and Recompilation
• Auto-parameterization
• By default, only used for queries with an evenly
distributed cardinality
• Optimize for ad hoc workloads
• Ad hoc plans are cached only on second execution
• Prepared statements
• Used by database APIs (ODBC, OLEDB)
• Object Plans plan cache store
• Beware parameter sniffing
Examining the Plan Cache
• sys.dm_exec_cached_plans
• One row per cached plan
• sys.dm_exec_query_plan
• Query plan in XML format
• sys.dm_exec_text_query_plan
• Query plan in text format
• sys.dm_exec_plan_attributes
• Plan attributes
• sys.dm_exec_query_stats and
sys.dm_exec_procedure_stats
• Plan statistics
Demonstration: Analyzing the Query Plan Cache
• Statistics changes
• KEEP PLAN query hint reduces recompilations caused
by statistics changes
• KEEPFIXED PLAN query hint prevents recompilations
caused by statistics changes
• Try to avoid coding patterns that generate extra
recompilations
Problems of the Plan Cache
• sys.dm_db_tuning_recommendations returns:
• A score between 0 and 100 to indicate the anticipated
performance impact
• A JSON string containing the recommendations,
including:
• Metrics used to identify plan choice regression
• Commands used to apply the recommendation
• Contents of sys.dm_db_tuning_recommendations
are retained until the instance is restarted
Plan Choice Correction
• DMVs:
• Parallel the plan cache DMVs
Forcing Query Execution Plans
• SSMS:
• Click Force Plan button when viewing a query plan in
the Query Store
• Click Unforce Plan button to undo
• Transact-SQL:
• Use sp_querystore_force_plan to force a plan
• Use sp_querystore_unforce_plan to unforce a plan
• Regularly check the performance of forced plans
Demonstration: Working with the Query Store
Logon Information
Virtual machine: 10987C-MIA-SQL
User name: ADVENTUREWORKS\Student
Password: Pa55w.rd