You are on page 1of 9

Level 200

Prepared By : Dinesh Asanka

Monitoring SQL Server

[Type the document subtitle]


This document discuss the ways of monitoring SQL Server

ee

Dinesh Asanka MVP SQL Server 1 Page Level 200

Contents
Contents................................................................................................................ 2 Why Should You Monitor?......................................................................................3 Determine You Monitoring Goals...........................................................................3 Monitoring Tools.................................................................................................... 3 Performance Monitor .........................................................................................3 SQL Profiler......................................................................................................... 3 Activity Monitor in SQL Server Management Studio...........................................3 Performance Dash Board Report .......................................................................4 Dynamic Management Views..............................................................................4 T-SQL.................................................................................................................. 4 Performance Monitor.............................................................................................4 System Monitor...................................................................................................4 Counter Logs ..................................................................................................... 6 SQL Profiler ........................................................................................................... 6 Defining a New Trace..........................................................................................6 Selecting Events.................................................................................................7 Filtering Events...................................................................................................7 Using the Profiler Trace......................................................................................7 Integrating Performance Monitor Data...............................................................7 Dynamic Management Views ................................................................................8 Viewing the Locking Information........................................................................8 Viewing the Query Plans ....................................................................................8 Viewing Blocking Information.............................................................................8 View Queries Waiting for Memory Grants ..........................................................9 Connected User information...............................................................................9 Memory Usage....................................................................................................9 Summary............................................................................................................... 9

Monitoring SQL Server

Why Should You Monitor?


As responsible DBA, its your job to know the health of your SQL Server so that you can take proactive actions. This will help you spot potential problems not yet visible to the end-user. For example, if a certain query has slowed down from 50ms to 250ms, then the end-user will not be alarmed, but you should be. As a sys admin, you must identify performance goals and factors that affect the performance as Microsoft SQL Server.

Determine You Monitoring Goals


Following are the reasons for monitoring SQL Servers Identify performance changes over time Audit user activity (What, when and who) Establish a baseline for a performance Diagnose a specific performance problem

Monitoring Tools
There are several tools available with SQL Server 2005.

Performance Monitor
Performance monitor tracks resource use on Micro Windows Server and Windows operating systems. It can monitor a SQL Server instance, locally or remotely, on Windows OS. The performance is useful in trend analysis, and it can generate alerts, but its not useful for ad-hoc monitoring. The key difference between profile and Performance Monitor is the Performance Monitor monitors resources (CPU, Memory, disk I/O etc) related to server processes while Profiler monitors database engine events.

SQL Profiler
All database engine process events are tracked by this tool, which has a graphical user interface. You can also store the data into a SQL table or file for later analysis, and you can replay the captured event on SQL Server step by step to see exactly what happened. It can monitor a SQL Server instance locally or remotely. The profiler works well for trend analysis, and is the only tool that can replay captured events. You can also use the Profiler within a custom application, by using the profiler system stored procedure.

Activity Monitor in SQL Server Management Studio


Activity Monitor works best for ad-hoc monitoring, but not very well for trend analysis. This tool graphically displays the following information. Processes running on an instance of SQL Server Locks

Monitoring SQL Server

User Activity Blocked processes

Performance Dash Board Report


Performance dash board report is a free add-in you can install to SQL Server 2005 SP2 version. From this you can view various reports from the SQL Server Management Studio.

Dynamic Management Views


Dynamic Management Views (DMVs) and functions return server state information that can be used to monitor the health of a server instance, diagnose problems, and tune performance. This is one of the best tools added to SQL Server 2005 for ad-hoc monitoring.

T-SQL
Some system stored procedures provide useful information for SQL Server monitoring, such as sp_who, sp_who2, sp_lock and few others. These stored procedures are best for ad-hoc monitoring, not trend analysis.

Performance Monitor
Performance monitor or perfmon includes two snap-ins: System Monitor and performance logs and Alert. Some servers have it installed in the administrative tools menu. Its also found at Control Found->Administrative Tools->Performance and it can be launched from SQL Server Profilers tools->Performance Monitor menu command.

System Monitor
System monitor is familiar to anyone with experience with Windows server administration. System monitor graphically displays multiple counters, aggregate but detailed data from the server internals. The performance counters are added o system monitor one counter a time using the plus-symbol button in the toolbar. A performance counter can watch the local server or a remote server. The counters can be watched as a timed line graph, a histogram bar graph or a real-time report. Counters are organized by object and, sometimes, instance. For example, SQL Server:Database object exposes many counters including the Transactions/Sec counter. This counter can be watched for all instances or as selected instances.

