SlideShare a Scribd company logo
1 of 32
Download to read offline
© 2019 Brent Ozar Unlimited®. All rights reserved. 1
Why Is The Same Query Sometimes Slow?
Parameter sniffing, and why OPTION RECOMPILE isn’t your friend.
Video, related articles, and more: BrentOzar.com/go/sniff
99-05: dev, architect, DBA
05-08: DBA, VM, SAN admin
08-10: MCM, Quest Software
Since: consulting DBA
www.BrentOzar.com
Help@BrentOzar.com
© 2019 Brent Ozar Unlimited®. All rights reserved. 2
Everyone thinks they
know something
about this.
They’re usually wrong. Buckle up.
People often:
• Blame statistics or fragmentation
• Use the wrong code to reproduce an issue
There is no single right answer
• Pros and cons to every option
• Evaluate each instance individually
It’s almost impossible to identify and diagnose this
without access to the production environment
© 2019 Brent Ozar Unlimited®. All rights reserved. 3
I want you to learn 3 things
1. What parameter sniffing is
2. How to react to parameter sniffing emergencies
3. 7 options for fixing the problem long-term
1. What parameter sniffing is
The first thing to learn
© 2019 Brent Ozar Unlimited®. All rights reserved. 4
CREATE INDEX IX_Reputation
ON dbo.Users(Reputation);
GO
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=1
ORDER BY DisplayName;
Build a query plan for the SELECT now.
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=1
ORDER BY DisplayName;
Breaking it down
Our index doesn’t have all the fields,
so we may need a key lookup
Will we use the Reputation index?
We’ll need a memory grant to
sort rows after we find ‘em
© 2019 Brent Ozar Unlimited®. All rights reserved. 5
Check out User.Reputation’s statistics
5.3 million Users
More than half have just 1 reputation point
But only 5,305 have exactly 2 points
So when you query for Reputation = 1…
Ignored Reputation index.
© 2019 Brent Ozar Unlimited®. All rights reserved. 6
But query for Reputation = 2…
It uses the Reputation index, but…
Has to look up each user for the * fields.
Lookups are expensive
Plan #1 Plan #2
• Preferred when there are a lot of rows
• Over SQL Server’s tipping point
• Preferred when there are just a few rows
• Uses the index, but still gets a request
for a covering index
© 2019 Brent Ozar Unlimited®. All rights reserved. 7
Statistics IO, TIME show just how expensive
Reputation = 1
Reputation = 2
Scans the
clustered index,
which only does
80,290 reads.
Takes ~15
seconds of CPU
time, 4 seconds of
clock time.
Seek + key
lookup, but needs
16,268 reads
because we
fetched 5,305
rows.
Takes hardly any
time at all.
The scorecard
Plain T-SQL
Reputation = 1 Duration 4.3s
CPU Time 14.6s
Logical Reads 80,290
Reputation = 2 Duration 0.3
CPU Time 0
Logical Reads 16,268
© 2019 Brent Ozar Unlimited®. All rights reserved. 8
SELECT * FROM dbo.Users
WHERE Reputation=1;
GO
SELECT * FROM dbo.Users
WHERE Reputation=2;
GO
SQL Server uses these literals to pick a plan
These estimated
row counts come
from statistics
Just like you learned in
“How to Think Like the Engine”…
© 2019 Brent Ozar Unlimited®. All rights reserved. 9
SQL Server checks the Reputation = ___
number against your statistics
Index statistics
• These are auto-generated when you
create the index
Column statistics
• Automatically created on the fly
when you run queries
• These have the “_WA_Sys” cryptic
names
CREATE PROCEDURE dbo.UsersByReputation
@Reputation int
AS
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=@Reputation
ORDER BY DisplayName;
GO
EXEC dbo.UsersByReputation @Reputation =1;
GO
EXEC dbo.UsersByReputation @Reputation =2;
GO
This does the same thing, right?
© 2019 Brent Ozar Unlimited®. All rights reserved. 10
Well… no.
Right click on the second execution plan…
© 2019 Brent Ozar Unlimited®. All rights reserved. 11
Scroll to the bottom of the XML…
Compiled value and runtime value are different
The compiled value came from the first time it was run
This parameter was “sniffed”
It’s really not that bad, though.
Reputation = 1
Reputation = 2
Still scans the
clustered index,
which only does
80,290 reads.
Takes ~15
seconds of CPU
time, 4 seconds of
clock time.
Scans the whole
table, but…
It’s still fast! Well,
pretty quick.
© 2019 Brent Ozar Unlimited®. All rights reserved. 12
The scorecard: not really a big deal.
Plain T-SQL Proc, Rep = 1
called first
Reputation = 1 Duration 4.3s 4.3s
CPU Time 14.6s 14.6s
Logical Reads 80,290 80,290
Reputation = 2 Duration 0.3 0.4
CPU Time 0.0 0.5
Logical Reads 16,268 80,486
Still consistent
Few people will notice
Worse, but who cares?
People don’t complain about this kind of parameter sniffing because
they don’t even notice it. Heck, they’d notice it if it WASN’T happening.
Sniffing saves us from CPU-burning compiles.
Query that compiles each
time – run 5K times
Query using cached
plan – run 5K times
% Processor Time on a 2 processor VM. Nothing running but this query.
© 2019 Brent Ozar Unlimited®. All rights reserved. 13
But what happens if…
Windows restarts
The SQL Server service restarts
Someone runs DBCC FREEPROCCACHE
Indexes on the Users table are rebuilt
Statistics on the Users table are updated
The server comes under memory pressure
And the queries are run in a different order?
That’s not good.
Now we have a query
plan optimized for tiny
amounts of data, just
5,305 expected rows.
See the yellow bangs?
Both queries have
problems.
More on that later.
© 2019 Brent Ozar Unlimited®. All rights reserved. 14
It gets worse. Much, much worse.
Reputation = 2
Reputation = 1
Perfect! Just
16,268 reads.
Super-fast too!
TEN MILLION
LOGICAL READS
SEVENTEEN
SECOND
RUNTIME
Note: 2 first
The scorecard: THIS is parameter sniffing.
Plain T-SQL Proc, Rep = 1
called first
Proc, Rep = 2
called first
Reputation = 1 Duration 4.3s 4.3s 16.9s
CPU Time 14.6s 14.6s 15.6s
Logical Reads 80,290 80,290 10,046,724
Reputation = 2 Duration 0.3 0.4 0.2
CPU Time 0.0 0.5 0.0
Logical Reads 16,268 80,486 16,268
OMG
OMG
When people complain about parameter sniffing,
THIS is the scenario they’re complaining about.
© 2019 Brent Ozar Unlimited®. All rights reserved. 15
Why so bad?
The estimates are
cached for the first
parameter we use:
• Row estimates
• Estimated cost
(which may be way
below the Cost
Threshold for
Parallelism)
• Memory grants
That was the
easy part.
© 2019 Brent Ozar Unlimited®. All rights reserved. 16
2. How to respond to
parameter sniffing emergencies
Next up, let’s just try not to freak out
The career progression of a perf tuner
“Let’s restart Windows!”
“Let’s restart the SQL Server service!”
“Let’s run DBCC FREEPROCCACHE!”
“Let’s rebuild all the indexes!”
“Let’s rebuild the indexes on the one table involved!”
“Let’s update statistics on the table!”
“Let’s just clear this one plan from cache.”
© 2019 Brent Ozar Unlimited®. All rights reserved. 17
How to free one plan from cache
Run sp_BlitzCache @ExpertMode = 1
Find the query that’s not usually on the suckerboard,
because he probably just got an unusually bad plan today
Scroll to the far right, and check out:
DBCC FREEPROCCACHE (mycrappysqlhandle)
Save the execution plan, then free it from cache.
Did the emergency stop? If so, you’ve found your culprit.
3. 7 ways to
fix it for good
© 2019 Brent Ozar Unlimited®. All rights reserved. 18
Option recompile,
right?
KB 968693 (from 2009)
© 2019 Brent Ozar Unlimited®. All rights reserved. 19
That’ll never happen
again, right?
KB 2965069 (from 2014)
© 2019 Brent Ozar Unlimited®. All rights reserved. 20
Yeah. So about that
option recompile.
Now you’re waiting to hear
the option that doesn’t suck.
© 2019 Brent Ozar Unlimited®. All rights reserved. 21
All these options suck.
You just have to find the right one
for each parameter sniffing problem,
and every problem is different.
You have a decision to make.
Can you get one good plan for all parameters?
• OPTIMIZE FOR UNKNOWN
• Declare a local variable
• OPTIMIZE FOR specific value
• Plan guides
• Covering indexes
Or do you need different plans for different parameters?
• OPTION RECOMPILE
• Stored procedure branching
© 2019 Brent Ozar Unlimited®. All rights reserved. 22
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT WITH RECOMPILE
AS
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=@Reputation
ORDER BY DisplayName;
Option RECOMPILE for the entire proc
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT WITH RECOMPILE
AS
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=@Reputation
ORDER BY DisplayName;
Option RECOMPILE for the entire proc
N
E
V
E
R
D
O
T
H
I
S
* Unless you purposely want to hide your
code from many monitoring tools, hee hee.
© 2019 Brent Ozar Unlimited®. All rights reserved. 23
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT
AS
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=@Reputation
ORDER BY DisplayName
OPTION (RECOMPILE);
Option RECOMPILE at the statement level
Option RECOMPILE at the statement level
Plan cache won’t track statement-level query stats
(although it will track stored-proc-level, you just won’t know which
queries were the expensive ones)
Burns CPU for every execution, compiling a new plan
Makes sense for rarely-run, wildly variable stored procs
(like once every minute or two, max)
© 2019 Brent Ozar Unlimited®. All rights reserved. 24
ALTER PROCEDURE UsersByReputation
@Reputation INT
AS
IF @Reputation = 1
EXEC UsersByReputation_1 @1
ELSE
EXEC UsersByReputation_Other @1
Stored procedure branching
Stored procedure branching
Like optimizing for a specific value:
• You’d better know your data pretty well.
• Your data better not change over time.
But now you can have 2 different sub-procedures,
each of which gets its own optimized plan.
They could even have the same code in them:
they’ll just get sniffed for the right values, and get the right plans.
(This is a pretty rarely used trick.)
© 2019 Brent Ozar Unlimited®. All rights reserved. 25
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT
AS
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=@Reputation
ORDER BY DisplayName
OPTION (OPTIMIZE FOR UNKNOWN);
GO
OPTIMIZE FOR UNKNOWN
OPTIMIZE FOR UNKNOWN
This forces everyone to use the density vector (just like a local variable).
In this case, it simply doesn’t work:
the density vector gives us a 314 estimate, which isn’t anywhere near our
real-world numbers for reputation 1 or 2.
In some cases, with widely spread-out data, this can work.
© 2019 Brent Ozar Unlimited®. All rights reserved. 26
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT
AS
DECLARE @ReputationUnknown INT;
SET @ReputationUnknown = @Reputation;
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation = @ReputationUnknown
ORDER BY DisplayName;
GO
Fake “OPTIMIZE FOR UNKNOWN”
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT
AS
DECLARE @ReputationUnknown INT;
SET @ReputationUnknown = @Reputation;
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation = @ReputationUnknown
ORDER BY DisplayName;
GO
Fake “OPTIMIZE FOR UNKNOWN”
N
E
V
E
R
D
O
T
H
I
S
© 2019 Brent Ozar Unlimited®. All rights reserved. 27
Fake “OPTIMIZE FOR UNKNOWN”
Exact same results as Optimize For Unknown
The “Optimize for Unknown” hint was added in SQL Server 2008
Prior to that, people did the “create another variable” trick sometimes
It has the same downsides:
• Often just not a very good execution plan
• May not be a stable plan over time
But you look like an idiot,
and people overwrite your code.
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT
AS
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=@Reputation
ORDER BY DisplayName
OPTION (OPTIMIZE FOR UNKNOWN);
GO
If you want the density vector, use this instead.
© 2019 Brent Ozar Unlimited®. All rights reserved. 28
ALTER PROCEDURE dbo.UsersByReputation
@Reputation INT
AS
SELECT TOP 10000 *
FROM dbo.Users
WHERE Reputation=@Reputation
ORDER BY DisplayName
OPTION (OPTIMIZE FOR @Reputation = 1)
OPTIMIZE FOR Value
OPTIMIZE FOR Value
You’d better know your data pretty well.
Your data better not change over time.
© 2019 Brent Ozar Unlimited®. All rights reserved. 29
Plan guides
You identify a very exact string, and the right query plan for it
You guide the plan: that plan sticks around even after restarts
2016’s Query Store makes this point-and-click easy
But it’s up to you to:
• Identify the string
• Construct the right query plan
• Know when you should un-pin it
• Make sure it works, and that it stays working
Plan guides fail silently.
Query changes at all? Guide won’t work.
Indexes in use disappeared? Guide stops working.
Doesn’t fix issues like memory grants:
if the memory ain’t there, the guide can’t do magic.
I love plan guides to fix emergency problems,
but they’re like duct tape.
You need a better plan within 48-72 hours.
© 2019 Brent Ozar Unlimited®. All rights reserved. 30
Hard solution: better plan for everyone
Most parameter sniffing issues have a simple cause:
• There’s no covering index, so
• Sometimes a seek + key lookup is better, but
• Sometimes a clustered index scan is better
You could solve it by creating a better index that fits more scenarios.
What about our demo query’s case?
Multi-Plan Solutions Would it work?
OPTION (RECOMPILE) Depends on frequency
Stored procedure branching Yes
Single-Plan Solutions Would it work?
OPTIMIZE FOR UNKNOWN
(or the internal local variable trick)
No, it’d estimate 314.7 rows
OPTIMIZE FOR @Reputation = 1 Yes
Plan guide Yes, but will fail when the query
changes
Get one good plan for everyone Clippy’s covering index wouldn’t
work, but a manual index would.
© 2019 Brent Ozar Unlimited®. All rights reserved. 31
This is doable.
Not easy, but
doable.
Recap
© 2019 Brent Ozar Unlimited®. All rights reserved. 32
You learned 3 things
1. What parameter sniffing is
2. How to react to parameter sniffing emergencies:
• sp_BlitzCache @ExpertMode = 1
• Save the plan
• Use the “free from cache” columns at the far right
3. Options for fixing the problem long-term: there’s no easy button
Learn more: BrentOzar.com/go/sniff

