SlideShare une entreprise Scribd logo
1  sur  56
Télécharger pour lire hors ligne
Grant Fritchey | www.ScaryDBA.com
www.ScaryDBA.com
Statistics and
the Query Optimization
Grant Fritchey
Product Evangelist
Red Gate Software
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
Grant Fritchey | www.ScaryDBA.com
grant@scarydba.com www.scarydba.com
@gfritchey
www.linkedin.com/in/s
carydba
Grant Fritchey
Product Evangelist, Red GateSoftware
Grant Fritchey | www.ScaryDBA.com
STATISTICS IN ACTION
4
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;
Grant Fritchey | www.ScaryDBA.com 6
Grant Fritchey | www.ScaryDBA.com 7
Grant Fritchey | www.ScaryDBA.com 8
Grant Fritchey | www.ScaryDBA.com
WHAT ARE STATISTICS
9
Grant Fritchey | www.ScaryDBA.com 10
DBCC
SHOW_STATISTICS('Person.Address',_WA_Sys_00000004_164452B1);
Grant Fritchey | www.ScaryDBA.com
Key Statistic Terms
 Rows Sampled
 Steps
 Density
 Range_hi_key
 Range_rows
 Eq_rows
 Avg_range_rows
 Cardinality
 Cardinality
 Cardinality
11
Grant Fritchey | www.ScaryDBA.com
Cardinality
 Selectivity
» Returned values /TotalValues
 Histogram
 Density
» 1/distinct values
 Compound Columns
» Selectivity * Selectivity
» Density * Density
 +Trace Flags which we’ll talk about
12
Grant Fritchey | www.ScaryDBA.com
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)
13
Grant Fritchey | www.ScaryDBA.com
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
14
Grant Fritchey | www.ScaryDBA.com
CAPTURING BEHAVIOR
15
Grant Fritchey | www.ScaryDBA.com
Capture Mechanisms
 Static
» DBCC SHOW_STATISTICS
» Execution Plans (sort of)
 Dynamic
» Trace Events
» Extended Events
16
Grant Fritchey | www.ScaryDBA.com
Auto_stats
17
Grant Fritchey | www.ScaryDBA.com
Missing_column_statistics
18
Grant Fritchey | www.ScaryDBA.com
Query_optimizer_estimate
_cardinality
19
Grant Fritchey | www.ScaryDBA.com
STATS ARE CREATED
20
Grant Fritchey | www.ScaryDBA.com 21
SELECT s.name,
s.auto_created,
s.user_created,
s.filter_definition,
sc.column_id,
c.name AS ColumnName
FROM sys.stats AS s
JOIN sys.stats_columns AS sc ON sc.stats_id = s.stats_id
AND sc.object_id = s.object_id
JOIN sys.columns AS c ON c.column_id = sc.column_id
AND c.object_id = s.object_id
WHERE s.object_id = OBJECT_ID('dbo.Address2')
Grant Fritchey | www.ScaryDBA.com 22
Grant Fritchey | www.ScaryDBA.com 23
Grant Fritchey | www.ScaryDBA.com 24
Grant Fritchey | www.ScaryDBA.com
What?
25
_WA_Sys_00000001_0A1E72EE
Grant Fritchey | www.ScaryDBA.com
What?
26
_WA_Sys_00000001_0A1E72EE
Hexidecimal Object ID
Grant Fritchey | www.ScaryDBA.com
What?
27
_WA_Sys_00000001_0A1E72EE
Hexidecimal Object ID
Table Column Number
Grant Fritchey | www.ScaryDBA.com
What?
28
_WA_Sys_00000001_0A1E72EE
Hexidecimal Object ID
Table Column Number
System
Grant Fritchey | www.ScaryDBA.com
What?
29
_WA_Sys_00000001_0A1E72EE
Hexidecimal Object ID
Table Column Number
System
The US State ofWashington… yes I’m serious
Grant Fritchey | www.ScaryDBA.com
YOU CAN CREATE STATS
30
Grant Fritchey | www.ScaryDBA.com 31
CREATE STATISTICS MyStats
ON Person.Person (Suffix)
WITH FULLSCAN;
Grant Fritchey | www.ScaryDBA.com 32
CREATE STATISTICS MyJrStats
ON Person.Person (Suffix)
WHERE Suffix = 'Jr.'
WITH FULLSCAN;
Grant Fritchey | www.ScaryDBA.com 33
CREATE STATISTICS MyComboStats
ON Person.Person (Title,Suffix)
WHERE Suffix = 'PhD'
WITH FULLSCAN;
Grant Fritchey | www.ScaryDBA.com
…Or Drop Them
34
DROP STATISTICS Person.Person.MyStats;
DROP STATISTICS Person.Person.MyJrStats;
DROP STATISTICS Person.Person.MyComboStats;
Grant Fritchey | www.ScaryDBA.com
STATS ARE MAINTAINED
35
Grant Fritchey | www.ScaryDBA.com
Dungeons and Dragons
 Add 1 Row when 0
 Add > 500 Rows when < 500
 Add 20% + 500 Rows when > 500
