SlideShare a Scribd company logo
1 of 50
Execution Plans for
Mere Mortals
A beginners look at execution plans.
Mike Lawell, Teammate, Linchpin People
2
Please silence
cell phones
3
Explore Everything PASS Has to Offer
FREE SQL SERVER AND BI WEB EVENTS FREE 1-DAY TRAINING EVENTS REGIONAL EVENT
LOCAL USER GROUPS AROUND
THE WORLD
FREE ONLINE TECHNICAL TRAINING
THIS IS COMMUNITY BUSINESS ANALYTICS TRAINING
SESSION RECORDINGS PASS NEWSLETTER
Agenda
We will be taking a look at Graphical Execution Plans from a beginners
perspective. The ride will include the following:
• Execution Steps
• Execution Plan Basics
• Basic Operators
• Join Operators
• Other Operators
4
Execution
Step by Step
6
On The Inside
Relational Engine
Optimizer
Command
Parser
Query
Executor
SNI*
User
Storage Engine
Buffer
Manager
Access
Methods
Transaction
Manager
SQL OS
Buffer Pool
Borrowed from Bradley Ball’s “SQL Internals, Recovery Models, & Backups” presentation
Plan Cache
Data
Cache
Data
*SQL Server Network Interface (SNI)
Relation Engine
1. Is the query syntactically correct?
SELECT [Name], [Number] FORM [Production].[Product]
Incorrect syntax near 'Production'.
SELCT [Name], [Number] FROM [Production].[Product]
Msg 156, Level 15, State 1, Line 3
Incorrect syntax near the keyword 'FROM'.
2. No Errors will be Output as Parse Tree to Algebrizer
Query Parsing
7
8
Query Parsing
SELECT [Name], [Number] FORM [Production].[Product]
Incorrect syntax near 'Production'.
9
Query Parsing
SELECT [Name], [Number] FROM [Production].[Product]
10
Create Plan
Execute
Parallel/
Not Parallel
Store in Plan
Cache (*)
Aggregate
Binding
Resolve
Data Types
Name
Resolution
Plan Creation
Algebrizer Query Optimizer
Recompile?
Storage Engine
No Results
Returned
7
Cost >
Cost for
Parallelism
8
No
Find Plan
Does Plan
Exist?
5
Yes
Hash Checked
in Plan Cache
3 4
6
1 2
5
What is a Hash?
A hash is a number that is generated by reading the contents of a document or
message. Different messages should generate different hash values, but the
same message causes the algorithm to generate the same hash value.
SELECT HASHBYTES('SHA','Hellow World')
0x5F341D31F6B6A8B15BC4E6704830BF37F99511D1
SELECT HASHBYTES('SHA','Hello World')
0x0A4D55A8D778E5022FAB701977C5D840BBC486D0
SELECT HASHBYTES('SHA','Hello World')
0xC2F14A3E371A79A792E6ED78FB07A4B0C26618B4
https://technet.microsoft.com/en-us/library/cc837966(v=sql.100).aspx
13
Cardinality Estimation
The optimization process depends on a cost estimation of each physical operator and the
estimated number of records (cardinality estimation) to be processed.
DBCC SHOW_STATISTICS ("[Sales].[SalesOrderDetailEnlarged]",
[PK_SalesOrderDetailEnlarged_SalesOrderID_SalesOrderDetailID]) WITH HISTOGRAM;
GO
The accuracy of the cardinality estimation depends upon the distribution of values in one or more
columns of a table (statistics).
RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS AVG_RANGE_ROWS
43659 0 12 0 1
47355 16015 68 3695 4.334236
51739 24056 72 4383 5.488478
57046 20733 67 5306 3.907463
65174 27775 48 8127 3.41762
101719 131906 36 36544 3.609512
107533 22424 60 5813 3.857561
14
Cardinality Estimation
There are multiple factors that can negatively impact the cardinality estimation
process:
1. Out of date Statistics
SELECT object_name(object_id) as TableName, name AS stats_name,
STATS_DATE(object_id, stats_id) AS statistics_update_date
FROM sys.stats
WHERE object_id = OBJECT_ID('[Sales].[SalesOrderDetailEnlarged]');
2. Cardinality Estimation Errors
https://www.sqlskills.com/blogs/joe/cardinality-estimation-model-version/
15
Which cardinality version am I using?
Execution Plan
Basics
Getting Started
17
Required Permissions
Server or database roles with permissions:
sysadmin, dbcreator or db_owner or showplan
To give showplan rights to the database:
GRANT SHOWPLAN TO [username];
How to Read
18
Basic Operators
Start Here
Basic Operators
DML Statements Access Methods
20
Other Operators
Join Operators
Making it Happen
22
Nested Loop
Non-blocking
Description
For each row in the top (outer) input, scan the
bottom (inner) input, and output matching rows.
Where does it happen: Joins with
indexes on join columns.
Nested Loop
SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate]
FROM [Sales].[SalesOrderHeader] soh
JOIN [Sales].[SalesOrderDetail] sod
ON sod.[SalesOrderID] = soh.[SalesOrderID]
WHERE soh.[OrderDate] = '2013-08-30 00:00:00.000'
Non-blocking
23
Nested Loop
SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate]
FROM [Sales].[SalesOrderHeader] soh
JOIN [Sales].[SalesOrderDetail] sod
ON sod.[SalesOrderID] = soh.[SalesOrderID]
WHERE soh.[OrderDate] = '2013-08-30 00:00:00.000'
Outer Loop
Inner Loop
Non-blocking
24
25
Nested Loop
26
Non-blocking
Nested Loop
SalesOrderID RevisionNumber OrderDate
55233 8 2013-08-30 00:00:00.000
55234 8 2013-08-30 00:00:00.000
55235 8 2013-08-30 00:00:00.000
55236 8 2013-08-30 00:00:00.000
55237 8 2013-08-30 00:00:00.000
55238 8 2013-08-30 00:00:00.000
55239 8 2013-08-30 00:00:00.000
55240 8 2013-08-30 00:00:00.000
55241 8 2013-08-30 00:00:00.000
55242 8 2013-08-30 00:00:00.000
55243 8 2013-08-30 00:00:00.000
55244 8 2013-08-30 00:00:00.000
55245 8 2013-08-30 00:00:00.000
55246 8 2013-08-30 00:00:00.000
55247 8 2013-08-30 00:00:00.000
55248 8 2013-08-30 00:00:00.000
55249 8 2013-08-30 00:00:00.000
55250 8 2013-08-30 00:00:00.000
55251 8 2013-08-30 00:00:00.000
55252 8 2013-08-30 00:00:00.000
55253 8 2013-08-30 00:00:00.000
SalesOrderID ProductID CarrierTrackingNumber OrderQty
55233 738 1590-499E-95 5
55233 792 1590-499E-95 5
55233 793 1590-499E-95 4
55233 794 1590-499E-95 4
55233 795 1590-499E-95 4
55233 796 1590-499E-95 5
55233 797 1590-499E-95 6
55233 798 1590-499E-95 2
55233 799 1590-499E-95 1
55233 800 1590-499E-95 1
55233 801 1590-499E-95 6
55233 835 1590-499E-95 6
55233 874 1590-499E-95 8
55233 875 1590-499E-95 8
55233 938 1590-499E-95 5
55233 939 1590-499E-95 5
55233 940 1590-499E-95 4
55233 973 1590-499E-95 5
55233 974 1590-499E-95 1
55233 975 1590-499E-95 1
27
Description
Match rows from two suitably sorted input
tables exploiting their sort order.
Where does it happen: Joins with
indexes on join columns sorted in an
appropriate sort order.
Merge
Non-blocking
Merge
SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate]
FROM [Sales].[SalesOrderHeader] soh
JOIN [Sales].[SalesOrderDetail] sod
ON sod.[SalesOrderID] = soh.[SalesOrderID]
Non-blocking
28
29
Merge
SalesOrderID RevisionNumber OrderDate
55233 8 2013-08-30 00:00:00.000
55234 8 2013-08-30 00:00:00.000
55235 8 2013-08-30 00:00:00.000
55236 8 2013-08-30 00:00:00.000
55237 8 2013-08-30 00:00:00.000
55238 8 2013-08-30 00:00:00.000
55239 8 2013-08-30 00:00:00.000
55240 8 2013-08-30 00:00:00.000
55241 8 2013-08-30 00:00:00.000
55242 8 2013-08-30 00:00:00.000
55243 8 2013-08-30 00:00:00.000
55244 8 2013-08-30 00:00:00.000
55245 8 2013-08-30 00:00:00.000
55246 8 2013-08-30 00:00:00.000
55247 8 2013-08-30 00:00:00.000
55248 8 2013-08-30 00:00:00.000
55249 8 2013-08-30 00:00:00.000
55250 8 2013-08-30 00:00:00.000
55251 8 2013-08-30 00:00:00.000
55252 8 2013-08-30 00:00:00.000
55253 8 2013-08-30 00:00:00.000
SalesOrderID ProductID CarrierTrackingNumber OrderQty
55233 738 1590-499E-95 5
55233 792 1590-499E-95 5
55233 793 1590-499E-95 4
55233 794 1590-499E-95 4
55233 795 1590-499E-95 4
55233 796 1590-499E-95 5
55233 797 1590-499E-95 6
55233 798 1590-499E-95 2
55233 799 1590-499E-95 1
55233 800 1590-499E-95 1
55233 801 1590-499E-95 6
55233 835 1590-499E-95 6
55233 874 1590-499E-95 8
55233 875 1590-499E-95 8
55233 938 1590-499E-95 5
55233 939 1590-499E-95 5
55233 940 1590-499E-95 4
55233 973 1590-499E-95 5
55233 974 1590-499E-95 1
55233 975 1590-499E-95 1
Non-blocking
30
Hash Match
Description
Use each row from the top input to build a hash
table, and each row from the bottom input to
probe into the hash table, outputting all
matching rows.
Where does it happen: Missing Index,
Missing Where Clause, Where Clause that is
non-sargable.
Hash Match
Blocking
SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty]
FROM [Sales].[SalesOrderDetail] sod1
JOIN [Sales].[SalesOrderDetail] sod2
ON [sod1].[ProductID] = [sod2].[ProductID]
AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber]
AND [sod1].[OrderQty] > 5
31
Hash Match
Hash Table
Blocking
32
Column A Column B
98234750198709872 8749872
Hashed Value
8Ax94Dd343S
Hash Match
Hash Table 1
Blocking
33
8Ax94Dd343S
1) From the first input (table) the
column data is hashed and put in
buckets in a “hash” table (in
tempdb).
2) Then it reads rows from input 2,
hashes the join columns and
compares the hash and values to
output matches.
8Ax94Dd343S
8Bx40XdF43D
8CxXDVa91f If a Match…
“Send” row data to next
operator and go to the next row.
34
Fixed Hash Match
Other Operators
Fun Stuff
36
Parallelism
SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty]
FROM [Sales].[SalesOrderDetail] sod1
JOIN [Sales].[SalesOrderDetail] sod2
ON [sod1].[ProductID] = [sod2].[ProductID]
AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber]
37
Parallelism
SET STATISTICS IO ON
SET STATISTICS TIME ON
SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty]
FROM [Sales].[SalesOrderDetail] sod1
JOIN [Sales].[SalesOrderDetail] sod2
ON [sod1].[ProductID] = [sod2].[ProductID]
AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber]
SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty]
FROM [Sales].[SalesOrderDetail] sod1
JOIN [Sales].[SalesOrderDetail] sod2
ON [sod1].[ProductID] = [sod2].[ProductID]
AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber]
OPTION(MAXDOP 1)
38
Parallelism
Table 'SalesOrderDetail'. Scan count 18, logical reads 2490, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical
reads 0, lob read-ahead reads 0.
Table 'Workfile'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-
ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob
read-ahead reads 0.
SQL Server Execution Times:
CPU time = 9593 ms, elapsed time = 2381 ms.
Table 'Workfile'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-
ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob
read-ahead reads 0.
Table 'SalesOrderDetail'. Scan count 2, logical reads 2490, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads
0, lob read-ahead reads 0.
SQL Server Execution Times:
CPU time = 7941 ms, elapsed time = 8372 ms.
39
Parallelism
40
Hash Aggregate
SELECT [sod1].[CarrierTrackingNumber], sum([sod1].[UnitPrice]) UnitPriceTotal,
sum([sod1].[OrderQty]) as OrderQtyTotal
FROM [Sales].[SalesOrderDetail] sod1
JOIN [Sales].[SalesOrderDetail] sod2
ON [sod1].[ProductID] = [sod2].[ProductID]
AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber]
AND [sod1].[OrderQty] > 5
GROUP BY [sod1].[CarrierTrackingNumber]
41
Stream Aggregate
SELECT [sod1].[CarrierTrackingNumber], sum([sod1].[UnitPrice])
UnitPriceTotal, sum([sod1].[OrderQty]) as OrderQtyTotal
FROM [Sales].[SalesOrderDetail] sod1
JOIN [Sales].[SalesOrderDetail] sod2
ON [sod1].[ProductID] = [sod2].[ProductID]
AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber]
AND [sod1].[OrderQty] > 5
GROUP BY [sod1].[CarrierTrackingNumber]
42
Sort Spill
Operator used tempdb to spill data during execution with spill level 2
SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate]
FROM [Sales].[SalesOrderHeader] soh
JOIN [Sales].[SalesOrderDetailEnlarged] sod
ON sod.[SalesOrderID] = soh.[SalesOrderID]
WHERE [sod].[CarrierTrackingNumber] > '41D0-42A8-A5'
ORDER BY [soh].[RevisionNumber], [soh].[OrderDate]
43
Sort Spill
SELECT TOP 1 [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate]
FROM [Sales].[SalesOrderHeader] soh
JOIN [Sales].[SalesOrderDetailEnlarged] sod
ON sod.[SalesOrderID] = soh.[SalesOrderID]
WHERE [sod].[CarrierTrackingNumber] > '41D0-42A8-A5'
ORDER BY [soh].[RevisionNumber], [soh].[OrderDate]
44
Implicit Conversion
SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate]
FROM [Sales].[SalesOrderHeaderEnlarged] soh
JOIN [Sales].[SalesOrderDetailEnlarged] sod
ON sod.[SalesOrderID] = soh.[SalesOrderID]
WHERE CONVERT(varchar(10),[soh].[OrderDate],110) = '04-14-2014'
Parameter Sniffing
During the optimization phase the parameters supplied to the parameterized
query or stored procedure are used to determine how well an index will work
based upon the statistics.
It usually results in a better plan, but sometimes do to skewed distribution of
data is results in bad parameter sniffing.
46
SQL Server 2016 Live Query
Live Query works with SQL Server 2014 + using SSMS 2016
SELECT pr.Name as ProductName, sod.OrderQty, sod.UnitPrice, soh.OrderDate
FROM [Sales].[SalesOrderDetailEnlarged] sod
JOIN [Sales].[SalesOrderHeaderEnlarged] soh
ON soh.SalesOrderID = sod.SalesOrderID
JOIN [Production].[Product] pr
ON pr.ProductID = sod.ProductID
WHERE soh.OrderDate between '2014-10-01' AND '2015-10-01'
OPTION(MAXDOP 1)
48
Cool Tools/Products
SQL Server Query Plan Analysis by Joe Sack
49
Additional Blogs to Checkout
When to Breakdown Complex Queries
Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator
50
Resources
http://www.red-gate.com/community/books/
Downloadable
FREE!
51
Session Evaluations
ways to access
Go to
passsummit.com/evals
Download the GuideBook App
and search: PASS Summit 2015
Follow the QR code link displayed
on session signage throughout the
conference venue and in the
program guide
Submit by 5pm
Friday November 6th to
WIN prizes
Your feedback is
important and valuable.
52
Mike Lawell
Mike Lawell
Principal Consultant
Twitter: @SQLDiver
Blog: SQLServerAssociates.com
LinkedIn: LinkedIn.com/in/MikeLawell