More Related Content

Similar to Why Parameter Sniffing Sometimes Slows Queries Down

MySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to HaveMySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to HaveSveta Smirnova
 
Geek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent Ozar
Geek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent OzarGeek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent Ozar
Geek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent OzarIDERA Software
 
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2SolarWinds
 
IBM Connect 2017: Back from the Dead: When Bad Code Kills a Good Server
IBM Connect 2017: Back from the Dead: When Bad Code Kills a Good ServerIBM Connect 2017: Back from the Dead: When Bad Code Kills a Good Server
IBM Connect 2017: Back from the Dead: When Bad Code Kills a Good ServerSerdar Basegmez
 
Become a Performance Diagnostics Hero
Become a Performance Diagnostics HeroBecome a Performance Diagnostics Hero
Become a Performance Diagnostics HeroTechWell
 
From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...
From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...
From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...Imperva Incapsula
 
Database Benchmarking: Miseries, Myths and Misconceptions
Database Benchmarking: Miseries, Myths and MisconceptionsDatabase Benchmarking: Miseries, Myths and Misconceptions
Database Benchmarking: Miseries, Myths and MisconceptionsIDERA Software
 
Open source: Top issues in the top enterprise packages
Open source: Top issues in the top enterprise packagesOpen source: Top issues in the top enterprise packages
Open source: Top issues in the top enterprise packagesRogue Wave Software
 
