SlideShare una empresa de Scribd logo
1 de 56
Descargar para leer sin conexión
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

Más contenido relacionado

Destacado

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
 

Destacado (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
 

Similar a 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
 

Similar a 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
 

Más 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
 

Más 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
 

Último

why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...Jack Cole
 
Statistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfStatistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfnikeshsingh56
 
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis modelDecoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis modelBoston Institute of Analytics
 
IBEF report on the Insurance market in India
IBEF report on the Insurance market in IndiaIBEF report on the Insurance market in India
IBEF report on the Insurance market in IndiaManalVerma4
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...Dr Arash Najmaei ( Phd., MBA, BSc)
 
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...Boston Institute of Analytics
 
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBoston Institute of Analytics
 
DATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etcDATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etclalithasri22
 
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfblazblazml
 
Non Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfNon Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfPratikPatil591646
 
Role of Consumer Insights in business transformation
Role of Consumer Insights in business transformationRole of Consumer Insights in business transformation
Role of Consumer Insights in business transformationAnnie Melnic
 
Presentation of project of business person who are success
Presentation of project of business person who are successPresentation of project of business person who are success
Presentation of project of business person who are successPratikSingh115843
 
Digital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfDigital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfNicoChristianSunaryo
 
Digital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksDigital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksdeepakthakur548787
 

Último (17)

why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
why-transparency-and-traceability-are-essential-for-sustainable-supply-chains...
 
Statistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdfStatistics For Management by Richard I. Levin 8ed.pdf
Statistics For Management by Richard I. Levin 8ed.pdf
 
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis modelDecoding Movie Sentiments: Analyzing Reviews with Data Analysis model
Decoding Movie Sentiments: Analyzing Reviews with Data Analysis model
 
IBEF report on the Insurance market in India
IBEF report on the Insurance market in IndiaIBEF report on the Insurance market in India
IBEF report on the Insurance market in India
 
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
6 Tips for Interpretable Topic Models _ by Nicha Ruchirawat _ Towards Data Sc...
 
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
Data Analysis Project Presentation: Unveiling Your Ideal Customer, Bank Custo...
 
2023 Survey Shows Dip in High School E-Cigarette Use
2023 Survey Shows Dip in High School E-Cigarette Use2023 Survey Shows Dip in High School E-Cigarette Use
2023 Survey Shows Dip in High School E-Cigarette Use
 
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis ProjectBank Loan Approval Analysis: A Comprehensive Data Analysis Project
Bank Loan Approval Analysis: A Comprehensive Data Analysis Project
 
DATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etcDATA ANALYSIS using various data sets like shoping data set etc
DATA ANALYSIS using various data sets like shoping data set etc
 
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdfEnglish-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
English-8-Q4-W3-Synthesizing-Essential-Information-From-Various-Sources-1.pdf
 
Data Analysis Project: Stroke Prediction
Data Analysis Project: Stroke PredictionData Analysis Project: Stroke Prediction
Data Analysis Project: Stroke Prediction
 
Non Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdfNon Text Magic Studio Magic Design for Presentations L&P.pdf
Non Text Magic Studio Magic Design for Presentations L&P.pdf
 
Role of Consumer Insights in business transformation
Role of Consumer Insights in business transformationRole of Consumer Insights in business transformation
Role of Consumer Insights in business transformation
 
Presentation of project of business person who are success
Presentation of project of business person who are successPresentation of project of business person who are success
Presentation of project of business person who are success
 
Digital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdfDigital Indonesia Report 2024 by We Are Social .pdf
Digital Indonesia Report 2024 by We Are Social .pdf
 
Insurance Churn Prediction Data Analysis Project
Insurance Churn Prediction Data Analysis ProjectInsurance Churn Prediction Data Analysis Project
Insurance Churn Prediction Data Analysis Project
 
Digital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing worksDigital Marketing Plan, how digital marketing works
Digital Marketing Plan, how digital marketing works
 

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