SlideShare uma empresa Scribd logo
1 de 21
Baixar para ler offline
NASI SPONSORZY I PARTNERZY
Stored Procedures –
Facts and Myths
Marcin Szeliga
www.sqlexpert.pl
http://blog.sqlexpert.pl/
http://www.facebook.com/SQLExpertpl
marcin@sqlexpert.pl
Agenda
• Basic Fact - Plan Caching and Reuse is (usually) a
Good Thing
• Obvious Consequence – You Should Avoid
Recompilations …
• But Sometimes Plan Reusing is a Bad Thing
• Recap
Plan Caching and Reuse is a Good
Thing
• Stored procedures
– Are a convenient container for code reuse
• They can be called many times and the query plans can be
reused, saving the time, CPU and memory

– Are optimized and compiled during their first execution
• Optimization is based on parameters supplied during this
execution
• Future executions will reuse the query plan stored in plan
cache
• There are at most two instances of a query plan at any time in
plan cache:
– One for all of the serial executions.
– One for all of the parallel executions

• From a query plan, an execution context is derived
– Execution contexts hold the values needed for a specific execution of
a query plan, and they are also cached and reused
Does compilation/recompilation
really matter?
• In terms of time
– Compilation is really expensive and CPU-heavy process

• In terms of memory
– Storing large number of execution plans the procedure cache “steals”
memory from the Buffer Pool
– The currently used formula looks like this:
• 75% 0-4GB + 10% 4-64GB + 5% 64GB
– On 16GB box 4.2 GB may be used for the procedure cache

• In terms of concurrency
– Getaways throttle simultaneous compilation to really small number
• Three of them:
– Small - 4 x number of logical CPUs allocated to SQL Server
– Medium - Number of logical CPUs allocated to SQL Server
– Large - 1

• Look for 'RESOURCE_SEMAPHORE_QUERY_COMPILE' wait
Demo
• Measuring compilation cost, in terms of time and
memory
• Looking inside the Procedure Cache
Stored procedures are not the only
option
• SQL Server can cache query plans for different types of
batches beside ad-hoc queries and stored procedures:
– Query preparation
• ODBC and OLE DB expose this functionality via
SQLPrepare/SQLExecute and ICommandPrepare interfaces
• Very similar result can be achieved by using sp_executesql

– Simple parameterization
• SQL Server automatically replaces constant literal values
with variables before the query plan will be compiled
• SQL Server 2008 allows us to forced parameterization of
almost all types of queries

– Dynamic SQL
• Strings submitted via EXEC for execution
Demo
• Checking two other options: query preparation and
forced parameterization
Avoiding recompilations due to plan
stability-related reasons
• Stored procedure (or a batch) must be recompiled if
not doing so would result in incorrect results or
actions
• 14 recompilation reasons
• 2 sub-categories:
– Scheme changes
– SET options changes
Recompilation due to schema
changes
• Putting all DML statements at the beginning of a stored
procedure will NOT minimize recompilations
– SQL Server 2005 onwards does statement level recompilations
• Deferred compilations mean that objects didn't exist during
creation the stored procedure

• The only solution is to use temporary tables
– SQL Server caches temporary objects but altering definitions of
those temporary objects disables this caching mechanism
• In addition, objects cannot have named constraints

• Accessing objects created outside the current scope requires
object id to name resolution
– Recompilation due to the changed scheme occurs
Demo
• Avoiding recompilation due to schema changes
Recompilation due to SET option
changes
• When an execution plan is created, the SQL Server stores
the environmental setting with it
– Some SET options used when the stored procedure was
created or altered will be saved as part of its metadata
– Some execution plan attributes are considered cache key
ones

• Subsequent execution will not trigger recompilations
– During the first execution a procedure is recompiled with
the correct values, and from now on its execution plan is
valid

• On SQL Server 2005 onwards this has a much less impact
than before
Demo
• Avoiding recompilation due to SET option changes
Recompilations due to plan
optimality-related reasons
•
•

•
•

SQL Server collects statistics about individual columns or sets of columns
Statistics contain:
– The average key length
– A single-column histogram, including up to 200 values of a given column
– The estimated number of rows matching the filter, or all rows in the table
Statistics can be not only automatically created but also kept up to date
Statistics will be considered stale when:
– The first row is inserted into the empty table
– The number of rows in the table was less or equal to 500 and the
colmodctr of the leading column of the statistics object has changed by
more than 500
– The table had more than 500 and the colmodctr of the leading column of
the statistics object has changed by more than 500 + 20% of the number
of rows
– If the statistics object is defined on a temporary table, there is an
additional threshold for recomputation at 6 rows
Recompilations due to statistics
changes
• Even if a statistic becomes outdated, it will not be
automatically updated after the modification completes
– It will automatically update the next time a query plan
uses it