More Related Content

Similar to Mike lawell executionplansformeremortals_2015

Fighting fraud: finding duplicates at scale (Highload+ 2019)
Fighting fraud: finding duplicates at scale (Highload+ 2019)Fighting fraud: finding duplicates at scale (Highload+ 2019)
Fighting fraud: finding duplicates at scale (Highload+ 2019)Alexey Grigorev
 
Kdata presentation english version
Kdata presentation english versionKdata presentation english version
Kdata presentation english versionK-process
 
Top 10 tips for Oracle performance
Top 10 tips for Oracle performanceTop 10 tips for Oracle performance
Top 10 tips for Oracle performanceGuy Harrison
 
Momentum Analytics Credentials
Momentum Analytics CredentialsMomentum Analytics Credentials
Momentum Analytics Credentialsmomentumanalytics
 
Snowflake Data Governance
Snowflake Data GovernanceSnowflake Data Governance
Snowflake Data Governancessuser538b022
 
Analisis gap dan thurstone
Analisis gap dan thurstoneAnalisis gap dan thurstone
Analisis gap dan thurstoneM Taufiq Budi H
 
Excel Workbook for Treasury Bond Portfolio Management
Excel Workbook for Treasury Bond Portfolio ManagementExcel Workbook for Treasury Bond Portfolio Management
Excel Workbook for Treasury Bond Portfolio ManagementWerner Riecke
 
