SlideShare une entreprise Scribd logo
1  sur  34
Télécharger pour lire hors ligne
The Two Faces of SQL
Parameter Sniffing
(or Just the Other Face)
About me
Project Manager @
11 years professional experience
MCPD .NET Web Development
ivelin.andreev@icb.bg
http://www.linkedin.com/in/ivelin
Business Interests
Web Development (ASP.NET, jQuery, AJAX)
SOA, Integration
GIS, Mapping
SQL optimization
2 |
Agenda
Execution plan cache
Parameter sniffing
Performance issues
Diagnostics
Solution options
Other RDBMS
Demos
Not all [animals] are created equal
Image source http://hateandanger.wordpress.com/2012/06/05/fair/
The Plan Cache
Execution plan cache (SQL Server)
Query plans
Ad hoc queries
Stored procedures and User functions
Triggers

Execution contexts (per user)

Retrieve plan
Retrieve: sys.dm_exec_query_plan (plan_handle)
Putting Query Plan in Cache
Compilation is CPU intensive
Plan evicted from cache when
ALTER PROCEDURE
sp_recompile
UPDATE STATISTICS (w/o SQL 2012)
DBCC FREEPROCCACHE
Cache buffer full

View cached plans
sys.dm_exec_query_stats
Variable run-time values - unknown for optimizer
Query Plan Generation
CREATE [PROCEDURE]
Syntactic check
No plan built at this point

Execution
Sniff parameters
Analyze distribution statistics
Create plan
Plan cache contains only estimated plans
Image source http://123child.com/images/mine/DSCN4763.JPG
Parameter Sniffing?
Def: Optimiser looking at input values
Estimates based on statistics
Notes
Applies to all versions of SQL Server
Local variables get standard assumption
Constants are not sniffed
Dr. Jekyll and Mr. Parameter Sniffing
Image source http://jtown67.deviantart.com/art/Jekyll-and-Hyde-352442994
When Parameter Sniffing Stinks
Parameter sniffing itself is not a problem
Until it is!

Negatively affecting performance?
1. Explain your customers
2. Other options ?
Performance problems caused by parameter
sniffing are considered to be by design
Typical Cases
1. Sniffing inappropriate for query usage
One group of calls very different from main bulk
Plan good for execution not appropriate for next
Index Seek + Key Lookup vs. Table Scan

2. No perfect index for the query
Not your DB design fault
Reproducible with AdventureWorks DB
DEMO 1: Reproduce parameter sniffing
Image source http://netdna.webdesignerdepot.com/uploads/2012/12/featured45@wdd2x.jpg
Gathering Information
DO NOT schedule DBCC FREEPROCCACHE
EXEC sp_recompile
If problem reoccurs:
(most likely)
Keep the slow plan to analyse it!
Which statement is slow?
Are there different query plans?
What are the index definitions?
What parameter values are sniffed
Are distribution statistics up to date?
Typical symptom is lots of logical reads
Cause and Symptoms
Cause: Cardinality Error
Huge difference - estimated/actual rows
Huge difference - resource cost for the same plan

Symptom: Logical Reads
Monitor deviation from average
Monitor high Min – Max fluctuations
DEMO 2: Gather information
Image source http://netdna.webdesignerdepot.com/uploads/2012/12/featured45@wdd2x.jpg
Solution 1 - Recompilation
Recompile SP on every execution
OPTION (RECOMPILE)
WITH RECOMPILE (Create/Execute)

Pros
The best query plan every time

Cons
CPU-intensive
Not suitable for SP used frequently
Plans not stored in cache (for debug)
Solution 2 – OPTIMIZE Query Hint
Use specified value when compiling the plan
You know a value that produces good plan
OPTION (OPTIMIZE FOR (@par=[Value]))
OPTIMIZE FOR UNKNOWN (SQL 2008 +)

Pros
“Good Enough” plan

Cons
Not for frequent data distribution changes
Solution 3 – Local Variables
Copy SP parameter to local variable
Pros
Same as “OPTIMIZE FOR UNKNOWN”
Works on every version of SQL server

Cons
Same as “OPTIMIZE FOR UNKNOWN”
Solution 4 – Trace Flag 4136
Average estimate instead of histogram stats
DBCC TRACEON (4136[, -1])