36
Grant Fritchey | www.ScaryDBA.com 37
CREATE INDEX AddressCity
ON dbo.Address2 (City);
DBCC SHOW_STATISTICS(Address2,AddressCity)
Grant Fritchey | www.ScaryDBA.com 38
SELECT * FROM dbo.Address2 AS a
WHERE City = 'Springfield';
Grant Fritchey | www.ScaryDBA.com 39
Grant Fritchey | www.ScaryDBA.com
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)
40
Grant Fritchey | www.ScaryDBA.com
YOU CAN SHOULD
MAINTAIN STATS
MANUALLY
41
Grant Fritchey | www.ScaryDBA.com
Automatic Maintenance
 AUTO_CREATE_STATISTICS
 AUTO_UPDATE_STATISTICS
» Uses rules in previous section
 AUTO_UPDATE_STATISTICS_ASYNC
» Test, test, test
42
Grant Fritchey | www.ScaryDBA.com
sp_updatestats
43
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)))
…
Grant Fritchey | www.ScaryDBA.com
sp_updatestats
44
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)))
…
Grant Fritchey | www.ScaryDBA.com
UPDATE STATISTICS
45
UPDATE STATISTICS Person.Address;
Grant Fritchey | www.ScaryDBA.com
UPDATE STATISTICS
46
UPDATE STATISTICS Person.Address
WITH FULLSCAN;
Grant Fritchey | www.ScaryDBA.com
UPDATE STATISTICS
47
UPDATE STATISTICS dbo.Address2
AddressCity;
Grant Fritchey | www.ScaryDBA.com
UPDATE STATISTICS
48
UPDATE STATISTICS
dbo.Address2 AddressCity
WITH FULLSCAN,NORECOMPUTE;
Grant Fritchey | www.ScaryDBA.com
STATISTICS AND
OPTIMIZER AT WORK
49
Grant Fritchey | www.ScaryDBA.com
Statistics Matter
50
Grant Fritchey | www.ScaryDBA.com
Compatibility Levels
51
ALTER DATABASE
AdventureWorks2012 SET
COMPATIBILITY_LEVEL = 120;
Grant Fritchey | www.ScaryDBA.com
Optimizer Switches
52
OPTION (QUERYTRACEON 2312);
DBCC TRACEON(4199);
DBCC FREEPROCCACHE();
Grant Fritchey | www.ScaryDBA.com
Recommendations
 Compatibility setting
 Automatic creation
 Automatic update
 Update asynchronous where necessary
 Use appropriate sample rate
53
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
Grant Fritchey | www.ScaryDBA.com
Resources
 Scarydba.com/resources
 Understanding SQL Server Cardinality Estimations
 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
55
Grant Fritchey | www.ScaryDBA.com
Questions?
56

Contenu connexe

En vedette

Simplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsSimplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsClayton Groom
 
The Query Store SQL Tuning
The Query Store SQL TuningThe Query Store SQL Tuning
The Query Store SQL TuningGrant Fritchey
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016Mark Tabladillo
 
Window functions for Data Science
Window functions for Data ScienceWindow functions for Data Science
Window functions for Data ScienceMark Tabladillo
 
Window functions in MariaDB 10.2
Window functions in MariaDB 10.2Window functions in MariaDB 10.2
Window functions in MariaDB 10.2Sergey Petrunya
 
Graphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks AgeGraphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks AgeLorenzo Alberton
 
Trees In The Database - Advanced data structures
Trees In The Database - Advanced data structuresTrees In The Database - Advanced data structures
Trees In The Database - Advanced data structuresLorenzo Alberton
 
Эволюция репликации в MySQL и MariaDB
Эволюция репликации в MySQL и MariaDBЭволюция репликации в MySQL и MariaDB
Эволюция репликации в MySQL и MariaDBSergey Petrunya
 

En vedette (9)

Simplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functionsSimplifying SQL with CTE's and windowing functions
Simplifying SQL with CTE's and windowing functions
 
The Query Store SQL Tuning
The Query Store SQL TuningThe Query Store SQL Tuning
The Query Store SQL Tuning
 
Window functions with SQL Server 2016
Window functions with SQL Server 2016Window functions with SQL Server 2016
Window functions with SQL Server 2016
 
Window functions for Data Science
Window functions for Data ScienceWindow functions for Data Science
Window functions for Data Science
 
Sql server windowing functions
Sql server windowing functionsSql server windowing functions
Sql server windowing functions
 
Window functions in MariaDB 10.2
Window functions in MariaDB 10.2Window functions in MariaDB 10.2
Window functions in MariaDB 10.2
 
Graphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks AgeGraphs in the Database: Rdbms In The Social Networks Age
Graphs in the Database: Rdbms In The Social Networks Age
 
Trees In The Database - Advanced data structures
Trees In The Database - Advanced data structuresTrees In The Database - Advanced data structures
Trees In The Database - Advanced data structures
 
Эволюция репликации в MySQL и MariaDB
Эволюция репликации в MySQL и MariaDBЭволюция репликации в MySQL и MariaDB
Эволюция репликации в MySQL и MariaDB
 

Similaire à Statistics and the Query Optimizer

Introducing Azure SQL Data Warehouse
Introducing Azure SQL Data WarehouseIntroducing Azure SQL Data Warehouse
Introducing Azure SQL Data WarehouseGrant Fritchey
 
Getting Started Reading Execution Plans
Getting Started Reading Execution PlansGetting Started Reading Execution Plans
Getting Started Reading Execution PlansGrant Fritchey
 
Azure SQL Database for the Earthed DBA
Azure SQL Database for the Earthed DBAAzure SQL Database for the Earthed DBA
Azure SQL Database for the Earthed DBAGrant Fritchey
 
Getting It Right Exactly Once: Principles for Streaming Architectures
Getting It Right Exactly Once: Principles for Streaming ArchitecturesGetting It Right Exactly Once: Principles for Streaming Architectures
Getting It Right Exactly Once: Principles for Streaming ArchitecturesSingleStore
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationJerod Johnson
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationNordic APIs
 
Learning to Rank Datasets for Search with Oscar Castaneda
Learning to Rank Datasets for Search with Oscar CastanedaLearning to Rank Datasets for Search with Oscar Castaneda
Learning to Rank Datasets for Search with Oscar CastanedaDatabricks
 
"Lessons learned using Apache Spark for self-service data prep in SaaS world"
"Lessons learned using Apache Spark for self-service data prep in SaaS world""Lessons learned using Apache Spark for self-service data prep in SaaS world"
"Lessons learned using Apache Spark for self-service data prep in SaaS world"Pavel Hardak
 
Lessons Learned Using Apache Spark for Self-Service Data Prep in SaaS World
Lessons Learned Using Apache Spark for Self-Service Data Prep in SaaS WorldLessons Learned Using Apache Spark for Self-Service Data Prep in SaaS World
Lessons Learned Using Apache Spark for Self-Service Data Prep in SaaS WorldDatabricks
 
Data Mining with SQL Server 2005
Data Mining with SQL Server 2005Data Mining with SQL Server 2005
Data Mining with SQL Server 2005Dean Willson
 
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...Flink Forward
 
Secrets of Enterprise Data Mining: SQL Saturday 328 Birmingham AL
Secrets of Enterprise Data Mining: SQL Saturday 328 Birmingham ALSecrets of Enterprise Data Mining: SQL Saturday 328 Birmingham AL
Secrets of Enterprise Data Mining: SQL Saturday 328 Birmingham ALMark Tabladillo
 
從數據處理到資料視覺化-商業智慧的實作與應用
從數據處理到資料視覺化-商業智慧的實作與應用從數據處理到資料視覺化-商業智慧的實作與應用
從數據處理到資料視覺化-商業智慧的實作與應用Pei-Syuan Li
 
SQL Server Optimization Checklist
SQL Server Optimization ChecklistSQL Server Optimization Checklist
SQL Server Optimization ChecklistGrant Fritchey
 
WJAX 2019 - Taking Distributed Tracing to the next level
WJAX 2019 - Taking Distributed Tracing to the next levelWJAX 2019 - Taking Distributed Tracing to the next level
WJAX 2019 - Taking Distributed Tracing to the next levelFrank Pfleger
 
Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)
Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)
Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)Cathrine Wilhelmsen
 
Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...
Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...
Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...Cathrine Wilhelmsen
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Miguel González-Fierro
 
