Query Performance Tuning: Start to Finish. Grant Fritchey



Similar documents
How To Improve Performance In A Database

PERFORMANCE TUNING IN MICROSOFT SQL SERVER DBMS

SQL Server 2012 Query. Performance Tuning. Grant Fritchey. Apress*

SOLIDWORKS Enterprise PDM - Troubleshooting Tools

Execution Plans: The Secret to Query Tuning Success. MagicPASS January 2015

The Database is Slow

Solving Performance Problems In SQL Server by Michal Tinthofer

SQL Server Execution Plans Second Edition

Users are Complaining that the System is Slow What Should I Do Now? Part 1

SQL Server Execution Plans Second Edition

Understanding SQL Server Execution Plans. Klaus Aschenbrenner Independent SQL Server Consultant SQLpassion.at

Optimising SQL Server CPU performance

Dynamic Management Views: Available on SQL Server 2005 and above, using TSQL queries these views can provide a wide variety of information.

Introduction. Part I: Finding Bottlenecks when Something s Wrong. Chapter 1: Performance Tuning 3

SQL Server Query Tuning

SQL Server Performance Tuning and Optimization

FHE DEFINITIVE GUIDE. ^phihri^^lv JEFFREY GARBUS. Joe Celko. Alvin Chang. PLAMEN ratchev JONES & BARTLETT LEARN IN G. y ti rvrrtuttnrr i t i r

"Charting the Course... MOC AC SQL Server 2014 Performance Tuning and Optimization. Course Summary

Course 55144: SQL Server 2014 Performance Tuning and Optimization

One of the database administrators

Performance Counters. Microsoft SQL. Technical Data Sheet. Overview:

Microsoft SQL Server: MS Performance Tuning and Optimization Digital

SQL Server Performance Assessment and Optimization Techniques Jeffry A. Schwartz Windows Technology Symposium December 6, 2004 Las Vegas, NV

Analyzing & Optimizing T-SQL Query Performance Part1: using SET and DBCC. Kevin Kline Senior Product Architect for SQL Server Quest Software

Understanding Query Processing and Query Plans in SQL Server. Craig Freedman Software Design Engineer Microsoft SQL Server

SQL Server Query Tuning

MS SQL Performance (Tuning) Best Practices:

SQL Server Performance Tuning and Optimization. Plamen Ratchev Tangra, Inc.

Response Time Analysis

Course 55144B: SQL Server 2014 Performance Tuning and Optimization

Inside the SQL Server Query Optimizer

Troubleshooting Performance Problems in SQL

About Me: Brent Ozar. Perfmon and Profiler 101

CHAPTER 8: OPTIMIZATION AND TROUBLESHOOTING

Brief background What the presentation is meant to cover: Relational, OLTP databases the type that 90% of our applications use

The 5-minute SQL Server Health Check

SQL Server 2014 Performance Tuning and Optimization 55144; 5 Days; Instructor-led

Optimizing Performance. Training Division New Delhi

Chapter 15: AppInsight for SQL

SQL Server Execution Plans

PERFORMANCE TUNING FOR PEOPLESOFT APPLICATIONS

Microsoft SharePoint 2010 on HP ProLiant DL380p Gen8 servers

Monitoring PostgreSQL database with Verax NMS

SQL Server Performance Intelligence

W I S E. SQL Server 2008/2008 R2 Advanced DBA Performance & WISE LTD.

OPTIMIZING QUERIES IN SQL SERVER 2008

Using Microsoft Performance Monitor. Guide

Improving SQL Server Performance

Performance rule violations usually result in increased CPU or I/O, time to fix the mistake, and ultimately, a cost to the business unit.