• Default mechanism may lead to unnecessary
recompilations
• Triggers are also being recompiled when the number of
rows in the inserted or deleted virtual tables changes
significantly from one execution to the next
• This is where hints come in
– KEEP PLAN, disables the “6 rows” rule
– KEEPFIXED PLAN disables recompilations due to statistics
changes completely
Demo
• Avoiding recompilation due to statistics changes
When Plan Reusing is a Bad Thing
• Optimization and execution are two completely separate
processes
– Sometime during an optimization SQL Server does not
know the actual values used in queries
– Incorrect estimation in one part of the execution plan can
(and probably will) be spread to others part of the plan

• Parameter Sniffing is an expected SQL Server behavior
– Parameter values used for the first execution of a stored
procedure will be used to compile an execution plan and
this plan will be used over and over again
– The problem arises when a stored procedure is executed
for the first time with unusual parameter values
Dealing with Parameter Sniffing
• You can:
– Disable plan caching for the problematic stored procedure
by adding WITH RECOMPILE to the procedure header
– Force a new compilation for a specific execution only by
adding WITH RECOMPILE to the EXEC statement
– Force a compilation with typical parameter values
• By using variables
• By using OPTIMIZE FOR UNKNOWN

• Remember, recompiling a new plan for a given parameter
value might be way cheaper than reusing a plan
optimized for different values
– Especially for DWs
Demo
• Parameter Sniffing Revealed
• Dealing with Parameter Sniffing
Recap
• Recompilation not only takes a lot of resources (both CPU
cycles and memory), but also can considerably slow down
your queries
• There are two other mechanisms, beside stored procedures
(queries preparation and auto-parameterization) that can be
used to avoid unnecessary recompilations
• Temporary tables, not the permanent ones, should be used
inside stored procedures
• Make an informed choice when to disable recompilations,
without changing database options and using table variables
• Parameter Sniffing is rather a feature than a bug and now you
know how to deal with it
NASI SPONSORZY I PARTNERZY

Organizacja: Polskie Stowarzyszenie Użytkowników SQL Server - PLSSUG
Produkcja: DATA MASTER Maciej Pilecki

Mais conteúdo relacionado

Mais procurados

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
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsfOracle performance tuning_sfsf
Oracle performance tuning_sfsfMao Geng
 
Why & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to queryWhy & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to queryAntonios Chatzipavlis
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuningSimon Huang
 
Less12 Proactive
Less12 ProactiveLess12 Proactive
Less12 Proactivevivaankumar
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Guy Harrison
 
Dynamic Database Solutions - Mitigating Performance Degradations
Dynamic Database Solutions - Mitigating Performance DegradationsDynamic Database Solutions - Mitigating Performance Degradations
Dynamic Database Solutions - Mitigating Performance DegradationsDobler Consulting
 
Oracle Database In-Memory and the Query Optimizer
Oracle Database In-Memory and the Query OptimizerOracle Database In-Memory and the Query Optimizer
Oracle Database In-Memory and the Query OptimizerChristian Antognini
 
Part2 Best Practices for Managing Optimizer Statistics
Part2 Best Practices for Managing Optimizer StatisticsPart2 Best Practices for Managing Optimizer Statistics
Part2 Best Practices for Managing Optimizer StatisticsMaria Colgan
 
Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...
Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...
Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...Microsoft
 
12c In Memory Management - Saurabh Gupta
12c In Memory Management - Saurabh Gupta 12c In Memory Management - Saurabh Gupta
12c In Memory Management - Saurabh Gupta pasalapudi123
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_planMaria Colgan
 
Ground Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planGround Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planMaria Colgan
 

Mais procurados (20)

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
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsfOracle performance tuning_sfsf
Oracle performance tuning_sfsf
 
Why & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to queryWhy & how to optimize sql server for performance from design to query
Why & how to optimize sql server for performance from design to query
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
Les 06 rec
Les 06 recLes 06 rec
Les 06 rec
 
Performance tuning in sql server
Performance tuning in sql serverPerformance tuning in sql server
Performance tuning in sql server
 