HTAP By Accident: Getting More From PostgreSQL Using Hardware Acceleration
HTAP By Accident: Getting More From PostgreSQL Using Hardware AccelerationHTAP By Accident: Getting More From PostgreSQL Using Hardware Acceleration
HTAP By Accident: Getting More From PostgreSQL Using Hardware AccelerationEDB
 

Similaire à Statistics and the Query Optimizer (20)

Introducing Azure SQL Data Warehouse
Introducing Azure SQL Data WarehouseIntroducing Azure SQL Data Warehouse
Introducing Azure SQL Data Warehouse
 
Getting Started Reading Execution Plans
Getting Started Reading Execution PlansGetting Started Reading Execution Plans
Getting Started Reading Execution Plans
 
Azure SQL Database for the Earthed DBA
Azure SQL Database for the Earthed DBAAzure SQL Database for the Earthed DBA
Azure SQL Database for the Earthed DBA
 
Getting It Right Exactly Once: Principles for Streaming Architectures
Getting It Right Exactly Once: Principles for Streaming ArchitecturesGetting It Right Exactly Once: Principles for Streaming Architectures
Getting It Right Exactly Once: Principles for Streaming Architectures
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API Integration
 
EpiServer find Macaw
EpiServer find MacawEpiServer find Macaw
EpiServer find Macaw
 
Why Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API IntegrationWhy Standards-Based Drivers Offer Better API Integration
Why Standards-Based Drivers Offer Better API Integration
 
Learning to Rank Datasets for Search with Oscar Castaneda
Learning to Rank Datasets for Search with Oscar CastanedaLearning to Rank Datasets for Search with Oscar Castaneda
Learning to Rank Datasets for Search with Oscar Castaneda
 
"Lessons learned using Apache Spark for self-service data prep in SaaS world"
"Lessons learned using Apache Spark for self-service data prep in SaaS world""Lessons learned using Apache Spark for self-service data prep in SaaS world"
"Lessons learned using Apache Spark for self-service data prep in SaaS world"
 
Lessons Learned Using Apache Spark for Self-Service Data Prep in SaaS World
Lessons Learned Using Apache Spark for Self-Service Data Prep in SaaS WorldLessons Learned Using Apache Spark for Self-Service Data Prep in SaaS World
Lessons Learned Using Apache Spark for Self-Service Data Prep in SaaS World
 
Data Mining with SQL Server 2005
Data Mining with SQL Server 2005Data Mining with SQL Server 2005
Data Mining with SQL Server 2005
 
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
Squirreling Away $640 Billion: How Stripe Leverages Flink for Change Data Cap...
 
Secrets of Enterprise Data Mining: SQL Saturday 328 Birmingham AL
Secrets of Enterprise Data Mining: SQL Saturday 328 Birmingham ALSecrets of Enterprise Data Mining: SQL Saturday 328 Birmingham AL
Secrets of Enterprise Data Mining: SQL Saturday 328 Birmingham AL
 
從數據處理到資料視覺化-商業智慧的實作與應用
從數據處理到資料視覺化-商業智慧的實作與應用從數據處理到資料視覺化-商業智慧的實作與應用
從數據處理到資料視覺化-商業智慧的實作與應用
 
SQL Server Optimization Checklist
SQL Server Optimization ChecklistSQL Server Optimization Checklist
SQL Server Optimization Checklist
 
