SlideShare a Scribd company logo
TEN QUERY TUNING 
TECHNIQUES 
Every SQL Programmer Should Know 
Kevin Kline 
Director of Engineering Services at SQL Sentry 
Microsoft MVP since 2003 
Facebook, LinkedIn, Twitter at KEKLINE 
KEKline@sqlsentry.com 
KevinEKline.com, ForITPros.com
FOR FRIENDS OF SQL SENTRY 
• Free Plan Explorer download: 
http://www.sqlsentry.net/plan-explorer/ 
• Free query tuning consultations: 
http://answers.sqlperformance.com. 
• Free new ebook (regularly $10) to attendees. 
Send request to sales@sqlsentry.net. 
• SQL Server educational videos, scripts, and 
slides: http://SQLSentry.TV 
• Tuning blog: http://www.sqlperformance.com/ 
• Monthly eNews tips and tricks: 
http://www.sqlsentry.net/newsletter-archive. 
asp
AGENDA 
• Introductions 
• Test & tuning environment 
• 1. Clearing caches 
• Looking for red flags 
• 2. Reading execution plans 
• Query tuning techniques: 
• 8 more specific examples of widespread approaches that lead to poor 
performance 
• Summary 
3
TEST & TUNING ENVIRONMENT 
• Code to clear the caches*: 
o CHECKPOINT 
o DBCC [FreeProcCache | FreeSystemCache | FlushProcInDB(<dbid>) ] 
o DBCC DropCleanBuffers 
• Code to set measurements: 
o SET STATISTICS [TIME | IO] 
o SET SHOWPLAN [TEXT | XML] or Graphic Execution Plans 
• Code for Dynamic Management Views (DMV) checks. 
o System info – sys.dm_os_performance_counters, sys.dm_os_wait_stats 
o Query info – sys.dm_exec_requests 
o Index info – sys.dm_db_index_usage_stats, sys.dm_io_virtual_file_stats
RED FLAGS IN YOUR SQL CODE 
• Red Flags Query Operators: 
o Lookups, Scans, Spools, Parallelism Operations 
• Other Red Flags: 
o Dissimilar estimated versus actual row counts 
o High physical reads 
o Missing statistics alarms 
o Large sort operations 
o Implicit data type conversions
DEMOS: DEFAULT CURSORS 
• I don’t always use cursors… 
o …but when I do, I avoid the default options 
o Slow and heavy-handed: Global, updateable, dynamic, scrollable 
o I use LOCAL FAST_FORWARD 
o May want to test STATIC vs. DYNAMIC, when tempdb is a 
bottleneck 
• Blog post: http://bit.ly/AB-cursors
DEMOS: WHERE IN VERSUS 
WHERE EXISTS 
• There are lots of ways to find data existing within 
subsets: 
• IN, EXISTS, JOIN, Apply, subquery 
• Which technique is best? 
• Blog post: http://bit.ly/AB-NOTIN
OPTIMIZING FOR SELECT VERSUS 
DML 
• Big differences between a SELECT and a DML 
statement that effects the same rows. 
• Shouldn’t blindly create every index the Tuning Advisor 
or execution plan tells you to! 
• Blog post - http://bit.ly/AB-BlindIndex
READS & INDEX STRUCTURE 
• 8K pages 
• Leaf pages ARE the data. 
• Non-leaf pages are pointers. 
Leaf Pages 
Root Page 
Level 0 
Intermediate 
Pages 
Level 1 
Level 2
WRITES & INDEX STRUCTURE 
• Each change to the leaf pages requires all index 
structures be updated. 
Leaf Pages 
Root Page 
Level 0 
Intermediate 
Pages 
Level 1 
Level 2 
Page 
Split 
DML 
Actual 
place-ment
DEMOS: UNWANTED RECOMPILES 
Execution 
In Memory? NO Load metadata 
compile 
optimize 
Execute 
YES 
ReComp
CAUSES OF RECOMPILE 
• Expected: Because we request it: 
• CREATE PROC … WITH RECOMPILE or EXEC myproc … WITH 
RECOMPILE 
• SP_RECOMPILE foo 
• Expected: Plan was aged out of memory 
• Unexpected: Interleaved DDL and DML 
• Unexpected: Big changes since last execution: 
• Schema changes to objects in underlying code 
• New/updated index statistics 
• Sp_configure
INTERLEAVED DDL AND DML 
• CREATE PROC testddldml AS … ; 
• CREATE TABLE #testdml; -- (DDL) 
• <some T-SQL code here> 
• INSERT INTO #testdml; -- (DML + RECOMPILE) 
• <some T-SQL code here> 
• ALTER TABLE #testdml; -- (DDL) 
• <some T-SQL code here> 
• INSERT INTO #testdml; -- (DML + RECOMPILE) 
• <some T-SQL code here> 
• DROP TABLE #testdml; -- (DDL) 
• <some T-SQL code here>
DEMOS: THE "KITCHEN SINK" 
PROCEDURE 
• Usually see it as a one-query-for-all-queries procedure, 
or even one-proc-for-for-all-transactions procedure: 
o Where name starts with S, or placed an order this year, or lives in Texas 
o Insert AND Update AND Delete AND Select 
• Conflicting optional parameters make optimization 
impossible 
o OPTION (RECOMPILE) 
o Dynamic SQL + Optimize for ad hoc workloads 
o Specialized procedures 
• Better approach? 
o Specialize and optimize each piece of code to do ONE THING really effectively
DEMOS: SP_EXECUTESQL VS. 
EXEC(…) 
• I don’t always use dynamic SQL… 
o …but when I do, I always use sp_executesql 
o Less fuss with concatenation and implicit/explicit conversions 
o Better protection against SQL injection (but not for all things) 
o At worst case, behavior is the same 
• Can promote better plan re-use 
• Encourages strongly typed parameters instead of 
building up a massive string
IMPLICIT CONVERSIONS 
• SQL Server has to do a lot of extra work / scans when 
conversion operations are assumed by the SQL 
programmer. 
• Happens all the time with data types you’d think wouldn’t 
need it, e.g. between date types and character types. 
• Very useful data type conversion chart at 
http://bit.ly/15bDRRA. 
• Data type precedence call also have an impact: 
http://bit.ly/13Zio1f.
IMPLICIT CONVERSION 
RESOURCES 
• Ian Stirk’s Column Mismatch Utility at 
http://www.sqlservercentral.com/articles/Administration/6 
5138/. 
• Jonathan Kehayias’ plan cache analyzer at 
http://sqlblog.com/blogs/jonathan_kehayias/archive/2010 
/01/08/finding-implicit-column-conversions-in-the-plan-cache. 
aspx. 
• Jonathan Kehayias’ index scan study at 
http://www.sqlperformance.com/2013/04/t-sql-queries/ 
implicit-conversion-costs
DEMOS: COMMA-DELIMITED 
PARAMETERS 
• Example: pass a comma-separated list of OrderIDs 
• String splitting is expensive, even using CLR 
• Table-valued parameters are typically a better approach
DEMOS: TEMPORARY 
STRUCTURES 
• Which are better, temp tables or temp variables? 
Temp Table Temp Variable 
Stored in? Tempdb Tempdb 
Statistics? Yes No (1 row) 
Indexs/Keys? Yes 1 UK / PK only 
Truncate? Yes No 
Recompiles? Yes No 
Parallelism? Yes No 
Metadata 
Overhead? 
Low Lowest 
Lock Overhead? Normal Lowest
CODING STANDARDS AND 
DISSIMILARITY 
• Might sound frivolous, but naming schemes are 
important 
o Convention is not important; but rather being consistent and logical 
• Story: dbo.UpdateCustomer vs. dbo.Customer_Update 
• Always specify schema when creating, altering, 
referencing objects 
o Object resolution works a little bit harder without it 
o More importantly, it can get the wrong answer 
o And will often yield multiple copies of the same plan 
• Do not use the sp_ prefix on stored procedures 
o This has observable overhead, no matter how specific you are
MIMICKING PRODUCTION 
• Your dev machine is usually nothing like production 
o Build representative data when you can 
o Build a stats-only database when you can’t (a.k.a. a database clone) 
• Will allow you to see plan issues, but not speed 
o Make sure settings are the same 
• @@VERSION, edition 
• Max memory if possible, sp_configure options 
• Logins (and permissions), tempdb settings 
• Parameterization settings, recovery model, compression, snapshot isolation 
• Compatibility level (usually not an issue when working with a restore) 
• Run a full business cycle workload after a restore 
o Simulate equivalent hardware: DBCC OPTIMIZER_WHATIF 
o Use Distributed Replay when you can 
• Not perfect, but more realistic than single-threaded trace replay
SUMMARY 
Let’s connect! 
Facebook, LinkedIn, Twitter 
at KEKLINE. 
Email at 
KEKline@sqlsentry.com 
Blogs at 
http://KevinEKline.com 
And 
http://ForITPros.com
WRAP UP 
Engage with us on social media 
o I’m thankful for your word of mouth promotions and 
endorsements! 
Share your tough SQL tuning problems with us: 
http://answers.sqlperformance.com 
Download SQL Sentry Plan Explorer for free: 
http://www.sqlsentry.com/plan-explorer/ 
Check out our other award winning tools: 
http://www.sqlsentry.net/download
NOLOCK 
http://www.flickr.com/photos/relyjus/4289185639/
NOLOCK 
• It is a turbo button …if you’re ok with inaccuracy 
• There are times it is perfectly valid 
o Ballpark row counts 
o Please use session-level setting, not table hint 
• Usually, though, better to use SNAPSHOT or RCSI 
o But test under heavy load