Pros
Evens “highs” and “lows”

Cons
Disables sniffing at SQL instance level
Affects all DBs
No benefit if data is evenly distributed
Solution 5 – Plan Guides
Attach fixed query plan to queries
Pros
Optimize query w/o changes in SQL text
3rd party vendor SQL optimization

Cons
Only one guide enabled for object
Modify object referred by plan guide causes error
DEMO 3: Fix parameter sniffing
Image source http://netdna.webdesignerdepot.com/uploads/2012/12/featured45@wdd2x.jpg
When it may not be Sniffing
SET Options
Many are cache keys
Causes different entries for one SP
ARITHABORT
Terminates query on overflow / divide-by-zero
SET ARITHABORT ON/OFF
Defaults (OFF – ADO.NET, ON - SSMS)

Always match ARITHABORT on troubleshoot
Poorly written SQL is always slow
Parameter Sniffing and Other RDMS
Bind Variable Peeking
Adaptive Cursor Sharing (11g) 2007
Enables statement to use multiple plans
Identify “bind-sensitive” cursor
Promote to “bind-aware” cursor
Track expected/actual operator cardinalities
Cache and use new plan

Notes
Enabled by default
Does not apply for >14 bind variables
Microsoft will fix that… When pigs fly
http://connect.microsoft.com/SQLServer/feedback/details/377959/
The Two Faces (Summary)
Dr. Jekyll
Parameter sniffing is not bad
Useful for performance tuning
Integral part of SQL server
Learn how to diagnose

Mr. Hyde
Until it is
At great cost for server
Oracle fixed it
Apply non-ideal solutions
Uneven data distribution and cost cannot be
derived. It is the optimiser that failed
Image source http://blogs.urbancode.com/agile/maslows-hammer-the-curse-of-tool-blindness
Credits
Milos Radivojevic
DB developer, Consultant, Speaker
http://sqlbits.com/Speakers/Milos_Radivojevic

Erland Sommarskog
SQL Server MVP
Consultant
http://www.sommarskog.se/
Sponsors

Contenu connexe

Tendances

Hovitaga OpenSQL Editor - Overview
Hovitaga OpenSQL Editor - OverviewHovitaga OpenSQL Editor - Overview
Hovitaga OpenSQL Editor - OverviewHovitaga Kft.
 
Taming the Data Science Monster with A New ‘Sword’ – U-SQL
Taming the Data Science Monster with A New ‘Sword’ – U-SQLTaming the Data Science Monster with A New ‘Sword’ – U-SQL
Taming the Data Science Monster with A New ‘Sword’ – U-SQLMichael Rys
 
Challenges on Distributed Machine Learning
Challenges on Distributed Machine LearningChallenges on Distributed Machine Learning
Challenges on Distributed Machine Learningjie cao
 
Hadoop training in bangalore
Hadoop training in bangaloreHadoop training in bangalore
Hadoop training in bangaloreTIB Academy
 
Distributed machine learning
Distributed machine learningDistributed machine learning
Distributed machine learningStanley Wang
 
Reproducible AI using MLflow and PyTorch
Reproducible AI using MLflow and PyTorchReproducible AI using MLflow and PyTorch
Reproducible AI using MLflow and PyTorchDatabricks
 
Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers, Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers, TIB Academy
 
Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...
Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...
Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...Rodney Joyce
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlnishantdavid9
 
Gender Prediction with Databricks AutoML Pipeline
Gender Prediction with Databricks AutoML PipelineGender Prediction with Databricks AutoML Pipeline
Gender Prediction with Databricks AutoML PipelineDatabricks
 

Tendances (10)

Hovitaga OpenSQL Editor - Overview
Hovitaga OpenSQL Editor - OverviewHovitaga OpenSQL Editor - Overview
Hovitaga OpenSQL Editor - Overview
 
Taming the Data Science Monster with A New ‘Sword’ – U-SQL
Taming the Data Science Monster with A New ‘Sword’ – U-SQLTaming the Data Science Monster with A New ‘Sword’ – U-SQL
Taming the Data Science Monster with A New ‘Sword’ – U-SQL
 
Challenges on Distributed Machine Learning
Challenges on Distributed Machine LearningChallenges on Distributed Machine Learning
Challenges on Distributed Machine Learning
 