Addhoc query
Addhoc queryAddhoc query
Addhoc query
 
Less12 Proactive
Less12 ProactiveLess12 Proactive
Less12 Proactive
 
Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)Top 10 tips for Oracle performance (Updated April 2015)
Top 10 tips for Oracle performance (Updated April 2015)
 
Dynamic Database Solutions - Mitigating Performance Degradations
Dynamic Database Solutions - Mitigating Performance DegradationsDynamic Database Solutions - Mitigating Performance Degradations
Dynamic Database Solutions - Mitigating Performance Degradations
 
Statistics
StatisticsStatistics
Statistics
 
11g nf sql_anlz
11g nf sql_anlz11g nf sql_anlz
11g nf sql_anlz
 
Les 14 perf_db
Les 14 perf_dbLes 14 perf_db
Les 14 perf_db
 
Oracle Database In-Memory and the Query Optimizer
Oracle Database In-Memory and the Query OptimizerOracle Database In-Memory and the Query Optimizer
Oracle Database In-Memory and the Query Optimizer
 
Part2 Best Practices for Managing Optimizer Statistics
Part2 Best Practices for Managing Optimizer StatisticsPart2 Best Practices for Managing Optimizer Statistics
Part2 Best Practices for Managing Optimizer Statistics
 
Part5 sql tune
Part5 sql tunePart5 sql tune
Part5 sql tune
 
Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...
Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...
Business Insight 2014 - Microsofts nye BI og database platform - Erling Skaal...
 
12c In Memory Management - Saurabh Gupta
12c In Memory Management - Saurabh Gupta 12c In Memory Management - Saurabh Gupta
12c In Memory Management - Saurabh Gupta
 
Explain the explain_plan
Explain the explain_planExplain the explain_plan
Explain the explain_plan
 
Ground Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_planGround Breakers Romania: Explain the explain_plan
Ground Breakers Romania: Explain the explain_plan
 

Destaque

SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...
SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...
SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...Polish SQL Server User Group
 
SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...
SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...
SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...Polish SQL Server User Group
 
SQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitectures
SQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitecturesSQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitectures
SQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitecturesPolish SQL Server User Group
 
SQLDay2013_PawełPotasiński_ParallelDataWareHouse
SQLDay2013_PawełPotasiński_ParallelDataWareHouseSQLDay2013_PawełPotasiński_ParallelDataWareHouse
SQLDay2013_PawełPotasiński_ParallelDataWareHousePolish SQL Server User Group
 
26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scripts
26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scripts26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scripts
26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scriptsPolish SQL Server User Group
 
SQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET DeveloperSQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET DeveloperPolish SQL Server User Group
 
SQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorld
SQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorldSQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorld
SQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorldPolish SQL Server User Group
 
SQLDay2013_PawełPotasiński_GeografiaSQLServer2012
SQLDay2013_PawełPotasiński_GeografiaSQLServer2012SQLDay2013_PawełPotasiński_GeografiaSQLServer2012
SQLDay2013_PawełPotasiński_GeografiaSQLServer2012Polish SQL Server User Group
 
SQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&Running
SQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&RunningSQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&Running
SQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&RunningPolish SQL Server User Group
 
38Spotkanie_PLSSUGweWroclawiu_Keynote
38Spotkanie_PLSSUGweWroclawiu_Keynote38Spotkanie_PLSSUGweWroclawiu_Keynote
38Spotkanie_PLSSUGweWroclawiu_KeynoteTobias Koprowski
 
CISSPDAY 2011 - 2 AM A Disaster just Began
CISSPDAY 2011 - 2 AM A Disaster just BeganCISSPDAY 2011 - 2 AM A Disaster just Began
CISSPDAY 2011 - 2 AM A Disaster just BeganTobias Koprowski
 

Destaque (20)

SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...
SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...
SQL DAY 2012 | DEV Track | Session 9 - Data Mining Analiza Przepływowa by M.S...
 
SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...
SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...
SQL DAY 2012 | DEV Track | Session 6 - Master Data Management by W.Bielski 6 ...
 
SQLDay2013_GrzegorzStolecki_KonsolidacjaBI
SQLDay2013_GrzegorzStolecki_KonsolidacjaBISQLDay2013_GrzegorzStolecki_KonsolidacjaBI
SQLDay2013_GrzegorzStolecki_KonsolidacjaBI
 
SQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitectures
SQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitecturesSQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitectures
SQLDay2013_MarcinSzeliga_SQLServer2012FastTrackDWReferenceArchitectures
 
SQLDay2013_PawełPotasiński_ParallelDataWareHouse
SQLDay2013_PawełPotasiński_ParallelDataWareHouseSQLDay2013_PawełPotasiński_ParallelDataWareHouse
SQLDay2013_PawełPotasiński_ParallelDataWareHouse
 
Sql day2015 fts
Sql day2015 ftsSql day2015 fts
Sql day2015 fts
 
SQLDay2013_MaciejPilecki_Lock&Latches
SQLDay2013_MaciejPilecki_Lock&LatchesSQLDay2013_MaciejPilecki_Lock&Latches
SQLDay2013_MaciejPilecki_Lock&Latches
 
SQLDay2013_ChrisWebb_SSASDesignMistakes
SQLDay2013_ChrisWebb_SSASDesignMistakesSQLDay2013_ChrisWebb_SSASDesignMistakes
SQLDay2013_ChrisWebb_SSASDesignMistakes
 
26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scripts
26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scripts26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scripts
26th_Meetup_of_PLSSUG_WROCLAW-ColumnStore_Indexes_byBeataZalewa_scripts
 
SQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET DeveloperSQLDay2013_Denny Cherry - Table indexing for the .NET Developer
SQLDay2013_Denny Cherry - Table indexing for the .NET Developer
 
SQLDay2013_GrzegorzStolecki_RealTimeOLAP
SQLDay2013_GrzegorzStolecki_RealTimeOLAPSQLDay2013_GrzegorzStolecki_RealTimeOLAP
SQLDay2013_GrzegorzStolecki_RealTimeOLAP
 
SQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorld
SQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorldSQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorld
SQLDay2013_Denny Cherry - SQLServer2012inaHighlyAvailableWorld
 
SQLDay2013_MarekAdamczuk_Kursory
SQLDay2013_MarekAdamczuk_KursorySQLDay2013_MarekAdamczuk_Kursory
SQLDay2013_MarekAdamczuk_Kursory
 
SQLDay2013_PawełPotasiński_GeografiaSQLServer2012
SQLDay2013_PawełPotasiński_GeografiaSQLServer2012SQLDay2013_PawełPotasiński_GeografiaSQLServer2012
SQLDay2013_PawełPotasiński_GeografiaSQLServer2012
 
SQLDay2011_Sesja02_Collation_Marek Adamczuk
SQLDay2011_Sesja02_Collation_Marek AdamczukSQLDay2011_Sesja02_Collation_Marek Adamczuk
SQLDay2011_Sesja02_Collation_Marek Adamczuk
 
SQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&Running
SQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&RunningSQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&Running
SQLDay2013_DennyCherry_GettingSQLServiceBrokerUp&Running
 
38Spotkanie_PLSSUGweWroclawiu_Keynote
38Spotkanie_PLSSUGweWroclawiu_Keynote38Spotkanie_PLSSUGweWroclawiu_Keynote
38Spotkanie_PLSSUGweWroclawiu_Keynote
 
SQLDay2013_ChrisWebb_DAXMD
SQLDay2013_ChrisWebb_DAXMDSQLDay2013_ChrisWebb_DAXMD
SQLDay2013_ChrisWebb_DAXMD
 
CISSPDAY 2011 - 2 AM A Disaster just Began
CISSPDAY 2011 - 2 AM A Disaster just BeganCISSPDAY 2011 - 2 AM A Disaster just Began
CISSPDAY 2011 - 2 AM A Disaster just Began
 
SQLDay2013_ChrisWebb_CubeDesign&PerformanceTuning
SQLDay2013_ChrisWebb_CubeDesign&PerformanceTuningSQLDay2013_ChrisWebb_CubeDesign&PerformanceTuning
SQLDay2013_ChrisWebb_CubeDesign&PerformanceTuning
 

Semelhante a SQLDay2013_MarcinSzeliga_StoredProcedures

SKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSING
SKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSINGSKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSING
SKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSINGSkillwise Group
 
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12cPresentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12cRonald Francisco Vargas Quesada
 
Geek Sync | Intro to Query Store
Geek Sync | Intro to Query StoreGeek Sync | Intro to Query Store
Geek Sync | Intro to Query StoreIDERA Software
 
Adapting and adopting spm v04
Adapting and adopting spm v04Adapting and adopting spm v04
Adapting and adopting spm v04Carlos Sierra
 
Optimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxOptimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxJasonTuran2
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptxKareemBullard1
 
Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Antonios Chatzipavlis
 
Database Systems Design, Implementation, and Management
Database Systems Design, Implementation, and ManagementDatabase Systems Design, Implementation, and Management
Database Systems Design, Implementation, and ManagementOllieShoresna
 
Database performance tuning and query optimization
Database performance tuning and query optimizationDatabase performance tuning and query optimization
Database performance tuning and query optimizationDhani Ahmad
 
LVOUG meetup #2 - Forcing SQL Execution Plan Instability
LVOUG meetup #2 - Forcing SQL Execution Plan InstabilityLVOUG meetup #2 - Forcing SQL Execution Plan Instability
LVOUG meetup #2 - Forcing SQL Execution Plan InstabilityMaris Elsins
 
Oracle EBS Production Support - Recommendations
Oracle EBS Production Support - RecommendationsOracle EBS Production Support - Recommendations
Oracle EBS Production Support - RecommendationsVigilant Technologies
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresJitendra Singh
 
Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...
Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...
Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...Leighton Nelson
 
Case Study Real Time Olap Cubes
Case Study Real Time Olap CubesCase Study Real Time Olap Cubes
Case Study Real Time Olap Cubesmister_zed
 
Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...
Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...
Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...Andrejs Karpovs
 
Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment.   Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment. Rolta
 
Using Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query PerformanceUsing Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query PerformanceGrant Fritchey
 
SQL Server 2017 - Adaptive Query Processing and Automatic Query Tuning
SQL Server 2017 - Adaptive Query Processing and Automatic Query TuningSQL Server 2017 - Adaptive Query Processing and Automatic Query Tuning
SQL Server 2017 - Adaptive Query Processing and Automatic Query TuningJavier Villegas
 
In Search of Plan Stability Part 2 with Karen Morton
In Search of Plan Stability Part 2 with Karen MortonIn Search of Plan Stability Part 2 with Karen Morton
In Search of Plan Stability Part 2 with Karen MortonEmbarcadero Technologies
 

Semelhante a SQLDay2013_MarcinSzeliga_StoredProcedures (20)

SKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSING
SKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSINGSKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSING
SKILLWISE-SSIS DESIGN PATTERN FOR DATA WAREHOUSING
 
Presentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12cPresentación Oracle Database Migración consideraciones 10g/11g/12c
Presentación Oracle Database Migración consideraciones 10g/11g/12c
 
Geek Sync | Intro to Query Store
Geek Sync | Intro to Query StoreGeek Sync | Intro to Query Store
Geek Sync | Intro to Query Store
 
Adapting and adopting spm v04
Adapting and adopting spm v04Adapting and adopting spm v04
Adapting and adopting spm v04
 
Optimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptxOptimizing Application Performance - 2022.pptx
Optimizing Application Performance - 2022.pptx
 
05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx05_DP_300T00A_Optimize.pptx
05_DP_300T00A_Optimize.pptx
 
Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019Modernizing your database with SQL Server 2019
Modernizing your database with SQL Server 2019
 
Database Systems Design, Implementation, and Management
Database Systems Design, Implementation, and ManagementDatabase Systems Design, Implementation, and Management
Database Systems Design, Implementation, and Management
 
Database performance tuning and query optimization
Database performance tuning and query optimizationDatabase performance tuning and query optimization
Database performance tuning and query optimization
 
LVOUG meetup #2 - Forcing SQL Execution Plan Instability
LVOUG meetup #2 - Forcing SQL Execution Plan InstabilityLVOUG meetup #2 - Forcing SQL Execution Plan Instability
LVOUG meetup #2 - Forcing SQL Execution Plan Instability
 
Oracle EBS Production Support - Recommendations
Oracle EBS Production Support - RecommendationsOracle EBS Production Support - Recommendations
Oracle EBS Production Support - Recommendations
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and UnderscoresPerformance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
 
Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...
Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...
Oracle Enteprise Manager Cloud Control 12c - Setting Up Metrics and Monitorin...
 
Case Study Real Time Olap Cubes
Case Study Real Time Olap CubesCase Study Real Time Olap Cubes
Case Study Real Time Olap Cubes
 
Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...
Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...
Reducing Your E-Business Suite Storage Footprint Using Oracle Advanced Compre...
 
01 oracle architecture
01 oracle architecture01 oracle architecture
01 oracle architecture
 
Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment.   Rolta’s application testing services for handling ever changing environment.
Rolta’s application testing services for handling ever changing environment.
 