Testing Persistent Storage Performance in Kubernetes with Sherlock
Testing Persistent Storage Performance in Kubernetes with SherlockTesting Persistent Storage Performance in Kubernetes with Sherlock
Testing Persistent Storage Performance in Kubernetes with SherlockScyllaDB
 
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...Lucidworks
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowKathy Brown
 
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresDynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresBrent Ozar
 
Llunitebe2018 worst config mgr cb mistakes
Llunitebe2018 worst config mgr cb mistakesLlunitebe2018 worst config mgr cb mistakes
Llunitebe2018 worst config mgr cb mistakesKenny Buntinx
 
BP206 - Let's Give Your LotusScript a Tune-Up
BP206 - Let's Give Your LotusScript a Tune-Up BP206 - Let's Give Your LotusScript a Tune-Up
BP206 - Let's Give Your LotusScript a Tune-Up Craig Schumann
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineBrent Ozar
 
JavaOne 2015: Top Performance Patterns Deep Dive
JavaOne 2015: Top Performance Patterns Deep DiveJavaOne 2015: Top Performance Patterns Deep Dive
JavaOne 2015: Top Performance Patterns Deep DiveAndreas Grabner
 
Ingesting Data at Blazing Speed Using Apache Orc
Ingesting Data at Blazing Speed Using Apache OrcIngesting Data at Blazing Speed Using Apache Orc
Ingesting Data at Blazing Speed Using Apache OrcDataWorks Summit
 