More Related Content

What's hot

Sql Server Performance Tuning
Sql Server Performance TuningSql Server Performance Tuning
Sql Server Performance Tuning
Bala Subra
 
Troubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel PoderTroubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel Poder
Tanel Poder
 
MySQL GTID 시작하기
MySQL GTID 시작하기MySQL GTID 시작하기
MySQL GTID 시작하기
I Goo Lee
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performance
PostgreSQL-Consulting
 
Tanel Poder - Performance stories from Exadata Migrations
Tanel Poder - Performance stories from Exadata MigrationsTanel Poder - Performance stories from Exadata Migrations
Tanel Poder - Performance stories from Exadata Migrations
Tanel Poder
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
Simon Huang
 
PostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability MethodsPostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability Methods
Mydbops
 
Microsoft SQL Server Query Tuning
Microsoft SQL Server Query TuningMicrosoft SQL Server Query Tuning
Microsoft SQL Server Query Tuning
Mark Ginnebaugh
 
Columnstore indexes in sql server 2014
Columnstore indexes in sql server 2014Columnstore indexes in sql server 2014
Columnstore indexes in sql server 2014
Antonios Chatzipavlis
 
Oracle Database performance tuning using oratop
Oracle Database performance tuning using oratopOracle Database performance tuning using oratop
Oracle Database performance tuning using oratop
Sandesh Rao
 