Monitoring SQL Server

Although there are hundreds of possible System Monitor counters, following table describes the counters commonly used when investing a SQL Server Installation. Object SQL Server: Buffer Manager Counter Buffer-cache hit ratio Description The percentage of reads found already cached in memory. Usefulness SQL Server typically does an excellent job if pre-fetching the data into memory. If the ratio is below 95 percent, more memory will improve performance. If CPU are regularly more than 60 percent active, additional CPU cores or a faster server will increase the performance. A good indicator of user activity. Disk throughout is a key hardware performance factor. Splitting the database across multiple disk subsystem will improve performance.

Processer

Percentage of processor time Batch requests per second Average disk-queue length

The total percentage of processor activity SQL batch activity The number of both reads and writes waiting on the disk; an indication of disk throughout; affected by the number of disk spindles on multi-disk RAID configuration. The disk-queue length should be less than the number of disk spindles plus two. The number of queries for which SQL Server could not cache execution plan in memory; an indication of poorly written

SQL Server: SQL Statistics Physical Disk

SQL Server: SQL Statistics

Failed autoparams per second

Locating and correcting the queries will improve performance.

Monitoring SQL Server

SQL Server : Locks

Average wait time and lock timeouts per second

SQL Server : User Connection SQL Server : Database

User connections Transaction per second

queries. A cause of serious performance problems; lock waits, the length of the waits, and the number of lock timeouts are all good indicators of the level of locking contention within a database The number of current connections The number of current transaction within a database

If locking issues are detected the indexing structure and transaction code should be examined.

Indicates potential database activity A good indicator of database activity

A complete list of SQL Server counters and their current values can be queried from the sys.dm_os_performance_counters dynamic management view.

Counter Logs
Performance monitor also includes the performance logs and alerts plug-in, which includes Counter Logs, Trace Alerts, and Alerts. This section focuses on Counter Logs. Counter Logs use the same server counters as System Monitor, but instead of graphically displaying the data in real time, the Counter Logs write the counter data to a log file. This means the data can be analysed after the fact or even replayed within SQK Server Profiler. Counter Logs configurations are listed under the Counter Logs node in Performance Monitor.

SQL Profiler
SQL Server profiler displays copious data about many number of detailed SQL Server events. The activity can be written watched on the Profiler Trace Properties window or recorded to a file or table for further analysis. The filters can be set to record all the activity or they can focus on a specific problem. SQL Server Profiler can be launched from the Tools menu in Management Studio or from SQL Server 2005s Start Menu. Profiler opens to an empty window; you must define a new trace or open a saved trace file to begin to see any action.

Defining a New Trace


When a new trace is created, a connection is created to a SQL Server and the Trace Properties dialog box is presented. The trace Properties General tab sets up the trace and the Events Selection tab defines the events and the data column to be recorded, as well as the filter. If the trace is running, the properties may be viewed but not changed. A trace configuration can be saved as a template to make creating new traces easier. A profiler trace is primarily viewed interactively. However, the data can be written to a file or a SQL Server table. This is useful for further manual analysis, viewing alongside System Monitor counter data, or importing into Database Engine Tuning Advisor.
6

Monitoring SQL Server

When Profiler data is written to a file, SQL Server writes 128KB chunks of data at a time for performance. Conversely, writing data to a table is a series of row inserts that hinders SQL Servers performance.

Selecting Events
The events selection tab determines the actions within SQL Server that the Profiler records. Like Performance Monitor, the Profiler can trace numerous key SQL Server events. The default template of events is useful for getting started.

Filtering Events
Profiler can capture so much information that it can fill a drive with data. Fortunately, Profiler Trace Filter can narrow the scope of your search to the data of interest. The filter uses a combination of equal and like operators, depending on the data types captured. A frustrating aspect of the filter is that it only works against collected data and the data collected for some columns may not be what was expected. For example, if you want to filter the trace to only those batches that reference a specific table or column, filtering by object name wont work. Defining a like filter using wildcards on the text data column, however, this will cause the profile to select only those batches that include that table name. Another popular Profiler trace filter is to filter for events with duration greater than specified time to select all the longer-running batches.

Using the Profiler Trace


