Before You Optimize:
Understanding Execution Plans




                        @IAmTimCorey
About Me
•   Worked with Microsoft SQL since 6.5
•   Started my career in VB6
•   Moved to .NET when it came out
•   Consultant, Adjunct Professor, Trainer, and
    Speaker
Agenda
•   Introduction to Execution Plans
•   Reading Execution Plans
•   Limitations
•   Additional Tools
•   Next Steps
What Are Execution Plans?
Basic Execution Plan
Types of Execution Plans
           Estimated           Actual
Graphical Ctrl + L        Ctrl + M
Text      SHOWPLAN_ALL    STATISTICS PROFILE
          SHOWPLAN_TEXT
XML       SHOWPLAN_XML    STATISTICS_XML
Estimated vs. Actual Details
List of Existing Plans
SELECT [cp].[refcounts]
 ,[cp].[usecounts]
 ,[cp].[objtype]
 ,[st].[dbid]
 ,[st].[objectid]
 ,[st].[text]
 ,[qp].[query_plan]
FROM sys.dm_exec_cached_plans cp
CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st
CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle)
qp;

* From SQL Server Execution Plans by Grant Fritchey – p. 23
Execution Plan Aging
Formula: Cost to compile * # of calls
Lazywriter: scans cache and decrements by one
each scan
Clear Cache: DBCC FREEPROCCACHE

Items are removed when:
• Memory is needed
• The age of the item is zero
• The plan is not currently in use
How Do You Read an Execution
           Plan?
Rebind and Rewind
Occur on certain loop joins. They represent
each time the system has to look through the
inner table again for more data.

Rebind – when the outer data changes
Rewind – when the outer data remains the same

More info: http://bit.ly/P7EUv3
Limitations
Ad Hoc Query Plans
Ad hoc plans will use the cache as long as:
• The schema is specified throughout
• The text doesn’t change (at all*)

* For queries with one table only, simple
parameterization will allow the parameters to
change while still reusing the cached plan. To
expand this to more complex queries, see this
reference: http://bit.ly/Oi3FDH
Parameter Sniffing
SQL Server designs execution plans based upon the
first set of parameters passed in. This can have
adverse effects. To get around it, you can:
• Use WITH RECOMPILE
• Use tailored stored procs
• Set a trace flag to disable parameter sniffing
• Use the OPTIMIZE FOR query hint
• Use sp_recompile to clear cache for stored proc
   or those that use a particular table

Read more here: http://bit.ly/MqNVOG
Additional Tools
SQL Sentry Plan Explorer




http://bit.ly/NDwBqh
AutoEPLoader




http://bit.ly/StcFVu
SQL Server Profiler
How Do I Learn More?
Further Resources
•   Book by Grant Fritchey - http://bit.ly/MtL0a2
•   Index Statistics - http://bit.ly/NTArHo
•   Query Parallelism - http://bit.ly/NlcS0s
•   Query Hints - http://bit.ly/N6YMKo
For questions, comments, and
 further information, catch me on
Twitter at @IAmTimCorey or email
      me@timothycorey.com

Before you optimize: Understanding Execution Plans

  • 1.
    Before You Optimize: UnderstandingExecution Plans @IAmTimCorey
  • 2.
    About Me • Worked with Microsoft SQL since 6.5 • Started my career in VB6 • Moved to .NET when it came out • Consultant, Adjunct Professor, Trainer, and Speaker
  • 3.
    Agenda • Introduction to Execution Plans • Reading Execution Plans • Limitations • Additional Tools • Next Steps
  • 4.
  • 5.
  • 6.
    Types of ExecutionPlans Estimated Actual Graphical Ctrl + L Ctrl + M Text SHOWPLAN_ALL STATISTICS PROFILE SHOWPLAN_TEXT XML SHOWPLAN_XML STATISTICS_XML
  • 7.
  • 8.
    List of ExistingPlans SELECT [cp].[refcounts] ,[cp].[usecounts] ,[cp].[objtype] ,[st].[dbid] ,[st].[objectid] ,[st].[text] ,[qp].[query_plan] FROM sys.dm_exec_cached_plans cp CROSS APPLY sys.dm_exec_sql_text(cp.plan_handle) st CROSS APPLY sys.dm_exec_query_plan(cp.plan_handle) qp; * From SQL Server Execution Plans by Grant Fritchey – p. 23
  • 9.
    Execution Plan Aging Formula:Cost to compile * # of calls Lazywriter: scans cache and decrements by one each scan Clear Cache: DBCC FREEPROCCACHE Items are removed when: • Memory is needed • The age of the item is zero • The plan is not currently in use
  • 10.
    How Do YouRead an Execution Plan?
  • 11.
    Rebind and Rewind Occuron certain loop joins. They represent each time the system has to look through the inner table again for more data. Rebind – when the outer data changes Rewind – when the outer data remains the same More info: http://bit.ly/P7EUv3
  • 12.
  • 13.
    Ad Hoc QueryPlans Ad hoc plans will use the cache as long as: • The schema is specified throughout • The text doesn’t change (at all*) * For queries with one table only, simple parameterization will allow the parameters to change while still reusing the cached plan. To expand this to more complex queries, see this reference: http://bit.ly/Oi3FDH
  • 14.
    Parameter Sniffing SQL Serverdesigns execution plans based upon the first set of parameters passed in. This can have adverse effects. To get around it, you can: • Use WITH RECOMPILE • Use tailored stored procs • Set a trace flag to disable parameter sniffing • Use the OPTIMIZE FOR query hint • Use sp_recompile to clear cache for stored proc or those that use a particular table Read more here: http://bit.ly/MqNVOG
  • 15.
  • 16.
    SQL Sentry PlanExplorer http://bit.ly/NDwBqh
  • 17.
  • 18.
  • 19.
    How Do ILearn More?
  • 20.
    Further Resources • Book by Grant Fritchey - http://bit.ly/MtL0a2 • Index Statistics - http://bit.ly/NTArHo • Query Parallelism - http://bit.ly/NlcS0s • Query Hints - http://bit.ly/N6YMKo
  • 21.
    For questions, comments,and further information, catch me on Twitter at @IAmTimCorey or email me@timothycorey.com

Editor's Notes

  • #4 What this presentation is NOT: Not about optimization. Use car illustration – check engine light is on. What does it mean? We will read the diagnostic information. We aren’t going to cover how to fix the problems we find. Identification is the step we are covering.
  • #5 Roadmap the database uses to get the data most efficiently.Why is this important? We need to know if our assumptions are rightDiscuss cached plans / plan creation costPermissions needed to view plan: GRANT SHOWPLAN TO <user>SQL determines most efficient or “close enough” for simple plansOnly DML (not DDL) gets a plan cache (only one way to do DDL)
  • #6 Demo #1
  • #7 Demo #1
  • #8 Demo #1
  • #9 Demo #2
  • #10 Invalidate cache by redoing indexes and other operations that would alter the plan’s effectiveness
  • #11 Demo #1Query cost (relative to the batch)Right to LeftDemo #3Type of operation (scan, seek, etc.) – pragmatic approach to getting dataCost of operation (relative to query)Details ViewTable scan(heap) vs. Index scan
  • #12 Demo #4
  • #14 Ad hoc also get a value of zero in the cache (easily wiped out)
  • #15 For example, if the parameter first used to call the query is on an indexed list and the value is found in five entries out of a thousand, the index will be used for the lookup. However, if the next time you pass in a value that can be found in 800 of the thousand records, a table scan would be a better option.
  • #16 Size (of the arrow) matters