Best Practices for Oracle Exadata and the Oracle Optimizer
Best Practices for Oracle Exadata and the Oracle OptimizerBest Practices for Oracle Exadata and the Oracle Optimizer
Best Practices for Oracle Exadata and the Oracle Optimizer
Edgar Alejandro Villegas
 
Wide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data ModelingWide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data Modeling
ScyllaDB
 
MySQL Atchitecture and Concepts
MySQL Atchitecture and ConceptsMySQL Atchitecture and Concepts
MySQL Atchitecture and Concepts
Tuyen Vuong
 
Online index rebuild automation
Online index rebuild automationOnline index rebuild automation
Online index rebuild automation
Carlos Sierra
 
Galera cluster for MySQL - Introduction Slides
Galera cluster for MySQL - Introduction SlidesGalera cluster for MySQL - Introduction Slides
Galera cluster for MySQL - Introduction Slides
Severalnines
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL ServerEnd-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
Kevin Kline
 
PostgreSQL and RAM usage
PostgreSQL and RAM usagePostgreSQL and RAM usage
PostgreSQL and RAM usage
Alexey Bashtanov
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
10 things, an Oracle DBA should care about when moving to PostgreSQL
10 things, an Oracle DBA should care about when moving to PostgreSQL10 things, an Oracle DBA should care about when moving to PostgreSQL
10 things, an Oracle DBA should care about when moving to PostgreSQL
PostgreSQL-Consulting
 
LISA2019 Linux Systems Performance
LISA2019 Linux Systems PerformanceLISA2019 Linux Systems Performance
LISA2019 Linux Systems Performance
Brendan Gregg
 

What's hot (20)

Sql Server Performance Tuning
Sql Server Performance TuningSql Server Performance Tuning
Sql Server Performance Tuning
 
Troubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel PoderTroubleshooting Complex Oracle Performance Problems with Tanel Poder
Troubleshooting Complex Oracle Performance Problems with Tanel Poder
 
MySQL GTID 시작하기
MySQL GTID 시작하기MySQL GTID 시작하기
MySQL GTID 시작하기
 
Linux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performanceLinux tuning to improve PostgreSQL performance
Linux tuning to improve PostgreSQL performance
 
Tanel Poder - Performance stories from Exadata Migrations
Tanel Poder - Performance stories from Exadata MigrationsTanel Poder - Performance stories from Exadata Migrations
Tanel Poder - Performance stories from Exadata Migrations
 
Oracle db performance tuning
Oracle db performance tuningOracle db performance tuning
Oracle db performance tuning
 
PostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability MethodsPostgreSQL Replication High Availability Methods
PostgreSQL Replication High Availability Methods
 
Microsoft SQL Server Query Tuning
Microsoft SQL Server Query TuningMicrosoft SQL Server Query Tuning
Microsoft SQL Server Query Tuning
 
Columnstore indexes in sql server 2014
Columnstore indexes in sql server 2014Columnstore indexes in sql server 2014
Columnstore indexes in sql server 2014
 
Oracle Database performance tuning using oratop
Oracle Database performance tuning using oratopOracle Database performance tuning using oratop
Oracle Database performance tuning using oratop
 
Best Practices for Oracle Exadata and the Oracle Optimizer
Best Practices for Oracle Exadata and the Oracle OptimizerBest Practices for Oracle Exadata and the Oracle Optimizer
Best Practices for Oracle Exadata and the Oracle Optimizer
 
Wide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data ModelingWide Column Store NoSQL vs SQL Data Modeling
Wide Column Store NoSQL vs SQL Data Modeling
 
MySQL Atchitecture and Concepts
MySQL Atchitecture and ConceptsMySQL Atchitecture and Concepts
MySQL Atchitecture and Concepts
 
Online index rebuild automation
Online index rebuild automationOnline index rebuild automation
Online index rebuild automation
 
Galera cluster for MySQL - Introduction Slides
Galera cluster for MySQL - Introduction SlidesGalera cluster for MySQL - Introduction Slides
Galera cluster for MySQL - Introduction Slides
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL ServerEnd-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
 
PostgreSQL and RAM usage
PostgreSQL and RAM usagePostgreSQL and RAM usage
PostgreSQL and RAM usage
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAsOracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
 
10 things, an Oracle DBA should care about when moving to PostgreSQL
10 things, an Oracle DBA should care about when moving to PostgreSQL10 things, an Oracle DBA should care about when moving to PostgreSQL
10 things, an Oracle DBA should care about when moving to PostgreSQL
 
LISA2019 Linux Systems Performance
LISA2019 Linux Systems PerformanceLISA2019 Linux Systems Performance
LISA2019 Linux Systems Performance
 

Viewers also liked

Top 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL ServerTop 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL Server
Kevin Kline
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First TimeSQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First Time
Dean Richards
 
Sql server performance tuning
Sql server performance tuningSql server performance tuning
Sql server performance tuning
ngupt28
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning BaselineSQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline
► Supreme Mandal ◄
 
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
Antonios Chatzipavlis
 
SQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database PerformanceSQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database Performance
Mark Ginnebaugh
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)
Harish Chand
 
Peter Allor - The New Era of Cognitive Security
Peter Allor - The New Era of Cognitive SecurityPeter Allor - The New Era of Cognitive Security
Peter Allor - The New Era of Cognitive Security
scoopnewsgroup
 