Kafka Streams State Stores Being Persistent
Kafka Streams State Stores Being PersistentKafka Streams State Stores Being Persistent
Kafka Streams State Stores Being Persistentconfluent
 
7 QC Tools and Problem Solving Presentation.pdf
7 QC Tools and Problem Solving Presentation.pdf7 QC Tools and Problem Solving Presentation.pdf
7 QC Tools and Problem Solving Presentation.pdfAzizOUBBAD1
 
7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdf
7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdf7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdf
7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdfEngFaisalAlrai
 
Neo4j Makes Graphs Easy: Nicole White
Neo4j Makes Graphs Easy: Nicole WhiteNeo4j Makes Graphs Easy: Nicole White
Neo4j Makes Graphs Easy: Nicole WhiteNeo4j
 
metadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docx
metadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docxmetadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docx
metadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docxARIV4
 
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019Dave Stokes
 
[Tutorial] building machine learning models for predictive maintenance applic...
[Tutorial] building machine learning models for predictive maintenance applic...[Tutorial] building machine learning models for predictive maintenance applic...
[Tutorial] building machine learning models for predictive maintenance applic...PAPIs.io
 

Similar to Mike lawell executionplansformeremortals_2015 (20)

Fighting fraud: finding duplicates at scale (Highload+ 2019)
Fighting fraud: finding duplicates at scale (Highload+ 2019)Fighting fraud: finding duplicates at scale (Highload+ 2019)
Fighting fraud: finding duplicates at scale (Highload+ 2019)
 