Hadoop training in bangalore
Hadoop training in bangaloreHadoop training in bangalore
Hadoop training in bangalore
 
Distributed machine learning
Distributed machine learningDistributed machine learning
Distributed machine learning
 
Reproducible AI using MLflow and PyTorch
Reproducible AI using MLflow and PyTorchReproducible AI using MLflow and PyTorch
Reproducible AI using MLflow and PyTorch
 
Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers, Hadoop tutorial for Freshers,
Hadoop tutorial for Freshers,
 
Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...
Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...
Data Science for Dummies - Data Engineering with Titanic dataset + Databricks...
 
Stored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sqlStored procedure tuning and optimization t sql
Stored procedure tuning and optimization t sql
 
Gender Prediction with Databricks AutoML Pipeline
Gender Prediction with Databricks AutoML PipelineGender Prediction with Databricks AutoML Pipeline
Gender Prediction with Databricks AutoML Pipeline
 

Similaire à The two faces of sql parameter sniffing

Data modeling star schema
Data modeling star schemaData modeling star schema
Data modeling star schemaSayed Ahmed
 
Be a database professional
Be a database professionalBe a database professional
Be a database professionalSayed Ahmed
 
Be a database professional
Be a database professionalBe a database professional
Be a database professionalSayed Ahmed
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimizationPractical SQL query monitoring and optimization
Practical SQL query monitoring and optimizationIvo Andreev
 
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginners
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginnersSQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginners
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginnersTobias Koprowski
 
Database migration from Sybase ASE to PostgreSQL @2013.pgconf.eu
Database migration from Sybase ASE to PostgreSQL @2013.pgconf.euDatabase migration from Sybase ASE to PostgreSQL @2013.pgconf.eu
Database migration from Sybase ASE to PostgreSQL @2013.pgconf.eualdaschwede80
 
SQL Server Query Optimization, Execution and Debugging Query Performance
SQL Server Query Optimization, Execution and Debugging Query PerformanceSQL Server Query Optimization, Execution and Debugging Query Performance
SQL Server Query Optimization, Execution and Debugging Query PerformanceVinod Kumar
 
Designing For Occasionally Connected Apps Slideshare
Designing For Occasionally Connected Apps SlideshareDesigning For Occasionally Connected Apps Slideshare
Designing For Occasionally Connected Apps SlideshareDean Willson
 
Datastage Online Training @ Adithya Elearning
Datastage Online Training @ Adithya ElearningDatastage Online Training @ Adithya Elearning
Datastage Online Training @ Adithya Elearningshanmukha rao dondapati
 
Very large scale distributed deep learning on BigDL
Very large scale distributed deep learning on BigDLVery large scale distributed deep learning on BigDL
Very large scale distributed deep learning on BigDLDESMOND YUEN
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part isqlserver.co.il
 
Ops Jumpstart: MongoDB Administration 101
Ops Jumpstart: MongoDB Administration 101Ops Jumpstart: MongoDB Administration 101
Ops Jumpstart: MongoDB Administration 101MongoDB
 
Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...
Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...
Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...Databricks
 
SQL Server - High availability
SQL Server - High availabilitySQL Server - High availability
SQL Server - High availabilityPeter Gfader
 
An approach to implement model classes in zend
An approach to implement model classes in zendAn approach to implement model classes in zend
An approach to implement model classes in zendswiss IT bridge
 
Mow2012 data services
Mow2012 data servicesMow2012 data services
Mow2012 data servicesSyed Shaaf
 

Similaire à The two faces of sql parameter sniffing (20)

Data modeling star schema
Data modeling star schemaData modeling star schema
Data modeling star schema
 
Be a database professional
Be a database professionalBe a database professional
Be a database professional
 
Be a database professional
Be a database professionalBe a database professional
Be a database professional
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimizationPractical SQL query monitoring and optimization
Practical SQL query monitoring and optimization
 
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginners
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginnersSQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginners
SQLSaturday#290_Kiev_AdHocMaintenancePlansForBeginners
 
Database migration from Sybase ASE to PostgreSQL @2013.pgconf.eu
Database migration from Sybase ASE to PostgreSQL @2013.pgconf.euDatabase migration from Sybase ASE to PostgreSQL @2013.pgconf.eu
Database migration from Sybase ASE to PostgreSQL @2013.pgconf.eu
 