Using Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query PerformanceUsing Query Store to Understand and Control Query Performance
Using Query Store to Understand and Control Query Performance
 
SQL Server 2017 - Adaptive Query Processing and Automatic Query Tuning
SQL Server 2017 - Adaptive Query Processing and Automatic Query TuningSQL Server 2017 - Adaptive Query Processing and Automatic Query Tuning
SQL Server 2017 - Adaptive Query Processing and Automatic Query Tuning
 
In Search of Plan Stability Part 2 with Karen Morton
In Search of Plan Stability Part 2 with Karen MortonIn Search of Plan Stability Part 2 with Karen Morton
In Search of Plan Stability Part 2 with Karen Morton
 

Mais de Polish SQL Server User Group

SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...
SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...
SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...Polish SQL Server User Group
 
26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_session
26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_session26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_session
26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_sessionPolish SQL Server User Group
 
SQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStolecki
SQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStoleckiSQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStolecki
SQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStoleckiPolish SQL Server User Group
 
SQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGrala
SQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGralaSQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGrala
SQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGralaPolish SQL Server User Group
 
SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...
SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...
SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...Polish SQL Server User Group
 
How to tune a database application without changing a single query - Maciej P...
How to tune a database application without changing a single query - Maciej P...How to tune a database application without changing a single query - Maciej P...
How to tune a database application without changing a single query - Maciej P...Polish SQL Server User Group
 
Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...
Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...
Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...Polish SQL Server User Group
 
Master Data Services – Po co nam kolejna usługa w Sql Server - Mariusz Koprowski
Master Data Services – Po co nam kolejna usługa w Sql Server - Mariusz KoprowskiMaster Data Services – Po co nam kolejna usługa w Sql Server - Mariusz Koprowski
Master Data Services – Po co nam kolejna usługa w Sql Server - Mariusz KoprowskiPolish SQL Server User Group
 

Mais de Polish SQL Server User Group (9)

SQLDay2013_MarcinSzeliga_DataInDataMining
SQLDay2013_MarcinSzeliga_DataInDataMiningSQLDay2013_MarcinSzeliga_DataInDataMining
SQLDay2013_MarcinSzeliga_DataInDataMining
 
SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...
SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...
SQL DAY 2012 | DEV Track | Session 8 - Getting Dimension with Data by C.Tecta...
 
26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_session
26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_session26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_session
26th_Meetup_of_PLSSUG-ColumnStore_Indexes_byBeataZalewa_session
 
SQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStolecki
SQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStoleckiSQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStolecki
SQLDay2011_Sesja03_Fakty,MiaryISwiatRealny_GrzegorzStolecki
 
SQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGrala
SQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGralaSQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGrala
SQLDay2011_Sesja01_ModelowanieIZasilanieWymiarówHurtowniDanych_ŁukaszGrala
 
SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...
SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...
SQLDay2011_Sesja05_MicrosoftSQLServerExecutionPlansFromCompilationToCachingTo...
 
How to tune a database application without changing a single query - Maciej P...
How to tune a database application without changing a single query - Maciej P...How to tune a database application without changing a single query - Maciej P...
How to tune a database application without changing a single query - Maciej P...
 
Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...
Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...
Co nowego w SQL Server 11 – Denali CTP1 - Grzegorz Stolecki, Łukasz Grala i K...
 
Master Data Services – Po co nam kolejna usługa w Sql Server - Mariusz Koprowski
Master Data Services – Po co nam kolejna usługa w Sql Server - Mariusz KoprowskiMaster Data Services – Po co nam kolejna usługa w Sql Server - Mariusz Koprowski
Master Data Services – Po co nam kolejna usługa w Sql Server - Mariusz Koprowski
 

Último

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfJayanti Pande
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3JemimahLaneBuaron
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAssociation for Project Management
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfchloefrazer622
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformChameera Dedduwage
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfchloefrazer622
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsTechSoup
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDThiyagu K
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityGeoBlogs
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...christianmathematics
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdfQucHHunhnh
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactPECB
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Disha Kariya
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajanpragatimahajan3
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 

Último (20)

Web & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdfWeb & Social Media Analytics Previous Year Question Paper.pdf
Web & Social Media Analytics Previous Year Question Paper.pdf
 
Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3Q4-W6-Restating Informational Text Grade 3
Q4-W6-Restating Informational Text Grade 3
 