Kdata presentation english version
Kdata presentation english versionKdata presentation english version
Kdata presentation english version
 
Top 10 tips for Oracle performance
Top 10 tips for Oracle performanceTop 10 tips for Oracle performance
Top 10 tips for Oracle performance
 
Momentum Analytics Credentials
Momentum Analytics CredentialsMomentum Analytics Credentials
Momentum Analytics Credentials
 
5 Cool Things About SQL
5 Cool Things About SQL5 Cool Things About SQL
5 Cool Things About SQL
 
Snowflake Data Governance
Snowflake Data GovernanceSnowflake Data Governance
Snowflake Data Governance
 
Dmaic
DmaicDmaic
Dmaic
 
Analisis gap dan thurstone
Analisis gap dan thurstoneAnalisis gap dan thurstone
Analisis gap dan thurstone
 
kakaogames 293490 Algorithm Investment Report
kakaogames 293490 Algorithm Investment Reportkakaogames 293490 Algorithm Investment Report
kakaogames 293490 Algorithm Investment Report
 
Excel Workbook for Treasury Bond Portfolio Management
Excel Workbook for Treasury Bond Portfolio ManagementExcel Workbook for Treasury Bond Portfolio Management
Excel Workbook for Treasury Bond Portfolio Management
 
Kafka Streams State Stores Being Persistent
Kafka Streams State Stores Being PersistentKafka Streams State Stores Being Persistent
Kafka Streams State Stores Being Persistent
 