Once the trace is captured it can be browsed through the Profiler trace window, although a more useful option is to configure the trace so save results to a database table. The data can then be analysed and manipulated as in any other SQL table. Once the file is written, you can open the file using SQL Server Profiler and display the trace data. Trace data may be saved to a table for further aggregate analysis using File>Save As. The entire trace file can be submitted as a workload of the database Tuning Advisor so that it can tune multiple queries.

Integrating Performance Monitor Data


System Monitor and Profiler each present their own unique perspective on the state of the server. You can merge the two sets of information and walk through a scenario viewing both perspectives using SQL Server Profiler. To set up the dual-perspective experience, simultaneously capture server performance logs using both Performance Monitors Counter Logs and SQL Server Profiler. These steps are specific,

1. Configure System Monitor with the exact counters you want to view later. Be sure
to get the scale and everything just right. Set up the Counter Log to the exact same configuration. 2. Configure Profiler with the right set of trace events. They must include the start and end time data columns sp Profiler can integrate the two logs later. Script the trace to T-SQL code. Close profiler.

Monitoring SQL Server

3. Manually start the Counter Log. Execute the T-SQL trace code to start the serverside trace. 4. Exercise the server with the code and load you want to analyse. 5. When the test is complete, stop both the counter Log and the server side trace. 6. Open profiler and open the saved trace file. 7. Use the File->Import Performance Data menu command to import the Counter Log.

Dynamic Management Views


Dynamic management views expose the current internal state of SQL Server and supply a wealth of information, most of it very useful for monitoring. Specifically, sys.dm_exec_cached_plans, sys.dm_exec_query_stats, sys.dm_exec_query_plan and sys.dm_exec_request provide a variety of information about current sessions.

Viewing the Locking Information


SELECT l.resource_type, l.resource_associated_entity_id, OBJECT_NAME(p.Object_ID) AS ObjectName, l.request_status, l.request_mode, l.request_session_id, l.resource_description FROM sys.dm_tran_locks l LEFT OUTER JOIN sys.partitions p ON p.hobt_id = l.resource_associated_entity_id

Viewing the Query Plans


select , , , qs.execution_count qs.total_elapsed_time, qs.last_elapsed_time qs.min_elapsed_time, qs.max_elapsed_time substring(st.text, (qs.statement_start_offset/2)+1 , ((case qs.statement_end_offset when -1 then datalength(st.text) else qs.statement_end_offset end - qs.statement_start_offset)/2) + 1) as statement_text , qp.query_plan from sys.dm_exec_query_stats as qs cross apply sys.dm_exec_sql_text(qs.sql_handle) as st

cross apply sys.dm_exec_query_plan (qs.plan_handle) as qp

Viewing Blocking Information


SELECT l.resource_type, l.resource_associated_entity_id, OBJECT_NAME(p.Object_ID) AS ObjectName, l.request_status, l.request_mode, l.request_session_id, l.resource_description, Monitoring SQL Server

t.blocking_session_id sys.dm_tran_locks l INNER JOIN sys.dm_os_waiting_tasks t ON l.lock_owner_address = t.resource_address LEFT OUTER JOIN sys.partitions p ON p.hobt_id = l.resource_associated_entity_id FROM

View Queries Waiting for Memory Grants


The following query will indicate the queries that are waiting for memory grants. SQL Server will analyze a query and determine how much memory it needs based on the estimated plan. If memory is not available at that time, the query will be suspended until the memory required is available. SELECT se.session_id AS SPID, se.login_name, se.HOST_NAME, se.program_name, se.status, mg.requested_memory_kb, DATEDIFF(mi, mg.request_time, GETDATE()) AS WaitingTime sys.dm_exec_query_memory_grants mg INNER JOIN sys.dm_exec_sessions se ON se.session_id = mg.session_id mg.grant_time IS NULL

FROM WHERE

Connected User information


SELECT login_name, COUNT(session_id) AS session_count FROM sys.dm_exec_sessions GROUP BY login_name

Memory Usage
SELECT NAME, TYPE, SUM(single_pages_kb + multi_pages_kb) AS MemoryUsedinKB FROM sys.dm_os_memory_clerks GROUP BY NAME, TYPE ORDER BY 3 desc

Summary
Monitoring SQL Server regularly and gathering the performance data is the key to identify performance problems. You have learnt which counters in Performance Monitor you need to watch to discover performance problems. This session also covered how to create a SQL trace on the server side to reduce the impact of gathering events inside SQL Server. As you have notified Dynamic Management Views and functions are extremely helpful, gathering a lot of useful information about SQL Server and the operating system.

Monitoring SQL Server

You might also like