sql server query performance tuning - springer978-1-4302-6742-3/1.pdf · sql server query...
Post on 24-Jun-2018
262 Views
Preview:
TRANSCRIPT
SQL Server Query Performance Tuning
Copyright © 2014 by Grant Fritchey
This work is subject to copyright. All rights are reserved by the Publisher, whether the whole or part of the material is concerned, specifically the rights of translation, reprinting, reuse of illustrations, recitation, broadcasting, reproduction on microfilms or in any other physical way, and transmission or information storage and retrieval, electronic adaptation, computer software, or by similar or dissimilar methodology now known or hereafter developed. Exempted from this legal reservation are brief excerpts in connection with reviews or scholarly analysis or material supplied specifically for the purpose of being entered and executed on a computer system, for exclusive use by the purchaser of the work. Duplication of this publication or parts thereof is permitted only under the provisions of the Copyright Law of the Publisher’s location, in its current version, and permission for use must always be obtained from Springer. Permissions for use may be obtained through RightsLink at the Copyright Clearance Center. Violations are liable to prosecution under the respective Copyright Law.
ISBN-13 (pbk): 978-1-4302-6743-0
ISBN-13 (electronic): 978-1-4302-6742-3
Trademarked names, logos, and images may appear in this book. Rather than use a trademark symbol with every occurrence of a trademarked name, logo, or image we use the names, logos, and images only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark.
The use in this publication of trade names, trademarks, service marks, and similar terms, even if they are not identified as such, is not to be taken as an expression of opinion as to whether or not they are subject to proprietary rights.
While the advice and information in this book are believed to be true and accurate at the date of publication, neither the authors nor the editors nor the publisher can accept any legal responsibility for any errors or omissions that may be made. The publisher makes no warranty, express or implied, with respect to the material contained herein.
Publisher: Heinz WeinheimerLead Editor: Jonathan GennickTechnical Reviewer: Joseph SackEditorial Board: Steve Anglin, Mark Beckner, Ewan Buckingham, Gary Cornell, Louise Corrigan,
Jim DeWolf, Jonathan Gennick, Robert Hutchinson, Michelle Lowman, James Markham, Matthew Moodie, Jeff Olson, Jeffrey Pepper, Douglas Pundick, Ben Renow-Clarke, Dominic Shakeshaft, Gwenan Spearing, Matt Wade, Steve Weiss
Coordinating Editor: Jill BalzanoCopy Editor: Kim WimpsettCompositor: SPi GlobalIndexer: SPi GlobalArtist: SPi GlobalCover Designer: Anna Ishchenko
Distributed to the book trade worldwide by Springer Science+Business Media New York, 233 Spring Street, 6th Floor, New York, NY 10013. Phone 1-800-SPRINGER, fax (201) 348-4505, e-mail orders-ny@springer-sbm.com, or visit www.springeronline.com.
For information on translations, please e-mail rights@apress.com, or visit www.apress.com.
Apress and friends of ED books may be purchased in bulk for academic, corporate, or promotional use. eBook versions and licenses are also available for most titles. For more information, reference our Special Bulk Sales–eBook Licensing web page at www.apress.com/bulk-sales.
Any source code or other supplementary materials referenced by the author in this text is available to readers at www.apress.com. For detailed information about how to locate your book’s source code, go to www.apress.com/source-code/.
iii
Contents at a Glance
About the Author ������������������������������������������������������������������������������������������������������������� xxiii
About the Technical Reviewer ������������������������������������������������������������������������������������������ xxv
Acknowledgments ���������������������������������������������������������������������������������������������������������� xxvii
Introduction ��������������������������������������������������������������������������������������������������������������������� xxix
Chapter 1: SQL Query Performance Tuning ■ ������������������������������������������������������������������������1
Chapter 2: Memory Performance Analysis ■ ����������������������������������������������������������������������17
Chapter 3: Disk Performance Analysis ■ ����������������������������������������������������������������������������35
Chapter 4: CPU Performance Analysis ■ �����������������������������������������������������������������������������47
Chapter 5: Creating a Baseline ■ ����������������������������������������������������������������������������������������57
Chapter 6: Query Performance Metrics ■ ���������������������������������������������������������������������������69
Chapter 7: Analyzing Query Performance ■ ����������������������������������������������������������������������85
Chapter 8: Index Architecture and Behavior ■ �����������������������������������������������������������������111
Chapter 9: Index Analysis ■ ����������������������������������������������������������������������������������������������143
Chapter 10: Database Engine Tuning Advisor ■ ����������������������������������������������������������������165
Chapter 11: Key Lookups and Solutions ■ ������������������������������������������������������������������������181
Chapter 12: Statistics, Data Distribution, and Cardinality ■ ���������������������������������������������193
Chapter 13: Index Fragmentation ■ ����������������������������������������������������������������������������������237
Chapter 14: Execution Plan Generation ■ �������������������������������������������������������������������������269
Chapter 15 Execution Plan Cache Behavior ■ �������������������������������������������������������������������283
■ Contents at a GlanCe
iv
Chapter 16: Parameter Sniffing ■ �������������������������������������������������������������������������������������311
Chapter 17: Query Recompilation ■ ����������������������������������������������������������������������������������321
Chapter 18: Query Design Analysis ■ �������������������������������������������������������������������������������355
Chapter 19: Reduce Query Resource Use ■ ����������������������������������������������������������������������379
Chapter 20: Blocking and Blocked Processes ■ ���������������������������������������������������������������397
Chapter 21: Causes and Solutions for Deadlocks ■ ����������������������������������������������������������443
Chapter 22: Row-by-Row Processing ■ ����������������������������������������������������������������������������459
Chapter 23: Memory-Optimized OLTP Tables and Procedures ■ ���������������������������������������483
Chapter 24: Database Performance Testing ■ ������������������������������������������������������������������505
Chapter 25: Database Workload Optimization ■ ���������������������������������������������������������������515
Chapter 26: SQL Server Optimization Checklist ■ ������������������������������������������������������������547
Index ���������������������������������������������������������������������������������������������������������������������������������565
v
Contents
About the Author ������������������������������������������������������������������������������������������������������������� xxiii
About the Technical Reviewer ������������������������������������������������������������������������������������������ xxv
Acknowledgments ���������������������������������������������������������������������������������������������������������� xxvii
Introduction ��������������������������������������������������������������������������������������������������������������������� xxix
Chapter 1: SQL Query Performance Tuning ■ ������������������������������������������������������������������������1
The Performance Tuning Process ��������������������������������������������������������������������������������������������������2
The Core Process ��������������������������������������������������������������������������������������������������������������������������������������������������� 2
Iterating the Process ��������������������������������������������������������������������������������������������������������������������������������������������� 5
Performance vs� Price �������������������������������������������������������������������������������������������������������������������8
Performance Targets ��������������������������������������������������������������������������������������������������������������������������������������������� 8
“Good Enough” Tuning ������������������������������������������������������������������������������������������������������������������������������������������� 8
Performance Baseline �������������������������������������������������������������������������������������������������������������������9
Where to Focus Efforts ����������������������������������������������������������������������������������������������������������������10
SQL Server Performance Killers ��������������������������������������������������������������������������������������������������11
Insufficient Indexing �������������������������������������������������������������������������������������������������������������������������������������������� 11
Inaccurate Statistics �������������������������������������������������������������������������������������������������������������������������������������������� 12
Improper Query Design ���������������������������������������������������������������������������������������������������������������������������������������� 12
Poorly Generated Execution Plans ����������������������������������������������������������������������������������������������������������������������� 12
Excessive Blocking and Deadlocks���������������������������������������������������������������������������������������������������������������������� 13
Non-Set-Based Operations ���������������������������������������������������������������������������������������������������������������������������������� 13
Inappropriate Database Design ��������������������������������������������������������������������������������������������������������������������������� 13
Excessive Fragmentation������������������������������������������������������������������������������������������������������������������������������������� 14
■ Contents
vi
Nonreusable Execution Plans ������������������������������������������������������������������������������������������������������������������������������ 14
Frequent Recompilation of Queries ��������������������������������������������������������������������������������������������������������������������� 14
Improper Use of Cursors �������������������������������������������������������������������������������������������������������������������������������������� 14
Improper Configuration of the Database Transaction Log ����������������������������������������������������������������������������������� 14
Excessive Use or Improper Configuration of tempdb ������������������������������������������������������������������������������������������ 15
Summary �������������������������������������������������������������������������������������������������������������������������������������15
Chapter 2: Memory Performance Analysis ■ ����������������������������������������������������������������������17
Performance Monitor Tool �����������������������������������������������������������������������������������������������������������17
Dynamic Management Objects ���������������������������������������������������������������������������������������������������19
Hardware Resource Bottlenecks �������������������������������������������������������������������������������������������������20
Identifying Bottlenecks ���������������������������������������������������������������������������������������������������������������������������������������� 20
Bottleneck Resolution ������������������������������������������������������������������������������������������������������������������������������������������ 21
Memory Bottleneck Analysis �������������������������������������������������������������������������������������������������������21
SQL Server Memory Management ����������������������������������������������������������������������������������������������������������������������� 21
Available Bytes ���������������������������������������������������������������������������������������������������������������������������������������������������� 25
Pages/Sec and Page Faults/Sec �������������������������������������������������������������������������������������������������������������������������� 25
Paging File %Usage and Page File %Usage �������������������������������������������������������������������������������������������������������� 25
Buffer Cache Hit Ratio ����������������������������������������������������������������������������������������������������������������������������������������� 26
Page Life Expectancy������������������������������������������������������������������������������������������������������������������������������������������� 26
Checkpoint Pages/Sec ����������������������������������������������������������������������������������������������������������������������������������������� 26
Lazy Writes/Sec ��������������������������������������������������������������������������������������������������������������������������������������������������� 27
Memory Grants Pending �������������������������������������������������������������������������������������������������������������������������������������� 27
Target Server Memory (KB) and Total Server Memory (KB) ��������������������������������������������������������������������������������� 27
Additional Memory Monitoring Tools �������������������������������������������������������������������������������������������27
DBCC MEMORYSTATUS ���������������������������������������������������������������������������������������������������������������������������������������� 27
Dynamic Management Objects ���������������������������������������������������������������������������������������������������������������������������� 29
Memory Bottleneck Resolutions��������������������������������������������������������������������������������������������������30
Optimizing Application Workload ������������������������������������������������������������������������������������������������������������������������� 32
Allocating More Memory to SQL Server ��������������������������������������������������������������������������������������������������������������� 32
Moving In-Memory Tables Back to Standard Storage ����������������������������������������������������������������������������������������� 32
■ Contents
vii
Increasing System Memory ��������������������������������������������������������������������������������������������������������������������������������� 33
Changing from a 32-Bit to a 64-Bit Processor ����������������������������������������������������������������������������������������������������� 33
Compressing Data ����������������������������������������������������������������������������������������������������������������������������������������������� 33
Enabling 3GB of Process Address Space ������������������������������������������������������������������������������������������������������������� 33
Addressing Fragmentation ���������������������������������������������������������������������������������������������������������������������������������� 34
Summary �������������������������������������������������������������������������������������������������������������������������������������34
Chapter 3: Disk Performance Analysis ■ ����������������������������������������������������������������������������35
Disk Bottleneck Analysis �������������������������������������������������������������������������������������������������������������35
Disk Counters ������������������������������������������������������������������������������������������������������������������������������������������������������ 35
% Disk Time ��������������������������������������������������������������������������������������������������������������������������������������������������������� 36
Current Disk Queue Length ���������������������������������������������������������������������������������������������������������������������������������� 36
Disk Transfers/Sec ����������������������������������������������������������������������������������������������������������������������������������������������� 37
Disk Bytes/Sec ����������������������������������������������������������������������������������������������������������������������������������������������������� 37
Avg� Disk Sec/Read and Avg� Disk Sec/Write ������������������������������������������������������������������������������������������������������ 37
Additional I/O Monitoring Tools ����������������������������������������������������������������������������������������������������37
Sys�dm_io_virtual_file_stats ������������������������������������������������������������������������������������������������������������������������������� 37
Sys�dm_os_wait_stats ���������������������������������������������������������������������������������������������������������������������������������������� 38
Disk Bottleneck Resolutions ��������������������������������������������������������������������������������������������������������38
Optimizing Application Workload ������������������������������������������������������������������������������������������������������������������������� 39
Using a Faster I/O Path ���������������������������������������������������������������������������������������������������������������������������������������� 39
Using a RAID Array ����������������������������������������������������������������������������������������������������������������������������������������������� 39
Using a SAN System �������������������������������������������������������������������������������������������������������������������������������������������� 41
Using Solid State Drives �������������������������������������������������������������������������������������������������������������������������������������� 41
Aligning Disks Properly ���������������������������������������������������������������������������������������������������������������������������������������� 42
Adding System Memory �������������������������������������������������������������������������������������������������������������������������������������� 42
Creating Multiple Files and Filegroups ���������������������������������������������������������������������������������������������������������������� 42
Moving the Log Files to a Separate Physical Disk ����������������������������������������������������������������������������������������������� 45
Using Partitioned Tables �������������������������������������������������������������������������������������������������������������������������������������� 45
Summary �������������������������������������������������������������������������������������������������������������������������������������46
■ Contents
viii
Chapter 4: CPU Performance Analysis ■ �����������������������������������������������������������������������������47
Processor Bottleneck Analysis ����������������������������������������������������������������������������������������������������47
% Processor Time ������������������������������������������������������������������������������������������������������������������������������������������������ 48
% Privileged Time ������������������������������������������������������������������������������������������������������������������������������������������������ 48
Processor Queue Length�������������������������������������������������������������������������������������������������������������������������������������� 48
Context Switches/Sec ������������������������������������������������������������������������������������������������������������������������������������������ 48
Batch Requests/Sec �������������������������������������������������������������������������������������������������������������������������������������������� 49
SQL Compilations/Sec ����������������������������������������������������������������������������������������������������������������������������������������� 49
SQL Recompilations/Sec ������������������������������������������������������������������������������������������������������������������������������������� 49
Other Tools for Measuring CPU Performance ������������������������������������������������������������������������������49
Sys�dm_os_wait_stats ���������������������������������������������������������������������������������������������������������������������������������������� 49
Sys�dm_os_workers and Sys�dm_os_schedulers ����������������������������������������������������������������������������������������������� 50
Processor Bottleneck Resolutions �����������������������������������������������������������������������������������������������50
Optimizing Application Workload ������������������������������������������������������������������������������������������������������������������������� 50
Eliminating Excessive Compiles/Recompiles ������������������������������������������������������������������������������������������������������ 50
Using More or Faster Processors ������������������������������������������������������������������������������������������������������������������������ 50
Not Running Unnecessary Software �������������������������������������������������������������������������������������������������������������������� 51
Network Bottleneck Analysis �������������������������������������������������������������������������������������������������������51
Bytes Total/Sec ���������������������������������������������������������������������������������������������������������������������������������������������������� 51
% Net Utilization �������������������������������������������������������������������������������������������������������������������������������������������������� 51
Network Bottleneck Resolutions �������������������������������������������������������������������������������������������������52
Optimizing Application Workload ������������������������������������������������������������������������������������������������������������������������� 52
SQL Server Overall Performance �������������������������������������������������������������������������������������������������52
Missing Indexes ��������������������������������������������������������������������������������������������������������������������������������������������������� 53
Database Concurrency����������������������������������������������������������������������������������������������������������������������������������������� 54
Nonreusable Execution Plans ������������������������������������������������������������������������������������������������������������������������������ 55
General Behavior ������������������������������������������������������������������������������������������������������������������������������������������������� 55
User Connections ������������������������������������������������������������������������������������������������������������������������������������������������� 56
Batch Requests/Sec �������������������������������������������������������������������������������������������������������������������������������������������� 56
Summary �������������������������������������������������������������������������������������������������������������������������������������56
■ Contents
ix
Chapter 5: Creating a Baseline ■ ����������������������������������������������������������������������������������������57
Considerations for Monitoring Virtual and Hosted Machines ������������������������������������������������������57
Creating a Baseline ���������������������������������������������������������������������������������������������������������������������58
Creating a Reusable List of Performance Counters ��������������������������������������������������������������������������������������������� 58
Creating a Counter Log Using the List of Performance Counters ������������������������������������������������������������������������ 61
Performance Monitor Considerations ������������������������������������������������������������������������������������������������������������������ 64
System Behavior Analysis Against Baseline �������������������������������������������������������������������������������������������������������� 66
Summary �������������������������������������������������������������������������������������������������������������������������������������68
Chapter 6: Query Performance Metrics ■ ���������������������������������������������������������������������������69
Extended Events ��������������������������������������������������������������������������������������������������������������������������69
Extended Events Sessions ����������������������������������������������������������������������������������������������������������������������������������� 70
Global Fields �������������������������������������������������������������������������������������������������������������������������������������������������������� 74
Event Filters ��������������������������������������������������������������������������������������������������������������������������������������������������������� 75
Event Fields ��������������������������������������������������������������������������������������������������������������������������������������������������������� 76
Data Storage �������������������������������������������������������������������������������������������������������������������������������������������������������� 78
Finishing the Session ������������������������������������������������������������������������������������������������������������������������������������������ 79
Extended Events Automation �������������������������������������������������������������������������������������������������������80
Creating a Session Script Using the GUI �������������������������������������������������������������������������������������������������������������� 80
Defining a Session Using T-SQL ��������������������������������������������������������������������������������������������������������������������������� 81
Extended Events Recommendations �������������������������������������������������������������������������������������������82
Set Max File Size Appropriately ��������������������������������������������������������������������������������������������������������������������������� 82
Avoid Debug Events ��������������������������������������������������������������������������������������������������������������������������������������������� 82
Avoid Use of No_Event_Loss ������������������������������������������������������������������������������������������������������������������������������� 83
Other Methods for Query Performance Metrics ��������������������������������������������������������������������������83
Summary �������������������������������������������������������������������������������������������������������������������������������������84
Chapter 7: Analyzing Query Performance ■ ����������������������������������������������������������������������85
Costly Queries �����������������������������������������������������������������������������������������������������������������������������85
Identifying Costly Queries ������������������������������������������������������������������������������������������������������������������������������������ 86
Costly Queries with a Single Execution ��������������������������������������������������������������������������������������������������������������� 87
■ Contents
x
Costly Queries with Multiple Executions ������������������������������������������������������������������������������������������������������������� 88
Identifying Slow-Running Queries ����������������������������������������������������������������������������������������������������������������������� 90
Execution Plans ���������������������������������������������������������������������������������������������������������������������������91
Analyzing a Query Execution Plan ����������������������������������������������������������������������������������������������������������������������� 92
Identifying the Costly Steps in an Execution Plan ����������������������������������������������������������������������������������������������� 95
Analyzing Index Effectiveness ����������������������������������������������������������������������������������������������������������������������������� 96
Analyzing Join Effectiveness ������������������������������������������������������������������������������������������������������������������������������� 98
Hash Join ������������������������������������������������������������������������������������������������������������������������������������������������������������� 99
Actual vs� Estimated Execution Plans ���������������������������������������������������������������������������������������������������������������� 103
Plan Cache ��������������������������������������������������������������������������������������������������������������������������������������������������������� 105
Query Resource Cost ����������������������������������������������������������������������������������������������������������������������������������������� 105
Client Statistics �������������������������������������������������������������������������������������������������������������������������������������������������� 105
Execution Time �������������������������������������������������������������������������������������������������������������������������������������������������� 106
STATISTICS IO ���������������������������������������������������������������������������������������������������������������������������������������������������� 108
Summary �����������������������������������������������������������������������������������������������������������������������������������109
Chapter 8: Index Architecture and Behavior ■ �����������������������������������������������������������������111
What Is an Index? ����������������������������������������������������������������������������������������������������������������������111
The Benefit of Indexes ��������������������������������������������������������������������������������������������������������������������������������������� 113
Index Overhead �������������������������������������������������������������������������������������������������������������������������������������������������� 115
Index Design Recommendations �����������������������������������������������������������������������������������������������117
Examine the WHERE Clause and JOIN Criteria Columns ������������������������������������������������������������������������������������ 117
Use Narrow Indexes ������������������������������������������������������������������������������������������������������������������������������������������� 119
Examine Column Uniqueness ���������������������������������������������������������������������������������������������������������������������������� 121
Examine the Column Data Type ������������������������������������������������������������������������������������������������������������������������� 124
Consider Column Order�������������������������������������������������������������������������������������������������������������������������������������� 124
Consider the Type of Index��������������������������������������������������������������������������������������������������������������������������������� 128
Clustered Indexes ����������������������������������������������������������������������������������������������������������������������128
Heap Tables ������������������������������������������������������������������������������������������������������������������������������������������������������� 128
Relationship with Nonclustered Indexes ����������������������������������������������������������������������������������������������������������� 129
Clustered Index Recommendations ������������������������������������������������������������������������������������������������������������������� 131
■ Contents
xi
When to Use a Clustered Index �������������������������������������������������������������������������������������������������������������������������� 134
Poor Design Practices for a Clustered Index ����������������������������������������������������������������������������������������������������� 135
Nonclustered Indexes ����������������������������������������������������������������������������������������������������������������137
Nonclustered Index Maintenance ���������������������������������������������������������������������������������������������������������������������� 137
Defining the Lookup Operation ������������������������������������������������������������������������������������������������������������������������� 137
Nonclustered Index Recommendations ������������������������������������������������������������������������������������������������������������� 137
Clustered vs� Nonclustered Indexes ������������������������������������������������������������������������������������������138
Benefits of a Clustered Index over a Nonclustered Index ���������������������������������������������������������������������������������� 138
Benefits of a Nonclustered Index over a Clustered Index ���������������������������������������������������������������������������������� 141
Summary �����������������������������������������������������������������������������������������������������������������������������������142
Chapter 9: Index Analysis ■ ����������������������������������������������������������������������������������������������143
Advanced Indexing Techniques �������������������������������������������������������������������������������������������������143
Covering Indexes ����������������������������������������������������������������������������������������������������������������������������������������������� 144
A Pseudoclustered Index ����������������������������������������������������������������������������������������������������������������������������������� 145
Recommendations ��������������������������������������������������������������������������������������������������������������������������������������������� 145
Index Intersections �������������������������������������������������������������������������������������������������������������������������������������������� 146
Index Joins �������������������������������������������������������������������������������������������������������������������������������������������������������� 148
Filtered Indexes ������������������������������������������������������������������������������������������������������������������������������������������������� 150
Indexed Views ���������������������������������������������������������������������������������������������������������������������������������������������������� 152
Index Compression �������������������������������������������������������������������������������������������������������������������������������������������� 156
Columnstore Indexes ����������������������������������������������������������������������������������������������������������������������������������������� 158
Special Index Types �������������������������������������������������������������������������������������������������������������������161
Full-Text ������������������������������������������������������������������������������������������������������������������������������������������������������������� 161
Spatial���������������������������������������������������������������������������������������������������������������������������������������������������������������� 161
XML �������������������������������������������������������������������������������������������������������������������������������������������������������������������� 161
Additional Characteristics of Indexes ����������������������������������������������������������������������������������������162
Different Column Sort Order ������������������������������������������������������������������������������������������������������������������������������ 162
Index on Computed Columns ����������������������������������������������������������������������������������������������������������������������������� 162
Index on BIT Data Type Columns������������������������������������������������������������������������������������������������������������������������ 162
CREATE INDEX Statement Processed As a Query ���������������������������������������������������������������������������������������������� 162
■ Contents
xii
Parallel Index Creation ��������������������������������������������������������������������������������������������������������������������������������������� 163
Online Index Creation ���������������������������������������������������������������������������������������������������������������������������������������� 163
Considering the Database Engine Tuning Advisor ��������������������������������������������������������������������������������������������� 163
Summary �����������������������������������������������������������������������������������������������������������������������������������163
Chapter 10: Database Engine Tuning Advisor ■ ����������������������������������������������������������������165
Database Engine Tuning Advisor Mechanisms ��������������������������������������������������������������������������165
Database Engine Tuning Advisor Examples �������������������������������������������������������������������������������170
Tuning a Query ��������������������������������������������������������������������������������������������������������������������������������������������������� 170
Tuning a Trace Workload ������������������������������������������������������������������������������������������������������������������������������������ 175
Tuning from the Procedure Cache ��������������������������������������������������������������������������������������������������������������������� 178
Database Engine Tuning Advisor Limitations �����������������������������������������������������������������������������179
Summary �����������������������������������������������������������������������������������������������������������������������������������180
Chapter 11: Key Lookups and Solutions ■ ������������������������������������������������������������������������181
Purpose of Lookups �������������������������������������������������������������������������������������������������������������������181
Drawbacks of Lookups ��������������������������������������������������������������������������������������������������������������183
Analyzing the Cause of a Lookup ����������������������������������������������������������������������������������������������184
Resolving Lookups ��������������������������������������������������������������������������������������������������������������������186
Using a Clustered Index ������������������������������������������������������������������������������������������������������������������������������������� 186
Using a Covering Index �������������������������������������������������������������������������������������������������������������������������������������� 186
Using an Index Join ������������������������������������������������������������������������������������������������������������������������������������������� 190
Summary �����������������������������������������������������������������������������������������������������������������������������������192
Chapter 12: Statistics, Data Distribution, and Cardinality ■ ���������������������������������������������193
The Role of Statistics in Query Optimization �����������������������������������������������������������������������������193
Statistics on an Indexed Column ����������������������������������������������������������������������������������������������������������������������� 194
Benefits of Updated Statistics ��������������������������������������������������������������������������������������������������������������������������� 195
Drawbacks of Outdated Statistics ��������������������������������������������������������������������������������������������������������������������� 198
Statistics on a Nonindexed Column �������������������������������������������������������������������������������������������200
Benefits of Statistics on a Nonindexed Column ������������������������������������������������������������������������������������������������� 200
Drawback of Missing Statistics on a Nonindexed Column �������������������������������������������������������������������������������� 205
■ Contents
xiii
Analyzing Statistics �������������������������������������������������������������������������������������������������������������������209
Density ��������������������������������������������������������������������������������������������������������������������������������������������������������������� 212
Statistics on a Multicolumn Index ��������������������������������������������������������������������������������������������������������������������� 212
Statistics on a Filtered Index ����������������������������������������������������������������������������������������������������������������������������� 214
Cardinality���������������������������������������������������������������������������������������������������������������������������������������������������������� 216
Statistics Maintenance ��������������������������������������������������������������������������������������������������������������219
Automatic Maintenance ������������������������������������������������������������������������������������������������������������������������������������� 219
Auto Create Statistics ���������������������������������������������������������������������������������������������������������������������������������������� 220
Auto Update Statistics ��������������������������������������������������������������������������������������������������������������������������������������� 220
Auto Update Statistics Asynchronously ������������������������������������������������������������������������������������������������������������� 222
Manual Maintenance ����������������������������������������������������������������������������������������������������������������������������������������� 223
Manage Statistics Settings �������������������������������������������������������������������������������������������������������������������������������� 224
Generate Statistics �������������������������������������������������������������������������������������������������������������������������������������������� 225
Statistics Maintenance Status ���������������������������������������������������������������������������������������������������225
Status of Auto Create Statistics ������������������������������������������������������������������������������������������������������������������������� 226
Status of Auto Update Statistics ������������������������������������������������������������������������������������������������������������������������ 226
Analyzing the Effectiveness of Statistics for a Query ����������������������������������������������������������������226
Resolving a Missing Statistics Issue ����������������������������������������������������������������������������������������������������������������� 227
Resolving an Outdated Statistics Issue ������������������������������������������������������������������������������������������������������������� 230
Recommendations ��������������������������������������������������������������������������������������������������������������������232
Backward Compatibility of Statistics ����������������������������������������������������������������������������������������������������������������� 232
Auto Create Statistics ���������������������������������������������������������������������������������������������������������������������������������������� 232
Auto Update Statistics ��������������������������������������������������������������������������������������������������������������������������������������� 233
Automatic Update Statistics Asynchronously ���������������������������������������������������������������������������������������������������� 235
Amount of Sampling to Collect Statistics ���������������������������������������������������������������������������������������������������������� 235
Summary �����������������������������������������������������������������������������������������������������������������������������������235
Chapter 13: Index Fragmentation ■ ����������������������������������������������������������������������������������237
Causes of Fragmentation ����������������������������������������������������������������������������������������������������������237
Page Split by an UPDATE Statement ������������������������������������������������������������������������������������������������������������������ 239
Page Split by an INSERT Statement ������������������������������������������������������������������������������������������������������������������� 244
■ Contents
xiv
Fragmentation Overhead �����������������������������������������������������������������������������������������������������������245
Analyzing the Amount of Fragmentation �����������������������������������������������������������������������������������247
Analyzing the Fragmentation of a Small Table ��������������������������������������������������������������������������250
Fragmentation Resolutions �������������������������������������������������������������������������������������������������������252
Dropping and Re-creating the Index ������������������������������������������������������������������������������������������������������������������ 252
Re-creating the Index with the DROP_EXISTING Clause ������������������������������������������������������������������������������������ 252
Executing the ALTER INDEX REBUILD Statement ����������������������������������������������������������������������������������������������� 253
Executing the ALTER INDEX REORGANIZE Statement ���������������������������������������������������������������������������������������� 255
Defragmentation and Partitions ������������������������������������������������������������������������������������������������������������������������� 257
Significance of the Fill Factor ����������������������������������������������������������������������������������������������������258
Automatic Maintenance ������������������������������������������������������������������������������������������������������������260
Summary �����������������������������������������������������������������������������������������������������������������������������������267
Chapter 14: Execution Plan Generation ■ �������������������������������������������������������������������������269
Execution Plan Generation ��������������������������������������������������������������������������������������������������������269
Parser ���������������������������������������������������������������������������������������������������������������������������������������������������������������� 271
Binding �������������������������������������������������������������������������������������������������������������������������������������������������������������� 271
Optimization ������������������������������������������������������������������������������������������������������������������������������������������������������ 273
Execution Plan Caching ������������������������������������������������������������������������������������������������������������������������������������� 280
Components of the Execution Plan ��������������������������������������������������������������������������������������������280
Query Plan ��������������������������������������������������������������������������������������������������������������������������������������������������������� 281
Execution Context ���������������������������������������������������������������������������������������������������������������������������������������������� 281
Aging of the Execution Plan ������������������������������������������������������������������������������������������������������281
Summary �����������������������������������������������������������������������������������������������������������������������������������281
Chapter 15: Execution Plan Cache Behavior ■ ������������������������������������������������������������������283
Analyzing the Execution Plan Cache �����������������������������������������������������������������������������������������283
Execution Plan Reuse ����������������������������������������������������������������������������������������������������������������284
Ad Hoc Workload �����������������������������������������������������������������������������������������������������������������������285
Prepared Workload �������������������������������������������������������������������������������������������������������������������������������������������� 286
Plan Reusability of an Ad Hoc Workload ������������������������������������������������������������������������������������������������������������ 286
Plan Reusability of a Prepared Workload ����������������������������������������������������������������������������������������������������������� 294
■ Contents
xv
Query Plan Hash and Query Hash ���������������������������������������������������������������������������������������������303
Execution Plan Cache Recommendations ���������������������������������������������������������������������������������306
Explicitly Parameterize Variable Parts of a Query ���������������������������������������������������������������������������������������������� 306
Create Stored Procedures to Implement Business Functionality ���������������������������������������������������������������������� 306
Code with sp_executesql to Avoid Stored Procedure Maintenance ������������������������������������������������������������������ 306
Implement the Prepare/Execute Model to Avoid Resending a Query String ������������������������������������������������������ 307
Avoid Ad Hoc Queries����������������������������������������������������������������������������������������������������������������������������������������� 307
Prefer sp_executesql Over EXECUTE for Dynamic Queries ������������������������������������������������������������������������������� 307
Parameterize Variable Parts of Queries with Care ��������������������������������������������������������������������������������������������� 308
Do Not Allow Implicit Resolution of Objects in Queries ������������������������������������������������������������������������������������� 308
Summary �����������������������������������������������������������������������������������������������������������������������������������309
Chapter 16: Parameter Sniffing ■ �������������������������������������������������������������������������������������311
Parameter Sniffing ��������������������������������������������������������������������������������������������������������������������311
Bad Parameter Sniffing ������������������������������������������������������������������������������������������������������������������������������������� 314
Mitigating Bad Parameter Sniffing �������������������������������������������������������������������������������������������������������������������� 317
Summary �����������������������������������������������������������������������������������������������������������������������������������319
Chapter 17: Query Recompilation ■ ����������������������������������������������������������������������������������321
Benefits and Drawbacks of Recompilation �������������������������������������������������������������������������������321
Identifying the Statement Causing Recompilation ��������������������������������������������������������������������324
Analyzing Causes of Recompilation ������������������������������������������������������������������������������������������326
Schema or Bindings Changes ���������������������������������������������������������������������������������������������������������������������������� 328
Statistics Changes ��������������������������������������������������������������������������������������������������������������������������������������������� 328
Deferred Object Resolution �������������������������������������������������������������������������������������������������������������������������������� 331
SET Options Changes����������������������������������������������������������������������������������������������������������������������������������������� 335
Execution Plan Aging ����������������������������������������������������������������������������������������������������������������������������������������� 336
Explicit Call to sp_recompile ����������������������������������������������������������������������������������������������������������������������������� 336
Explicit Use of RECOMPILE �������������������������������������������������������������������������������������������������������������������������������� 337
Avoiding Recompilations �����������������������������������������������������������������������������������������������������������340
Don’t Interleave DDL and DML Statements ������������������������������������������������������������������������������������������������������� 340
Avoiding Recompilations Caused by Statistics Change ������������������������������������������������������������������������������������� 342
■ Contents
xvi
Using the KEEPFIXED PLAN Option �������������������������������������������������������������������������������������������������������������������� 342
Disable Auto Update Statistics on the Table ������������������������������������������������������������������������������������������������������ 344
Using Table Variables ����������������������������������������������������������������������������������������������������������������������������������������� 344
Avoiding Changing SET Options Within a Stored Procedure ������������������������������������������������������������������������������ 346
Using OPTIMIZE FOR Query Hint ������������������������������������������������������������������������������������������������������������������������ 347
Using Plan Guides ���������������������������������������������������������������������������������������������������������������������������������������������� 349
Summary �����������������������������������������������������������������������������������������������������������������������������������354
Chapter 18: Query Design Analysis ■ �������������������������������������������������������������������������������355
Query Design Recommendations ����������������������������������������������������������������������������������������������355
Operating on Small Result Sets �������������������������������������������������������������������������������������������������356
Limit the Number of Columns in select_list ������������������������������������������������������������������������������������������������������ 356
Use Highly Selective WHERE Clauses ���������������������������������������������������������������������������������������������������������������� 357
Using Indexes Effectively ����������������������������������������������������������������������������������������������������������357
Avoid Nonsargable Search Conditions ��������������������������������������������������������������������������������������������������������������� 358
Avoid Arithmetic Operators on the WHERE Clause Column ������������������������������������������������������������������������������� 362
Avoid Functions on the WHERE Clause Column ������������������������������������������������������������������������������������������������� 364
Avoiding Optimizer Hints �����������������������������������������������������������������������������������������������������������366
JOIN Hint ������������������������������������������������������������������������������������������������������������������������������������������������������������ 367
INDEX Hints �������������������������������������������������������������������������������������������������������������������������������������������������������� 370
Using Domain and Referential Integrity �������������������������������������������������������������������������������������372
NOT NULL Constraint ����������������������������������������������������������������������������������������������������������������������������������������� 372
Declarative Referential Integrity ������������������������������������������������������������������������������������������������������������������������ 375
Summary �����������������������������������������������������������������������������������������������������������������������������������377
Chapter 19: Reduce Query Resource Use ■ ����������������������������������������������������������������������379
Avoiding Resource-Intensive Queries ����������������������������������������������������������������������������������������379
Avoid Data Type Conversion ������������������������������������������������������������������������������������������������������������������������������� 379
Use EXISTS over COUNT(*) to Verify Data Existence ������������������������������������������������������������������������������������������ 382
Use UNION ALL Instead of UNION ����������������������������������������������������������������������������������������������������������������������� 383
Use Indexes for Aggregate and Sort Conditions ������������������������������������������������������������������������������������������������ 384
■ Contents
xvii
Avoid Local Variables in a Batch Query ������������������������������������������������������������������������������������������������������������� 385
Be Careful When Naming Stored Procedures ���������������������������������������������������������������������������������������������������� 389
Reducing the Number of Network Round-Trips �������������������������������������������������������������������������391
Execute Multiple Queries Together �������������������������������������������������������������������������������������������������������������������� 391
Use SET NOCOUNT ��������������������������������������������������������������������������������������������������������������������������������������������� 392
Reducing the Transaction Cost ��������������������������������������������������������������������������������������������������392
Reduce Logging Overhead ��������������������������������������������������������������������������������������������������������������������������������� 392
Reduce Lock Overhead �������������������������������������������������������������������������������������������������������������������������������������� 394
Summary �����������������������������������������������������������������������������������������������������������������������������������395
Chapter 20: Blocking and Blocked Processes ■ ���������������������������������������������������������������397
Blocking Fundamentals �������������������������������������������������������������������������������������������������������������397
Understanding Blocking ������������������������������������������������������������������������������������������������������������398
Atomicity ������������������������������������������������������������������������������������������������������������������������������������������������������������ 398
Consistency ������������������������������������������������������������������������������������������������������������������������������������������������������� 401
Isolation ������������������������������������������������������������������������������������������������������������������������������������������������������������� 401
Durability ����������������������������������������������������������������������������������������������������������������������������������������������������������� 402
Locks �����������������������������������������������������������������������������������������������������������������������������������������403
Lock Granularity������������������������������������������������������������������������������������������������������������������������������������������������� 403
Row-Level Lock ������������������������������������������������������������������������������������������������������������������������������������������������� 404
Page-Level Lock ������������������������������������������������������������������������������������������������������������������������������������������������ 406
Extent-Level Lock ���������������������������������������������������������������������������������������������������������������������������������������������� 406
Heap or B-tree Lock ������������������������������������������������������������������������������������������������������������������������������������������� 407
Table-Level Lock ������������������������������������������������������������������������������������������������������������������������������������������������ 407
Database-Level Lock ����������������������������������������������������������������������������������������������������������������������������������������� 407
Lock Operations and Modes ������������������������������������������������������������������������������������������������������408
Lock Escalation �������������������������������������������������������������������������������������������������������������������������������������������������� 408
Lock Modes ������������������������������������������������������������������������������������������������������������������������������������������������������� 408
Exclusive (X) Mode �������������������������������������������������������������������������������������������������������������������������������������������� 413
Intent Shared (IS), Intent Exclusive (IX and Shared with Intent Exclusive (SIX) Modes ������������������������������������� 413
Schema Modification (Sch-M) and Schema Stability (Sch-S) Modes ���������������������������������������������������������������� 414
■ Contents
xviii
Bulk Update (BU) Mode �������������������������������������������������������������������������������������������������������������������������������������� 414
Key-range Mode ������������������������������������������������������������������������������������������������������������������������������������������������ 415
Lock Compatibility ��������������������������������������������������������������������������������������������������������������������������������������������� 415
Isolation Levels ��������������������������������������������������������������������������������������������������������������������������415
Read Uncommitted �������������������������������������������������������������������������������������������������������������������������������������������� 416
Read Committed ������������������������������������������������������������������������������������������������������������������������������������������������ 416
Repeatable Read ����������������������������������������������������������������������������������������������������������������������������������������������� 417
Serializable �������������������������������������������������������������������������������������������������������������������������������������������������������� 420
Snapshot ������������������������������������������������������������������������������������������������������������������������������������������������������������ 425
Effect of Indexes on Locking �����������������������������������������������������������������������������������������������������425
Effect of a Nonclustered Index �������������������������������������������������������������������������������������������������������������������������� 426
Effect of a Clustered Index �������������������������������������������������������������������������������������������������������������������������������� 428
Effect of Indexes on the Serializable Isolation Level ����������������������������������������������������������������������������������������� 429
Capturing Blocking Information �������������������������������������������������������������������������������������������������429
Capturing Blocking Information with SQL ���������������������������������������������������������������������������������������������������������� 430
Extended Events and the blocked_process_report Event ��������������������������������������������������������������������������������� 432
Blocking Resolutions �����������������������������������������������������������������������������������������������������������������434
Optimize the Queries ����������������������������������������������������������������������������������������������������������������������������������������� 435
Decrease the Isolation Level ������������������������������������������������������������������������������������������������������������������������������ 435
Partition the Contended Data ����������������������������������������������������������������������������������������������������436
Recommendations to Reduce Blocking �������������������������������������������������������������������������������������437
Automation to Detect and Collect Blocking Information������������������������������������������������������������438
Summary �����������������������������������������������������������������������������������������������������������������������������������441
Chapter 21: Causes and Solutions for Deadlocks ■ ����������������������������������������������������������443
Deadlock Fundamentals ������������������������������������������������������������������������������������������������������������443
Choosing the Deadlock Victim ��������������������������������������������������������������������������������������������������������������������������� 444
Using Error Handling to Catch a Deadlock ��������������������������������������������������������������������������������������������������������� 445
Deadlock Analysis ���������������������������������������������������������������������������������������������������������������������446
Collecting Deadlock Information������������������������������������������������������������������������������������������������������������������������ 446
Analyzing the Deadlock ������������������������������������������������������������������������������������������������������������������������������������� 448
■ Contents
xix
Avoiding Deadlocks �������������������������������������������������������������������������������������������������������������������455
Accessing Resources in the Same Physical Order �������������������������������������������������������������������������������������������� 455
Decreasing the Number of Resources Accessed ����������������������������������������������������������������������������������������������� 456
Minimizing Lock Contention ������������������������������������������������������������������������������������������������������������������������������ 456
Summary �����������������������������������������������������������������������������������������������������������������������������������458
Chapter 22: Row-by-Row Processing ■ ����������������������������������������������������������������������������459
Cursor Fundamentals ����������������������������������������������������������������������������������������������������������������459
Cursor Location ������������������������������������������������������������������������������������������������������������������������������������������������� 461
Cursor Concurrency ������������������������������������������������������������������������������������������������������������������������������������������� 462
Cursor Types ������������������������������������������������������������������������������������������������������������������������������������������������������ 463
Cursor Cost Comparison ������������������������������������������������������������������������������������������������������������������������������������ 466
Cost Comparison on Cursor Location ���������������������������������������������������������������������������������������������������������������� 466
Cost Comparison on Cursor Concurrency ���������������������������������������������������������������������������������������������������������� 468
Read-Only ���������������������������������������������������������������������������������������������������������������������������������������������������������� 468
Cost Comparison on Cursor Type ����������������������������������������������������������������������������������������������������������������������� 469
Default Result Set ����������������������������������������������������������������������������������������������������������������������472
Benefits ������������������������������������������������������������������������������������������������������������������������������������������������������������� 472
Multiple Active Result Sets �������������������������������������������������������������������������������������������������������������������������������� 472
Drawbacks ��������������������������������������������������������������������������������������������������������������������������������������������������������� 473
Cursor Overhead �����������������������������������������������������������������������������������������������������������������������475
Analyzing Overhead with T-SQL Cursors ����������������������������������������������������������������������������������������������������������� 476
Cursor Recommendations ��������������������������������������������������������������������������������������������������������������������������������� 480
Summary �����������������������������������������������������������������������������������������������������������������������������������481
Chapter 23: Memory-Optimized OLTP Tables and Procedures ■ ���������������������������������������483
In-Memory OLTP Fundamentals ������������������������������������������������������������������������������������������������483
System Requirements ��������������������������������������������������������������������������������������������������������������������������������������� 484
Basic Setup ������������������������������������������������������������������������������������������������������������������������������������������������������� 484
Create Tables ����������������������������������������������������������������������������������������������������������������������������������������������������� 485
In-Memory Indexes �������������������������������������������������������������������������������������������������������������������������������������������� 490
Hash Index ��������������������������������������������������������������������������������������������������������������������������������������������������������� 490
■ Contents
xx
Natively Compiled Stored Procedures ���������������������������������������������������������������������������������������495
Recommendations ��������������������������������������������������������������������������������������������������������������������497
Baselines ����������������������������������������������������������������������������������������������������������������������������������������������������������� 498
Correct Workload ����������������������������������������������������������������������������������������������������������������������������������������������� 498
Memory Optimization Advisor ���������������������������������������������������������������������������������������������������������������������������� 498
Native Compilation Advisor �������������������������������������������������������������������������������������������������������������������������������� 502
Summary �����������������������������������������������������������������������������������������������������������������������������������504
Chapter 24: Database Performance Testing ■ ������������������������������������������������������������������505
Database Performance Testing �������������������������������������������������������������������������������������������������505
A Repeatable Process ���������������������������������������������������������������������������������������������������������������������������������������� 506
Distributed Replay ��������������������������������������������������������������������������������������������������������������������������������������������� 506
Capturing Data with the Server-Side Trace �������������������������������������������������������������������������������507
Distributed Replay for Database Testing �����������������������������������������������������������������������������������511
Configuring the Client ���������������������������������������������������������������������������������������������������������������������������������������� 512
Running the Distributed Tests ���������������������������������������������������������������������������������������������������������������������������� 512
Conclusion ���������������������������������������������������������������������������������������������������������������������������������513
Chapter 25: Database Workload Optimization ■ ���������������������������������������������������������������515
Workload Optimization Fundamentals���������������������������������������������������������������������������������������515
Workload Optimization Steps ���������������������������������������������������������������������������������������������������������������������������� 516
Sample Workload ����������������������������������������������������������������������������������������������������������������������������������������������� 517
Capturing the Workload �������������������������������������������������������������������������������������������������������������520
Analyzing the Workload �������������������������������������������������������������������������������������������������������������520
Identifying the Costliest Query ��������������������������������������������������������������������������������������������������522
Determining the Baseline Resource Use of the Costliest Query ������������������������������������������������������������������������ 523
Overall Resource Use ����������������������������������������������������������������������������������������������������������������������������������������� 524
Detailed Resource Use��������������������������������������������������������������������������������������������������������������������������������������� 524
Analyzing and Optimizing External Factors �������������������������������������������������������������������������������526
Analyzing the Connection Options Used by the Application ������������������������������������������������������������������������������� 527
Analyzing the Effectiveness of Statistics ����������������������������������������������������������������������������������������������������������� 527
■ Contents
xxi
Analyzing the Need for Defragmentation ����������������������������������������������������������������������������������������������������������� 528
Analyzing the Internal Behavior of the Costliest Query ������������������������������������������������������������������������������������� 532
Analyzing the Query Execution Plan ������������������������������������������������������������������������������������������������������������������ 533
Identifying the Costly Steps in the Execution Plan �������������������������������������������������������������������������������������������� 534
Analyzing the Processing Strategy �������������������������������������������������������������������������������������������������������������������� 534
Optimizing the Costliest Query �������������������������������������������������������������������������������������������������������������������������� 535
Modifying the Code �������������������������������������������������������������������������������������������������������������������������������������������� 535
Fixing the Key Lookup Operation ����������������������������������������������������������������������������������������������������������������������� 538
Tuning the Second Query ����������������������������������������������������������������������������������������������������������������������������������� 539
Creating a Wrapper Procedure �������������������������������������������������������������������������������������������������������������������������� 541
Analyzing the Effect on Database Workload ������������������������������������������������������������������������������542
Iterating Through Optimization Phases �������������������������������������������������������������������������������������543
Summary �����������������������������������������������������������������������������������������������������������������������������������546
Chapter 26: SQL Server Optimization Checklist ■ ������������������������������������������������������������547
Database Design �����������������������������������������������������������������������������������������������������������������������547
Balancing Under- and Overnormalization ���������������������������������������������������������������������������������������������������������� 548
Benefiting from Entity-Integrity Constraints ������������������������������������������������������������������������������������������������������ 549
Benefiting from Domain and Referential Integrity Constraints �������������������������������������������������������������������������� 551
Adopting Index-Design Best Practices �������������������������������������������������������������������������������������������������������������� 552
Avoiding the Use of the sp_ Prefix for Stored Procedure Names ���������������������������������������������������������������������� 554
Minimizing the Use of Triggers �������������������������������������������������������������������������������������������������������������������������� 554
Consider Putting Tables into In-Memory Storage ���������������������������������������������������������������������������������������������� 554
Configuration Settings ���������������������������������������������������������������������������������������������������������������554
Memory Configuration Options �������������������������������������������������������������������������������������������������������������������������� 555
Cost Threshold for Parallelism ��������������������������������������������������������������������������������������������������������������������������� 555
Max Degree of Parallelism ��������������������������������������������������������������������������������������������������������������������������������� 555
Optimize for Ad Hoc Workloads ������������������������������������������������������������������������������������������������������������������������� 555
Blocked Process Threshold ������������������������������������������������������������������������������������������������������������������������������� 555
Database File Layout ����������������������������������������������������������������������������������������������������������������������������������������� 556
Database Compression �������������������������������������������������������������������������������������������������������������������������������������� 556
■ Contents
xxii
Database Administration �����������������������������������������������������������������������������������������������������������556
Keep the Statistics Up-to-Date �������������������������������������������������������������������������������������������������������������������������� 557
Maintain a Minimum Amount of Index Defragmentation ����������������������������������������������������������������������������������� 557
Avoid Database Functions Such As AUTO_CLOSE or AUTO_SHRINK ������������������������������������������������������������������ 557
Database Backup ����������������������������������������������������������������������������������������������������������������������558
Incremental and Transaction Log Backup Frequency ���������������������������������������������������������������������������������������� 558
Backup Scheduling Distribution ������������������������������������������������������������������������������������������������������������������������ 558
Backup Compression ����������������������������������������������������������������������������������������������������������������������������������������� 559
Query Design �����������������������������������������������������������������������������������������������������������������������������559
Use the Command SET NOCOUNT ON ���������������������������������������������������������������������������������������������������������������� 560
Explicitly Define the Owner of an Object ����������������������������������������������������������������������������������������������������������� 560
Avoid Nonsargable Search Conditions ��������������������������������������������������������������������������������������������������������������� 560
Avoid Arithmetic Expressions on the WHERE Clause Column ���������������������������������������������������������������������������� 561
Avoid Optimizer Hints ���������������������������������������������������������������������������������������������������������������������������������������� 561
Stay Away from Nesting Views �������������������������������������������������������������������������������������������������������������������������� 562
Ensure No Implicit Data Type Conversions �������������������������������������������������������������������������������������������������������� 562
Minimize Logging Overhead ������������������������������������������������������������������������������������������������������������������������������ 562
Adopt Best Practices for Reusing Execution Plans �������������������������������������������������������������������������������������������� 562
Adopt Best Practices for Database Transactions ����������������������������������������������������������������������������������������������� 563
Eliminate or Reduce the Overhead of Database Cursors ����������������������������������������������������������������������������������� 564
Natively Compile Stored Procedures ����������������������������������������������������������������������������������������������������������������� 564
Summary �����������������������������������������������������������������������������������������������������������������������������������564
Index ���������������������������������������������������������������������������������������������������������������������������������565
xxiii
About the Author
Grant Fritchey, SQL Server MVP, works for Red Gate Software, a market-leading software-tools vendor, as its product evangelist. He’s done development of large-scale applications in languages such as VB, C#, and Java, and he has worked in SQL Server since version 6.0. In addition, he has worked in insurance, finance, and consulting, as well as for three failed dot coms. He is the author of SQL Server Execution Plans (Simple Talk Publishing, 2012) and SQL Server 2012 Query Performance Tuning (Apress, 2012). Grant is a coauthor of Beginning SQL Server 2012 Administration (Apress, 2012) and has one chapter in SQL Server MVP Deep Dives Volume 2 (Manning, 2011) and Pro SQL Server 2012 Practices (Apress 2012). Grant travels and presents on various SQL Server topics at large conferences and small user groups around the world.
xxv
About the Technical Reviewer
Joseph Sack (SackHQ.com) is an independent consultant based in Minneapolis, Minnesota. With more than 17 years of experience in the industry, Joe is a consultant, author, speaker, SQL MVP, and SQL Server Microsoft Certified Master specializing in performance tuning, high availability, and disaster recovery. His latest publication is the Microsoft white paper “Optimizing Your Query Plans with the SQL Server 2014 Cardinality Estimator.”
xxvii
Acknowledgments
I realize I might be repeating myself, but certain things do bear repeating. Book writing, hard. Thank the gods I don’t have to do this alone. Jonathan Gennick of Apress tried to convince me that the book needed an update, but I talked him out of it. Then we talked some more, and I realized he was right. Thanks for your patience and trust taking me down this path again, Jonathan. I found myself on my knees begging Joe Sack to be my tech editor again. This is as much his book as it is mine. Thanks for all your patient instruction, Joe. As before, anything that’s wrong with this book is not from anything that you did. Thanks.
While I don’t work there anymore, I learned so much at FM Global that I still need to give them credit for helping to build me, which helped to build this book.
Finally, thanks to the family for putting up with me going through this process again. Special thanks to my wife Michele for her help with some of the graphics.
—Grant Fritchey
xxix
Introduction
After all the years of work on SQL Server by Microsoft and all the work put in by talented data professionals, you’d think that fundamental performance problems would be a thing of the past, but they’re not. Performance is frequently one of the last things on people’s minds when they’re developing a system. Unfortunately, that means it usually becomes the biggest problem after that system goes to production. You can’t simply rely on getting a phone call that tells you that procedure X on database Y that runs on server Z is running slow. You need to have mechanisms in place to find this information for yourself. You also can’t work off the general word slow. Slow compared to what? Last week? Last month? The way it ran in your development system? And once you’ve identified something as actually running slow, you need to identify why. Does it need an index? Does it have an index that it isn’t using? Is it the CPU, the disk, the memory, the number of users, the amount of data? And now that you’ve identified what and why, you have to do something about it. How? Rewrite the query? Change the WHERE clause? The questions that will come your way when you start performance tuning are endless.
This book provides you with the tools you need to answer those questions. I’ll show you how to set up mechanisms for collecting performance metrics on your server for the SQL Server instances and databases living there. I’ll go over the more tactical methods of collecting data on individual T-SQL calls. Along the way, I’ll be discussing index structure, choice, and maintenance; how best to write your T-SQL code; how to test that code; and a whole slew of other topics. One of my goals when writing this book was to deliver all these things using examples that resemble the types of queries you’ll see in the real world. The tools and methods presented are mostly available with SQL Server Standard edition, although some are available only with SQL Server Enterprise edition. These are called out whenever you might encounter them. Almost all the tuning advice in the book is directly applicable to Microsoft Azure SQL Database (MASD), as well as to the more earthbound SQL Server 2014. Most of the tuning advice in the book is also immediately applicable to servers running within virtual machines (VMs). The primary differences for both MASD and VMs relate to what performance metrics you can collect and how much trust to put in them. The performance solutions that are code and structure related are immediately applicable to both these environments.
An argument can be made that a lot of the fundamentals for query tuning have not changed radically from SQL Server 2008 to 2012 to 2014. Therefore, the need for a new, updated version of this book may not be immediately clear. What has changed over those various releases of SQL Server is where queries run, what metrics are available to understand the system, and what tools you have available to tune your queries. The point of this latest update to the book, in addition to adding information about the new functionality available within SQL Server 2014, is to clarify the types of information and responses available on those other environments. I’ve taken the opportunity to completely restructure and rename the chapters. Several new chapters have been introduced, allowing me to both expand the scope of the material within the book and make it much easier to consume.
The main point is to learn how to answer all the various questions that are going to be presented to you. This book gives you the tools to do that and to answer those questions in a methodical manner that eliminates much of the guesswork that is so common in performance optimization today. Performance problems aren’t something to be feared. With the right tools, you can tackle performance problems with a calmness and reliability that will earn the respect of your peers and your clients. That will contribute directly to your success and theirs.
■ IntroduCtIon
xxx
Who This Book Is ForThis book is for just about anyone responsible for the performance of the system. Database administrators, certainly, are targeted because they’re responsible for setting up the systems, creating the infrastructure, and monitoring it over time. Developers are too, because who else is going to generate all the well-formed and highly performant T-SQL code? Database devel-opers, more than anyone, are the target audience, if only because that’s what I do for work. Anyone who has the capability to write T-SQL, design tables, implement indexes, or manipulate server settings on the SQL Server system is going to need this information to one degree or another.
How This Book Is StructuredThe purpose of this book was to use as many “real-looking” queries as possible. To do this, I needed a “real” database. I could have created one and forced everyone to track down the download. Instead, I chose to use the sample database created by Microsoft, called AdventureWorks2012. This is available through CodePlex (www.codeplex.com/MSFTDBProdSamples). I suggest keeping a copy of the restore handy and resetting your sample database after you have read a couple of topics from the book. Microsoft updates these databases over time, so you might see different sets of data or different behavior with some of the queries than what is listed in this book. I chose AdventureWorks2012 not because it represents a perfect database design but because it suffers from a number of design flaws and data distribution issues that make it more accurately reflect the real world instead of some flawless test case.
To a degree, this book builds on the knowledge presented from previous chapters. However, most of the chapters present information unique within that topic, so it is possible for you to jump in and out of particular chapters. You will still receive the most benefit by a sequential reading of Chapter 1 through Chapter 26.
Chapter 1, “SQL Query Performance Tuning,” introduces the iterative process of performance ••tuning. You’ll get a first glimpse at establishing a performance baseline, identifying bottlenecks, resolving the problems, and quantifying the improvements.
Chapter 2, “Memory Performance Analysis,” starts the process using Performance Monitor ••metrics and dynamic management objects as mechanisms for collecting information about memory on your systems.
Chapter 3, “Disk Performance Analysis,” continues exploring the system of bottlenecks with ••a chapter dedicated to understanding how to collect metrics on disk performance. You’ll use Performance Monitor and dynamic management objects again as well as add a number of additional T-SQL queries.
Chapter 4, “CPU Performance Analysis,” concludes the system bottleneck discussions with ••CPU. I’ll also cover some network monitoring, although that is a fairly rare issue within SQL Server, and there’s little a DBA or developer can do about it usually. The tools used are the same as in the preceding chapters.
Chapter 5, “Creating a Baseline,” takes the information from all three of the preceding chapters ••and uses it to define a baseline. A baseline represents a known point in your system from which you can compare to understand how performance is changing over time within your system.
Chapter 6, “Query Performance Metrics,” defines the best ways to look “under the hood” and ••see what kinds of queries are being run on your system. It provides a detailed look at the new Extended Events tools. Several of the most useful dynamic management views and functions used to monitor queries are first identified in this chapter.
■ IntroduCtIon
xxxi
Chapter 7, “Analyzing Query Performance,” walks you through consuming the metrics ••gathered in the previous chapter and shows various methods available to analyze query performance. You’re introduced for the first time to query execution plans as well as other utilities available within SQL Server for determining which queries are longest running, most frequently called, or in need of tuning.
Chapter 8, “Index Architecture and Behavior,” explains indexes and index architecture. It ••defines the differences between clustered and nonclustered indexes. It shows which types of indexes work best with different types of querying. Basic index maintenance is also introduced.
Chapter 9, “Index Analysis,” adds to the information from the preceding chapter and supplies ••more information about the use and functionality of indexes within SQL Server.
Chapter 10, “Database Engine Tuning Advisor,” covers the Microsoft tool Database Engine ••Tuning Advisor. The chapter goes over in detail how to use the Database Engine Tuning Advisor; you’re introduced to the various mechanisms for calling the tool and shown how it works under real loads.
Chapter 11, “Key Lookups and Solutions,” takes on the classic performance problem, the key ••lookup, which is also known as the bookmark lookup. This chapter explores various solutions to the lookup operation.
Chapter 12, “Statistics, Data Distribution, and Cardinality,” introduces the concept of ••statistics. The optimizer uses statistics to make decisions regarding the execution of the query. Maintaining statistics, understanding how they’re stored, learning how they work, and learning how they affect your queries are all topics covered within this chapter.
Chapter 13, “Index Fragmentation,” shows how indexes fragment over time. You’ll learn how ••to identify when an index is fragmented. You’ll also see what happens to your queries as indexes fragment, and you’ll learn mechanisms to eliminate index fragmentation.
Chapter 14, “Execution Plan Generation,” presents the mechanisms that SQL Server uses to ••create execution plans. Plan reuse is an important concept within SQL Server. You’ll learn how to identify whether plans are being reused. You’ll get various mechanisms for looking at the cache. This chapter also introduces dynamic management views that allow excellent access to the cache.
Chapter 15, “Execution Plan Cache Behavior,” covers information about how plans move in ••and out of cache as well as other details about execution plan behaviors including query and plan hash and your ability to reuse execution plans in cache.
Chapter 16, “Parameter Sniffing,” explains the extremely helpful process running ••automatically within SQL Server called parameter sniffing. But, parameter sniffing can go bad and cause serious performance issues. The problem, and the solutions, all go back to system statistics.
Chapter 17, “Query Recompilation,” displays how and when SQL Server will recompile plans ••that were stored in cache. You’ll learn how plan recompiles can hurt or help the performance of your system. You’ll pick up mechanisms for forcing a recompile and for preventing one.
Chapter 18, “Query Design Analysis,” reveals how to write queries that perform well within ••your system. Common mistakes are explored, and solutions are provided. You’ll learn several best practices to avoid common bottlenecks.
■ IntroduCtIon
xxxii
Chapter 19, “Reduce Query Resource Use,” demonstrates various methods to ensure you’re ••using fewer resources such as CPU and I/O when running your queries. You’ll learn about a number of antipatterns that you should avoid while writing your T-SQL.
Chapter 20, “Blocking and Blocked Processes,” teaches the best ways to recognize when ••various sessions on your server are in contention for resources. You’ll learn how to monitor for blocking along with methods and techniques to avoid blocked sessions.
Chapter 21, “Causes and Solutions for Deadlocks,” shows how deadlocks occur on your ••system. You’ll get methods for identifying sessions involved with deadlocks. The chapter also presents best practices for avoiding deadlocks or fixing your code if deadlocks are already occurring.
Chapter 22, “Row-by-Row Processing,” diagrams the inherent costs that cursors present to ••set-oriented T-SQL code. However, when cursors are unavoidable, you need to understand how they work, what they do, and how best to tune them within your environment if eliminating them outright is not an option.
Chapter 23, “Memory-Optimized OLTP Tables and Procedures,” introduces the new ••capabilities of in-memory data storage and retrieval. You’ll also see how the in-memory stored procedure can radically change performance in a positive fashion. But, this technology isn’t universally applicable, so I’ll also go over some of the limitations and best practices for applicability.
Chapter 24, “Database Performance Testing,” provides you with mechanisms to replicate the ••performance of your production system onto test systems in order to help you validate that the changes you’ve introduced to your queries really are helpful. You’ll be using the Distributed Replay utility, introduced in SQL Server 2012, along with all the other tools you’ve been using throughout the book.
Chapter 25, “Database Workload Optimization,” demonstrates how to take the information ••presented in all the previous chapters and put it to work on a real database workload. You’ll identify the worst-performing procedures and put them through various tuning methods to arrive at better performance.
Chapter 26, “SQL Server Optimization Checklist,” summarizes all the preceding chapters into ••a set of checklists and best practices. The goal of the chapter is to enable you to have a place for quickly reviewing all you have learned from the rest of the book.
Downloading the CodeYou can download the code examples used in this book from the Source Code section of the Apress web site (www.apress.com). Most of the code is straight T-SQL stored in .sql files, which can be opened and used in any SQL Server T-SQL editing tool. There are a couple of PowerShell scripts that will have to be run through a PowerShell command line.
Contacting the AuthorYou can contact the author, Grant Fritchey, at grant@scarydba.com. You can visit his blog at http://scarydba.com.
top related