Presentation is loading. Please wait.

Presentation is loading. Please wait.

Need for Speed? Top Five SQL Server Query Tuning Tips

Similar presentations


Presentation on theme: "Need for Speed? Top Five SQL Server Query Tuning Tips"— Presentation transcript:

1 Need for Speed? Top Five SQL Server Query Tuning Tips
11/17/2018 Need for Speed? Top Five SQL Server Query Tuning Tips Janis Griffin Senior DBA / Performance Evangelist

2 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
11/17/2018 Who Am I Senior DBA / Performance Evangelist for SolarWinds Twitter® Current – 25+ Years in Oracle®, SQL Server®, ASE, and now MySQL® DBA and Developer Specialize in Performance Tuning Review Database Performance for Customers and Prospects Common Question – How do I tune it? © 2018 SolarWinds Worldwide, LLC. All rights reserved.

3 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Agenda Challenges Of Tuning Top Five Tuning Tips Monitor Wait Time Find the right SQL statements to work on Get Baseline Metrics Review the Execution Plan Know which Optimizer Features are being used Gather Object Information Review Table, Column, Index & Constraint information Understand Column Selectivity & Statistics Find the Driving Table Consider SQL Diagramming Engineer out the Stupid © 2018 SolarWinds Worldwide, LLC. All rights reserved.

4 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Challenges of Tuning SQL Tuning is Hard Who should tune – DBA or Developer Which SQL to tune Requires Expertise in Many Areas Technical – Plan, Data Access, SQL Design Business – What is the Purpose of SQL? Tuning Takes Time Large Number of SQL Statements Each Statement is Different Low Priority in Some Companies Vendor Applications Focus on Hardware or System Issues Never Ending © 2018 SolarWinds Worldwide, LLC. All rights reserved.

5 Tuning Query Performance
Consider these tips as building blocks for your ‘Tuning’ toolbox. © 2018 SOLARWINDS WORLDWIDE, LLC. ALL RIGHTS RESERVED.

6 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
1. Monitor Wait Time Understand the total time a Query spends in Database Measure time while Query executes SQL Server helps by providing Wait Types Focus on Total Wait Time © 2018 SolarWinds Worldwide, LLC. All rights reserved. 5

7 Wait Time Tables (DMVs - 2005 & Up)
2008 + dm_exec_requests start_time status sql_handle plan_handle start/stop offset database_id user_id blocking_session wait_type wait_time dm_os_wait_stats wait_type waiting_tasks_count wait_time_ms 2000 only sysprocesses loginame hostname programname spid dbid waittype waittime Lastwaittype waitresource sql_handle stmt_start stmt_end cmd dm_exec_sessions login_time login_name host_name program_name session_id dm_exec_sql_text text dm_exec_query_stats execution_count total_logical_writes total_physical_reads total_logical_reads dm_exec_query_plan query_plan © 2018 SolarWinds Worldwide, LLC. All rights reserved.

8 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Wait Type DMV Problem No Time Based View What happened between 3am-5am this morning not possible to get from the DMV objects Need to use other tools Run example query (on next slide), include timestamp and save in table Extended Events Session to gather waits and query results System_health session gathers SQLs & Waits – hard to see trends Query Store or Solarwinds Database Performance Analyzer (DPA) Different DMV Problem © 2018 SolarWinds Worldwide, LLC. All rights reserved.

9 View Wait Types at Session Level
sys.dm_exec_requests Real-time view into what each session/SQL is waiting on Status Column tells you what state it’s in Suspended - means the session is waiting on the wait_type Running/Runnable - means the session is on the CPU or in queue Sleeping - means the session is idle SELECT r.session_id, r.wait_time, r.status, r.wait_type, r.blocking_session_id, s.text, r.statement_start_offset, r.statement_end_offset, p.query_plan FROM sys.dm_exec_requests r OUTER APPLY sys.dm_exec_sql_text (r.sql_handle) s OUTER APPLY sys.dm_exec_text_query_plan (r.plan_handle, r.statement_start_offset, r.statement_end_offset) p WHERE r.status <> ’background’ AND r.status <> ’sleeping’ AND r.session_id <> © 2018 SolarWinds Worldwide, LLC. All rights reserved.