Sql good practices
Sql good practicesSql good practices
Sql good practices
 
SQL Server Query Optimization, Execution and Debugging Query Performance
SQL Server Query Optimization, Execution and Debugging Query PerformanceSQL Server Query Optimization, Execution and Debugging Query Performance
SQL Server Query Optimization, Execution and Debugging Query Performance
 
Designing For Occasionally Connected Apps Slideshare
Designing For Occasionally Connected Apps SlideshareDesigning For Occasionally Connected Apps Slideshare
Designing For Occasionally Connected Apps Slideshare
 
Datastage Online Training @ Adithya Elearning
Datastage Online Training @ Adithya ElearningDatastage Online Training @ Adithya Elearning
Datastage Online Training @ Adithya Elearning
 
Very large scale distributed deep learning on BigDL
Very large scale distributed deep learning on BigDLVery large scale distributed deep learning on BigDL
Very large scale distributed deep learning on BigDL
 
Resume
ResumeResume
Resume
 
Ashutosh_Resume
Ashutosh_Resume Ashutosh_Resume
Ashutosh_Resume
 
1 extreme performance - part i
1   extreme performance - part i1   extreme performance - part i
1 extreme performance - part i
 
Ops Jumpstart: MongoDB Administration 101
Ops Jumpstart: MongoDB Administration 101Ops Jumpstart: MongoDB Administration 101
Ops Jumpstart: MongoDB Administration 101
 
Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...
Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...
Accelerating Deep Learning Training with BigDL and Drizzle on Apache Spark wi...
 
SQL Server - High availability
SQL Server - High availabilitySQL Server - High availability
SQL Server - High availability
 
An approach to implement model classes in zend
An approach to implement model classes in zendAn approach to implement model classes in zend
An approach to implement model classes in zend
 
Mow2012 data services
Mow2012 data servicesMow2012 data services
Mow2012 data services
 
DavidWible_res
DavidWible_resDavidWible_res
DavidWible_res
 

Plus de Ivo Andreev

Cybersecurity and Generative AI - for Good and Bad vol.2
Cybersecurity and Generative AI - for Good and Bad vol.2Cybersecurity and Generative AI - for Good and Bad vol.2
Cybersecurity and Generative AI - for Good and Bad vol.2Ivo Andreev
 
Architecting AI Solutions in Azure for Business
Architecting AI Solutions in Azure for BusinessArchitecting AI Solutions in Azure for Business
Architecting AI Solutions in Azure for BusinessIvo Andreev
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadIvo Andreev
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIIvo Andreev
 
How do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for DevelopersHow do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for DevelopersIvo Andreev
 
OpenAI GPT in Depth - Questions and Misconceptions
OpenAI GPT in Depth - Questions and MisconceptionsOpenAI GPT in Depth - Questions and Misconceptions
OpenAI GPT in Depth - Questions and MisconceptionsIvo Andreev
 
Cutting Edge Computer Vision for Everyone
Cutting Edge Computer Vision for EveryoneCutting Edge Computer Vision for Everyone
Cutting Edge Computer Vision for EveryoneIvo Andreev
 
Collecting and Analysing Spaceborn Data
Collecting and Analysing Spaceborn DataCollecting and Analysing Spaceborn Data
Collecting and Analysing Spaceborn DataIvo Andreev
 
Collecting and Analysing Satellite Data with Azure Orbital
Collecting and Analysing Satellite Data with Azure OrbitalCollecting and Analysing Satellite Data with Azure Orbital
Collecting and Analysing Satellite Data with Azure OrbitalIvo Andreev
 
Language Studio and Custom Models
Language Studio and Custom ModelsLanguage Studio and Custom Models
Language Studio and Custom ModelsIvo Andreev
 
CosmosDB for IoT Scenarios
CosmosDB for IoT ScenariosCosmosDB for IoT Scenarios
CosmosDB for IoT ScenariosIvo Andreev
 
Forecasting time series powerful and simple
Forecasting time series powerful and simpleForecasting time series powerful and simple
Forecasting time series powerful and simpleIvo Andreev
 