APM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across SectorsAPM Welcome, APM North West Network Conference, Synergies Across Sectors
APM Welcome, APM North West Network Conference, Synergies Across Sectors
 
Arihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdfArihant handbook biology for class 11 .pdf
Arihant handbook biology for class 11 .pdf
 
A Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy ReformA Critique of the Proposed National Education Policy Reform
A Critique of the Proposed National Education Policy Reform
 
Disha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdfDisha NEET Physics Guide for classes 11 and 12.pdf
Disha NEET Physics Guide for classes 11 and 12.pdf
 
Introduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The BasicsIntroduction to Nonprofit Accounting: The Basics
Introduction to Nonprofit Accounting: The Basics
 
Measures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SDMeasures of Dispersion and Variability: Range, QD, AD and SD
Measures of Dispersion and Variability: Range, QD, AD and SD
 
Paris 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activityParis 2024 Olympic Geographies - an activity
Paris 2024 Olympic Geographies - an activity
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptxINDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
INDIA QUIZ 2024 RLAC DELHI UNIVERSITY.pptx
 
1029-Danh muc Sach Giao Khoa khoi 6.pdf
1029-Danh muc Sach Giao Khoa khoi  6.pdf1029-Danh muc Sach Giao Khoa khoi  6.pdf
1029-Danh muc Sach Giao Khoa khoi 6.pdf
 
Beyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global ImpactBeyond the EU: DORA and NIS 2 Directive's Global Impact
Beyond the EU: DORA and NIS 2 Directive's Global Impact
 
Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..Sports & Fitness Value Added Course FY..
Sports & Fitness Value Added Course FY..
 
Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1Código Creativo y Arte de Software | Unidad 1
Código Creativo y Arte de Software | Unidad 1
 
social pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajansocial pharmacy d-pharm 1st year by Pragati K. Mahajan
social pharmacy d-pharm 1st year by Pragati K. Mahajan
 
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"Mattingly "AI & Prompt Design: The Basics of Prompt Design"
Mattingly "AI & Prompt Design: The Basics of Prompt Design"
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 