Storage and SQL Server capacity planning and configuration (SharePoint...

This presentation is an introduction to the SQL Server Profiler tool.

Performance data collection and analysis process

Developing Microsoft SQL Server Databases 20464C; 5 Days

Whitepaper: performance of SqlBulkCopy

PRO: Optimizing and Maintaining a Database Administration Solution by Using Microsoft SQL Server Practice Test. Version 2.

Enhancing SQL Server Performance

The Complete Performance Solution for Microsoft SQL Server

Improve query performance with the new SQL Server 2016 Query Store!!

SQL Server 200x Optimizing Stored Procedure Performance

MONITORING MICROSOFT WINDOWS SERVER 2003

Advanced Oracle SQL Tuning

ONSITE TRAINING CATALOG

Developing Microsoft SQL Server Databases MOC 20464

20464C: Developing Microsoft SQL Server Databases

50439B: Basics of Transact SQL with SQL Server 2008 R2

1Z0-117 Oracle Database 11g Release 2: SQL Tuning. Oracle

SQL SERVER FREE TOOLS

Oracle Database 11g: SQL Tuning Workshop Release 2

Deployment Planning Guide

LearnFromGuru Polish your knowledge

Course 20464: Developing Microsoft SQL Server Databases

SQL Server 2016 New Features!

David Dye. Extract, Transform, Load

Oracle EXAM - 1Z Oracle Database 11g Release 2: SQL Tuning. Buy Full Product.

Squeezing The Most Performance from your VMware-based SQL Server

How to Guide: SQL Server 2005 Consolidation

Course Outline. SQL Server 2014 Performance Tuning and Optimization Course 55144: 5 days Instructor Led

Teradata Utilities Class Outline

Database Maintenance Essentials

ProSystem fx Engagement. Deployment Planning Guide

Microsoft SQL Server performance tuning for Microsoft Dynamics NAV

Oracle Database 11g: SQL Tuning Workshop

SQL Query Performance Tuning: Tips and Best Practices

PERFORMANCE TUNING WITH WAIT STATISTICS. Microsoft Corporation Presented by Joe Sack, Dedicated Support Engineer

Server 2008 SQL. Administration in Action ROD COLLEDGE MANNING. Greenwich. (74 w. long.)

WW TSS-02\03 MS SQL Server Extended Performance & Tuning

Response Time Analysis

Performance Tuning and Optimizing SQL Databases 2016

Developing Microsoft SQL Server Databases

IBM DB2: LUW Performance Tuning and Monitoring for Single and Multiple Partition DBs

Microsoft SQL Server 2000 Index Defragmentation Best Practices

Course 20464C: Developing Microsoft SQL Server Databases

Basic Tuning Tools Monitoring tools overview Enterprise Manager V$ Views, Statistics and Metrics Wait Events

AV-005: Administering and Implementing a Data Warehouse with SQL Server 2014

ArcSDE for Microsoft SQL Server Administration. Rob Stauder, ESRI

Perfmon counters for Enterprise MOSS

Oracle Database 11g: Performance Tuning DBA Release 2

SQL Server Performance Tuning Using Wait Statistics: A Beginner s Guide. By Jonathan Kehayias and Erin Stellato

1. This lesson introduces the Performance Tuning course objectives and agenda

FIGURE Selecting properties for the event log.

Transcription:

Query Performance Tuning: Start to Finish Grant Fritchey

Who? Product Evangelist for Red Gate Software Microsoft SQL Server MVP PASS Chapter President Author: SQL Server Execution Plans SQL Server 2008 Query Performance Tuning Distilled 2

Why Tune Queries? Most volatile aspect of a database system Subject to changes in data Affected by changes in structure Impacted by poor coding choices Victim of resource contention 3

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 4

Query Performance Tuning Start to Finish GATHERING METRICS 5

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 6

Where to Start Tuning? Random Pick a query? Ask a user? Alphabetically? Knowledge based Baseline Metrics Records 7

Server Metrics Start Query Tuning at the Server Hardware Operating System SQL Server Establish a Baseline Now is a good time Save the data 8

Tools for the Baseline Performance Monitor Dynamic Management Objects (DMO) SQL Data Collection Third Party Software 9

Where Do Problems Occur? Memory Disk I/O Processor Network DO NOT SIMPLY TRUST THESE NUMBERS 10

Memory Object Counter Values Memory Pages/sec Peaks < 50 Page Faults/sec Compare with baseline value for trend analysis SQL Server: Buffer Manager Buffer cache hit ratio Average value >= 90 Page Life Expectancy Average value > 300 Checkpoint Pages/Sec Peak < 30 SQL Server:Memory Manager Memory Grants Pending Peaks = 0 11

Disk I/O Object Counter Values PhysicalDisk % Disk Time Peaks < 85% Avg. Disk Queue Length* Disk Transfers/sec Avg. Disk sec/read Avg. Disk sec/write Peaks < 3 per disk Maximum value < 100 per disk Compare to baseline Compare to baseline * Meaningless on a SAN 12

Processor Object Counter Value Processor % Processor Time Peaks < 80% System Context Switches/sec Peaks < 1,000 Processor Queue Length Peaks < 3 SQL Statistics Batch Requests/sec Compare to Baseline SQL Compilations/sec Peaks > 100 SQL Recompilations/sec 13

Network Object Counter Value Network Interface Bytes Total/sec Peaks < 50% of NIC capacity Network Segment % Net Utilization Peaks <80% of network bandwidth 14

Performance Monitor Positives: Absolute Best Do It Yourself Option Powerful Accurate Easy to Use Ubiquitous Negatives A lot of work to set up, maintain & clean data Very little direction 15

Dynamic Management Objects Positives Easy to use In a language you know Data is ready to query Ubiquitous Negatives Incomplete No direction 16

SQL Data Collection Positives Immediate results Pre-generated reports Easy to implement Negatives Enterprise Only 2008 Only Limited Data Set 17

Third Party Tools Positives Lots of Direction Ready to consume reports Immediate returns Negatives Costly May not collect what you need or want 18

Wait Stats & Queues sys.dm_os_wait_stats Sys.dm_exec_requests Sys.dm_waiting_tasks 19

Query Metrics This is where you live Too much information Save the data, just not in its original form DO NOT USE PROFILER ON PRODUCTION SYSTEMS 20

The Server Side Trace Profiler to Generate the Script Files work best Clean and Store the Data Profiler GUI can be used to Browse Data Works with Perfmon Data Schedule the Start and Stop 21

RML Utilities Free Huge Time Savings Excellent Resource Still Need Long-Term Storage & Reporting 22

Query DMOs Sys.dm_exec_requests Sys.dm_exec_query_stats Sys.dm_exec_procedure_stats 23

Metrics Resources SQL Server 2008 Query Performance Tuning Distilled Microsoft White Paper: Performance Tuning Waits and Queues.doc http://technet.microsoft.com/enus/library/cc966413.aspx Microsoft White Paper: Troubleshooting Performance Problems in SQL Server 2008 http://msdn.microsoft.com/enus/library/dd672789.aspx Brad McGehee Louis Davidson & 24

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 25

Questions? 26

Query Performance Tuning: Start to Finish OPTIMIZER, STATISTICS, INDEXES & CONSTRAINTS 27

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 28

Optimizer Simply an Amazing piece of Software Cost-based Not Perfect Plan on Helping the Optimizer 29

Relational Engine QUERY 30

Relational Engine QUERY Relational Engine 31

Relational Engine QUERY Relational Engine Query Parsor Syntax Check Parse Tree 32

Relational Engine QUERY Relational Engine Query Parsor Syntax Check Parse Tree Algebrizer Resolves Objects Query Processor Tree 33

Relational Engine QUERY Relational Engine Query Parsor Syntax Check Parse Tree Algebrizer Resolves Objects Query Processor Tree Optimizer Execution Plan 34

Relational Engine QUERY Relational Engine DATA Query Parsor Syntax Check Parse Tree Algebrizer Resolves Objects Query Processor Tree Optimizer Execution Plan Storage Engine 35

Observing the Optimizer Sys.dm_exec_query_optimizer_info Execution Plans 36

Statistics Information about the Distribution of the Data Created on Index Keys Created on columns Created manually Cardinality By Default, Created Automatically By Default, Maintained Automatically Automatic Maintenance Is Not Enough 37

Investigating Statistics DBCC SHOW_STATISTICS(table, target) Header Density Histogram 38

Histogram 200 steps across the data An equal distribution of rows Leads to best possible sampling of data But it s not perfect "1-50" "51-100" "101-150" "150-200" 39

Updating Statistics sp_updatestats Can resample Won t run everywhere UPDATE STATISTICS X WITH FULLSCAN 40

Indexes Clustered Index Primary Key Default (but not necessary) Data is stored at the leaf level Data is ordered by the key Non-clustered Index Uses cluster key or RID of a heap INCLUDE stored at leaf And the rest outside the scope of this session 41

Constraints Primary Key Cluster by default, but doesn t have to be Always an index Foreign Key No indexes are created with this constraint Unique Constraint This constraint is an index 42

What s All This Mean? SELECT ID FROM TableA WHERE ID = 42 Table A 43

What s All This Mean? SELECT a.id, b.name, c.value FROM TableA as a JOIN TableB as b On a.id = B.ID JOIN TableC as c ON b.otherid = c.otherid WHERE a.id = 42 SCAN LOOP HASH MERGE 324 Possible Plans 44

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 45

Questions? 46

Optimizer Resources Dr. Dewitt s Key Note, PASS Summit 2010 http://www.facebook.com/l.php?u=http%3a%2f %2Fwww.slideshare.net%2FGraySystemsLab% 2Fpass-summit-2010-keynote-daviddewitt&h=306f5 Inside SQL Server 2008 T-SQL Querying Itzik Ben-Gan SQL Server 2008 Internals Kalen Delaney 47

Query Performance Tuning: Start to Finish READING EXECUTION PLANS 48

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 49

Why Execution Plans What will be accessed What indexes were used What kind of joins were used How much did all these operations cost Tuning Troubleshooting 50

Concepts and Architecture Relational Engine Estimated Execution Plan Storage Engine Actual Execution Plan Optimizer Cost-Based Just an estimate Not based on your computer Cache Most queries go to cache 51

Graphical Plans Basic Execution Join Update Delete Insert Sub-select Views 52

XML Plans Every Graphical Plan is XML All cached plans are XML Text plans show less information 53

Indicators Scans (but not always) Hash Joins (but not always) Work Tables (but not always) Extra Operators Fat Pipes Estimated/Actual Disparity 54

Execution Plan Resources SQL Server Execution Plans Microsoft Whitepapers and Web Sites Statistics used by the Query Optimizer http://www.microsoft.com/technet/prodtechnol/sql/2005/qrystats.mspx Compilation and Caching http://www.microsoft.com/technet/prodtechnol/sql/2005/recomp.mspx Showplan Security http://technet.microsoft.com/en-us/library/ms189602.aspx Understanding Joins http://technet.microsoft.com/en-us/library/ms191426.aspx Analyzing a Query http://technet.microsoft.com/en-us/library/ms191227.aspx Database Engine Developer Info Center http://technet.microsoft.com/en-us/library/ms191267.aspx Database Engine Architect Info Center http://technet.microsoft.com/en-us/library/ms175560.aspx Forcing Query Plans http://download.microsoft.com/download/4/7/a/47a548b9-249e-484c-abd7-29f31282b04d/forcing_query_plans.doc PASS Top 10 Execution Plan Web Sites 55

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 56

Questions? 57

Query Performance Tuning: Start to Finish DYNAMIC MANAGEMENT OBJECTS 58

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 59

What is a DMOs Internal State Data Functions and Views Security VIEW SERVER STATE VIEW DATABASE STATE 60

Currently Running Answer Immediate Questions Not Cache Dependent But is dependent on execution Options: Sys.dm_exec_requests Sys.dm_tran_active_transactions Sys.dm_os_waiting_tasks Sys.dm_db_index_operational_stats 61

Recently Running Answer Historical Questions Aggregate data, not individual calls Completely dependent on the cache Options: Sys.dm_exec_query_stats Sys.dm_exec_procedure_stats 62

Execution Plans Estimated Plans Only Parameters are unavailable Cache Dependent Options: Sys.dm_exec_cached_plans Sys.dm_exec_query_plan Sys.dm_exec_text_query_plan 63

Query Text Batch Text Statement Text Using Offset Cache Dependent Options: Sys.dm_exec_sql_text 64

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 65

Questions? 66

Query Performance Tuning: Start to Finish COMMON PROBLEMS 67

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 68

Common Problems Slow Running Query Key Lookup Parameter Sniffing Index Use Table Valued User Defined Functions Triggers Other Ways to Get Them 69

Slow Running Query Description Most commonly used purpose for execution plans Great tool for observing behavior Lousy tool for comparing performance Drilling down is the key Indications Fat pipes Scans Estimated/Actual Extra operations Solutions Fix it 70

Key Lookup Description AKA Bookmark Lookup Not necessarily a problem Indications Key Lookup Operator and a Join Solutions Change Query Change the index INCLUDE 71

Parameter Sniffing Description In general, this is a good thing Depends on the data distribution and parameters used Indications Intermittent poor performance Disparity on estimated & actual rows Different execution plans at different times Solutions OPTIMIZE FOR query hint Use local parameters Last resort RECOMPILE query hint Last last resort Plan Guides 72

Index Use Descriptions Just because you see the index name, doesn t mean it s getting used properly Scans are not necessarily bad Seeks are not necessarily good Indications Table Scan Index Scan Extra operators like table spool or sort Solutions Create an index Modify an index Modify the query 73

Table Valued User Defined Functions Description Yes, I see it. It says 0%. It s a lie. One row is a tragedy; one million is a statistic. Joseph Stalin (sort of) Indications Table Scan with a cost of 0% Or Table Valued Function with a cost of 0% Solutions When working with more than a few rows don t use them 74

Triggers Description Triggers are not immediately visible Estimated plan won t display Slow performance from query that shouldn t be Querying from optimizer TEST TEST TEST this Indications Second plan with the actual plan No hint of it in the estimated plan Solutions Be sure the trigger is optimized Avoid where possible 75

Individual Statement is Slow Large queries or lots of queries The exact execution plan you want may be hard to find SHOWPLAN_XML - Estimated STATISTICS XML - Actual 76

Query is Sometimes Slow Intermittent behavior is hard to catch Profiler Not the gui Server-side trace Even with a server-side trace, capturing execution plans is more expensive (primarily disk space), exercise restraint Data size increase from 2k to 64k for an XML Plan per statement Added overhead for storage and processing 77

Query Was Slow Earlier Today Knowing that the query is in cache is the key Once it s in cache, DMV s are your friend sys.dm_exec_cached_plans sys.dm_exec_query_plan Really large plans won t be stored here sys.dm_exec_query_stats sys.dm_exec_plan_attributes sys.dm_exec_sql_text sys.dm_exec_text_query_plan Used for really large plans 78

Identifying Similar Queries Ad hoc systems need hugs/tuning too Identifying similar queries can suggest needed indexes Similar queries could be candidates for procedures Multiple stored procedures may have same query Query Hash to see similarities in query Query Plan Hash to see similarities in query plan 79

Working With Large Plans Really large plans are hard to read Large plans in text Large plans in XML In XML, XQuery opens up the plan Using XML has other benefits 80

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 81

Questions? 82

Query Performance Tuning: Start to Finish ADVANCED SOLUTIONS 83

Advanced Solutions Query Hints JOIN Hints Table Hints Plan Guides Plan Forcing 84

Hints Are you smarter than these guys? Have you spent more time working on SQL Server internals than these guys? Then why do you think you should take control of the optimizer? 85

Query Hints Unions Joins FORCE ORDER MAXDOP OPTIMIZE FOR ROBUST PLAN KEEPFIXED PLAN 86

Join Hints Loop Merge Hash 87

Table Hints NOEXPAND INDEX() FAST N 88

Plan Guides For Use When You Can t Modify Code Three Kinds Object SQL Template Applies Hints 89

Plan Forcing USE PLAN As close as you can get to direct control of the Optimizer Still can t actually control it Absolute Last Ditch Efforts Limits: Must be a valid plan No INSERT, UPDATE, DELETE No distributed or full text queries Cursors can only be static or fast_forward 90

Finish Line The ability to collect performance metrics on their servers as part of an overall query tuning methodology The ability to generate, read, and understand execution plans from multiple sources in support of troubleshooting poorly performing queries An understanding of how the optimizer works in support of writing better TSQL code as well as troubleshooting poorly performing queries A working knowledge of DMVs that will help them identify and fix performance issues on their servers The ability to address common query performance problems 91

Questions? 92

Please Complete the Evaluation Form Pick up your evaluation form: In each presentation room Drop off your completed form Near the exit of each presentation room At the registration area Presented by Dell 93

THANK YOU! Presented by Dell For attending this session and PASS SQLRally Orlando, Florida