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
Ad

Recommended

Performance tuning in sql server
Performance tuning in sql server
Antonios Chatzipavlis
 
SQL Server Performance Tuning Baseline
SQL Server Performance Tuning Baseline
► Supreme Mandal ◄
 
MS-SQL SERVER ARCHITECTURE
MS-SQL SERVER ARCHITECTURE
Douglas Bernardini
 
Analyzing awr report
Analyzing awr report
satish Gaddipati
 
Physical architecture of sql server
Physical architecture of sql server
Divya Sharma
 
Oracle statistics by example
Oracle statistics by example
Mauro Pagano
 
Postgresql database administration volume 1
Postgresql database administration volume 1
Federico Campoli
 
Date warehousing concepts
Date warehousing concepts
pcherukumalla
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
Database performance tuning and query optimization
Database performance tuning and query optimization
Dhani Ahmad
 
Oracle sql high performance tuning
Oracle sql high performance tuning
Guy Harrison
 
Oracle Performance Tools of the Trade
Oracle Performance Tools of the Trade
Carlos Sierra
 
Sql server basics
Sql server basics
Dilfaroz Khan
 
Oracle database performance tuning
Oracle database performance tuning
Yogiji Creations
 
Sql server basics
Sql server basics
VishalJharwade
 
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Julien Le Dem
 
Sql Server Performance Tuning
Sql Server Performance Tuning
Bala Subra
 
Best Practices for Becoming an Exceptional Postgres DBA
Best Practices for Becoming an Exceptional Postgres DBA
EDB
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
Enkitec
 
Sql server performance tuning
Sql server performance tuning
ngupt28
 
Hit Refresh with Oracle GoldenGate Microservices
Hit Refresh with Oracle GoldenGate Microservices
Bobby Curtis
 
Understanding and controlling transaction logs
Understanding and controlling transaction logs
Red Gate Software
 
오라클 DB 아키텍처와 튜닝
오라클 DB 아키텍처와 튜닝
철민 권
 
Centralized Logging System Using ELK Stack
Centralized Logging System Using ELK Stack
Rohit Sharma
 
Ms sql server architecture
Ms sql server architecture
Ajeet Singh
 
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Carlos Sierra
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
Jitendra Singh
 
Top 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL Server
Kevin Kline
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First Time
Dean Richards
 

More Related Content

What's hot (20)

Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
Database performance tuning and query optimization
Database performance tuning and query optimization
Dhani Ahmad
 
Oracle sql high performance tuning
Oracle sql high performance tuning
Guy Harrison
 
Oracle Performance Tools of the Trade
Oracle Performance Tools of the Trade
Carlos Sierra
 
Sql server basics
Sql server basics
Dilfaroz Khan
 
Oracle database performance tuning
Oracle database performance tuning
Yogiji Creations
 
Sql server basics
Sql server basics
VishalJharwade
 
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Julien Le Dem
 
Sql Server Performance Tuning
Sql Server Performance Tuning
Bala Subra
 
Best Practices for Becoming an Exceptional Postgres DBA
Best Practices for Becoming an Exceptional Postgres DBA
EDB
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
Enkitec
 
Sql server performance tuning
Sql server performance tuning
ngupt28
 
Hit Refresh with Oracle GoldenGate Microservices
Hit Refresh with Oracle GoldenGate Microservices
Bobby Curtis
 
Understanding and controlling transaction logs
Understanding and controlling transaction logs
Red Gate Software
 
오라클 DB 아키텍처와 튜닝
오라클 DB 아키텍처와 튜닝
철민 권
 
Centralized Logging System Using ELK Stack
Centralized Logging System Using ELK Stack
Rohit Sharma
 
Ms sql server architecture
Ms sql server architecture
Ajeet Singh
 
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Carlos Sierra
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
Jitendra Singh
 
Microsoft SQL Server internals & architecture
Microsoft SQL Server internals & architecture
Kevin Kline
 
Database performance tuning and query optimization
Database performance tuning and query optimization
Dhani Ahmad
 
Oracle sql high performance tuning
Oracle sql high performance tuning
Guy Harrison
 
Oracle Performance Tools of the Trade
Oracle Performance Tools of the Trade
Carlos Sierra
 
Oracle database performance tuning
Oracle database performance tuning
Yogiji Creations
 
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Efficient Data Storage for Analytics with Parquet 2.0 - Hadoop Summit 2014
Julien Le Dem
 
