SQL Server Enterprise Architect Summit: June 09-12, 2009 Shanghai, China
SQL Server Enterprise Architect Summit: June 09-12, 2009 Shanghai, China
Howard Yin
Principal Program Manager
SQL Server Customer Advisory Team
Microsoft Corp.
Agenda
• SQLCAT Introduction
• Query Optimizer Architecture
• Query Plan Analysis
• Influencing Plan Selection
• Special Considerations
– Parameterized Queries
– Temporary Tables and Table Variables
– Parallel Queries
• References
Query Execution
Statistics, Costing) (Query Operators,
Plan Cache Management Memory Grants,
Parallelism)
Storage Engine (Access Methods, Database Page
Cache, Locking, Transactions, …)
SQL-OS (Schedulers, Buffer Pool, Memory
Management, Synchronization Primitives, …)
Query Optimization
Language Processing (Parse/Bind/View Expansion)
Statistics, Costing)
Parallelism)
Storage Engine (Access Methods, Database Page
Cache, Locking, Transactions, …)
SQL-OS (Schedulers, Buffer Pool, Memory
Management, Synchronization Primitives, …)
parse/bind
Query optimizer
Hash join
Generate … Concat
Join
alternatives
… Unio … … …
n Estimate cost
… … … Output
Input
Metadata Physical
Indices Properties
Statistics Memory
Constraints Number of
User cores
• Query block
SELECT SUM(T.a) GroupBy T.c, sum(T.a) GroupBy T.c, sum(T.a)
FROM T, R
Filter (T.b=R.b and R.c = 5) Join (T.b=R.b)
WHERE T.b = R.b
AND R.c = 5 Cross product Filter (R.c = 5)
T
GROUP BY T.c
T R R
A B A B A B
A A
• Optimizer Statistics
• Indexes and constraints
• Memory
• Logical number of processors
Microsoft Confidential
| SQL Server Customer Advisory Team 29
Statistics Issues
… and Best Practices
• Statistics are used to derive Cardinality Estimate (CE) on each query
operation
– Filter, Join, GroupBy, …
– Warning column in showplan if missing statistics
• Limitations
– CE gets progressively less reliable across multiple joins and group-by’s
– Hidden correlations tough to handle
• Data-level correlation: Two columns that are correlated
• Predicate-level correlation: Multiple predicates that are not independent
– Data skew impacts estimates, especially with sampled statistics
• Hard to correctly guess density from sample
• Recompilation if number of changes to a column exceeds thresholds
• (Re)Compilations requiring a statistic stall if auto_update stats is
executing
– Consider AUTO_UPDATE_STATISTICS_ASYNC Database option
• Best practices
– Reasons to turn off AUTO_UPDATE on a statistic
• If it is causing unnecessary recompilation - lots of updates but they don’t
change nature/distribution of data
• For increased predictability during work-day if can be scheduled during off
time
– Sometimes, FULLSCAN stats necessary – schedule periodic update stats
Microsoft Confidential
| SQL Server Customer Advisory Team 30
Upgrade Considerations
• Upgrade from SS 2000
– All SS 2000 stats are considered automatically
“stale” => autostats will take care of the
“upgrade”
– Best Practice is to update statistics manually as a
part of the upgrade step
– If stats are maintained manually they all should
be manually updated during upgrade
• sp_updatestats @resample = 'resample‘
– Details of changes are described in
http://www.microsoft.com/technet/prodtechnol
/sql/2005/qrystats.mspx
• Upgrade from SS 2005
– No need to update statistics
Microsoft Confidential
| SQL Server Customer Advisory Team 31
Agenda
• SQLCAT Introduction
• Query Optimizer Architecture
• Statistics Used by Optimizer
• Query Plan Analysis
• Influencing Plan Selection
• Parameterized Queries
• References
QUERY
HINT
Microsoft Confidential
| SQL Server Customer Advisory Team 45
Hints - New in 2005 and 2008
• RECOMPILE hint for individual queries
• The following hints provide more control to
“fix” the plan
– OPTIMIZE FOR hint to force particular values of
parameters to be used by the optimizer
– USE PLAN to enforce particular query plan
– PARAMETERIZATION hint
• Database level
• Inside a Plan Guide
– Plan Guides
• FORCESEEK – new table access hint in SQL
Server 2008
Microsoft Confidential
| SQL Server Customer Advisory Team 46
Recompile Hint
• In SS 2000: CREATE PROCEDURE WITH
RECOMPILE
• In SS 2005 and 2008, an individual
statement may have OPTION (RECOMPILE)
– Better alternative to dynamic SQL when
forcing recompilation for each new set of
variables was suggested in Shiloh
– Easier syntax
– No need to grant access to all referenced
objects; execute on the sp suffices
Microsoft Confidential
| SQL Server Customer Advisory Team 47
Optimize For Hint
OPTION ( OPTIMIZE FOR ( @variable_name
= literal_constant [ ,…n ] ) )
Microsoft Confidential
| SQL Server Customer Advisory Team 48
Use Plan Hint
• Plan Stability Feature
• Idea: Use a captured XML Showplan in
a USE PLAN query hint to guide the
optimizer to choose the same plan
Microsoft Confidential
| SQL Server Customer Advisory Team 49
Plan Forcing
Usage: Query
SELECT * FROM t
OPTION (
USE PLAN N‘<ShowPlanXML> …</ShowPlanXML>’
)
Query Hint
String literal
of XML Showplan
Microsoft Confidential
| SQL Server Customer Advisory Team 50
What’s Forced by Plan Hint
• Plan topology and order of evaluation
• Execution algorithms
• Index solutions
• Objects referenced in the query
Microsoft Confidential
| SQL Server Customer Advisory Team 51
Plan Hint Limitations
• No INSERT/UPDATE/DELETE in 2005,
YES in 2008
• No Distributed Query
• No Full-text queries
• Static, Fast_Forward cursors only
Microsoft Confidential
| SQL Server Customer Advisory Team 52
Plan Guides - Idea
• Out-of-band query hinting
• Scenario: query is known but cannot be modified
directly in the source code yet some hinting is
desirable
• Replace the Original Query by the hinted version
using “Plan Guide” system table
Original Query Hinted Version
Microsoft Confidential
| SQL Server Customer Advisory Team 53
Plan Guides Feature Overview
• Create: sp_create_plan_guide
• Drop/Enable/Disable:
sp_control_plan_guide
• Matching:
– During module (SP, DML trigger, multi-
statement TVF, scalar UDF) compilation
– During batch compilation
– Targets
• original user query
• Simple- or Force-parameterized query
Microsoft Confidential
| SQL Server Customer Advisory Team 54
Scenarios (all pertain to an app you
can’t change)
• Force use of a MERGE JOIN operation for a
specific query in a user-submitted batch
• Force optimizer to always use “worst case”
parameter value
• Force compilation sharing for queries with a
format that is the same except constant
literals are different
– Specify FORCED PARAMETERIZATION in plan
guide
• For use of a specific plan for a manually
parameterized query
Microsoft Confidential
| SQL Server Customer Advisory Team 55
New around plan guides in
2008
• Plan Freezing - ability to create a plan from the
plan cache directly
– The plan guide is automatically created by invoking
sp_create_plan_guide_from_cache
• See documentation for the sp for boilerplate code
• sys.fn_validate_plan_guide function validates if
the plan guide is still valid (after e.g. some
metadata changes)
• SQL Profiler trace events "Plan_guide_successful"
and "Plan_guide_unsuccessful" are located under
the "Performance" category
• Perfmon counters "Guided Plan Executions/sec"
and "Misguided Plan Executions/sec“ provide
similar function as the trace events above
Microsoft Confidential
| SQL Server Customer Advisory Team 56
Agenda
• SQLCAT Introduction
• Query Optimizer Architecture
• Query Plan Analysis
• Influencing Plan Selection
• Parameterized Queries
• References
Microsoft Confidential
63
&