SQLDay2013_MarcinSzeliga_StoredProcedures

  • 1. NASI SPONSORZY I PARTNERZY
  • 2. Stored Procedures – Facts and Myths Marcin Szeliga www.sqlexpert.pl http://blog.sqlexpert.pl/ http://www.facebook.com/SQLExpertpl marcin@sqlexpert.pl
  • 3. Agenda • Basic Fact - Plan Caching and Reuse is (usually) a Good Thing • Obvious Consequence – You Should Avoid Recompilations … • But Sometimes Plan Reusing is a Bad Thing • Recap
  • 4. Plan Caching and Reuse is a Good Thing • Stored procedures – Are a convenient container for code reuse • They can be called many times and the query plans can be reused, saving the time, CPU and memory – Are optimized and compiled during their first execution • Optimization is based on parameters supplied during this execution • Future executions will reuse the query plan stored in plan cache • There are at most two instances of a query plan at any time in plan cache: – One for all of the serial executions. – One for all of the parallel executions • From a query plan, an execution context is derived – Execution contexts hold the values needed for a specific execution of a query plan, and they are also cached and reused
  • 5. Does compilation/recompilation really matter? • In terms of time – Compilation is really expensive and CPU-heavy process • In terms of memory – Storing large number of execution plans the procedure cache “steals” memory from the Buffer Pool – The currently used formula looks like this: • 75% 0-4GB + 10% 4-64GB + 5% 64GB – On 16GB box 4.2 GB may be used for the procedure cache • In terms of concurrency – Getaways throttle simultaneous compilation to really small number • Three of them: – Small - 4 x number of logical CPUs allocated to SQL Server – Medium - Number of logical CPUs allocated to SQL Server – Large - 1 • Look for 'RESOURCE_SEMAPHORE_QUERY_COMPILE' wait
  • 6. Demo • Measuring compilation cost, in terms of time and memory • Looking inside the Procedure Cache
  • 7. Stored procedures are not the only option • SQL Server can cache query plans for different types of batches beside ad-hoc queries and stored procedures: – Query preparation • ODBC and OLE DB expose this functionality via SQLPrepare/SQLExecute and ICommandPrepare interfaces • Very similar result can be achieved by using sp_executesql – Simple parameterization • SQL Server automatically replaces constant literal values with variables before the query plan will be compiled • SQL Server 2008 allows us to forced parameterization of almost all types of queries – Dynamic SQL • Strings submitted via EXEC for execution
  • 8. Demo • Checking two other options: query preparation and forced parameterization
  • 9. Avoiding recompilations due to plan stability-related reasons • Stored procedure (or a batch) must be recompiled if not doing so would result in incorrect results or actions • 14 recompilation reasons • 2 sub-categories: – Scheme changes – SET options changes
  • 10. Recompilation due to schema changes • Putting all DML statements at the beginning of a stored procedure will NOT minimize recompilations – SQL Server 2005 onwards does statement level recompilations • Deferred compilations mean that objects didn't exist during creation the stored procedure • The only solution is to use temporary tables – SQL Server caches temporary objects but altering definitions of those temporary objects disables this caching mechanism • In addition, objects cannot have named constraints • Accessing objects created outside the current scope requires object id to name resolution – Recompilation due to the changed scheme occurs
  • 11. Demo • Avoiding recompilation due to schema changes
  • 12. Recompilation due to SET option changes • When an execution plan is created, the SQL Server stores the environmental setting with it – Some SET options used when the stored procedure was created or altered will be saved as part of its metadata – Some execution plan attributes are considered cache key ones • Subsequent execution will not trigger recompilations – During the first execution a procedure is recompiled with the correct values, and from now on its execution plan is valid • On SQL Server 2005 onwards this has a much less impact than before
  • 13. Demo • Avoiding recompilation due to SET option changes
  • 14. Recompilations due to plan optimality-related reasons • • • • SQL Server collects statistics about individual columns or sets of columns Statistics contain: – The average key length – A single-column histogram, including up to 200 values of a given column – The estimated number of rows matching the filter, or all rows in the table Statistics can be not only automatically created but also kept up to date Statistics will be considered stale when: – The first row is inserted into the empty table – The number of rows in the table was less or equal to 500 and the colmodctr of the leading column of the statistics object has changed by more than 500 – The table had more than 500 and the colmodctr of the leading column of the statistics object has changed by more than 500 + 20% of the number of rows – If the statistics object is defined on a temporary table, there is an additional threshold for recomputation at 6 rows
  • 15. Recompilations due to statistics changes • Even if a statistic becomes outdated, it will not be automatically updated after the modification completes – It will automatically update the next time a query plan uses it • Default mechanism may lead to unnecessary recompilations • Triggers are also being recompiled when the number of rows in the inserted or deleted virtual tables changes significantly from one execution to the next • This is where hints come in – KEEP PLAN, disables the “6 rows” rule – KEEPFIXED PLAN disables recompilations due to statistics changes completely
  • 16. Demo • Avoiding recompilation due to statistics changes
  • 17. When Plan Reusing is a Bad Thing • Optimization and execution are two completely separate processes – Sometime during an optimization SQL Server does not know the actual values used in queries – Incorrect estimation in one part of the execution plan can (and probably will) be spread to others part of the plan • Parameter Sniffing is an expected SQL Server behavior – Parameter values used for the first execution of a stored procedure will be used to compile an execution plan and this plan will be used over and over again – The problem arises when a stored procedure is executed for the first time with unusual parameter values
  • 18. Dealing with Parameter Sniffing • You can: – Disable plan caching for the problematic stored procedure by adding WITH RECOMPILE to the procedure header – Force a new compilation for a specific execution only by adding WITH RECOMPILE to the EXEC statement – Force a compilation with typical parameter values • By using variables • By using OPTIMIZE FOR UNKNOWN • Remember, recompiling a new plan for a given parameter value might be way cheaper than reusing a plan optimized for different values – Especially for DWs
  • 19. Demo • Parameter Sniffing Revealed • Dealing with Parameter Sniffing
  • 20. Recap • Recompilation not only takes a lot of resources (both CPU cycles and memory), but also can considerably slow down your queries • There are two other mechanisms, beside stored procedures (queries preparation and auto-parameterization) that can be used to avoid unnecessary recompilations • Temporary tables, not the permanent ones, should be used inside stored procedures • Make an informed choice when to disable recompilations, without changing database options and using table variables • Parameter Sniffing is rather a feature than a bug and now you know how to deal with it
  • 21. NASI SPONSORZY I PARTNERZY Organizacja: Polskie Stowarzyszenie Użytkowników SQL Server - PLSSUG Produkcja: DATA MASTER Maciej Pilecki