10 Top Wait Types at Instance Level
sys.dm_os_wait_stats Cumulative since instance startup DBCC SQLPERF (N'sys.dm_os_wait_stats', CLEAR); Exclude idle wait types Query on next slide © 2018 SolarWinds Worldwide, LLC. All rights reserved.

11 Instance Level Query – 95% of the waits
WITH Waits AS (SELECT wait_type, wait_time_ms / AS WaitS, (wait_time_ms - signal_wait_time_ms) / AS ResourceS, signal_wait_time_ms / AS SignalS, waiting_tasks_count AS WaitCount, * wait_time_ms / SUM (wait_time_ms) OVER() AS Percentage, ROW_NUMBER() OVER(ORDER BY wait_time_ms DESC) AS RowNum FROM sys.dm_os_wait_stats WHERE wait_type NOT IN ( N'BROKER_EVENTHANDLER',N'BROKER_RECEIVE_WAITFOR',N'BROKER_TASK_STOP',N'BROKER_TO_FLUSH', N'BROKER_TRANSMITTER',N'CHECKPOINT_QUEUE', N'CHKPT',N'CLR_AUTO_EVENT', N'CLR_MANUAL_EVENT',N'CLR_SEMAPHORE', N'DBMIRROR_DBM_EVENT',N'DBMIRROR_EVENTS_QUEUE',N'DBMIRROR_WORKER_QUEUE',N'DBMIRRORING_CMD',N'DIRTY_PAGE_POLL', N'DISPATCHER_QUEUE_SEMAPHORE',N'EXECSYNC',N'FSAGENT',N'FT_IFTS_SCHEDULER_IDLE_WAIT',N'FT_IFTSHC_MUTEX', N'HADR_CLUSAPI_CALL',N'HADR_FILESTREAM_IOMGR_IOCOMPLETION',N'HADR_LOGCAPTURE_WAIT',N'HADR_NOTIFICATION_DEQUEUE', N'HADR_TIMER_TASK',N'HADR_WORK_QUEUE',N'KSOURCE_WAKEUP',N'LAZYWRITER_SLEEP',N'LOGMGR_QUEUE',N'ONDEMAND_TASK_QUEUE', N'PWAIT_ALL_COMPONENTS_INITIALIZED',N'QDS_PERSIST_TASK_MAIN_LOOP_SLEEP', N'QDS_CLEANUP_STALE_QUERIES_TASK_MAIN_LOOP_SLEEP',N'REQUEST_FOR_DEADLOCK_SEARCH',N'RESOURCE_QUEUE', N'SERVER_IDLE_CHECK',N'SLEEP_BPOOL_FLUSH',N'SLEEP_DBSTARTUP',N'SLEEP_DCOMSTARTUP', N'SLEEP_MASTERDBREADY',N'SLEEP_MASTERMDREADY',N'SLEEP_MASTERUPGRADED',N'SLEEP_MSDBSTARTUP', N'SLEEP_SYSTEMTASK',N'SLEEP_TASK',N'SLEEP_TEMPDBSTARTUP',N'SNI_HTTP_ACCEPT', N'SP_SERVER_DIAGNOSTICS_SLEEP',N'SQLTRACE_BUFFER_FLUSH',N'SQLTRACE_INCREMENTAL_FLUSH_SLEEP', N'SQLTRACE_WAIT_ENTRIES',N'WAIT_FOR_RESULTS',N'WAITFOR',N'WAITFOR_TASKSHUTDOWN', N'WAIT_XTP_HOST_WAIT',N'WAIT_XTP_OFFLINE_CKPT_NEW_LOG',N'WAIT_XTP_CKPT_CLOSE',N'XE_DISPATCHER_JOIN', N'XE_DISPATCHER_WAIT',N'XE_TIMER_EVENT') AND waiting_tasks_count > 0) SELECT MAX (W1.wait_type) AS WaitType, CAST (MAX (W1.WaitS) AS DECIMAL (16,2)) AS Wait_S, CAST (MAX (W1.ResourceS) AS DECIMAL (16,2)) AS Resource_S, CAST (MAX (W1.SignalS) AS DECIMAL (16,2)) AS Signal_S, MAX (W1.WaitCount) AS WaitCount, CAST (MAX (W1.Percentage) AS DECIMAL (5,2)) AS Percentage, CAST ((MAX (W1.WaitS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS AvgWait_S, CAST ((MAX (W1.ResourceS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS AvgRes_S, CAST ((MAX (W1.SignalS) / MAX (W1.WaitCount)) AS DECIMAL (16,4)) AS AvgSig_S FROM Waits AS W1 INNER JOIN Waits AS W2 ON W2.RowNum <= W1.RowNum GROUP BY W1.RowNum HAVING SUM (W2.Percentage) - MAX (W1.Percentage) < 95; GO 2012 Idle Events Only © 2018 SolarWinds Worldwide, LLC. All rights reserved.

12 Base Query - Not Rocket Science
INSERT INTO rta_data SELECT r.session_id, r.wait_time, r.status, r.wait_type, r.blocking_session_id, s.text, r.statement_start_offset, r.statement_end_offset, p.query_plan, CURRENT_TIMESTAMP time_polled FROM sys.dm_exec_requests r OUTER APPLY sys.dm_exec_sql_text (r.sql_handle) s OUTER APPLY sys.dm_exec_text_query_plan (r.plan_handle, r.statement_start_offset, r.statement_end_offset) p WHERE r.status <> 'background' AND r.status <> 'sleeping' AND r.session_id <> First create a table for the WTA data WITH rta (sql_text, wait_type, time_in_second) AS (SELECT text as sql_text, wait_type, COUNT(*) as time_in_second FROM rta_data rta GROUP BY text,wait_type) ,tot (text, tot_time) (SELECT text, COUNT(*) as tot_time FROM rta_data GROUP BY text) SELECT sql_text, wait_type, time_in_second, tot_time FROM rta JOIN tot ON sql_text = text ORDER BY tot_time, time_in_second, wait_type, sql_text SELECT r.session_id, r.wait_time, r.status, r.wait_type, r.blocking_session_id, s.text, r.statement_start_offset, r.statement_end_offset,p.query_plan, CURRENT_TIMESTAMP time_polled INTO rta_data FROM sys.dm_exec_requests r OUTER APPLY sys.dm_exec_sql_text (r.sql_handle) s OUTER APPLY sys.dm_exec_text_query_plan (r.plan_handle, r.statement_start_offset, r.statement_end_offset) p WHERE r.status <> 'background' AND r.status <> 'sleeping' AND r.session_id <> © 2018 SolarWinds Worldwide, LLC. All rights reserved.

13 Query spent almost 5 minutes in the database - most its time on CPU
Base Query – Cont. WITH rta (sql_text, wait_type, time_in_second) AS (SELECT text as sql_text, wait_type, COUNT(*) as time_in_second FROM rta_data rta GROUP BY text,wait_type) ,tot (text, tot_time) AS (SELECT text, COUNT(*) as tot_time FROM rta_data GROUP BY text) SELECT sql_text, wait_type, time_in_second, tot_time FROM rta JOIN tot ON sql_text = text ORDER BY tot_time, time_in_second, wait_type, sql_text Query spent almost 5 minutes in the database - most its time on CPU © 2018 SolarWinds Worldwide, LLC. All rights reserved.

14 2012+ Extended Events (2016 example)
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

15 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
2017 Query Store Find Top 10 Queries Waiting The Most SELECT TOP 10 qt.query_sql_text, q.query_id, p.plan_id, ws.wait_category_desc, sum(total_query_wait_time_ms) AS sum_total_wait_ms FROM sys.query_store_wait_stats ws JOIN sys.query_store_plan p ON ws.plan_id = p.plan_id JOIN sys.query_store_query q ON p.query_id = q.query_id JOIN sys.query_store_query_text qt ON q.query_text_id = qt.query_text_id WHERE ws.wait_category_desc != 'Idle' GROUP BY qt.query_sql_text, q.query_id, p.plan_id, ws.wait_category_desc ORDER BY sum_total_wait_ms DESC Over 1 hour waiting on Parallelism © 2018 SolarWinds Worldwide, LLC. All rights reserved.

16 Wait Time Analysis (WTA)
Focus on SQL statements spending the most time in the database Almost 1 ½ hour of wait time. 68% on Memory/CPU 18% on Resource Semaphore 14% on IO_Completion © 2018 SolarWinds Worldwide, LLC. All rights reserved.

17 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
WTA Benefits © 2018 SolarWinds Worldwide, LLC. All rights reserved.

18 Wait Types – Give Great Clues
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

19 Wait Types – Give Great Clues
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

20 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
WTA Benefits – Cont. Get baseline metrics How long does it take now What is acceptable (10 sec, 2 min, 1 hour) Record Logical Reads for tuning comparison Collect Wait Type Information Locking / Blocking (LCK) I/O problem (PAGEIOLATCH) Latch contention (LATCH) Network slowdown (NETWORK) May be multiple issues All have different resolutions © 2018 SolarWinds Worldwide, LLC. All rights reserved.

21 2. Review the Execution Plan
SET SHOWPLAN_XML { ON | OFF } 2. Review the Execution Plan SQL Server Management Studio (SSMS) Estimated Execution Plan - can be wrong for many reasons SET SHOWPLAN_XML { ON | OFF } Actual Execution Plan – must execute query Can be dangerous in production / Wrong in test SET STATISTICS XML { ON | OFF } SQL Server Profiler Tracing / Extended Events Performance: Execution Plan (2000) Showplan XML (2005+) Works when you know a problem will occur DM_EXEC_QUERY_PLAN Cached execution plan of executed query © 2018 SolarWinds Worldwide, LLC. All rights reserved.

22 DM_EXEC_QUERY_PLAN Example
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

23 Examine the Execution Plan
Find Expensive Operators Examine CPU / IO costs, row counts Look for full table or clustered index scans Review the Predicate Information Know how parameters are being interpreted Review the data types / Implicit conversions? Know which step filtering predicate is applied Review Join Methods Nested Loops join: Usually efficient for smaller data sets Merge Join: Efficient for larger data sets. Hash Match join: Useful on very large data sets (DW) © 2018 SolarWinds Worldwide, LLC. All rights reserved.

24 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Review Logical IO © 2018 SolarWinds Worldwide, LLC. All rights reserved.

25 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Execution Plan CREATE NONCLUSTERED INDEX <Name of Missing Index, sysname ON Sales.OrderHeader(OnlineOrderFlag) INCLUDE (OrderID,OrderDate,CustomerID,SubTotal) © 2018 SolarWinds Worldwide, LLC. All rights reserved.

26 3. Gather Object Information 3. Gather Object Information
Get Table Definition View / Table valued function? Where does it physically reside Review Keys & Constraints Size / Selectivity / Datatypes of Columns Data Profile Task / Viewer – Integration Services Statistic Gathering? alter set auto_update_statistics on; SSMS can help… © 2018 SolarWinds Worldwide, LLC. All rights reserved.

27 Review Table & Column Info - Cont. Review Table & Column Info - Cont.
Get All Row Counts Review the ‘Selected’ Columns Use of ‘*’ or scalar functions Look performance degraders CASE, CAST, CONVERT Sub-queries SARG-able vs non-SARG-able Examine WHERE & JOIN clauses Bad signs No filters Majority of table returned © 2018 SolarWinds Worldwide, LLC. All rights reserved.

28 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Review Indexes Get Index definitions Know the order of columns and their selectivity Review existing keys and constraints Know Multi-Table Relationships (ERD) Primary key and foreign definitions Check and not null constraints Tip: Keys & constraints help create better execution plans © 2018 SolarWinds Worldwide, LLC. All rights reserved.

29 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Review Indexes – Cont. Make sure the optimizer can use the index Functions on indexed columns can turn off index Consider rewriting Look for implicit conversions Get sample parameter values Know left leading column if multi-column Know Index Rebuild Schedules © 2018 SolarWinds Worldwide, LLC. All rights reserved.

30 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
4. Find The Driving Table Need to know the size of the actual data sets of each step In Joins (Right, Left, Outer) What are the filtering predicates When is each filtering predicate applied Try to filter earlier rather than later Compare size of final result set with rows examined Drive the query with the table that returns the least amount of data To reduce logical reads © 2018 SolarWinds Worldwide, LLC. All rights reserved.

31 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Case Study SELECT c.CustomerID , p.FirstName , p.LastName , oh.OrderID , oh.OrderDate , oh.SubTotal, pr.Name, pr.Color, od.OrderQty FROM Sales.OrderHeader AS oh INNER JOIN Sales.Customer AS c ON c.CustomerID = oh.CustomerID INNER JOIN Person.Person AS p ON p.BusinessEntityID = c.PersonID INNER JOIN Sales.OrderDetail AS od ON od.OrderID = oh.OrderID INNER JOIN Production.Product AS pr ON pr.ProductID = od.ProductID WHERE oh.OnlineOrderFlag = 1 and p.LastName like 'C%' and pr.Name like 'Mountain%42' and pr.ProductID like '9%' Joins Filtering Predicates © 2018 SolarWinds Worldwide, LLC. All rights reserved.

32 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Execution Plan CREATE NONCLUSTERED INDEX <Name of Missing Index, sysname ON Sales.OrderHeader(OnlineOrderFlag) INCLUDE (OrderID,OrderDate,CustomerID,SubTotal) © 2018 SolarWinds Worldwide, LLC. All rights reserved.

33 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Review Logical IO © 2018 SolarWinds Worldwide, LLC. All rights reserved.

34 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Use SQL Diagramming Great Book “SQL Tuning” by Dan Tow Great book that teaches SQL Diagramming Oldie but a Goodie OD .6% OH C P PR 88% 7% 1 67 3 18699 Join Selectivity select avg(cnt) from (select productid, count(*) cnt from sales.orderdetail oh group by productid) a Filtering Selectivity select count(1) from sales.OrderHeader oh where oh.OnlineOrderFlag = 1 select / *100 = 87.90 select count(1) from person.Person p where p.LastName like 'C%‘ select / * 100 = 6.93 select count(1) from production.Product pr where pr.Name like 'Mountain%42‘ and pr.ProductID like '9%' select 3.00 / * 100 = 0.59 © 2018 SolarWinds Worldwide, LLC. All rights reserved.

35 Drive the Query by Product
Why isn’t the clustered primary key being used? © 2018 SolarWinds Worldwide, LLC. All rights reserved.

36 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Why the Key Lookup? © 2018 SolarWinds Worldwide, LLC. All rights reserved.

37 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Implicit Conversion © 2018 SolarWinds Worldwide, LLC. All rights reserved.

38 5. Engineer out the Stupid
Look for Performance Inhibitors Cursor or row by row processing Parallel processing Hard-coded Hints Nested views Linked servers Abuse of Wild Cards (*) or No Where Clause Code-based SQL Generators (e.g. EMF; LINQ; nHibernate) Implicit Data Conversions Non-SARG-able / Scalar Functions Select… where upper(first_name) = ‘JANIS’ © 2018 SolarWinds Worldwide, LLC. All rights reserved.

39 Try to Fix the Stupid First
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

40 Change Indexes to Reduce I/O
Adding indexes is not always the right thing to do! Consider Insert, Update & Delete activity Covering index CREATE NONCLUSTERED INDEX CIX_OrderHeader_OnlineOrderFlag ON Sales.OrderHeader(OnlineOrderFlag) INCLUDE (OrderID,OrderDate,CustomerID,SubTotal) Filtered index CREATE NONCLUSTERED INDEX FIX_OrderHeader_OnlineOrderFlag WHERE OnlineOrderFlag = 1 Combination CREATE NONCLUSTERED INDEX FcIX_OrderHeader_OnlineOrderFlag © 2018 SolarWinds Worldwide, LLC. All rights reserved.

41 Add Covering Index on OrderDetail
CREATE NONCLUSTERED INDEX CIX_OrderDetail_ProductID ON Sales.OrderDetail(ProductID) INCLUDE (OrderID,OrderQty) © 2018 SolarWinds Worldwide, LLC. All rights reserved.

42 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Re-Run the Query Make Small Changes Consider adjusting indexes Re-run & check run-time details Compare results with baseline metrics Use ‘Logical Reads’ as a key measurement Did you improve it? No? Rinse & Repeat © 2018 SolarWinds Worldwide, LLC. All rights reserved.

43 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Still high Cost? © 2018 SolarWinds Worldwide, LLC. All rights reserved.

44 Add Index in OrderHeader
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

45 Monitor Your Tuning Results
Monitor the improvement Be able to prove that tuning made a difference Take new metric measurements Compare them to initial readings Brag about the improvements – no one else will Monitor for next tuning opportunity Tuning is iterative There is always room for improvement Make sure you tune things that make a difference Shameless Product Pitch - DPA © 2018 SolarWinds Worldwide, LLC. All rights reserved.

46 Before Performance Tuning
Query before tuning: 1 sec / avg exes 2500 exes / hour 100,000 rows processed 300,000,000 Logical IOs © 2018 SolarWinds Worldwide, LLC. All rights reserved. © 2018 SolarWinds Worldwide, LLC. All rights reserved.

47 After Performance Tuning
Added 1st index Added 2nd index Query after tuning: 490ms / avg exes 6000+ exes / hour 200,000+ rows processed 24,000,000 Logical IOs

48 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Case Study Flights by City & Day of Week CREATE PROCEDURE VARCHAR(10) AS SELECT o.carrier, uc.description AS carrier_name, o.fl_date,o.fl_num,o.tail_num ,ao.description AS origin_airport,co.Description AS origin_city ,ad.description AS destination_airport ,cd.Description AS destination_city ,w.Description Day_of_Wed FROM t_ontime_2015 o INNER JOIN L_UNIQUE_CARRIERS AS uc ON uc.Code = o.UNIQUE_CARRIER INNER JOIN L_AIRPORT_ID AS ao ON ao.Code = o.ORIGIN_AIRPORT_ID INNER JOIN L_AIRPORT_ID AS ad ON ad.Code = o.DEST_AIRPORT_ID INNER JOIN L_CITY_MARKET_ID AS co ON co.Code = o.ORIGIN_CITY_MARKET_ID INNER JOIN L_CITY_MARKET_ID AS cd ON cd.Code = o.DEST_CITY_MARKET_ID INNER JOIN L_WEEKDAYS AS w ON w.Code = o.DAY_OF_WEEK WHERE fl_date AND co.Description AND w.Description © 2018 SolarWinds Worldwide, LLC. All rights reserved.

49 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Case Study US DOT - On-time Performance © 2018 SolarWinds Worldwide, LLC. All rights reserved.

50 Query spending the most time (WTA)
Run-Time Details: Over 50% spent on CPU, Latch_EX & CXPACKET LIO = 381,217,970 © 2018 SolarWinds Worldwide, LLC. All rights reserved.

51 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
CXPACKET Wait Type Indicates a SPID is waiting on parallel processes to complete or start It’s more of a status - not necessarily a problem select session_id, exec_context_id, wait_type, wait_duration_ms, resource_description from sys.dm_os_waiting_tasks where session_id in (select session_id from sys.dm_exec_requests where wait_type='CXPACKET') order by session_id, exec_context_id; ACCESS_METHODS_DATASET_PARENT: Points to MAXDOP setting Default is: max degree of parallelism = 0 (unlimited) Great article by Paul Randall Most-common-latch-classes © 2018 SolarWinds Worldwide, LLC. All rights reserved.

52 Get & Examine the Execution Plan
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

53 Review Table & Column Info
0 = Heap 1 = Clustered Index 2 or greater = nonclustered index © 2018 SolarWinds Worldwide, LLC. All rights reserved.

54 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Add Clustered Indexes CREATE UNIQUE CLUSTERED INDEX l_airport_id_code ON l_airport_id(code); CREATE UNIQUE CLUSTERED INDEX l_city_market_id_code ON l_city_market_id(code); CREATE UNIQUE CLUSTERED INDEX l_unique_carriers_code ON l_unique_carriers(code); CREATE UNIQUE CLUSTERED INDEX l_weekdays_code ON l_weekdays(code); CREATE UNIQUE CLUSTERED INDEX t_ontime_flight ON t_ontime_2015 (origin_city_market_id,carrier,fl_num,fl_date,origin_airport_seq_id); © 2018 SolarWinds Worldwide, LLC. All rights reserved.

55 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Find the Driving Table 800k O 8% 1 w 405k 13% 18k ad 1 19k 1 uc ao 1 co cd .02% Filtering Selectivity select count(1) from t_ontime_2015 where fl_date between ' :00:00.000' and' :00:00.000‘; select / * 100 = 8.23 select count(1) from L_CITY_MARKET_ID where description = 'Chicago, IL' select 1.00 / * 100 = 0.017 select count(*) from L_WEEKDAYS where description = 'Friday' select 1.00 / 8 * 100 = 12.50 © 2018 SolarWinds Worldwide, LLC. All rights reserved.

56 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Tune the Query © 2018 SolarWinds Worldwide, LLC. All rights reserved.

57 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Fix the Stupid CREATE PROCEDURE get_city_day_flights NVARCHAR(255) AS SELECT o.carrier, uc.description AS carrier_name, o.fl_date,o.fl_num,o.tail_num ,ao.description AS origin_airport,co.Description AS origin_city ,ad.description AS destination_airport ,cd.Description AS destination_city ,w.Description Day_of_Wed FROM t_ontime_2015 o INNER JOIN L_UNIQUE_CARRIERS AS uc ON uc.Code = o.UNIQUE_CARRIER INNER JOIN L_AIRPORT_ID AS ao ON ao.Code = o.ORIGIN_AIRPORT_ID INNER JOIN L_AIRPORT_ID AS ad ON ad.Code = o.DEST_AIRPORT_ID INNER JOIN L_CITY_MARKET_ID AS co ON co.Code = o.ORIGIN_CITY_MARKET_ID INNER JOIN L_CITY_MARKET_ID AS cd ON cd.Code = o.DEST_CITY_MARKET_ID INNER JOIN L_WEEKDAYS AS w ON w.Code = o.DAY_OF_WEEK WHERE fl_date AND co.Description AND w.Description © 2018 SolarWinds Worldwide, LLC. All rights reserved.

58 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Make Small Changes © 2018 SolarWinds Worldwide, LLC. All rights reserved.

59 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Adjust the index create index IX_L_City_market_id_desc on L_CITY_MARKET_ID(Description); © 2018 SolarWinds Worldwide, LLC. All rights reserved.

60 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Re-run the Query Run-Time Details: Over 85% spent on ASYNC_NETWORK_IO Rest on CPU & PAGEIOLATCH LIOs = 29,839,105 © 2018 SolarWinds Worldwide, LLC. All rights reserved.

61 Monitor Tuning Results
© 2018 SolarWinds Worldwide, LLC. All rights reserved.

62 © 2018 SolarWinds Worldwide, LLC. All rights reserved.
Summary There are a lot of challenges in Query Tuning If you remember the Top 5 Tips, they should take you a long way 1. Monitor Wait time Look at wait events, record baseline metrics 2. Review the Execution Plan Look for expensive steps, know what’s supporting the plan 3. Gather Object Information For expensive objects – know what the optimizer knows 4. Find the Driving Table Consider SQL Diagramming techniques 5. Engineer out the Stupid Q & A © 2018 SolarWinds Worldwide, LLC. All rights reserved.

63 Resolve performance issues quickly
Try Database Performance Analyzer FREE for 14 days Improve root cause of slow performance Quickly identify root cause of issues that impact end-user response time See historical trends over days, months, and years Understand impact of VMware® performance © 2018 SolarWinds Worldwide, LLC. All rights reserved.

64 © 2018 SolarWinds Worldwide, LLC. All rights reserved.


Download ppt "Need for Speed? Top Five SQL Server Query Tuning Tips"

Similar presentations


Ads by Google