Statistics And the Query Optimizer

56
Grant Fritchey | www.ScaryDBA.com www.ScaryDBA.com Statistics and the Query Optimizer Grant Fritchey Product Evangelist Red Gate Software

description

There are any number of tricks and traps around getting the query optimizer to provide you with an optimal execution plan that gets you your data quickly and efficiently. But, at the end of the day, the principal driving factor of the optimizer, and therefore of your queries, are the statistics that define your data. This session teaches you how those statistics are put together and maintained by SQL Server. Different types of maintenance results in different levels of accuracy within statistics so we detail what the structures and information looks like after this maintenance. Your understanding of how the optimizer works with statistics will better enable you to understand why you’re getting the performance and types of execution plans that you are getting. Understanding enables you to write better t-sql statements and deal with performance problems such as bad parameter sniffing.

Transcript of Statistics And the Query Optimizer

Page 1: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.comwww.ScaryDBA.com

Statistics and the Query Optimizer

Grant FritcheyProduct EvangelistRed Gate Software

Page 2: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com

Goals Learn how SQL Server creates, stores and

maintains statistics Understand how the optimizer consumes

statistics to arrive at an execution plan Learn various methods for controlling

statistics to take more direct control of your queries

Page 3: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com

[email protected] www.scarydba.com

@gfritcheywww.linkedin.com/in/scarydba

Grant FritcheyProduct Evangelist, Red Gate Software

Page 4: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 4

STATISTICS IN ACTION

Page 5: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com

CREATE PROC dbo.spAddressByCity @City NVARCHAR(30)AS SELECT a.AddressID, a.AddressLine1, a.AddressLine2, a.City, sp.[Name] AS StateProvinceName, a.PostalCode FROM Person.Address AS a JOIN Person.StateProvince AS sp ON a.StateProvinceID = sp.StateProvinceID WHERE a.City = @City;

Page 6: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 6

Page 7: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 7

Page 8: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 8

Page 9: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 9

WHAT ARE STATISTICS

Page 10: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 10

DBCC SHOW_STATISTICS('Person.Address',_WA_Sys_00000004_164452B1);

Page 11: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 11

Key Statistic Terms Rows Sampled Steps Density Range_hi_key Range_rows Eq_rows Avg_range_rows Cardinality Cardinality Cardinality

Page 12: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 12

Cardinality Selectivity» Returned values / Total Values

Histogram Density» 1/distinct values

Compound Columns» Selectivity * Selectivity» Density * Density

+ Trace Flags which we’ll talk about

Page 13: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 13

Estimates vs. Cardinality Comparing variables Using != and NOT Predicates comparing columns within a

table Functions w/o constant value Joins using arithmetic or string operations No statistics!

Skewed distribution (eh)

Page 14: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 14

Statistics are used to… Determine cardinality which is used to…» Determine number of rows processed

which is used to…—Determine cost of the operation in the plan

which is used to…– Pick the operations used in the plan which is used

to» Return your data in an efficient manner which

is used for whatever the heck the business wants

Page 15: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 15

CAPTURING BEHAVIOR

Page 16: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 16

Capture Mechanisms Static» DBCC SHOW_STATISTICS» Execution Plans (sort of)

Dynamic» Trace Events» Extended Events

Page 17: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 17

Auto_stats

Page 18: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 18

Missing_column_statistics

Page 19: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 19

Query_optimizer_estimate_cardinality

Page 20: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 20

STATS ARE CREATED

Page 21: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 21

SELECT s.name, s.auto_created, s.user_created, s.filter_definition, sc.column_id, c.name AS ColumnNameFROM sys.stats AS s JOIN sys.stats_columns AS sc ON sc.stats_id = s.stats_idAND sc.object_id = s.object_id JOIN sys.columns AS c ON c.column_id = sc.column_idAND c.object_id = s.object_idWHERE s.object_id = OBJECT_ID('dbo.Address2')

Page 22: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 22

Page 23: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 23

Page 24: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 24

Page 25: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 25

What?

_WA_Sys_00000001_0A1E72EE

Page 26: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 26

What?

_WA_Sys_00000001_0A1E72EE

Hexidecimal Object ID

Page 27: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 27

What?

_WA_Sys_00000001_0A1E72EE

Hexidecimal Object ID

Table Column Number

Page 28: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 28

What?

_WA_Sys_00000001_0A1E72EE

Hexidecimal Object ID

Table Column Number

System

Page 29: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 29

What?