Sql Server Performance Tuning
Sql Server Performance Tuning
Bala Subra
 
Best Practices for Becoming an Exceptional Postgres DBA
Best Practices for Becoming an Exceptional Postgres DBA
EDB
 
Oracle Performance Tuning Fundamentals
Oracle Performance Tuning Fundamentals
Enkitec
 
Sql server performance tuning
Sql server performance tuning
ngupt28
 
Hit Refresh with Oracle GoldenGate Microservices
Hit Refresh with Oracle GoldenGate Microservices
Bobby Curtis
 
Understanding and controlling transaction logs
Understanding and controlling transaction logs
Red Gate Software
 
오라클 DB 아키텍처와 튜닝
오라클 DB 아키텍처와 튜닝
철민 권
 
Centralized Logging System Using ELK Stack
Centralized Logging System Using ELK Stack
Rohit Sharma
 
Ms sql server architecture
Ms sql server architecture
Ajeet Singh
 
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Understanding SQL Trace, TKPROF and Execution Plan for beginners
Carlos Sierra
 
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Oracle Database Performance Tuning Advanced Features and Best Practices for DBAs
Zohar Elkayam
 
Performance Stability, Tips and Tricks and Underscores
Performance Stability, Tips and Tricks and Underscores
Jitendra Singh
 

Viewers also liked (19)

Top 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL Server
Kevin Kline
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First Time
Dean Richards
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
Kevin Kline
 
Why & 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 Performance
Mark Ginnebaugh
 
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 Security
scoopnewsgroup
 
Reduce 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 Toolkit
Kevin Kline
 
SQL 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 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 educativo
apegon1
 
Lluvias en el norte 24.03.17
Lluvias en el norte 24.03.17
Manuel Placido
 
Gender gap in public speaking
Gender gap in public speaking
Shiftbalance
 
kintone Café Akita Vol.1 対面開発
kintone Café Akita Vol.1 対面開発
kintone papers
 
パケットが教えてくれた ルートサーバが 13個の理由
パケットが教えてくれた ルートサーバが 13個の理由
@ otsuka752
 
Emergencias 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/6
Mauricio Lema
 
RUNNING Smalltalk - 実践Smalltalk
RUNNING Smalltalk - 実践Smalltalk
Sho Yoshida
 
Top 10 DBA Mistakes on Microsoft SQL Server
Top 10 DBA Mistakes on Microsoft SQL Server
Kevin Kline
 
SQL Server Query Tuning Tips - Get it Right the First Time
SQL Server Query Tuning Tips - Get it Right the First Time
Dean Richards
 
End-to-end Troubleshooting Checklist for Microsoft SQL Server
End-to-end Troubleshooting Checklist for Microsoft SQL Server
Kevin Kline
 
Why & 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 Performance
Mark Ginnebaugh
 
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 Security
scoopnewsgroup
 
Reduce 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 Toolkit
Kevin Kline
 
SQL 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 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 educativo
apegon1
 
Lluvias en el norte 24.03.17
Lluvias en el norte 24.03.17
Manuel Placido
 
Gender gap in public speaking
Gender gap in public speaking
Shiftbalance
 
kintone Café Akita Vol.1 対面開発
kintone Café Akita Vol.1 対面開発
kintone papers
 
パケットが教えてくれた ルートサーバが 13個の理由
パケットが教えてくれた ルートサーバが 13個の理由
@ otsuka752
 
Emergencias 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/6
Mauricio Lema
 
RUNNING Smalltalk - 実践Smalltalk
RUNNING Smalltalk - 実践Smalltalk
Sho Yoshida
 
Ad

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

02 database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
SQL Server Performance Tuning | Query Tuning training | SQLSchool Training In...
SQL Server Performance Tuning | Query Tuning training | SQLSchool Training In...
SequelGate
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimization
Ivo Andreev
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
BRIJESH KUMAR
 
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
cookie1969
 
SQL Server 2012 Best Practices
SQL Server 2012 Best Practices
Microsoft TechNet - Belgium and Luxembourg
 
Query Tuning for Database Pros & Developers
Query Tuning for Database Pros & Developers
Code Mastery
 
Advanced tips for making Oracle databases faster
Advanced tips for making Oracle databases faster
SolarWinds
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
paulguerin
 