Data oriented design and c++
Data oriented design and c++Data oriented design and c++
Data oriented design and c++Mike Acton
 
Apache Kudu: Technical Deep Dive


Apache Kudu: Technical Deep Dive

Apache Kudu: Technical Deep Dive


Apache Kudu: Technical Deep Dive

Cloudera, Inc.
 

Similar to Why Parameter Sniffing Sometimes Slows Queries Down (20)

MySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to HaveMySQL Database Monitoring: Must, Good and Nice to Have
MySQL Database Monitoring: Must, Good and Nice to Have
 
Geek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent Ozar
Geek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent OzarGeek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent Ozar
Geek Sync | Planning a SQL Server to Azure Migration in 2021 - Brent Ozar
 
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
 
IBM Connect 2017: Back from the Dead: When Bad Code Kills a Good Server
IBM Connect 2017: Back from the Dead: When Bad Code Kills a Good ServerIBM Connect 2017: Back from the Dead: When Bad Code Kills a Good Server
IBM Connect 2017: Back from the Dead: When Bad Code Kills a Good Server
 
Become a Performance Diagnostics Hero
Become a Performance Diagnostics HeroBecome a Performance Diagnostics Hero
Become a Performance Diagnostics Hero
 
From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...
From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...
From 1000/day to 1000/sec: The Evolution of Incapsula's BIG DATA System [Surg...
 
Database Benchmarking: Miseries, Myths and Misconceptions
Database Benchmarking: Miseries, Myths and MisconceptionsDatabase Benchmarking: Miseries, Myths and Misconceptions
Database Benchmarking: Miseries, Myths and Misconceptions
 
Open source: Top issues in the top enterprise packages
Open source: Top issues in the top enterprise packagesOpen source: Top issues in the top enterprise packages
Open source: Top issues in the top enterprise packages
 
Testing Persistent Storage Performance in Kubernetes with Sherlock
Testing Persistent Storage Performance in Kubernetes with SherlockTesting Persistent Storage Performance in Kubernetes with Sherlock
Testing Persistent Storage Performance in Kubernetes with Sherlock
 
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...
High Performance Solr and JVM Tuning Strategies used for MapQuest’s Search Ah...
 
Top Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To KnowTop Tips Every Notes Developer Needs To Know
Top Tips Every Notes Developer Needs To Know
 
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored ProceduresDynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
Dynamic SQL: How to Build Fast Multi-Parameter Stored Procedures
 
Llunitebe2018 worst config mgr cb mistakes
Llunitebe2018 worst config mgr cb mistakesLlunitebe2018 worst config mgr cb mistakes
Llunitebe2018 worst config mgr cb mistakes
 
BP206 - Let's Give Your LotusScript a Tune-Up
BP206 - Let's Give Your LotusScript a Tune-Up BP206 - Let's Give Your LotusScript a Tune-Up
BP206 - Let's Give Your LotusScript a Tune-Up
 
Introduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the EngineIntroduction to SQL Server Internals: How to Think Like the Engine
Introduction to SQL Server Internals: How to Think Like the Engine
 
How to think like the engine
How to think like the engineHow to think like the engine
How to think like the engine
 
JavaOne 2015: Top Performance Patterns Deep Dive
JavaOne 2015: Top Performance Patterns Deep DiveJavaOne 2015: Top Performance Patterns Deep Dive
JavaOne 2015: Top Performance Patterns Deep Dive
 
Ingesting Data at Blazing Speed Using Apache Orc
Ingesting Data at Blazing Speed Using Apache OrcIngesting Data at Blazing Speed Using Apache Orc
Ingesting Data at Blazing Speed Using Apache Orc
 