Reduce latency and boost sql server io performance
Reduce latency and boost sql server io performanceReduce latency and boost sql server io performance
Reduce latency and boost sql server io performance
Kevin Kline
 
Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server ToolkitUltimate Free SQL Server Toolkit
Ultimate Free SQL Server Toolkit
Kevin Kline
 
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
Vinod Kumar
 
The use of blogs in teaching and learning literature in FL
The use of blogs in teaching and learning literature in FLThe use of blogs in teaching and learning literature in FL
The use of blogs in teaching and learning literature in FL
University of Limerick
 
Mediación escolar e implantación de un plan de mediación en un centro educativo
Mediación escolar e implantación de un plan de mediación en un centro educativoMediación escolar e implantación de un plan de mediación en un centro educativo
Mediación escolar e implantación de un plan de mediación en un centro educativo
apegon1
 
Lluvias en el norte 24.03.17
Lluvias en el norte 24.03.17Lluvias en el norte 24.03.17
Lluvias en el norte 24.03.17
Manuel Placido
 
Gender gap in public speaking
Gender gap in public speakingGender gap in public speaking
Gender gap in public speaking
Shiftbalance
 
kintone Café Akita Vol.1 対面開発
kintone Café Akita Vol.1 対面開発kintone Café Akita Vol.1 対面開発
kintone Café Akita Vol.1 対面開発
kintone papers
 
パケットが教えてくれた ルートサーバが 13個の理由
パケットが教えてくれた ルートサーバが 13個の理由パケットが教えてくれた ルートサーバが 13個の理由
パケットが教えてくれた ルートサーバが 13個の理由
@ otsuka752
 
Emergencias oncológicas (Diplomado UniRemington) Parte 4/6
Emergencias oncológicas (Diplomado UniRemington) Parte 4/6Emergencias oncológicas (Diplomado UniRemington) Parte 4/6
Emergencias oncológicas (Diplomado UniRemington) Parte 4/6
Mauricio Lema
 
Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6
Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6
Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6
Mauricio Lema
 

Viewers also liked (20)

Top 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL ServerTop 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL Server
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architectureMicrosoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First TimeSQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First Time
 
Sql server performance tuning
Sql server performance tuningSql server performance tuning
Sql server performance tuning
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning BaselineSQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline
 
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
 
SQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database PerformanceSQL Server Tuning to Improve Database Performance
SQL Server Tuning to Improve Database Performance
 
Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)Performance tuning and optimization (ppt)
Performance tuning and optimization (ppt)
 
Peter Allor - The New Era of Cognitive Security
Peter Allor - The New Era of Cognitive SecurityPeter Allor - The New Era of Cognitive Security
Peter Allor - The New Era of Cognitive Security
 
Reduce latency and boost sql server io performance
Reduce latency and boost sql server io performanceReduce latency and boost sql server io performance
Reduce latency and boost sql server io performance
 
Ultimate Free SQL Server Toolkit
Ultimate Free SQL Server ToolkitUltimate Free SQL Server Toolkit
Ultimate Free SQL Server Toolkit
 
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
 
The use of blogs in teaching and learning literature in FL
The use of blogs in teaching and learning literature in FLThe use of blogs in teaching and learning literature in FL
The use of blogs in teaching and learning literature in FL
 
Mediación escolar e implantación de un plan de mediación en un centro educativo
Mediación escolar e implantación de un plan de mediación en un centro educativoMediación escolar e implantación de un plan de mediación en un centro educativo
Mediación escolar e implantación de un plan de mediación en un centro educativo
 
Lluvias en el norte 24.03.17
Lluvias en el norte 24.03.17Lluvias en el norte 24.03.17
Lluvias en el norte 24.03.17
 
Gender gap in public speaking
Gender gap in public speakingGender gap in public speaking
Gender gap in public speaking
 
kintone Café Akita Vol.1 対面開発
kintone Café Akita Vol.1 対面開発kintone Café Akita Vol.1 対面開発
kintone Café Akita Vol.1 対面開発
 
パケットが教えてくれた ルートサーバが 13個の理由
パケットが教えてくれた ルートサーバが 13個の理由パケットが教えてくれた ルートサーバが 13個の理由
パケットが教えてくれた ルートサーバが 13個の理由
 
Emergencias oncológicas (Diplomado UniRemington) Parte 4/6
Emergencias oncológicas (Diplomado UniRemington) Parte 4/6Emergencias oncológicas (Diplomado UniRemington) Parte 4/6
Emergencias oncológicas (Diplomado UniRemington) Parte 4/6
 
Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6
Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6
Quimioterapia paliativa (Diplomado UniRemington) Parte 5c/6
 

Similar to Ten query tuning techniques every SQL Server programmer should know

Always On Availability Group Maintenance Operations
Always On Availability Group Maintenance OperationsAlways On Availability Group Maintenance Operations
Always On Availability Group Maintenance Operations
John Martin
 
Bringing DevOps to the Database
Bringing DevOps to the DatabaseBringing DevOps to the Database
Bringing DevOps to the Database
Michaela Murray
 
Database Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance AnalysisDatabase Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance Analysis
DAGEOP LTD
 
Breaking data
Breaking dataBreaking data
Breaking data
Terry Bunio
 
Common SQL Server Mistakes and How to Avoid Them with Tim Radney
Common SQL Server Mistakes and How to Avoid Them with Tim RadneyCommon SQL Server Mistakes and How to Avoid Them with Tim Radney
Common SQL Server Mistakes and How to Avoid Them with Tim Radney
Embarcadero Technologies
 
Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional test
Harry Zheng
 
Taming the shrew Power BI
Taming the shrew Power BITaming the shrew Power BI
Taming the shrew Power BI
Kellyn Pot'Vin-Gorman
 