Six sigma technique
Six sigma techniqueSix sigma technique
Six sigma technique
 
shinsegae 004170 Algorithm Investment Report
shinsegae 004170 Algorithm Investment Reportshinsegae 004170 Algorithm Investment Report
shinsegae 004170 Algorithm Investment Report
 
7 QC Tools and Problem Solving Presentation.pdf
7 QC Tools and Problem Solving Presentation.pdf7 QC Tools and Problem Solving Presentation.pdf
7 QC Tools and Problem Solving Presentation.pdf
 
7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdf
7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdf7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdf
7_QC_Tools_and_Problem_Solving_Presentation_1656881575.pdf
 
Neo4j Makes Graphs Easy: Nicole White
Neo4j Makes Graphs Easy: Nicole WhiteNeo4j Makes Graphs Easy: Nicole White
Neo4j Makes Graphs Easy: Nicole White
 
metadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docx
metadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docxmetadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docx
metadatacoreProperties.xmlModel2015-07-13T030104Zthua3267th.docx
 
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
MySQL 8 - UKOUG Techfest Brighton December 2nd, 2019
 
[Tutorial] building machine learning models for predictive maintenance applic...
[Tutorial] building machine learning models for predictive maintenance applic...[Tutorial] building machine learning models for predictive maintenance applic...
[Tutorial] building machine learning models for predictive maintenance applic...
 
Bean Co.pptx
Bean Co.pptxBean Co.pptx
Bean Co.pptx
 