Data oriented design and c++
Data oriented design and c++Data oriented design and c++
Data oriented design and c++
 
Apache Kudu: Technical Deep Dive


Apache Kudu: Technical Deep Dive

Apache Kudu: Technical Deep Dive


Apache Kudu: Technical Deep Dive


 

More from IDERA Software

The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...IDERA Software
 
Problems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloudProblems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloudIDERA Software
 
Public cloud uses and limitations
Public cloud uses and limitationsPublic cloud uses and limitations
Public cloud uses and limitationsIDERA Software
 
Optimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptxOptimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptxIDERA Software
 
Monitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL ServerMonitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL ServerIDERA Software
 
Database administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databasesDatabase administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databasesIDERA Software
 
Six tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costsSix tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costsIDERA Software
 
Idera live 2021: The Power of Abstraction by Steve Hoberman
Idera live 2021:  The Power of Abstraction by Steve HobermanIdera live 2021:  The Power of Abstraction by Steve Hoberman
Idera live 2021: The Power of Abstraction by Steve HobermanIDERA Software
 
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian Flug
Idera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian FlugIdera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian Flug
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian FlugIDERA Software
 
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...IDERA Software
 
Idera live 2021: Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021:  Managing Digital Transformation on a Budget by Bert ScalzoIdera live 2021:  Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021: Managing Digital Transformation on a Budget by Bert ScalzoIDERA Software
 
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...IDERA Software
 
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...IDERA Software
 
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...IDERA Software
 
Idera live 2021: Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021:  Performance Tuning Azure SQL Database by Monica RathbunIdera live 2021:  Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021: Performance Tuning Azure SQL Database by Monica RathbunIDERA Software
 
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERAGeek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERAIDERA Software
 
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...IDERA Software
 
Benefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERABenefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERAIDERA Software
 
Achieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERAAchieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERAIDERA Software
 
Benefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERABenefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERAIDERA Software
 

More from IDERA Software (20)

The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...The role of the database administrator (DBA) in 2020: Changes, challenges, an...
The role of the database administrator (DBA) in 2020: Changes, challenges, an...
 
Problems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloudProblems and solutions for migrating databases to the cloud
Problems and solutions for migrating databases to the cloud
 
Public cloud uses and limitations
Public cloud uses and limitationsPublic cloud uses and limitations
Public cloud uses and limitations
 
Optimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptxOptimize the performance, cost, and value of databases.pptx
Optimize the performance, cost, and value of databases.pptx
 
Monitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL ServerMonitor cloud database with SQL Diagnostic Manager for SQL Server
Monitor cloud database with SQL Diagnostic Manager for SQL Server
 
Database administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databasesDatabase administrators (dbas) face increasing pressure to monitor databases
Database administrators (dbas) face increasing pressure to monitor databases
 
Six tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costsSix tips for cutting sql server licensing costs
Six tips for cutting sql server licensing costs
 
Idera live 2021: The Power of Abstraction by Steve Hoberman
Idera live 2021:  The Power of Abstraction by Steve HobermanIdera live 2021:  The Power of Abstraction by Steve Hoberman
Idera live 2021: The Power of Abstraction by Steve Hoberman
 
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian Flug
Idera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian FlugIdera live 2021:  Why Data Lakes are Critical for AI, ML, and IoT  By Brian Flug
Idera live 2021: Why Data Lakes are Critical for AI, ML, and IoT By Brian Flug
 
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
Idera live 2021: Will Data Vault add Value to Your Data Warehouse? 3 Signs th...
 
Idera live 2021: Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021:  Managing Digital Transformation on a Budget by Bert ScalzoIdera live 2021:  Managing Digital Transformation on a Budget by Bert Scalzo
Idera live 2021: Managing Digital Transformation on a Budget by Bert Scalzo
 
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...Idera live 2021:  Keynote Presentation The Future of Data is The Data Cloud b...
Idera live 2021: Keynote Presentation The Future of Data is The Data Cloud b...
 
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...Idera live 2021:   Managing Databases in the Cloud - the First Step, a Succes...
Idera live 2021: Managing Databases in the Cloud - the First Step, a Succes...
 
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...Idera live 2021:  Database Auditing - on-Premises and in the Cloud by Craig M...
Idera live 2021: Database Auditing - on-Premises and in the Cloud by Craig M...
 
Idera live 2021: Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021:  Performance Tuning Azure SQL Database by Monica RathbunIdera live 2021:  Performance Tuning Azure SQL Database by Monica Rathbun
Idera live 2021: Performance Tuning Azure SQL Database by Monica Rathbun
 
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERAGeek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
Geek Sync | How to Be the DBA When You Don't Have a DBA - Eric Cobb | IDERA
 
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
How Users of a Performance Monitoring Tool Can Benefit from an Inventory Mana...
 
Benefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERABenefits of Third Party Tools for MySQL | IDERA
Benefits of Third Party Tools for MySQL | IDERA
 
Achieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERAAchieve More with Less Resources | IDERA
Achieve More with Less Resources | IDERA
 
Benefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERABenefits of SQL Server 2017 and 2019 | IDERA
Benefits of SQL Server 2017 and 2019 | IDERA
 