SQL Server Tips & Tricks
SQL Server Tips & TricksSQL Server Tips & Tricks
SQL Server Tips & Tricks
Ike Ellis
 
Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014
Ike Ellis
 
Continuous database deployment
Continuous database deploymentContinuous database deployment
Continuous database deployment
Mike (Michael) Acord
 
DMann-SQLDeveloper4Reporting
DMann-SQLDeveloper4ReportingDMann-SQLDeveloper4Reporting
DMann-SQLDeveloper4Reporting
David Mann
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World Domination
cPanel
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
Steven Smith
 
[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary
[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary
[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary
Hiram Fleitas León
 
Optimizing Access with SQL Server
Optimizing Access with SQL ServerOptimizing Access with SQL Server
Optimizing Access with SQL Server
PRPASS Chapter
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
Performance Benchmarking: Tips, Tricks, and Lessons Learned
Performance Benchmarking: Tips, Tricks, and Lessons LearnedPerformance Benchmarking: Tips, Tricks, and Lessons Learned
Performance Benchmarking: Tips, Tricks, and Lessons Learned
Tim Callaghan
 
KoprowskiT_Session2_SDNEvent_SourceControlForDBA
KoprowskiT_Session2_SDNEvent_SourceControlForDBAKoprowskiT_Session2_SDNEvent_SourceControlForDBA
KoprowskiT_Session2_SDNEvent_SourceControlForDBA
Tobias Koprowski
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
Steven Smith
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
ColdFusionConference
 

Similar to Ten query tuning techniques every SQL Server programmer should know (20)

Always On Availability Group Maintenance Operations
Always On Availability Group Maintenance OperationsAlways On Availability Group Maintenance Operations
Always On Availability Group Maintenance Operations
 
Bringing DevOps to the Database
Bringing DevOps to the DatabaseBringing DevOps to the Database
Bringing DevOps to the Database
 
Database Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance AnalysisDatabase Fundamental Concepts- Series 1 - Performance Analysis
Database Fundamental Concepts- Series 1 - Performance Analysis
 
Breaking data
Breaking dataBreaking data
Breaking data
 
Common SQL Server Mistakes and How to Avoid Them with Tim Radney
Common SQL Server Mistakes and How to Avoid Them with Tim RadneyCommon SQL Server Mistakes and How to Avoid Them with Tim Radney
Common SQL Server Mistakes and How to Avoid Them with Tim Radney
 
Database continuous integration, unit test and functional test
Database continuous integration, unit test and functional testDatabase continuous integration, unit test and functional test
Database continuous integration, unit test and functional test
 
Taming the shrew Power BI
Taming the shrew Power BITaming the shrew Power BI
Taming the shrew Power BI
 
SQL Server Tips & Tricks
SQL Server Tips & TricksSQL Server Tips & Tricks
SQL Server Tips & Tricks
 
Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014Tips & Tricks SQL in the City Seattle 2014
Tips & Tricks SQL in the City Seattle 2014
 
Continuous database deployment
Continuous database deploymentContinuous database deployment
Continuous database deployment
 
DMann-SQLDeveloper4Reporting
DMann-SQLDeveloper4ReportingDMann-SQLDeveloper4Reporting
DMann-SQLDeveloper4Reporting
 
Yapc10 Cdt World Domination
Yapc10   Cdt World DominationYapc10   Cdt World Domination
Yapc10 Cdt World Domination
 
Improving The Quality of Existing Software
Improving The Quality of Existing SoftwareImproving The Quality of Existing Software
Improving The Quality of Existing Software
 
[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary
[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary
[DBA]_HiramFleitas_SQL_PASS_Summit_2017_Summary
 
Optimizing Access with SQL Server
Optimizing Access with SQL ServerOptimizing Access with SQL Server
Optimizing Access with SQL Server
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Performance Benchmarking: Tips, Tricks, and Lessons Learned
Performance Benchmarking: Tips, Tricks, and Lessons LearnedPerformance Benchmarking: Tips, Tricks, and Lessons Learned
Performance Benchmarking: Tips, Tricks, and Lessons Learned
 
KoprowskiT_Session2_SDNEvent_SourceControlForDBA
KoprowskiT_Session2_SDNEvent_SourceControlForDBAKoprowskiT_Session2_SDNEvent_SourceControlForDBA
KoprowskiT_Session2_SDNEvent_SourceControlForDBA
 
Improving the Quality of Existing Software
Improving the Quality of Existing SoftwareImproving the Quality of Existing Software
Improving the Quality of Existing Software
 
Building better SQL Server Databases
Building better SQL Server DatabasesBuilding better SQL Server Databases
Building better SQL Server Databases
 

Recently uploaded

Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...
Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...
Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...
weiwchu
 
Histology of Muscle types histology o.ppt
Histology of Muscle types histology o.pptHistology of Muscle types histology o.ppt
Histology of Muscle types histology o.ppt
SamanArshad11
 
Selcuk Topal Arbitrum Scientific Report.pdf
Selcuk Topal Arbitrum Scientific Report.pdfSelcuk Topal Arbitrum Scientific Report.pdf
Selcuk Topal Arbitrum Scientific Report.pdf
SelcukTOPAL2
 
CT AnGIOGRAPHY of pulmonary embolism.pptx
CT AnGIOGRAPHY of pulmonary embolism.pptxCT AnGIOGRAPHY of pulmonary embolism.pptx
CT AnGIOGRAPHY of pulmonary embolism.pptx
RejoJohn2
 
Training on CSPro and step by steps.pptx
Training on CSPro and step by steps.pptxTraining on CSPro and step by steps.pptx
Training on CSPro and step by steps.pptx
lenjisoHussein
 
How AI is Revolutionizing Data Collection.pdf
How AI is Revolutionizing Data Collection.pdfHow AI is Revolutionizing Data Collection.pdf
How AI is Revolutionizing Data Collection.pdf
PromptCloud
 
Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...
Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...
Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...
femim26318
 
Getting Started with Interactive Brokers API and Python.pdf
Getting Started with Interactive Brokers API and Python.pdfGetting Started with Interactive Brokers API and Python.pdf
Getting Started with Interactive Brokers API and Python.pdf
Riya Sen
 
PRODUCT | RESEARCH-PRESENTATION-1.1.pptx
PRODUCT | RESEARCH-PRESENTATION-1.1.pptxPRODUCT | RESEARCH-PRESENTATION-1.1.pptx
PRODUCT | RESEARCH-PRESENTATION-1.1.pptx
amazenolmedojeruel
 
Aws MLOps Interview Questions with answers
Aws MLOps Interview Questions  with answersAws MLOps Interview Questions  with answers
Aws MLOps Interview Questions with answers
Sathiakumar Chandr
 
Acid Base Practice Test 4- KEY.pdfkkjkjk
Acid Base Practice Test 4- KEY.pdfkkjkjkAcid Base Practice Test 4- KEY.pdfkkjkjk
Acid Base Practice Test 4- KEY.pdfkkjkjk
talha2khan2k
 
Full Disclosure Board Policy.docx BRGY LICUMA
Full  Disclosure Board Policy.docx BRGY LICUMAFull  Disclosure Board Policy.docx BRGY LICUMA
Full Disclosure Board Policy.docx BRGY LICUMA
brgylicumaormoccity
 
SAMPLE PRODUCT RESEARCH PR - strikingly.pptx
SAMPLE PRODUCT RESEARCH PR - strikingly.pptxSAMPLE PRODUCT RESEARCH PR - strikingly.pptx
SAMPLE PRODUCT RESEARCH PR - strikingly.pptx
wojakmodern
 
Audits Of Complaints Against the PPD Report_2022.pdf
Audits Of Complaints Against the PPD Report_2022.pdfAudits Of Complaints Against the PPD Report_2022.pdf
Audits Of Complaints Against the PPD Report_2022.pdf
evwcarr
 
future-of-asset-management-future-of-asset-management
future-of-asset-management-future-of-asset-managementfuture-of-asset-management-future-of-asset-management
future-of-asset-management-future-of-asset-management
Aadee4
 
Accounting and Auditing Laws-Rules-and-Regulations
Accounting and Auditing Laws-Rules-and-RegulationsAccounting and Auditing Laws-Rules-and-Regulations
Accounting and Auditing Laws-Rules-and-Regulations
DALubis
 
Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...
Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...
Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...
rightmanforbloodline
 
393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf
393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf
393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf
Ladislau5
 
Cal Girls Hotel Safari Jaipur | | Girls Call Free Drop Service
Cal Girls Hotel Safari Jaipur | | Girls Call Free Drop ServiceCal Girls Hotel Safari Jaipur | | Girls Call Free Drop Service
Cal Girls Hotel Safari Jaipur | | Girls Call Free Drop Service
Deepikakumari457585
 
SOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERING
SOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERINGSOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERING
SOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERING
PrabhuB33
 

Recently uploaded (20)

Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...
Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...
Harnessing Wild and Untamed (Publicly Available) Data for the Cost efficient ...
 
Histology of Muscle types histology o.ppt
Histology of Muscle types histology o.pptHistology of Muscle types histology o.ppt
Histology of Muscle types histology o.ppt
 
Selcuk Topal Arbitrum Scientific Report.pdf
Selcuk Topal Arbitrum Scientific Report.pdfSelcuk Topal Arbitrum Scientific Report.pdf
Selcuk Topal Arbitrum Scientific Report.pdf
 
CT AnGIOGRAPHY of pulmonary embolism.pptx
CT AnGIOGRAPHY of pulmonary embolism.pptxCT AnGIOGRAPHY of pulmonary embolism.pptx
CT AnGIOGRAPHY of pulmonary embolism.pptx
 
Training on CSPro and step by steps.pptx
Training on CSPro and step by steps.pptxTraining on CSPro and step by steps.pptx
Training on CSPro and step by steps.pptx
 
How AI is Revolutionizing Data Collection.pdf
How AI is Revolutionizing Data Collection.pdfHow AI is Revolutionizing Data Collection.pdf
How AI is Revolutionizing Data Collection.pdf
 
Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...
Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...
Cal Girls Mansarovar Jaipur | 08445551418 | Rajni High Profile Girls Call in ...
 
Getting Started with Interactive Brokers API and Python.pdf
Getting Started with Interactive Brokers API and Python.pdfGetting Started with Interactive Brokers API and Python.pdf
Getting Started with Interactive Brokers API and Python.pdf
 
PRODUCT | RESEARCH-PRESENTATION-1.1.pptx
PRODUCT | RESEARCH-PRESENTATION-1.1.pptxPRODUCT | RESEARCH-PRESENTATION-1.1.pptx
PRODUCT | RESEARCH-PRESENTATION-1.1.pptx
 
Aws MLOps Interview Questions with answers
Aws MLOps Interview Questions  with answersAws MLOps Interview Questions  with answers
Aws MLOps Interview Questions with answers
 
Acid Base Practice Test 4- KEY.pdfkkjkjk
Acid Base Practice Test 4- KEY.pdfkkjkjkAcid Base Practice Test 4- KEY.pdfkkjkjk
Acid Base Practice Test 4- KEY.pdfkkjkjk
 
Full Disclosure Board Policy.docx BRGY LICUMA
Full  Disclosure Board Policy.docx BRGY LICUMAFull  Disclosure Board Policy.docx BRGY LICUMA
Full Disclosure Board Policy.docx BRGY LICUMA
 
SAMPLE PRODUCT RESEARCH PR - strikingly.pptx
SAMPLE PRODUCT RESEARCH PR - strikingly.pptxSAMPLE PRODUCT RESEARCH PR - strikingly.pptx
SAMPLE PRODUCT RESEARCH PR - strikingly.pptx
 
Audits Of Complaints Against the PPD Report_2022.pdf
Audits Of Complaints Against the PPD Report_2022.pdfAudits Of Complaints Against the PPD Report_2022.pdf
Audits Of Complaints Against the PPD Report_2022.pdf
 
future-of-asset-management-future-of-asset-management
future-of-asset-management-future-of-asset-managementfuture-of-asset-management-future-of-asset-management
future-of-asset-management-future-of-asset-management
 
Accounting and Auditing Laws-Rules-and-Regulations
Accounting and Auditing Laws-Rules-and-RegulationsAccounting and Auditing Laws-Rules-and-Regulations
Accounting and Auditing Laws-Rules-and-Regulations
 
Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...
Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...
Solution Manual for First Course in Abstract Algebra A, 8th Edition by John B...
 
393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf
393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf
393947940-The-Dell-EMC-PowerMax-Family-Overview.pdf
 
Cal Girls Hotel Safari Jaipur | | Girls Call Free Drop Service
Cal Girls Hotel Safari Jaipur | | Girls Call Free Drop ServiceCal Girls Hotel Safari Jaipur | | Girls Call Free Drop Service
Cal Girls Hotel Safari Jaipur | | Girls Call Free Drop Service
 
SOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERING
SOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERINGSOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERING
SOFTWARE ENGINEERING-UNIT-1SOFTWARE ENGINEERING
 

Ten query tuning techniques every SQL Server programmer should know

  • 1. TEN QUERY TUNING TECHNIQUES Every SQL Programmer Should Know Kevin Kline Director of Engineering Services at SQL Sentry Microsoft MVP since 2003 Facebook, LinkedIn, Twitter at KEKLINE KEKline@sqlsentry.com KevinEKline.com, ForITPros.com
  • 2. FOR FRIENDS OF SQL SENTRY • Free Plan Explorer download: http://www.sqlsentry.net/plan-explorer/ • Free query tuning consultations: http://answers.sqlperformance.com. • Free new ebook (regularly $10) to attendees. Send request to sales@sqlsentry.net. • SQL Server educational videos, scripts, and slides: http://SQLSentry.TV • Tuning blog: http://www.sqlperformance.com/ • Monthly eNews tips and tricks: http://www.sqlsentry.net/newsletter-archive. asp
  • 3. AGENDA • Introductions • Test & tuning environment • 1. Clearing caches • Looking for red flags • 2. Reading execution plans • Query tuning techniques: • 8 more specific examples of widespread approaches that lead to poor performance • Summary 3
  • 4. TEST & TUNING ENVIRONMENT • Code to clear the caches*: o CHECKPOINT o DBCC [FreeProcCache | FreeSystemCache | FlushProcInDB(<dbid>) ] o DBCC DropCleanBuffers • Code to set measurements: o SET STATISTICS [TIME | IO] o SET SHOWPLAN [TEXT | XML] or Graphic Execution Plans • Code for Dynamic Management Views (DMV) checks. o System info – sys.dm_os_performance_counters, sys.dm_os_wait_stats o Query info – sys.dm_exec_requests o Index info – sys.dm_db_index_usage_stats, sys.dm_io_virtual_file_stats
  • 5. RED FLAGS IN YOUR SQL CODE • Red Flags Query Operators: o Lookups, Scans, Spools, Parallelism Operations • Other Red Flags: o Dissimilar estimated versus actual row counts o High physical reads o Missing statistics alarms o Large sort operations o Implicit data type conversions
  • 6. DEMOS: DEFAULT CURSORS • I don’t always use cursors… o …but when I do, I avoid the default options o Slow and heavy-handed: Global, updateable, dynamic, scrollable o I use LOCAL FAST_FORWARD o May want to test STATIC vs. DYNAMIC, when tempdb is a bottleneck • Blog post: http://bit.ly/AB-cursors
  • 7. DEMOS: WHERE IN VERSUS WHERE EXISTS • There are lots of ways to find data existing within subsets: • IN, EXISTS, JOIN, Apply, subquery • Which technique is best? • Blog post: http://bit.ly/AB-NOTIN
  • 8. OPTIMIZING FOR SELECT VERSUS DML • Big differences between a SELECT and a DML statement that effects the same rows. • Shouldn’t blindly create every index the Tuning Advisor or execution plan tells you to! • Blog post - http://bit.ly/AB-BlindIndex
  • 9. READS & INDEX STRUCTURE • 8K pages • Leaf pages ARE the data. • Non-leaf pages are pointers. Leaf Pages Root Page Level 0 Intermediate Pages Level 1 Level 2
  • 10. WRITES & INDEX STRUCTURE • Each change to the leaf pages requires all index structures be updated. Leaf Pages Root Page Level 0 Intermediate Pages Level 1 Level 2 Page Split DML Actual place-ment
  • 11. DEMOS: UNWANTED RECOMPILES Execution In Memory? NO Load metadata compile optimize Execute YES ReComp
  • 12. CAUSES OF RECOMPILE • Expected: Because we request it: • CREATE PROC … WITH RECOMPILE or EXEC myproc … WITH RECOMPILE • SP_RECOMPILE foo • Expected: Plan was aged out of memory • Unexpected: Interleaved DDL and DML • Unexpected: Big changes since last execution: • Schema changes to objects in underlying code • New/updated index statistics • Sp_configure
  • 13. INTERLEAVED DDL AND DML • CREATE PROC testddldml AS … ; • CREATE TABLE #testdml; -- (DDL) • <some T-SQL code here> • INSERT INTO #testdml; -- (DML + RECOMPILE) • <some T-SQL code here> • ALTER TABLE #testdml; -- (DDL) • <some T-SQL code here> • INSERT INTO #testdml; -- (DML + RECOMPILE) • <some T-SQL code here> • DROP TABLE #testdml; -- (DDL) • <some T-SQL code here>
  • 14. DEMOS: THE "KITCHEN SINK" PROCEDURE • Usually see it as a one-query-for-all-queries procedure, or even one-proc-for-for-all-transactions procedure: o Where name starts with S, or placed an order this year, or lives in Texas o Insert AND Update AND Delete AND Select • Conflicting optional parameters make optimization impossible o OPTION (RECOMPILE) o Dynamic SQL + Optimize for ad hoc workloads o Specialized procedures • Better approach? o Specialize and optimize each piece of code to do ONE THING really effectively
  • 15. DEMOS: SP_EXECUTESQL VS. EXEC(…) • I don’t always use dynamic SQL… o …but when I do, I always use sp_executesql o Less fuss with concatenation and implicit/explicit conversions o Better protection against SQL injection (but not for all things) o At worst case, behavior is the same • Can promote better plan re-use • Encourages strongly typed parameters instead of building up a massive string
  • 16. IMPLICIT CONVERSIONS • SQL Server has to do a lot of extra work / scans when conversion operations are assumed by the SQL programmer. • Happens all the time with data types you’d think wouldn’t need it, e.g. between date types and character types. • Very useful data type conversion chart at http://bit.ly/15bDRRA. • Data type precedence call also have an impact: http://bit.ly/13Zio1f.
  • 17. IMPLICIT CONVERSION RESOURCES • Ian Stirk’s Column Mismatch Utility at http://www.sqlservercentral.com/articles/Administration/6 5138/. • Jonathan Kehayias’ plan cache analyzer at http://sqlblog.com/blogs/jonathan_kehayias/archive/2010 /01/08/finding-implicit-column-conversions-in-the-plan-cache. aspx. • Jonathan Kehayias’ index scan study at http://www.sqlperformance.com/2013/04/t-sql-queries/ implicit-conversion-costs
  • 18. DEMOS: COMMA-DELIMITED PARAMETERS • Example: pass a comma-separated list of OrderIDs • String splitting is expensive, even using CLR • Table-valued parameters are typically a better approach
  • 19. DEMOS: TEMPORARY STRUCTURES • Which are better, temp tables or temp variables? Temp Table Temp Variable Stored in? Tempdb Tempdb Statistics? Yes No (1 row) Indexs/Keys? Yes 1 UK / PK only Truncate? Yes No Recompiles? Yes No Parallelism? Yes No Metadata Overhead? Low Lowest Lock Overhead? Normal Lowest
  • 20. CODING STANDARDS AND DISSIMILARITY • Might sound frivolous, but naming schemes are important o Convention is not important; but rather being consistent and logical • Story: dbo.UpdateCustomer vs. dbo.Customer_Update • Always specify schema when creating, altering, referencing objects o Object resolution works a little bit harder without it o More importantly, it can get the wrong answer o And will often yield multiple copies of the same plan • Do not use the sp_ prefix on stored procedures o This has observable overhead, no matter how specific you are
  • 21. MIMICKING PRODUCTION • Your dev machine is usually nothing like production o Build representative data when you can o Build a stats-only database when you can’t (a.k.a. a database clone) • Will allow you to see plan issues, but not speed o Make sure settings are the same • @@VERSION, edition • Max memory if possible, sp_configure options • Logins (and permissions), tempdb settings • Parameterization settings, recovery model, compression, snapshot isolation • Compatibility level (usually not an issue when working with a restore) • Run a full business cycle workload after a restore o Simulate equivalent hardware: DBCC OPTIMIZER_WHATIF o Use Distributed Replay when you can • Not perfect, but more realistic than single-threaded trace replay
  • 22. SUMMARY Let’s connect! Facebook, LinkedIn, Twitter at KEKLINE. Email at KEKline@sqlsentry.com Blogs at http://KevinEKline.com And http://ForITPros.com
  • 23. WRAP UP Engage with us on social media o I’m thankful for your word of mouth promotions and endorsements! Share your tough SQL tuning problems with us: http://answers.sqlperformance.com Download SQL Sentry Plan Explorer for free: http://www.sqlsentry.com/plan-explorer/ Check out our other award winning tools: http://www.sqlsentry.net/download
  • 25. NOLOCK • It is a turbo button …if you’re ok with inaccuracy • There are times it is perfectly valid o Ballpark row counts o Please use session-level setting, not table hint • Usually, though, better to use SNAPSHOT or RCSI o But test under heavy load