Mike lawell executionplansformeremortals_2015

  • 1. Execution Plans for Mere Mortals A beginners look at execution plans. Mike Lawell, Teammate, Linchpin People
  • 3. 3 Explore Everything PASS Has to Offer FREE SQL SERVER AND BI WEB EVENTS FREE 1-DAY TRAINING EVENTS REGIONAL EVENT LOCAL USER GROUPS AROUND THE WORLD FREE ONLINE TECHNICAL TRAINING THIS IS COMMUNITY BUSINESS ANALYTICS TRAINING SESSION RECORDINGS PASS NEWSLETTER
  • 4. Agenda We will be taking a look at Graphical Execution Plans from a beginners perspective. The ride will include the following: • Execution Steps • Execution Plan Basics • Basic Operators • Join Operators • Other Operators 4
  • 6. 6 On The Inside Relational Engine Optimizer Command Parser Query Executor SNI* User Storage Engine Buffer Manager Access Methods Transaction Manager SQL OS Buffer Pool Borrowed from Bradley Ball’s “SQL Internals, Recovery Models, & Backups” presentation Plan Cache Data Cache Data *SQL Server Network Interface (SNI)
  • 7. Relation Engine 1. Is the query syntactically correct? SELECT [Name], [Number] FORM [Production].[Product] Incorrect syntax near 'Production'. SELCT [Name], [Number] FROM [Production].[Product] Msg 156, Level 15, State 1, Line 3 Incorrect syntax near the keyword 'FROM'. 2. No Errors will be Output as Parse Tree to Algebrizer Query Parsing 7
  • 8. 8 Query Parsing SELECT [Name], [Number] FORM [Production].[Product] Incorrect syntax near 'Production'.
  • 9. 9 Query Parsing SELECT [Name], [Number] FROM [Production].[Product]
  • 10. 10 Create Plan Execute Parallel/ Not Parallel Store in Plan Cache (*) Aggregate Binding Resolve Data Types Name Resolution Plan Creation Algebrizer Query Optimizer Recompile? Storage Engine No Results Returned 7 Cost > Cost for Parallelism 8 No Find Plan Does Plan Exist? 5 Yes Hash Checked in Plan Cache 3 4 6 1 2 5
  • 11. What is a Hash? A hash is a number that is generated by reading the contents of a document or message. Different messages should generate different hash values, but the same message causes the algorithm to generate the same hash value. SELECT HASHBYTES('SHA','Hellow World') 0x5F341D31F6B6A8B15BC4E6704830BF37F99511D1 SELECT HASHBYTES('SHA','Hello World') 0x0A4D55A8D778E5022FAB701977C5D840BBC486D0 SELECT HASHBYTES('SHA','Hello World') 0xC2F14A3E371A79A792E6ED78FB07A4B0C26618B4 https://technet.microsoft.com/en-us/library/cc837966(v=sql.100).aspx
  • 12. 13 Cardinality Estimation The optimization process depends on a cost estimation of each physical operator and the estimated number of records (cardinality estimation) to be processed. DBCC SHOW_STATISTICS ("[Sales].[SalesOrderDetailEnlarged]", [PK_SalesOrderDetailEnlarged_SalesOrderID_SalesOrderDetailID]) WITH HISTOGRAM; GO The accuracy of the cardinality estimation depends upon the distribution of values in one or more columns of a table (statistics). RANGE_HI_KEY RANGE_ROWS EQ_ROWS DISTINCT_RANGE_ROWS AVG_RANGE_ROWS 43659 0 12 0 1 47355 16015 68 3695 4.334236 51739 24056 72 4383 5.488478 57046 20733 67 5306 3.907463 65174 27775 48 8127 3.41762 101719 131906 36 36544 3.609512 107533 22424 60 5813 3.857561
  • 13. 14 Cardinality Estimation There are multiple factors that can negatively impact the cardinality estimation process: 1. Out of date Statistics SELECT object_name(object_id) as TableName, name AS stats_name, STATS_DATE(object_id, stats_id) AS statistics_update_date FROM sys.stats WHERE object_id = OBJECT_ID('[Sales].[SalesOrderDetailEnlarged]'); 2. Cardinality Estimation Errors https://www.sqlskills.com/blogs/joe/cardinality-estimation-model-version/
  • 16. 17 Required Permissions Server or database roles with permissions: sysadmin, dbcreator or db_owner or showplan To give showplan rights to the database: GRANT SHOWPLAN TO [username];
  • 19. Basic Operators DML Statements Access Methods 20 Other Operators
  • 21. 22 Nested Loop Non-blocking Description For each row in the top (outer) input, scan the bottom (inner) input, and output matching rows. Where does it happen: Joins with indexes on join columns.
  • 22. Nested Loop SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate] FROM [Sales].[SalesOrderHeader] soh JOIN [Sales].[SalesOrderDetail] sod ON sod.[SalesOrderID] = soh.[SalesOrderID] WHERE soh.[OrderDate] = '2013-08-30 00:00:00.000' Non-blocking 23
  • 23. Nested Loop SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate] FROM [Sales].[SalesOrderHeader] soh JOIN [Sales].[SalesOrderDetail] sod ON sod.[SalesOrderID] = soh.[SalesOrderID] WHERE soh.[OrderDate] = '2013-08-30 00:00:00.000' Outer Loop Inner Loop Non-blocking 24
  • 25. 26 Non-blocking Nested Loop SalesOrderID RevisionNumber OrderDate 55233 8 2013-08-30 00:00:00.000 55234 8 2013-08-30 00:00:00.000 55235 8 2013-08-30 00:00:00.000 55236 8 2013-08-30 00:00:00.000 55237 8 2013-08-30 00:00:00.000 55238 8 2013-08-30 00:00:00.000 55239 8 2013-08-30 00:00:00.000 55240 8 2013-08-30 00:00:00.000 55241 8 2013-08-30 00:00:00.000 55242 8 2013-08-30 00:00:00.000 55243 8 2013-08-30 00:00:00.000 55244 8 2013-08-30 00:00:00.000 55245 8 2013-08-30 00:00:00.000 55246 8 2013-08-30 00:00:00.000 55247 8 2013-08-30 00:00:00.000 55248 8 2013-08-30 00:00:00.000 55249 8 2013-08-30 00:00:00.000 55250 8 2013-08-30 00:00:00.000 55251 8 2013-08-30 00:00:00.000 55252 8 2013-08-30 00:00:00.000 55253 8 2013-08-30 00:00:00.000 SalesOrderID ProductID CarrierTrackingNumber OrderQty 55233 738 1590-499E-95 5 55233 792 1590-499E-95 5 55233 793 1590-499E-95 4 55233 794 1590-499E-95 4 55233 795 1590-499E-95 4 55233 796 1590-499E-95 5 55233 797 1590-499E-95 6 55233 798 1590-499E-95 2 55233 799 1590-499E-95 1 55233 800 1590-499E-95 1 55233 801 1590-499E-95 6 55233 835 1590-499E-95 6 55233 874 1590-499E-95 8 55233 875 1590-499E-95 8 55233 938 1590-499E-95 5 55233 939 1590-499E-95 5 55233 940 1590-499E-95 4 55233 973 1590-499E-95 5 55233 974 1590-499E-95 1 55233 975 1590-499E-95 1
  • 26. 27 Description Match rows from two suitably sorted input tables exploiting their sort order. Where does it happen: Joins with indexes on join columns sorted in an appropriate sort order. Merge Non-blocking
  • 27. Merge SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate] FROM [Sales].[SalesOrderHeader] soh JOIN [Sales].[SalesOrderDetail] sod ON sod.[SalesOrderID] = soh.[SalesOrderID] Non-blocking 28
  • 28. 29 Merge SalesOrderID RevisionNumber OrderDate 55233 8 2013-08-30 00:00:00.000 55234 8 2013-08-30 00:00:00.000 55235 8 2013-08-30 00:00:00.000 55236 8 2013-08-30 00:00:00.000 55237 8 2013-08-30 00:00:00.000 55238 8 2013-08-30 00:00:00.000 55239 8 2013-08-30 00:00:00.000 55240 8 2013-08-30 00:00:00.000 55241 8 2013-08-30 00:00:00.000 55242 8 2013-08-30 00:00:00.000 55243 8 2013-08-30 00:00:00.000 55244 8 2013-08-30 00:00:00.000 55245 8 2013-08-30 00:00:00.000 55246 8 2013-08-30 00:00:00.000 55247 8 2013-08-30 00:00:00.000 55248 8 2013-08-30 00:00:00.000 55249 8 2013-08-30 00:00:00.000 55250 8 2013-08-30 00:00:00.000 55251 8 2013-08-30 00:00:00.000 55252 8 2013-08-30 00:00:00.000 55253 8 2013-08-30 00:00:00.000 SalesOrderID ProductID CarrierTrackingNumber OrderQty 55233 738 1590-499E-95 5 55233 792 1590-499E-95 5 55233 793 1590-499E-95 4 55233 794 1590-499E-95 4 55233 795 1590-499E-95 4 55233 796 1590-499E-95 5 55233 797 1590-499E-95 6 55233 798 1590-499E-95 2 55233 799 1590-499E-95 1 55233 800 1590-499E-95 1 55233 801 1590-499E-95 6 55233 835 1590-499E-95 6 55233 874 1590-499E-95 8 55233 875 1590-499E-95 8 55233 938 1590-499E-95 5 55233 939 1590-499E-95 5 55233 940 1590-499E-95 4 55233 973 1590-499E-95 5 55233 974 1590-499E-95 1 55233 975 1590-499E-95 1 Non-blocking
  • 29. 30 Hash Match Description Use each row from the top input to build a hash table, and each row from the bottom input to probe into the hash table, outputting all matching rows. Where does it happen: Missing Index, Missing Where Clause, Where Clause that is non-sargable.
  • 30. Hash Match Blocking SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty] FROM [Sales].[SalesOrderDetail] sod1 JOIN [Sales].[SalesOrderDetail] sod2 ON [sod1].[ProductID] = [sod2].[ProductID] AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber] AND [sod1].[OrderQty] > 5 31
  • 31. Hash Match Hash Table Blocking 32 Column A Column B 98234750198709872 8749872 Hashed Value 8Ax94Dd343S
  • 32. Hash Match Hash Table 1 Blocking 33 8Ax94Dd343S 1) From the first input (table) the column data is hashed and put in buckets in a “hash” table (in tempdb). 2) Then it reads rows from input 2, hashes the join columns and compares the hash and values to output matches. 8Ax94Dd343S 8Bx40XdF43D 8CxXDVa91f If a Match… “Send” row data to next operator and go to the next row.
  • 35. 36 Parallelism SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty] FROM [Sales].[SalesOrderDetail] sod1 JOIN [Sales].[SalesOrderDetail] sod2 ON [sod1].[ProductID] = [sod2].[ProductID] AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber]
  • 36. 37 Parallelism SET STATISTICS IO ON SET STATISTICS TIME ON SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty] FROM [Sales].[SalesOrderDetail] sod1 JOIN [Sales].[SalesOrderDetail] sod2 ON [sod1].[ProductID] = [sod2].[ProductID] AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber] SELECT [sod1].[ProductID], [sod1].[CarrierTrackingNumber], [sod1].[UnitPrice], [sod1].[OrderQty] FROM [Sales].[SalesOrderDetail] sod1 JOIN [Sales].[SalesOrderDetail] sod2 ON [sod1].[ProductID] = [sod2].[ProductID] AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber] OPTION(MAXDOP 1)
  • 37. 38 Parallelism Table 'SalesOrderDetail'. Scan count 18, logical reads 2490, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. Table 'Workfile'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read- ahead reads 0. Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 9593 ms, elapsed time = 2381 ms. Table 'Workfile'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read- ahead reads 0. Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. Table 'SalesOrderDetail'. Scan count 2, logical reads 2490, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0. SQL Server Execution Times: CPU time = 7941 ms, elapsed time = 8372 ms.
  • 39. 40 Hash Aggregate SELECT [sod1].[CarrierTrackingNumber], sum([sod1].[UnitPrice]) UnitPriceTotal, sum([sod1].[OrderQty]) as OrderQtyTotal FROM [Sales].[SalesOrderDetail] sod1 JOIN [Sales].[SalesOrderDetail] sod2 ON [sod1].[ProductID] = [sod2].[ProductID] AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber] AND [sod1].[OrderQty] > 5 GROUP BY [sod1].[CarrierTrackingNumber]
  • 40. 41 Stream Aggregate SELECT [sod1].[CarrierTrackingNumber], sum([sod1].[UnitPrice]) UnitPriceTotal, sum([sod1].[OrderQty]) as OrderQtyTotal FROM [Sales].[SalesOrderDetail] sod1 JOIN [Sales].[SalesOrderDetail] sod2 ON [sod1].[ProductID] = [sod2].[ProductID] AND [sod1].[CarrierTrackingNumber] = [sod2].[CarrierTrackingNumber] AND [sod1].[OrderQty] > 5 GROUP BY [sod1].[CarrierTrackingNumber]
  • 41. 42 Sort Spill Operator used tempdb to spill data during execution with spill level 2 SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate] FROM [Sales].[SalesOrderHeader] soh JOIN [Sales].[SalesOrderDetailEnlarged] sod ON sod.[SalesOrderID] = soh.[SalesOrderID] WHERE [sod].[CarrierTrackingNumber] > '41D0-42A8-A5' ORDER BY [soh].[RevisionNumber], [soh].[OrderDate]
  • 42. 43 Sort Spill SELECT TOP 1 [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate] FROM [Sales].[SalesOrderHeader] soh JOIN [Sales].[SalesOrderDetailEnlarged] sod ON sod.[SalesOrderID] = soh.[SalesOrderID] WHERE [sod].[CarrierTrackingNumber] > '41D0-42A8-A5' ORDER BY [soh].[RevisionNumber], [soh].[OrderDate]
  • 43. 44 Implicit Conversion SELECT [sod].[CarrierTrackingNumber], [sod].[OrderQty], [soh].[RevisionNumber], [soh].[OrderDate] FROM [Sales].[SalesOrderHeaderEnlarged] soh JOIN [Sales].[SalesOrderDetailEnlarged] sod ON sod.[SalesOrderID] = soh.[SalesOrderID] WHERE CONVERT(varchar(10),[soh].[OrderDate],110) = '04-14-2014'
  • 44. Parameter Sniffing During the optimization phase the parameters supplied to the parameterized query or stored procedure are used to determine how well an index will work based upon the statistics. It usually results in a better plan, but sometimes do to skewed distribution of data is results in bad parameter sniffing.
  • 45. 46 SQL Server 2016 Live Query Live Query works with SQL Server 2014 + using SSMS 2016 SELECT pr.Name as ProductName, sod.OrderQty, sod.UnitPrice, soh.OrderDate FROM [Sales].[SalesOrderDetailEnlarged] sod JOIN [Sales].[SalesOrderHeaderEnlarged] soh ON soh.SalesOrderID = sod.SalesOrderID JOIN [Production].[Product] pr ON pr.ProductID = sod.ProductID WHERE soh.OrderDate between '2014-10-01' AND '2015-10-01' OPTION(MAXDOP 1)
  • 46. 48 Cool Tools/Products SQL Server Query Plan Analysis by Joe Sack
  • 47. 49 Additional Blogs to Checkout When to Breakdown Complex Queries Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator
  • 49. 51 Session Evaluations ways to access Go to passsummit.com/evals Download the GuideBook App and search: PASS Summit 2015 Follow the QR code link displayed on session signage throughout the conference venue and in the program guide Submit by 5pm Friday November 6th to WIN prizes Your feedback is important and valuable.
  • 50. 52 Mike Lawell Mike Lawell Principal Consultant Twitter: @SQLDiver Blog: SQLServerAssociates.com LinkedIn: LinkedIn.com/in/MikeLawell