WJAX 2019 - Taking Distributed Tracing to the next level
WJAX 2019 - Taking Distributed Tracing to the next levelWJAX 2019 - Taking Distributed Tracing to the next level
WJAX 2019 - Taking Distributed Tracing to the next level
 
Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)
Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)
Tools and Tips For Data Warehouse Developers (SQLSaturday Slovenia)
 
Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...
Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...
Tools and Tips: From Accidental to Efficient Data Warehouse Developer (SQLSat...
 
Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...Running Intelligent Applications inside a Database: Deep Learning with Python...
Running Intelligent Applications inside a Database: Deep Learning with Python...
 
HTAP By Accident: Getting More From PostgreSQL Using Hardware Acceleration
HTAP By Accident: Getting More From PostgreSQL Using Hardware AccelerationHTAP By Accident: Getting More From PostgreSQL Using Hardware Acceleration
HTAP By Accident: Getting More From PostgreSQL Using Hardware Acceleration
 

Plus de Grant Fritchey

Migrating To PostgreSQL
Migrating To PostgreSQLMigrating To PostgreSQL
Migrating To PostgreSQLGrant Fritchey
 
PostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and AlertingPostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and AlertingGrant Fritchey
 
Automating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOpsAutomating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOpsGrant Fritchey
 
Learn To Effectively Use Extended Events_Techorama.pdf
Learn To Effectively Use Extended Events_Techorama.pdfLearn To Effectively Use Extended Events_Techorama.pdf
Learn To Effectively Use Extended Events_Techorama.pdfGrant Fritchey
 
Using Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query PerformanceUsing Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query PerformanceGrant Fritchey
 
You Should Be Standing Here: Learn How To Present a Session
You Should Be Standing Here: Learn How To Present a SessionYou Should Be Standing Here: Learn How To Present a Session
You Should Be Standing Here: Learn How To Present a SessionGrant Fritchey
 
Redgate Community Circle: Tools For SQL Server Performance Tuning
Redgate Community Circle: Tools For SQL Server Performance TuningRedgate Community Circle: Tools For SQL Server Performance Tuning
Redgate Community Circle: Tools For SQL Server Performance TuningGrant Fritchey
 
10 Steps To Global Data Compliance
10 Steps To Global Data Compliance10 Steps To Global Data Compliance
10 Steps To Global Data ComplianceGrant Fritchey
 
Time to Use the Columnstore Index
Time to Use the Columnstore IndexTime to Use the Columnstore Index
Time to Use the Columnstore IndexGrant Fritchey
 
Introduction to SQL Server in Containers
Introduction to SQL Server in ContainersIntroduction to SQL Server in Containers
Introduction to SQL Server in ContainersGrant Fritchey
 
SQL Injection: How It Works, How to Stop It
SQL Injection: How It Works, How to Stop ItSQL Injection: How It Works, How to Stop It
SQL Injection: How It Works, How to Stop ItGrant Fritchey
 
Privacy and Protection in the World of Database DevOps
Privacy and Protection in the World of Database DevOpsPrivacy and Protection in the World of Database DevOps
Privacy and Protection in the World of Database DevOpsGrant Fritchey
 
SQL Server Tools for Query Tuning
SQL Server Tools for Query TuningSQL Server Tools for Query Tuning
SQL Server Tools for Query TuningGrant Fritchey
 
Extending DevOps to SQL Server
Extending DevOps to SQL ServerExtending DevOps to SQL Server
Extending DevOps to SQL ServerGrant Fritchey
 
Introducing Azure Databases
Introducing Azure DatabasesIntroducing Azure Databases
Introducing Azure DatabasesGrant Fritchey
 
Statistis, Row Counts, Execution Plans and Query Tuning
Statistis, Row Counts, Execution Plans and Query TuningStatistis, Row Counts, Execution Plans and Query Tuning
Statistis, Row Counts, Execution Plans and Query TuningGrant Fritchey
 
Understanding Your Servers, All Your Servers
Understanding Your Servers, All Your ServersUnderstanding Your Servers, All Your Servers
Understanding Your Servers, All Your ServersGrant Fritchey
 
Changing Your Habits: Tips to Tune Your T-SQL
Changing Your Habits: Tips to Tune Your T-SQLChanging Your Habits: Tips to Tune Your T-SQL
Changing Your Habits: Tips to Tune Your T-SQLGrant Fritchey
 
Top Tips for Better T-SQL
Top Tips for Better T-SQLTop Tips for Better T-SQL
Top Tips for Better T-SQLGrant Fritchey
 

Plus de Grant Fritchey (20)

Migrating To PostgreSQL
Migrating To PostgreSQLMigrating To PostgreSQL
Migrating To PostgreSQL
 
PostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and AlertingPostgreSQL Performance Problems: Monitoring and Alerting
PostgreSQL Performance Problems: Monitoring and Alerting
 
Automating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOpsAutomating Database Deployments Using Azure DevOps
Automating Database Deployments Using Azure DevOps
 
Learn To Effectively Use Extended Events_Techorama.pdf
Learn To Effectively Use Extended Events_Techorama.pdfLearn To Effectively Use Extended Events_Techorama.pdf
Learn To Effectively Use Extended Events_Techorama.pdf
 
Using Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query PerformanceUsing Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query Performance
 
You Should Be Standing Here: Learn How To Present a Session
You Should Be Standing Here: Learn How To Present a SessionYou Should Be Standing Here: Learn How To Present a Session
You Should Be Standing Here: Learn How To Present a Session
 
Redgate Community Circle: Tools For SQL Server Performance Tuning
Redgate Community Circle: Tools For SQL Server Performance TuningRedgate Community Circle: Tools For SQL Server Performance Tuning
Redgate Community Circle: Tools For SQL Server Performance Tuning
 
10 Steps To Global Data Compliance
10 Steps To Global Data Compliance10 Steps To Global Data Compliance
10 Steps To Global Data Compliance
 
Time to Use the Columnstore Index
Time to Use the Columnstore IndexTime to Use the Columnstore Index
Time to Use the Columnstore Index
 
Introduction to SQL Server in Containers
Introduction to SQL Server in ContainersIntroduction to SQL Server in Containers
Introduction to SQL Server in Containers
 
DevOps for the DBA
DevOps for the DBADevOps for the DBA
DevOps for the DBA
 
SQL Injection: How It Works, How to Stop It
SQL Injection: How It Works, How to Stop ItSQL Injection: How It Works, How to Stop It
SQL Injection: How It Works, How to Stop It
 
Privacy and Protection in the World of Database DevOps
Privacy and Protection in the World of Database DevOpsPrivacy and Protection in the World of Database DevOps
Privacy and Protection in the World of Database DevOps
 
SQL Server Tools for Query Tuning
SQL Server Tools for Query TuningSQL Server Tools for Query Tuning
SQL Server Tools for Query Tuning
 
Extending DevOps to SQL Server
Extending DevOps to SQL ServerExtending DevOps to SQL Server
Extending DevOps to SQL Server
 
Introducing Azure Databases
Introducing Azure DatabasesIntroducing Azure Databases
Introducing Azure Databases
 
Statistis, Row Counts, Execution Plans and Query Tuning
Statistis, Row Counts, Execution Plans and Query TuningStatistis, Row Counts, Execution Plans and Query Tuning
Statistis, Row Counts, Execution Plans and Query Tuning
 
Understanding Your Servers, All Your Servers
Understanding Your Servers, All Your ServersUnderstanding Your Servers, All Your Servers
Understanding Your Servers, All Your Servers
 
Changing Your Habits: Tips to Tune Your T-SQL
Changing Your Habits: Tips to Tune Your T-SQLChanging Your Habits: Tips to Tune Your T-SQL
Changing Your Habits: Tips to Tune Your T-SQL
 
Top Tips for Better T-SQL
Top Tips for Better T-SQLTop Tips for Better T-SQL
Top Tips for Better T-SQL
 

Dernier

Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxolyaivanovalion
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysismanisha194592
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...amitlee9823
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Delhi Call girls
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxfirstjob4
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightDelhi Call girls
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Delhi Call girls
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxolyaivanovalion
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...shivangimorya083
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptxAnupama Kate
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Serviceranjana rawat
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfLars Albertsson
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...Pooja Nehwal
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusTimothy Spann
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxolyaivanovalion
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Callshivangimorya083
 

Dernier (20)

Mature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptxMature dropshipping via API with DroFx.pptx
Mature dropshipping via API with DroFx.pptx
 
April 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's AnalysisApril 2024 - Crypto Market Report's Analysis
April 2024 - Crypto Market Report's Analysis
 
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
Chintamani Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore ...
 
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
Best VIP Call Girls Noida Sector 22 Call Me: 8448380779
 
Introduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptxIntroduction-to-Machine-Learning (1).pptx
Introduction-to-Machine-Learning (1).pptx
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 nightCheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
Cheap Rate Call girls Sarita Vihar Delhi 9205541914 shot 1500 night
 
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
Call Girls in Sarai Kale Khan Delhi 💯 Call Us 🔝9205541914 🔝( Delhi) Escorts S...
 
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
 
Ravak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptxRavak dropshipping via API with DroFx.pptx
Ravak dropshipping via API with DroFx.pptx
 
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...Vip Model  Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
Vip Model Call Girls (Delhi) Karol Bagh 9711199171✔️Body to body massage wit...
 
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in  KishangarhDelhi 99530 vip 56974 Genuine Escort Service Call Girls in  Kishangarh
Delhi 99530 vip 56974 Genuine Escort Service Call Girls in Kishangarh
 
100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx100-Concepts-of-AI by Anupama Kate .pptx
100-Concepts-of-AI by Anupama Kate .pptx
 
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
(PARI) Call Girls Wanowrie ( 7001035870 ) HI-Fi Pune Escorts Service
 
Schema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdfSchema on read is obsolete. Welcome metaprogramming..pdf
Schema on read is obsolete. Welcome metaprogramming..pdf
 
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...{Pooja:  9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
{Pooja: 9892124323 } Call Girl in Mumbai | Jas Kaur Rate 4500 Free Hotel Del...
 
Generative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and MilvusGenerative AI on Enterprise Cloud with NiFi and Milvus
Generative AI on Enterprise Cloud with NiFi and Milvus
 
BabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptxBabyOno dropshipping via API with DroFx.pptx
BabyOno dropshipping via API with DroFx.pptx
 
Sampling (random) method and Non random.ppt
Sampling (random) method and Non random.pptSampling (random) method and Non random.ppt
Sampling (random) method and Non random.ppt
 
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
꧁❤ Greater Noida Call Girls Delhi ❤꧂ 9711199171 ☎️ Hard And Sexy Vip Call
 

Statistics and the Query Optimizer

  • 1. Grant Fritchey | www.ScaryDBA.com www.ScaryDBA.com Statistics and the Query Optimization Grant Fritchey Product Evangelist Red Gate Software
  • 2. 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
  • 3. Grant Fritchey | www.ScaryDBA.com grant@scarydba.com www.scarydba.com @gfritchey www.linkedin.com/in/s carydba Grant Fritchey Product Evangelist, Red GateSoftware
  • 4. Grant Fritchey | www.ScaryDBA.com STATISTICS IN ACTION 4
  • 5. 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;
  • 6. Grant Fritchey | www.ScaryDBA.com 6
  • 7. Grant Fritchey | www.ScaryDBA.com 7
  • 8. Grant Fritchey | www.ScaryDBA.com 8
  • 9. Grant Fritchey | www.ScaryDBA.com WHAT ARE STATISTICS 9
  • 10. Grant Fritchey | www.ScaryDBA.com 10 DBCC SHOW_STATISTICS('Person.Address',_WA_Sys_00000004_164452B1);
  • 11. Grant Fritchey | www.ScaryDBA.com Key Statistic Terms  Rows Sampled  Steps  Density  Range_hi_key  Range_rows  Eq_rows  Avg_range_rows  Cardinality  Cardinality  Cardinality 11
  • 12. Grant Fritchey | www.ScaryDBA.com Cardinality  Selectivity » Returned values /TotalValues  Histogram  Density » 1/distinct values  Compound Columns » Selectivity * Selectivity » Density * Density  +Trace Flags which we’ll talk about 12
  • 13. Grant Fritchey | www.ScaryDBA.com 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) 13
  • 14. Grant Fritchey | www.ScaryDBA.com 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 14
  • 15. Grant Fritchey | www.ScaryDBA.com CAPTURING BEHAVIOR 15
  • 16. Grant Fritchey | www.ScaryDBA.com Capture Mechanisms  Static » DBCC SHOW_STATISTICS » Execution Plans (sort of)  Dynamic » Trace Events » Extended Events 16
  • 17. Grant Fritchey | www.ScaryDBA.com Auto_stats 17
  • 18. Grant Fritchey | www.ScaryDBA.com Missing_column_statistics 18
  • 19. Grant Fritchey | www.ScaryDBA.com Query_optimizer_estimate _cardinality 19
  • 20. Grant Fritchey | www.ScaryDBA.com STATS ARE CREATED 20
  • 21. Grant Fritchey | www.ScaryDBA.com 21 SELECT s.name, s.auto_created, s.user_created, s.filter_definition, sc.column_id, c.name AS ColumnName FROM sys.stats AS s JOIN sys.stats_columns AS sc ON sc.stats_id = s.stats_id AND sc.object_id = s.object_id JOIN sys.columns AS c ON c.column_id = sc.column_id AND c.object_id = s.object_id WHERE s.object_id = OBJECT_ID('dbo.Address2')
  • 22. Grant Fritchey | www.ScaryDBA.com 22
  • 23. Grant Fritchey | www.ScaryDBA.com 23
  • 24. Grant Fritchey | www.ScaryDBA.com 24
  • 25. Grant Fritchey | www.ScaryDBA.com What? 25 _WA_Sys_00000001_0A1E72EE
  • 26. Grant Fritchey | www.ScaryDBA.com What? 26 _WA_Sys_00000001_0A1E72EE Hexidecimal Object ID
  • 27. Grant Fritchey | www.ScaryDBA.com What? 27 _WA_Sys_00000001_0A1E72EE Hexidecimal Object ID Table Column Number
  • 28. Grant Fritchey | www.ScaryDBA.com What? 28 _WA_Sys_00000001_0A1E72EE Hexidecimal Object ID Table Column Number System
  • 29. Grant Fritchey | www.ScaryDBA.com What? 29 _WA_Sys_00000001_0A1E72EE Hexidecimal Object ID Table Column Number System The US State ofWashington… yes I’m serious
  • 30. Grant Fritchey | www.ScaryDBA.com YOU CAN CREATE STATS 30
  • 31. Grant Fritchey | www.ScaryDBA.com 31 CREATE STATISTICS MyStats ON Person.Person (Suffix) WITH FULLSCAN;
  • 32. Grant Fritchey | www.ScaryDBA.com 32 CREATE STATISTICS MyJrStats ON Person.Person (Suffix) WHERE Suffix = 'Jr.' WITH FULLSCAN;
  • 33. Grant Fritchey | www.ScaryDBA.com 33 CREATE STATISTICS MyComboStats ON Person.Person (Title,Suffix) WHERE Suffix = 'PhD' WITH FULLSCAN;
  • 34. Grant Fritchey | www.ScaryDBA.com …Or Drop Them 34 DROP STATISTICS Person.Person.MyStats; DROP STATISTICS Person.Person.MyJrStats; DROP STATISTICS Person.Person.MyComboStats;
  • 35. Grant Fritchey | www.ScaryDBA.com STATS ARE MAINTAINED 35
  • 36. Grant Fritchey | www.ScaryDBA.com Dungeons and Dragons  Add 1 Row when 0  Add > 500 Rows when < 500  Add 20% + 500 Rows when > 500 36
  • 37. Grant Fritchey | www.ScaryDBA.com 37 CREATE INDEX AddressCity ON dbo.Address2 (City); DBCC SHOW_STATISTICS(Address2,AddressCity)
  • 38. Grant Fritchey | www.ScaryDBA.com 38 SELECT * FROM dbo.Address2 AS a WHERE City = 'Springfield';
  • 39. Grant Fritchey | www.ScaryDBA.com 39
  • 40. Grant Fritchey | www.ScaryDBA.com 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) 40
  • 41. Grant Fritchey | www.ScaryDBA.com YOU CAN SHOULD MAINTAIN STATS MANUALLY 41
  • 42. Grant Fritchey | www.ScaryDBA.com Automatic Maintenance  AUTO_CREATE_STATISTICS  AUTO_UPDATE_STATISTICS » Uses rules in previous section  AUTO_UPDATE_STATISTICS_ASYNC » Test, test, test 42
  • 43. Grant Fritchey | www.ScaryDBA.com sp_updatestats 43 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))) …
  • 44. Grant Fritchey | www.ScaryDBA.com sp_updatestats 44 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))) …
  • 45. Grant Fritchey | www.ScaryDBA.com UPDATE STATISTICS 45 UPDATE STATISTICS Person.Address;
  • 46. Grant Fritchey | www.ScaryDBA.com UPDATE STATISTICS 46 UPDATE STATISTICS Person.Address WITH FULLSCAN;
  • 47. Grant Fritchey | www.ScaryDBA.com UPDATE STATISTICS 47 UPDATE STATISTICS dbo.Address2 AddressCity;
  • 48. Grant Fritchey | www.ScaryDBA.com UPDATE STATISTICS 48 UPDATE STATISTICS dbo.Address2 AddressCity WITH FULLSCAN,NORECOMPUTE;
  • 49. Grant Fritchey | www.ScaryDBA.com STATISTICS AND OPTIMIZER AT WORK 49
  • 50. Grant Fritchey | www.ScaryDBA.com Statistics Matter 50
  • 51. Grant Fritchey | www.ScaryDBA.com Compatibility Levels 51 ALTER DATABASE AdventureWorks2012 SET COMPATIBILITY_LEVEL = 120;
  • 52. Grant Fritchey | www.ScaryDBA.com Optimizer Switches 52 OPTION (QUERYTRACEON 2312); DBCC TRACEON(4199); DBCC FREEPROCCACHE();
  • 53. Grant Fritchey | www.ScaryDBA.com Recommendations  Compatibility setting  Automatic creation  Automatic update  Update asynchronous where necessary  Use appropriate sample rate 53
  • 54. 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
  • 55. Grant Fritchey | www.ScaryDBA.com Resources  Scarydba.com/resources  Understanding SQL Server Cardinality Estimations  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 55
  • 56. Grant Fritchey | www.ScaryDBA.com Questions? 56