SQL Query Tuning
SQL Query Tuning
Table of Contents
SQL Server 2005: SQL Query Tuning ..........................................................................................................................3 Lab Setup.......................................................................................................................................................................4 Exercise 1 Troubleshooting Deadlocks with SQL Profiler............................................................................................5 Exercise 2 Isolating a Slow Running Query Using SQL Profiler..................................................................................9 Exercise 3 Examining an Execution Plan ....................................................................................................................11 Exercise 4 Using the Database Tuning Advisor ..........................................................................................................12
concepts in this module and as a result may not comply with Microsoft security recommendations.
After completing this lab, you will be able to: Use the SQL Profiler to troubleshoot deadlocks Generate a query plan for a poorly performing query and save the plan as an XML document Use the Database Tuning Advisor
are based on beta builds of the product. The intent of these labs is to provide you with a general feel of some of the planned features for the next release of SQL Server. As with all software development projects, the final version may differ from beta builds in both features and user interface. For the latest details on SQL Server 2005, please visit http://www.microsoft.com/sql/2005/.
Scenario
You are the database administrator for the AdventureWorks database. Your users are experiencing frequent deadlocks and you are concerned that the deadlocks might be a cause of poor system performance. You have isolated a query that is often involved in deadlocks. You will capture a trace of the events leading up to the deadlock and the details of the deadlock itself, using SQL Profiler. After tracking down the cause of the deadlocks, you realize that it is not a major cause of system performance degradation, so you decide to investigate key queries. You will analyze the queries by inspecting the query plans being used for them, and you will employ the Index Tuning Advisor to suggest optimum indexes. Experience with basic administration tasks in SQL Server 2000 A familiarity with the Transact-SQL language Completed the SQL Server Management Studio hands-on lab
Prerequisites
45 Minutes
Page 3 of 12
Lab Setup
Tasks 1. Log in. Detailed Steps 1. Log in using the Administrator user account. The password is Pass@word1.
Page 4 of 12
NOTE: Not all data items are available for every event. This is also true in SQL Server 2000 Profiler, but isnt obvious from the way data items are selected in that version. For example, performance data items, such as duration, reads, and writes, are not
Page 5 of 12
SQL Server 2005: SQL Query Tuning Tasks available for starting events. These performance data items are only available for events such as SP:Completed (stored procedure completion event) and SP:StmtCompleted (statement completion within a stored procedure). In addition, some events have data for EventSubClass, BinaryData and IntegerData, and others do not. Detailed Steps
apply any additional filters for this exercise, but you may want to explore which data items allow filters and which do not. Some data items allow a range filter. You can use this filter to specify exact values that must match, or a range of values specified by greater than or less than operators. Other data items allow a pattern-matching filter, which you can use with like or not like operators. If you rightclick on any data item or event name, the shortcut menu includes the option, Organize Columns. This option allows you to rearrange the order in which the data items appear in your output. Generate a multi-table deadlock.
RPC:Completed In SQL Profiler for 2005, filters are set in the Events Selection screen. 9. Scroll to the right until you find the DatabaseID column. You may need to increase the width of the columns to see the full names. 10. Right-click the DatabaseID column heading and select Edit Column Filter. Expand the Not equal to node, and type in the number 4. Click OK. This will filter out all activity in the msdb database. 11. Right-click the DatabaseName column heading and select Edit Column Filter. Expand the Not like node, and type in ReportServer. Click OK. This will filter out all activity in the ReportServer database. 12. Click the Events Extraction Settings tab. Select the Save Deadlock XML Events Separately checkbox. Verify that the current directory is C:\SQL Labs\User Projects, enter the File name XMLdeadlock, and click Save. Click Each Deadlock XML batch in a distinct file, and click Run. The trace begins.
o o o o
2.
1. 2.
3.
4. 5.
From the Windows task bar, select Start | All Programs | Microsoft SQL Server 2005 | SQL Server Management Studio. When the Connect to Server dialog box appears, enter localhost as the Server name, and verify that Windows Authentication is selected as the authentication method. Click Connect. Select the File | Open | Project/Solution menu item. Navigate to C:\SQL Labs\Lab Projects\Tuning Lab\Exercise 1. Select Exercise 1.ssmssln and click Open. In the Solution Explorer window, double-click Copy tables.sql under the Queries folder, to open this SQL script. Press F5 or click the Execute toolbar button.
This script, which can take a few minutes depending upon the speed of your machine,
Page 6 of 12
SQL Server 2005: SQL Query Tuning Tasks Detailed Steps to run, makes copies of several tables from the AdventureWorks database. When you modify data in the following tasks, you will be working with the new copies and will not be affecting the original data. After inspecting the statements, you can close this script. 6. Open the SQL script First part multi table deadlock.sql. This script allows you to create a deadlock. The scenario is that you need to change the Active status for two of your vendors to false. You also need to update the contact data for these vendors, to identify two contacts as owners. The script in First part multi table deadlock.sql updates the NewVendor data for Vendor ID 1, and then attempts to update the NewVendorContact data for Vendor ID 1. However, you will not execute the entire script at once. 7. Select a portion of the script, beginning at the first line and ending before the comment line that reads Only execute up to this point in the first batch. Press F5 or click the Execute button. 8. Open the SQL script Second part multi table deadlock.sql. The script in Second part multi table deadlock.sql updates the NewVendorContact data for Vendor ID 15, and then attempts to update the NewVendor data for Vendor ID 15. Again, you will not execute the entire script all at once. 9. Select the portion of the script from the first line down to before the comment line that reads Only execute up to this point in the first batch. Press F5 or click the Execute button. 10. Use the down-arrows in the upper right corner of the code window to select First part multi table deadlock.sql. Select only the second UPDATE statement in the transaction, after the comment Next, start execution here, and click the Execute button. The update statement will not complete executing, because it will be blocked by the first update in the transaction in the Second part multi table deadlock.sql script. This is not a deadlock yet, because there is only one blocking process and one blocked process. 11. Go back to the query window for Second part multi table deadlock.sql. Select only the second UPDATE statement in the transaction, beginning after the comment Next, start execution here, and click the Execute button. This second update will be blocked by the first update in the transaction in the First part multi table deadlock.sql script. Because both processes are now blocking each other, this is a true deadlock. SQL Server will detect the deadlock and choose one process as the victim. You should see this message in the results window for one of the deadlock scripts (the Process ID may be different on your computer):
Msg 1205, Level 13, State 45, Line 1 Transaction (Process ID 57) was deadlocked on lock resources with another process and has been chosen as the deadlock victim. Rerun the transaction.
Note: You have executed a BEGIN TRAN and no COMMIT TRAN or ROLLBACK TRAN. You would normally want to avoid this, because transactions held open across batches have a greater chance of being involved in a deadlock. This exercise violates that recommendation intentionally to cause a deadlock.
The transaction is rolled back when the deadlock error message is generated, and all the locks are released. The other winning transaction is then no longer blocked and can complete its second update. 12. Run the last line (ROLLBACK TRAN) in the transaction that wasnt the deadlock victim, to rollback the transaction.
NOTE: The transaction that
Page 7 of 12
SQL Server 2005: SQL Query Tuning Tasks was not the deadlock victim is still pending, although it has completed both its updates. It has been neither committed nor rolled back. 3. Examine the captured deadlock information. Detailed Steps
1.
2.
Return to your running trace in the SQL Profiler and click the Stop Selected Trace toolbar button, which has a red square icon. Near the end of the trace you will see two rows that begin with Lock:Deadlock Chain. Select the Deadlock Graph event below the Lock:Deadlock Chain events. When you select this event in Profiler, Deadlock Graph information appears in the lower window of the Profiler, similar to that shown in Figure 1.
Figure 1: Sample Deadlock Graph This visual representation of the processes involved in deadlock includes the type and mode of lock each process held, the type of lock each process was waiting on, and some information about the actual resource on which the lock was placed.
Page 8 of 12
4.
5.
Page 9 of 12
SQL Server 2005: SQL Query Tuning Tasks Detailed Steps 5. Once the script execution completes, go back to the trace running in SQL Profiler and stop the trace by clicking the Stop Selected Trace button, the red square in the toolbar. 6. Scroll to the right to find the Duration column. Only some of the events have a duration listed. 7. Isolate the event with the greatest value in the Duration column. Select that row in the Profiler output, and you should see the query in the lower Profiler window. 8. Look in your C:\SQL Labs\User Projects\ directory. It should contain several .SQLPlan files. Select the most recent file and open it in Management Studio by right-clicking on the file name, choosing Open. Having query plans in XML allows third party vendors to develop software to interpret and display them. In addition, an XML query plan can be sent to a support provider, who can then view it in a graphical format and see the same output that appears in SQL Server Management Studio.
Page 10 of 12
Page 11 of 12
3. 4.
5. 6. 7. 8. 9.
10.
Page 12 of 12