Sql good practices
Sql good practices
Deepak Mehtani
 
3 query tuning techniques every sql server programmer should know
3 query tuning techniques every sql server programmer should know
Rodrigo Crespi
 
Microsoft SQL Server Query Tuning
Microsoft SQL Server Query Tuning
Mark Ginnebaugh
 
31063115_1679409488310Developer_Tuning_Tips_-_UTOUG_Mar_2023.pdf
31063115_1679409488310Developer_Tuning_Tips_-_UTOUG_Mar_2023.pdf
TricantinoLopezPerez
 
Hpd 1
Hpd 1
dikshagupta111
 
Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
Nirav Shah
 
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
SolarWinds
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsf
Mao Geng
 
Oracle sql tuning
Oracle sql tuning
bishnupriya Panda
 
T sql performance guidelines for better db stress powers
T sql performance guidelines for better db stress powers
Shehap Elnagar
 
02 database oprimization - improving sql performance - ent-db
02 database oprimization - improving sql performance - ent-db
uncleRhyme
 
SQL Server Performance Tuning | Query Tuning training | SQLSchool Training In...
SQL Server Performance Tuning | Query Tuning training | SQLSchool Training In...
SequelGate
 
Practical SQL query monitoring and optimization
Practical SQL query monitoring and optimization
Ivo Andreev
 
SQL Database Performance Tuning for Developers
SQL Database Performance Tuning for Developers
BRIJESH KUMAR
 
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
NOCOUG_201311_Fine_Tuning_Execution_Plans.pdf
cookie1969
 
Query Tuning for Database Pros & Developers
Query Tuning for Database Pros & Developers
Code Mastery
 
Advanced tips for making Oracle databases faster
Advanced tips for making Oracle databases faster
SolarWinds
 
Myth busters - performance tuning 101 2007
Myth busters - performance tuning 101 2007
paulguerin
 
3 query tuning techniques every sql server programmer should know
3 query tuning techniques every sql server programmer should know
Rodrigo Crespi
 
Microsoft SQL Server Query Tuning
Microsoft SQL Server Query Tuning
Mark Ginnebaugh
 
31063115_1679409488310Developer_Tuning_Tips_-_UTOUG_Mar_2023.pdf
31063115_1679409488310Developer_Tuning_Tips_-_UTOUG_Mar_2023.pdf
TricantinoLopezPerez
 
Database Performance Tuning
Database Performance Tuning
Arno Huetter
 
Top 10 Oracle SQL tuning tips
Top 10 Oracle SQL tuning tips
Nirav Shah
 
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
Stop the Chaos! Get Real Oracle Performance by Query Tuning Part 2
SolarWinds
 
Oracle performance tuning_sfsf
Oracle performance tuning_sfsf
Mao Geng
 
T sql performance guidelines for better db stress powers
T sql performance guidelines for better db stress powers
Shehap Elnagar
 
Ad

Recently uploaded (20)

最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
taqyea
 
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
payalmistryb
 
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
Tamanna36
 
deep_learning_presentation related to llm
deep_learning_presentation related to llm
sayedabdussalam11
 
美国毕业证范本中华盛顿大学学位证书CWU学生卡购买
美国毕业证范本中华盛顿大学学位证书CWU学生卡购买
Taqyea
 
BCG-Executive-Perspectives-CEOs-Guide-to-Maximizing-Value-from-AI-EP0-3July20...
BCG-Executive-Perspectives-CEOs-Guide-to-Maximizing-Value-from-AI-EP0-3July20...
benediktnetzer1
 
Indigo dyeing Presentation (2).pptx as dye
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
 
Prescriptive Process Monitoring Under Uncertainty and Resource Constraints: A...
Prescriptive Process Monitoring Under Uncertainty and Resource Constraints: A...
Mahmoud Shoush
 
英国毕业证范本利物浦约翰摩尔斯大学成绩单底纹防伪LJMU学生证办理学历认证
英国毕业证范本利物浦约翰摩尔斯大学成绩单底纹防伪LJMU学生证办理学历认证
taqyed
 
最新版美国约翰霍普金斯大学毕业证(JHU毕业证书)原版定制
最新版美国约翰霍普金斯大学毕业证(JHU毕业证书)原版定制
Taqyea
 
Flextronics Employee Safety Data-Project-2.pptx
Flextronics Employee Safety Data-Project-2.pptx
kilarihemadri
 