_WA_Sys_00000001_0A1E72EE

Hexidecimal Object ID

Table Column Number

System

The US State of Washington… yes I’m serious

Page 30: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 30

YOU CAN CREATE STATS

Page 31: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 31

CREATE STATISTICS MyStatsON Person.Person (Suffix)WITH FULLSCAN;

Page 32: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 32

CREATE STATISTICS MyJrStatsON Person.Person (Suffix)WHERE Suffix = 'Jr.'WITH FULLSCAN;

Page 33: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 33

CREATE STATISTICS MyComboStatsON Person.Person (Title,Suffix)WHERE Suffix = 'PhD'WITH FULLSCAN;

Page 34: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 34

…Or Drop Them

DROP STATISTICS Person.Person.MyStats;DROP STATISTICS Person.Person.MyJrStats;DROP STATISTICS Person.Person.MyComboStats;

Page 35: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 35

STATS ARE MAINTAINED

Page 36: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 36

Dungeons and Dragons Add 1 Row when 0 Add > 500 Rows when < 500 Add 20% + 500 Rows when > 500

Page 37: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 37

CREATE INDEX AddressCityON dbo.Address2 (City);

DBCC SHOW_STATISTICS(Address2,AddressCity)

Page 38: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 38

SELECT * FROM dbo.Address2 AS aWHERE City = 'Springfield';

Page 39: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 39

Page 40: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 40

Advanced D&D Trace Flag 2371» SQL Sever 2008 R2 Sp1 and above» After 25,000 rows

—Percentage changed based on number of rows—Reducing as the number grows

Trace Flag 4137»Minimum selectivity instead of multiplication

on AND predicates Trace Flag 9471 (SQL Server 2014)»Minimum selectivity on AND and OR

predicates Trace Flag 9472 (SQL Server 2014)» Independence (pre-2014 behavior)

Page 41: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 41

YOU CAN SHOULD MAINTAIN STATS MANUALLY

Page 42: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 42

Automatic Maintenance AUTO_CREATE_STATISTICS AUTO_UPDATE_STATISTICS» Uses rules in previous section

AUTO_UPDATE_STATISTICS_ASYNC» Test, test, test

Page 43: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 43

sp_updatestats

ALTER procedure [sys].[sp_updatestats]@resample char(8)='NO'As…if ((@ind_rowmodctr <> 0) or ((@is_ver_current is not null) and (@is_ver_current = 0)))…

Page 44: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 44

sp_updatestats

ALTER procedure [sys].[sp_updatestats]@resample char(8)='NO'As…

if ((@ind_rowmodctr <> 0) or ((@is_ver_current is not null) and

(@is_ver_current = 0)))…

Page 45: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 45

UPDATE STATISTICS

UPDATE STATISTICS Person.Address;

Page 46: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 46

UPDATE STATISTICS

UPDATE STATISTICS Person.Address WITH FULLSCAN;

Page 47: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 47

UPDATE STATISTICS

UPDATE STATISTICS dbo.Address2 AddressCity;

Page 48: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 48

UPDATE STATISTICS

UPDATE STATISTICS dbo.Address2 AddressCity WITH FULLSCAN,NORECOMPUTE;

Page 49: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 49

STATISTICS AND OPTIMIZER AT WORK

Page 50: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 50

Statistics Matter

Page 51: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 51

Compatibility Levels

ALTER DATABASE AdventureWorks2012 SET COMPATIBILITY_LEVEL = 120;

Page 52: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 52

Optimizer Switches

OPTION (QUERYTRACEON 2312);

DBCC TRACEON(4199);DBCC FREEPROCCACHE();

Page 53: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 53

Recommendations Compatibility setting Automatic creation Automatic update Update asynchronous where necessary Use appropriate sample rate

Page 54: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com

Goals Learn how SQL Server creates, stores and

maintains statistics Understand how the optimizer consumes

statistics to arrive at an execution plan Learn various methods for controlling

statistics to take more direct control of your queries

Page 55: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com 55

Resources Understanding SQL Server Cardinality Esti

mations Fixing Cardinality Estimation Errors Statistics Used by the Optimizer First look at the

query_optimizer_estimate_cardinality XE Event

Changes to automatic update statistics inSQL Server – traceflag 2371

Cardinality Estimation for Multiple Predicates

Page 56: Statistics And the Query Optimizer

Grant Fritchey | www.ScaryDBA.com

Questions?

56

How would you… ?

What happens when… ?

Why does… ?

When do I… ?