Constrained Optimization with Genetic Algorithms and Project Bonsai
Constrained Optimization with Genetic Algorithms and Project BonsaiConstrained Optimization with Genetic Algorithms and Project Bonsai
Constrained Optimization with Genetic Algorithms and Project BonsaiIvo Andreev
 
Azure security guidelines for developers
Azure security guidelines for developers Azure security guidelines for developers
Azure security guidelines for developers Ivo Andreev
 
Autonomous Machines with Project Bonsai
Autonomous Machines with Project BonsaiAutonomous Machines with Project Bonsai
Autonomous Machines with Project BonsaiIvo Andreev
 
Global azure virtual 2021 - Azure Lighthouse
Global azure virtual 2021 - Azure LighthouseGlobal azure virtual 2021 - Azure Lighthouse
Global azure virtual 2021 - Azure LighthouseIvo Andreev
 
Flux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JSFlux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JSIvo Andreev
 
Azure architecture design patterns - proven solutions to common challenges
Azure architecture design patterns - proven solutions to common challengesAzure architecture design patterns - proven solutions to common challenges
Azure architecture design patterns - proven solutions to common challengesIvo Andreev
 
Industrial IoT on Azure
Industrial IoT on AzureIndustrial IoT on Azure
Industrial IoT on AzureIvo Andreev
 
The Power of Auto ML and How Does it Work
The Power of Auto ML and How Does it WorkThe Power of Auto ML and How Does it Work
The Power of Auto ML and How Does it WorkIvo Andreev
 

Plus de Ivo Andreev (20)

Cybersecurity and Generative AI - for Good and Bad vol.2
Cybersecurity and Generative AI - for Good and Bad vol.2Cybersecurity and Generative AI - for Good and Bad vol.2
Cybersecurity and Generative AI - for Good and Bad vol.2
 
Architecting AI Solutions in Azure for Business
Architecting AI Solutions in Azure for BusinessArchitecting AI Solutions in Azure for Business
Architecting AI Solutions in Azure for Business
 
Cybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and BadCybersecurity Challenges with Generative AI - for Good and Bad
Cybersecurity Challenges with Generative AI - for Good and Bad
 
JS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AIJS-Experts - Cybersecurity for Generative AI
JS-Experts - Cybersecurity for Generative AI
 
How do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for DevelopersHow do OpenAI GPT Models Work - Misconceptions and Tips for Developers
How do OpenAI GPT Models Work - Misconceptions and Tips for Developers
 
OpenAI GPT in Depth - Questions and Misconceptions
OpenAI GPT in Depth - Questions and MisconceptionsOpenAI GPT in Depth - Questions and Misconceptions
OpenAI GPT in Depth - Questions and Misconceptions
 
Cutting Edge Computer Vision for Everyone
Cutting Edge Computer Vision for EveryoneCutting Edge Computer Vision for Everyone
Cutting Edge Computer Vision for Everyone
 
Collecting and Analysing Spaceborn Data
Collecting and Analysing Spaceborn DataCollecting and Analysing Spaceborn Data
Collecting and Analysing Spaceborn Data
 
Collecting and Analysing Satellite Data with Azure Orbital
Collecting and Analysing Satellite Data with Azure OrbitalCollecting and Analysing Satellite Data with Azure Orbital
Collecting and Analysing Satellite Data with Azure Orbital
 
Language Studio and Custom Models
Language Studio and Custom ModelsLanguage Studio and Custom Models
Language Studio and Custom Models
 
CosmosDB for IoT Scenarios
CosmosDB for IoT ScenariosCosmosDB for IoT Scenarios
CosmosDB for IoT Scenarios
 
Forecasting time series powerful and simple
Forecasting time series powerful and simpleForecasting time series powerful and simple
Forecasting time series powerful and simple
 
Constrained Optimization with Genetic Algorithms and Project Bonsai
Constrained Optimization with Genetic Algorithms and Project BonsaiConstrained Optimization with Genetic Algorithms and Project Bonsai
Constrained Optimization with Genetic Algorithms and Project Bonsai
 
Azure security guidelines for developers
Azure security guidelines for developers Azure security guidelines for developers
Azure security guidelines for developers
 