llm_presentation and deep learning methods
llm_presentation and deep learning methods
sayedabdussalam11
 
All the DataOps, all the paradigms .
All the DataOps, all the paradigms .
Lars Albertsson
 
11_L2_Defects_and_Trouble_Shooting_2014[1].pdf
11_L2_Defects_and_Trouble_Shooting_2014[1].pdf
gun3awan88
 
The Influence off Flexible Work Policies
The Influence off Flexible Work Policies
sales480687
 
Boost Business Efficiency with Professional Data Entry Services
Boost Business Efficiency with Professional Data Entry Services
eloiacs eloiacs
 
定制OCAD学生卡加拿大安大略艺术与设计大学成绩单范本,OCAD成绩单复刻
定制OCAD学生卡加拿大安大略艺术与设计大学成绩单范本,OCAD成绩单复刻
taqyed
 
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
taqyea
 
reporting monthly for genset & Air Compressor.pptx
reporting monthly for genset & Air Compressor.pptx
dacripapanjaitan
 
Shifting Focus on AI: How it Can Make a Positive Difference
Shifting Focus on AI: How it Can Make a Positive Difference
1508 A/S
 
最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
最新版意大利米兰大学毕业证(UNIMI毕业证书)原版定制
taqyea
 
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
YEAP !NOT WHAT YOU THINK aakshdjdncnkenfj
payalmistryb
 
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
NVIDIA Triton Inference Server, a game-changing platform for deploying AI mod...
Tamanna36
 
deep_learning_presentation related to llm
deep_learning_presentation related to llm
sayedabdussalam11
 
美国毕业证范本中华盛顿大学学位证书CWU学生卡购买
美国毕业证范本中华盛顿大学学位证书CWU学生卡购买
Taqyea
 
BCG-Executive-Perspectives-CEOs-Guide-to-Maximizing-Value-from-AI-EP0-3July20...
BCG-Executive-Perspectives-CEOs-Guide-to-Maximizing-Value-from-AI-EP0-3July20...
benediktnetzer1
 
Indigo dyeing Presentation (2).pptx as dye
Indigo dyeing Presentation (2).pptx as dye
shreeroop1335
 
Prescriptive Process Monitoring Under Uncertainty and Resource Constraints: A...
Prescriptive Process Monitoring Under Uncertainty and Resource Constraints: A...
Mahmoud Shoush
 
英国毕业证范本利物浦约翰摩尔斯大学成绩单底纹防伪LJMU学生证办理学历认证
英国毕业证范本利物浦约翰摩尔斯大学成绩单底纹防伪LJMU学生证办理学历认证
taqyed
 
最新版美国约翰霍普金斯大学毕业证(JHU毕业证书)原版定制
最新版美国约翰霍普金斯大学毕业证(JHU毕业证书)原版定制
Taqyea
 
Flextronics Employee Safety Data-Project-2.pptx
Flextronics Employee Safety Data-Project-2.pptx
kilarihemadri
 
llm_presentation and deep learning methods
llm_presentation and deep learning methods
sayedabdussalam11
 
All the DataOps, all the paradigms .
All the DataOps, all the paradigms .
Lars Albertsson
 
11_L2_Defects_and_Trouble_Shooting_2014[1].pdf
11_L2_Defects_and_Trouble_Shooting_2014[1].pdf
gun3awan88
 
The Influence off Flexible Work Policies
The Influence off Flexible Work Policies
sales480687
 
Boost Business Efficiency with Professional Data Entry Services
Boost Business Efficiency with Professional Data Entry Services
eloiacs eloiacs
 
定制OCAD学生卡加拿大安大略艺术与设计大学成绩单范本,OCAD成绩单复刻
定制OCAD学生卡加拿大安大略艺术与设计大学成绩单范本,OCAD成绩单复刻
taqyed
 
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
最新版美国芝加哥大学毕业证(UChicago毕业证书)原版定制
taqyea
 
reporting monthly for genset & Air Compressor.pptx
reporting monthly for genset & Air Compressor.pptx
dacripapanjaitan
 
Shifting Focus on AI: How it Can Make a Positive Difference
Shifting Focus on AI: How it Can Make a Positive Difference
1508 A/S
 

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 [email protected] 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 [email protected]. • 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 [email protected] 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