Editor's Notes

  1. SQL Server Network Interface
  2. The query optimizer checks the hash against the plan cache. If it exists use it and the optimization step is skipped and plan is passed to query execution. The query optimizer uses the query processor tree and the statistics to determine an estimated execution plan. The optimizer goes through a process of using different types of joins and indexes and assigns a cost to each step by CPU and I/O and determines a cost for each possible estimated plan it generates. Once an acceptable estimated plan is found it is stored in the plan cache then sent to the query execution.
  3. The query optimizer checks the hash against the plan cache. If it exists use it and the optimization step is skipped and plan is passed to query execution. The query optimizer uses the query processor tree and the statistics to determine an estimated execution plan. The optimizer goes through a process of using different types of joins and indexes and assigns a cost to each step by CPU and I/O and determines a cost for each possible estimated plan it generates. Once an acceptable estimated plan is found it is stored in the plan cache then sent to the query execution.
  4. Zoomit to show fine print!
  5. Cardinality Estimation Model Version 120 (new model) 70 old model.
  6. Cardinality Estimation Model Version 120 (new model) 70 old model.
  7. Physical order of process is SELECT pulls data from the next operator left to right top to bottom. Easier to understand from right to left top to bottom.
  8. Seeing a hash match is a good indication of an opportunity for tuning by adding an index, improving the join or where clause. If that isn’t possible, the hash match is the most efficient option you have.
  9. In the first input, the data is hashed then dropped into a hash bucket. Then a hash is applied to the data in the second input. There can be duplicates in the bucket so an additional predicate comparison to ensure join uniqueness.
  10. In the first input, the data is hashed then dropped into a hash bucket. Then a hash is applied to the data in the second input. There can be duplicates in the bucket so an additional predicate comparison to ensure join uniqueness.
  11. Discuss parallelism and what it is.
  12. ZoomIt!
  13. Average is a count and sum
  14. Disabled statistics. https://www.simple-talk.com/sql/performance/never-ignore-a-sort-warning-in-sql-server/
  15. Object Names, Data types, Aggregate Binding
  16. Notes for attendees (not in sessions).
  17. Did recompile get triggered? Over cost threshold for parallelism?