Autonomous Machines with Project Bonsai
Autonomous Machines with Project BonsaiAutonomous Machines with Project Bonsai
Autonomous Machines with Project Bonsai
 
Global azure virtual 2021 - Azure Lighthouse
Global azure virtual 2021 - Azure LighthouseGlobal azure virtual 2021 - Azure Lighthouse
Global azure virtual 2021 - Azure Lighthouse
 
Flux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JSFlux QL - Nexgen Management of Time Series Inspired by JS
Flux QL - Nexgen Management of Time Series Inspired by JS
 
Azure architecture design patterns - proven solutions to common challenges
Azure architecture design patterns - proven solutions to common challengesAzure architecture design patterns - proven solutions to common challenges
Azure architecture design patterns - proven solutions to common challenges
 
Industrial IoT on Azure
Industrial IoT on AzureIndustrial IoT on Azure
Industrial IoT on Azure
 
The Power of Auto ML and How Does it Work
The Power of Auto ML and How Does it WorkThe Power of Auto ML and How Does it Work
The Power of Auto ML and How Does it Work
 

Dernier

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...masabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrandmasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdfPearlKirahMaeRagusta1
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...masabamasaba
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareJim McKeeth
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024Mind IT Systems
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durbanmasabamasaba
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfVishalKumarJha10
 

Dernier (20)

call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
%+27788225528 love spells in Vancouver Psychic Readings, Attraction spells,Br...
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand%in Midrand+277-882-255-28 abortion pills for sale in midrand
%in Midrand+277-882-255-28 abortion pills for sale in midrand
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
Define the academic and professional writing..pdf
Define the academic and professional writing..pdfDefine the academic and professional writing..pdf
Define the academic and professional writing..pdf
 
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
%+27788225528 love spells in new york Psychic Readings, Attraction spells,Bri...
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
Announcing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK SoftwareAnnouncing Codolex 2.0 from GDK Software
Announcing Codolex 2.0 from GDK Software
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
10 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 202410 Trends Likely to Shape Enterprise Technology in 2024
10 Trends Likely to Shape Enterprise Technology in 2024
 
%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban%in Durban+277-882-255-28 abortion pills for sale in Durban
%in Durban+277-882-255-28 abortion pills for sale in Durban
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdfintroduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
introduction-to-automotive Andoid os-csimmonds-ndctechtown-2021.pdf
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 