Recently uploaded

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraDeakin University
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Alan Dix
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxnull - The Open Security Community
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsPrecisely
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 

Recently uploaded (20)

#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
The transition to renewables in India.pdf
The transition to renewables in India.pdfThe transition to renewables in India.pdf
The transition to renewables in India.pdf
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Artificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning eraArtificial intelligence in the post-deep learning era
Artificial intelligence in the post-deep learning era
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...Swan(sea) Song – personal research during my six years at Swansea ... and bey...
Swan(sea) Song – personal research during my six years at Swansea ... and bey...
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptxMaking_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
Making_way_through_DLL_hollowing_inspite_of_CFG_by_Debjeet Banerjee.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptxVulnerability_Management_GRC_by Sohang Sengupta.pptx
Vulnerability_Management_GRC_by Sohang Sengupta.pptx
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Unlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power SystemsUnlocking the Potential of the Cloud for IBM Power Systems
Unlocking the Potential of the Cloud for IBM Power Systems
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 

Why Parameter Sniffing Sometimes Slows Queries Down

  • 1. © 2019 Brent Ozar Unlimited®. All rights reserved. 1 Why Is The Same Query Sometimes Slow? Parameter sniffing, and why OPTION RECOMPILE isn’t your friend. Video, related articles, and more: BrentOzar.com/go/sniff 99-05: dev, architect, DBA 05-08: DBA, VM, SAN admin 08-10: MCM, Quest Software Since: consulting DBA www.BrentOzar.com Help@BrentOzar.com
  • 2. © 2019 Brent Ozar Unlimited®. All rights reserved. 2 Everyone thinks they know something about this. They’re usually wrong. Buckle up. People often: • Blame statistics or fragmentation • Use the wrong code to reproduce an issue There is no single right answer • Pros and cons to every option • Evaluate each instance individually It’s almost impossible to identify and diagnose this without access to the production environment
  • 3. © 2019 Brent Ozar Unlimited®. All rights reserved. 3 I want you to learn 3 things 1. What parameter sniffing is 2. How to react to parameter sniffing emergencies 3. 7 options for fixing the problem long-term 1. What parameter sniffing is The first thing to learn
  • 4. © 2019 Brent Ozar Unlimited®. All rights reserved. 4 CREATE INDEX IX_Reputation ON dbo.Users(Reputation); GO SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=1 ORDER BY DisplayName; Build a query plan for the SELECT now. SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=1 ORDER BY DisplayName; Breaking it down Our index doesn’t have all the fields, so we may need a key lookup Will we use the Reputation index? We’ll need a memory grant to sort rows after we find ‘em
  • 5. © 2019 Brent Ozar Unlimited®. All rights reserved. 5 Check out User.Reputation’s statistics 5.3 million Users More than half have just 1 reputation point But only 5,305 have exactly 2 points So when you query for Reputation = 1… Ignored Reputation index.
  • 6. © 2019 Brent Ozar Unlimited®. All rights reserved. 6 But query for Reputation = 2… It uses the Reputation index, but… Has to look up each user for the * fields. Lookups are expensive Plan #1 Plan #2 • Preferred when there are a lot of rows • Over SQL Server’s tipping point • Preferred when there are just a few rows • Uses the index, but still gets a request for a covering index
  • 7. © 2019 Brent Ozar Unlimited®. All rights reserved. 7 Statistics IO, TIME show just how expensive Reputation = 1 Reputation = 2 Scans the clustered index, which only does 80,290 reads. Takes ~15 seconds of CPU time, 4 seconds of clock time. Seek + key lookup, but needs 16,268 reads because we fetched 5,305 rows. Takes hardly any time at all. The scorecard Plain T-SQL Reputation = 1 Duration 4.3s CPU Time 14.6s Logical Reads 80,290 Reputation = 2 Duration 0.3 CPU Time 0 Logical Reads 16,268
  • 8. © 2019 Brent Ozar Unlimited®. All rights reserved. 8 SELECT * FROM dbo.Users WHERE Reputation=1; GO SELECT * FROM dbo.Users WHERE Reputation=2; GO SQL Server uses these literals to pick a plan These estimated row counts come from statistics Just like you learned in “How to Think Like the Engine”…
  • 9. © 2019 Brent Ozar Unlimited®. All rights reserved. 9 SQL Server checks the Reputation = ___ number against your statistics Index statistics • These are auto-generated when you create the index Column statistics • Automatically created on the fly when you run queries • These have the “_WA_Sys” cryptic names CREATE PROCEDURE dbo.UsersByReputation @Reputation int AS SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=@Reputation ORDER BY DisplayName; GO EXEC dbo.UsersByReputation @Reputation =1; GO EXEC dbo.UsersByReputation @Reputation =2; GO This does the same thing, right?
  • 10. © 2019 Brent Ozar Unlimited®. All rights reserved. 10 Well… no. Right click on the second execution plan…
  • 11. © 2019 Brent Ozar Unlimited®. All rights reserved. 11 Scroll to the bottom of the XML… Compiled value and runtime value are different The compiled value came from the first time it was run This parameter was “sniffed” It’s really not that bad, though. Reputation = 1 Reputation = 2 Still scans the clustered index, which only does 80,290 reads. Takes ~15 seconds of CPU time, 4 seconds of clock time. Scans the whole table, but… It’s still fast! Well, pretty quick.
  • 12. © 2019 Brent Ozar Unlimited®. All rights reserved. 12 The scorecard: not really a big deal. Plain T-SQL Proc, Rep = 1 called first Reputation = 1 Duration 4.3s 4.3s CPU Time 14.6s 14.6s Logical Reads 80,290 80,290 Reputation = 2 Duration 0.3 0.4 CPU Time 0.0 0.5 Logical Reads 16,268 80,486 Still consistent Few people will notice Worse, but who cares? People don’t complain about this kind of parameter sniffing because they don’t even notice it. Heck, they’d notice it if it WASN’T happening. Sniffing saves us from CPU-burning compiles. Query that compiles each time – run 5K times Query using cached plan – run 5K times % Processor Time on a 2 processor VM. Nothing running but this query.
  • 13. © 2019 Brent Ozar Unlimited®. All rights reserved. 13 But what happens if… Windows restarts The SQL Server service restarts Someone runs DBCC FREEPROCCACHE Indexes on the Users table are rebuilt Statistics on the Users table are updated The server comes under memory pressure And the queries are run in a different order? That’s not good. Now we have a query plan optimized for tiny amounts of data, just 5,305 expected rows. See the yellow bangs? Both queries have problems. More on that later.
  • 14. © 2019 Brent Ozar Unlimited®. All rights reserved. 14 It gets worse. Much, much worse. Reputation = 2 Reputation = 1 Perfect! Just 16,268 reads. Super-fast too! TEN MILLION LOGICAL READS SEVENTEEN SECOND RUNTIME Note: 2 first The scorecard: THIS is parameter sniffing. Plain T-SQL Proc, Rep = 1 called first Proc, Rep = 2 called first Reputation = 1 Duration 4.3s 4.3s 16.9s CPU Time 14.6s 14.6s 15.6s Logical Reads 80,290 80,290 10,046,724 Reputation = 2 Duration 0.3 0.4 0.2 CPU Time 0.0 0.5 0.0 Logical Reads 16,268 80,486 16,268 OMG OMG When people complain about parameter sniffing, THIS is the scenario they’re complaining about.
  • 15. © 2019 Brent Ozar Unlimited®. All rights reserved. 15 Why so bad? The estimates are cached for the first parameter we use: • Row estimates • Estimated cost (which may be way below the Cost Threshold for Parallelism) • Memory grants That was the easy part.
  • 16. © 2019 Brent Ozar Unlimited®. All rights reserved. 16 2. How to respond to parameter sniffing emergencies Next up, let’s just try not to freak out The career progression of a perf tuner “Let’s restart Windows!” “Let’s restart the SQL Server service!” “Let’s run DBCC FREEPROCCACHE!” “Let’s rebuild all the indexes!” “Let’s rebuild the indexes on the one table involved!” “Let’s update statistics on the table!” “Let’s just clear this one plan from cache.”
  • 17. © 2019 Brent Ozar Unlimited®. All rights reserved. 17 How to free one plan from cache Run sp_BlitzCache @ExpertMode = 1 Find the query that’s not usually on the suckerboard, because he probably just got an unusually bad plan today Scroll to the far right, and check out: DBCC FREEPROCCACHE (mycrappysqlhandle) Save the execution plan, then free it from cache. Did the emergency stop? If so, you’ve found your culprit. 3. 7 ways to fix it for good
  • 18. © 2019 Brent Ozar Unlimited®. All rights reserved. 18 Option recompile, right? KB 968693 (from 2009)
  • 19. © 2019 Brent Ozar Unlimited®. All rights reserved. 19 That’ll never happen again, right? KB 2965069 (from 2014)
  • 20. © 2019 Brent Ozar Unlimited®. All rights reserved. 20 Yeah. So about that option recompile. Now you’re waiting to hear the option that doesn’t suck.
  • 21. © 2019 Brent Ozar Unlimited®. All rights reserved. 21 All these options suck. You just have to find the right one for each parameter sniffing problem, and every problem is different. You have a decision to make. Can you get one good plan for all parameters? • OPTIMIZE FOR UNKNOWN • Declare a local variable • OPTIMIZE FOR specific value • Plan guides • Covering indexes Or do you need different plans for different parameters? • OPTION RECOMPILE • Stored procedure branching
  • 22. © 2019 Brent Ozar Unlimited®. All rights reserved. 22 ALTER PROCEDURE dbo.UsersByReputation @Reputation INT WITH RECOMPILE AS SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=@Reputation ORDER BY DisplayName; Option RECOMPILE for the entire proc ALTER PROCEDURE dbo.UsersByReputation @Reputation INT WITH RECOMPILE AS SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=@Reputation ORDER BY DisplayName; Option RECOMPILE for the entire proc N E V E R D O T H I S * Unless you purposely want to hide your code from many monitoring tools, hee hee.
  • 23. © 2019 Brent Ozar Unlimited®. All rights reserved. 23 ALTER PROCEDURE dbo.UsersByReputation @Reputation INT AS SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=@Reputation ORDER BY DisplayName OPTION (RECOMPILE); Option RECOMPILE at the statement level Option RECOMPILE at the statement level Plan cache won’t track statement-level query stats (although it will track stored-proc-level, you just won’t know which queries were the expensive ones) Burns CPU for every execution, compiling a new plan Makes sense for rarely-run, wildly variable stored procs (like once every minute or two, max)
  • 24. © 2019 Brent Ozar Unlimited®. All rights reserved. 24 ALTER PROCEDURE UsersByReputation @Reputation INT AS IF @Reputation = 1 EXEC UsersByReputation_1 @1 ELSE EXEC UsersByReputation_Other @1 Stored procedure branching Stored procedure branching Like optimizing for a specific value: • You’d better know your data pretty well. • Your data better not change over time. But now you can have 2 different sub-procedures, each of which gets its own optimized plan. They could even have the same code in them: they’ll just get sniffed for the right values, and get the right plans. (This is a pretty rarely used trick.)
  • 25. © 2019 Brent Ozar Unlimited®. All rights reserved. 25 ALTER PROCEDURE dbo.UsersByReputation @Reputation INT AS SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=@Reputation ORDER BY DisplayName OPTION (OPTIMIZE FOR UNKNOWN); GO OPTIMIZE FOR UNKNOWN OPTIMIZE FOR UNKNOWN This forces everyone to use the density vector (just like a local variable). In this case, it simply doesn’t work: the density vector gives us a 314 estimate, which isn’t anywhere near our real-world numbers for reputation 1 or 2. In some cases, with widely spread-out data, this can work.
  • 26. © 2019 Brent Ozar Unlimited®. All rights reserved. 26 ALTER PROCEDURE dbo.UsersByReputation @Reputation INT AS DECLARE @ReputationUnknown INT; SET @ReputationUnknown = @Reputation; SELECT TOP 10000 * FROM dbo.Users WHERE Reputation = @ReputationUnknown ORDER BY DisplayName; GO Fake “OPTIMIZE FOR UNKNOWN” ALTER PROCEDURE dbo.UsersByReputation @Reputation INT AS DECLARE @ReputationUnknown INT; SET @ReputationUnknown = @Reputation; SELECT TOP 10000 * FROM dbo.Users WHERE Reputation = @ReputationUnknown ORDER BY DisplayName; GO Fake “OPTIMIZE FOR UNKNOWN” N E V E R D O T H I S
  • 27. © 2019 Brent Ozar Unlimited®. All rights reserved. 27 Fake “OPTIMIZE FOR UNKNOWN” Exact same results as Optimize For Unknown The “Optimize for Unknown” hint was added in SQL Server 2008 Prior to that, people did the “create another variable” trick sometimes It has the same downsides: • Often just not a very good execution plan • May not be a stable plan over time But you look like an idiot, and people overwrite your code. ALTER PROCEDURE dbo.UsersByReputation @Reputation INT AS SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=@Reputation ORDER BY DisplayName OPTION (OPTIMIZE FOR UNKNOWN); GO If you want the density vector, use this instead.
  • 28. © 2019 Brent Ozar Unlimited®. All rights reserved. 28 ALTER PROCEDURE dbo.UsersByReputation @Reputation INT AS SELECT TOP 10000 * FROM dbo.Users WHERE Reputation=@Reputation ORDER BY DisplayName OPTION (OPTIMIZE FOR @Reputation = 1) OPTIMIZE FOR Value OPTIMIZE FOR Value You’d better know your data pretty well. Your data better not change over time.
  • 29. © 2019 Brent Ozar Unlimited®. All rights reserved. 29 Plan guides You identify a very exact string, and the right query plan for it You guide the plan: that plan sticks around even after restarts 2016’s Query Store makes this point-and-click easy But it’s up to you to: • Identify the string • Construct the right query plan • Know when you should un-pin it • Make sure it works, and that it stays working Plan guides fail silently. Query changes at all? Guide won’t work. Indexes in use disappeared? Guide stops working. Doesn’t fix issues like memory grants: if the memory ain’t there, the guide can’t do magic. I love plan guides to fix emergency problems, but they’re like duct tape. You need a better plan within 48-72 hours.
  • 30. © 2019 Brent Ozar Unlimited®. All rights reserved. 30 Hard solution: better plan for everyone Most parameter sniffing issues have a simple cause: • There’s no covering index, so • Sometimes a seek + key lookup is better, but • Sometimes a clustered index scan is better You could solve it by creating a better index that fits more scenarios. What about our demo query’s case? Multi-Plan Solutions Would it work? OPTION (RECOMPILE) Depends on frequency Stored procedure branching Yes Single-Plan Solutions Would it work? OPTIMIZE FOR UNKNOWN (or the internal local variable trick) No, it’d estimate 314.7 rows OPTIMIZE FOR @Reputation = 1 Yes Plan guide Yes, but will fail when the query changes Get one good plan for everyone Clippy’s covering index wouldn’t work, but a manual index would.
  • 31. © 2019 Brent Ozar Unlimited®. All rights reserved. 31 This is doable. Not easy, but doable. Recap
  • 32. © 2019 Brent Ozar Unlimited®. All rights reserved. 32 You learned 3 things 1. What parameter sniffing is 2. How to react to parameter sniffing emergencies: • sp_BlitzCache @ExpertMode = 1 • Save the plan • Use the “free from cache” columns at the far right 3. Options for fixing the problem long-term: there’s no easy button Learn more: BrentOzar.com/go/sniff