The two faces of sql parameter sniffing

  • 1. The Two Faces of SQL Parameter Sniffing (or Just the Other Face)
  • 2. About me Project Manager @ 11 years professional experience MCPD .NET Web Development ivelin.andreev@icb.bg http://www.linkedin.com/in/ivelin Business Interests Web Development (ASP.NET, jQuery, AJAX) SOA, Integration GIS, Mapping SQL optimization 2 |
  • 3. Agenda Execution plan cache Parameter sniffing Performance issues Diagnostics Solution options Other RDBMS Demos
  • 4. Not all [animals] are created equal Image source http://hateandanger.wordpress.com/2012/06/05/fair/
  • 5. The Plan Cache Execution plan cache (SQL Server) Query plans Ad hoc queries Stored procedures and User functions Triggers Execution contexts (per user) Retrieve plan Retrieve: sys.dm_exec_query_plan (plan_handle)
  • 6. Putting Query Plan in Cache Compilation is CPU intensive Plan evicted from cache when ALTER PROCEDURE sp_recompile UPDATE STATISTICS (w/o SQL 2012) DBCC FREEPROCCACHE Cache buffer full View cached plans sys.dm_exec_query_stats
  • 7. Variable run-time values - unknown for optimizer
  • 8. Query Plan Generation CREATE [PROCEDURE] Syntactic check No plan built at this point Execution Sniff parameters Analyze distribution statistics Create plan
  • 9. Plan cache contains only estimated plans Image source http://123child.com/images/mine/DSCN4763.JPG
  • 10. Parameter Sniffing? Def: Optimiser looking at input values Estimates based on statistics Notes Applies to all versions of SQL Server Local variables get standard assumption Constants are not sniffed
  • 11. Dr. Jekyll and Mr. Parameter Sniffing Image source http://jtown67.deviantart.com/art/Jekyll-and-Hyde-352442994
  • 12. When Parameter Sniffing Stinks Parameter sniffing itself is not a problem Until it is! Negatively affecting performance? 1. Explain your customers 2. Other options ?
  • 13. Performance problems caused by parameter sniffing are considered to be by design
  • 14. Typical Cases 1. Sniffing inappropriate for query usage One group of calls very different from main bulk Plan good for execution not appropriate for next Index Seek + Key Lookup vs. Table Scan 2. No perfect index for the query Not your DB design fault Reproducible with AdventureWorks DB
  • 15. DEMO 1: Reproduce parameter sniffing Image source http://netdna.webdesignerdepot.com/uploads/2012/12/featured45@wdd2x.jpg
  • 16. Gathering Information DO NOT schedule DBCC FREEPROCCACHE EXEC sp_recompile If problem reoccurs: (most likely) Keep the slow plan to analyse it! Which statement is slow? Are there different query plans? What are the index definitions? What parameter values are sniffed Are distribution statistics up to date?
  • 17. Typical symptom is lots of logical reads
  • 18. Cause and Symptoms Cause: Cardinality Error Huge difference - estimated/actual rows Huge difference - resource cost for the same plan Symptom: Logical Reads Monitor deviation from average Monitor high Min – Max fluctuations
  • 19. DEMO 2: Gather information Image source http://netdna.webdesignerdepot.com/uploads/2012/12/featured45@wdd2x.jpg
  • 20. Solution 1 - Recompilation Recompile SP on every execution OPTION (RECOMPILE) WITH RECOMPILE (Create/Execute) Pros The best query plan every time Cons CPU-intensive Not suitable for SP used frequently Plans not stored in cache (for debug)
  • 21. Solution 2 – OPTIMIZE Query Hint Use specified value when compiling the plan You know a value that produces good plan OPTION (OPTIMIZE FOR (@par=[Value])) OPTIMIZE FOR UNKNOWN (SQL 2008 +) Pros “Good Enough” plan Cons Not for frequent data distribution changes
  • 22. Solution 3 – Local Variables Copy SP parameter to local variable Pros Same as “OPTIMIZE FOR UNKNOWN” Works on every version of SQL server Cons Same as “OPTIMIZE FOR UNKNOWN”
  • 23. Solution 4 – Trace Flag 4136 Average estimate instead of histogram stats DBCC TRACEON (4136[, -1]) Pros Evens “highs” and “lows” Cons Disables sniffing at SQL instance level Affects all DBs No benefit if data is evenly distributed
  • 24. Solution 5 – Plan Guides Attach fixed query plan to queries Pros Optimize query w/o changes in SQL text 3rd party vendor SQL optimization Cons Only one guide enabled for object Modify object referred by plan guide causes error
  • 25. DEMO 3: Fix parameter sniffing Image source http://netdna.webdesignerdepot.com/uploads/2012/12/featured45@wdd2x.jpg
  • 26. When it may not be Sniffing SET Options Many are cache keys Causes different entries for one SP ARITHABORT Terminates query on overflow / divide-by-zero SET ARITHABORT ON/OFF Defaults (OFF – ADO.NET, ON - SSMS) Always match ARITHABORT on troubleshoot
  • 27. Poorly written SQL is always slow
  • 28. Parameter Sniffing and Other RDMS Bind Variable Peeking Adaptive Cursor Sharing (11g) 2007 Enables statement to use multiple plans Identify “bind-sensitive” cursor Promote to “bind-aware” cursor Track expected/actual operator cardinalities Cache and use new plan Notes Enabled by default Does not apply for >14 bind variables
  • 29. Microsoft will fix that… When pigs fly
  • 31. The Two Faces (Summary) Dr. Jekyll Parameter sniffing is not bad Useful for performance tuning Integral part of SQL server Learn how to diagnose Mr. Hyde Until it is At great cost for server Oracle fixed it Apply non-ideal solutions
  • 32. Uneven data distribution and cost cannot be derived. It is the optimiser that failed Image source http://blogs.urbancode.com/agile/maslows-hammer-the-curse-of-tool-blindness
  • 33. Credits Milos Radivojevic DB developer, Consultant, Speaker http://sqlbits.com/Speakers/Milos_Radivojevic Erland Sommarskog SQL Server MVP Consultant http://www.sommarskog.se/