join the MSSQLTips community

Today's Site Sponsor


 

SQL Compare quickly and easily compares and synchronizes SQL Server database schemas
 



SQL Server performance monitoring: Idera SQL diagnostic manager

Analyzing the SQL Server Plan Cache

Written By: Atif Shehzad -- 1/8/2009 -- read/post comments -- print -- Bookmark and Share

Rating: (not rated yet) Rate

Problem
The cache management mechanism plays an important role in performance of any system. Like any reliable DBMS, SQL Server enjoys a sophisticated cache management system for optimized performance without the need for any user intervention. There are ways to add a plan or data to the SQL Server cache or to remove a plan or data from SQL Server cache, but these techniques are only recommended for testing or troubleshooting purposes. Keeping in mind the importance of the cache mechanism, how could one get the plans and their usage statistics in SQL Server?

Solution
In releases prior to SQL Server 7.0, the plan cache was a separately configurable cache area in total memory used by SQL Server. Only stored procedures were cached in that part of cache. For this reason it was named the procedural cache. In SQL Server 7.0 and forwards the plan cache is not a separate area of memory in SQL Server. Now SQL Server uses a very dynamic integrated memory management and cache management mechanism.

The following script may be used on SQL Server 2000 and forward. It will provide contents of the SQL Server plan cache along with usage frequency.

Script # 1: Get SQL Server plan cache contents and their usage for SQL Server 2000 and onwards
USE Master
GO SELECT UseCounts, RefCounts,CacheObjtype, ObjType, DB_NAME(dbid) as DatabaseName, SQL FROM syscacheobjects ORDER BY dbid,usecounts DESC,objtype GO

Following is a partial result set from script #1 for SQL Server 2000.

For SQL Server 2005 and forward, DMVs have been introduced to get this information.  So to get the contents of the plan cache along with usage statistics, you may use the following DMV script.

Script # 2: Get SQL Server plan cache contents and their usage for SQL Server 2005 and onwards
USE master
GO SELECT UseCounts,RefCounts, Cacheobjtype, Objtype, ISNULL(DB_NAME(dbid),'ResourceDB') AS DatabaseName, TEXT AS SQL FROM sys.dm_exec_cached_plans CROSS APPLY sys.dm_exec_sql_text(plan_handle) ORDER BY dbid,usecounts DESC; GO

Following is a partial result set from script #2  for SQL Server 2005.

The overall fields used in the above scripts along with their description are as follows:

Column Definition
UseCounts is usage count of this cached object since it was cached
RefCounts is the count of how many times other cached objects have referenced this object
CacheObjType is the type of object in the plan cache.

SQL Server 2000 may have following types of cache objects

  • Compiled Plan
  • Executable Plan
  • Parse Tree
  • Cursor Parse Tree
  • Extended Stored Procedure

SQL Server 2005 and SQL Server 2008 may have following types of cache objects

  • Compiled Plan
  • Parse Tree
  • Extended Proc
  • CLR Compiled Functions
  • CLR Compiled Procedures
ObjType is the type of object with respect to its database.

SQL Server may have the following types of database objects in the plan cache

  • Stored Procedure
  • Prepared statement
  • Ad hoc query
  • ReplProc (replication procedure)
  • Trigger
  • View
  • Default
  • User table
  • System table
  • Check
  • Rule

Note: Prior to SQL Server 2005 ad hoc query was rarely cached. Now from SQL Sever 2005 and forward the ad hoc queries will be cached although the ad hoc query is cached it requires an exact textual match to be used. Even the provided parameters of the query should be the same for reuse.

DatabaseName is the name of the database to which the cached object belongs.  For some batches this column may be NULL.
SQL is the SQL code that is stored in the plan cache.

By using the above scripts you can gain insight into the objects along with their usage frequency in SQL Server. Remember for SQL Server 2000 you need to use the system table syscacheobjects and for SQL Server 2005 and onwards the DMV sys.dm_exec_cached_plans is used primarily.

While testing or troubleshooting you may need to clear the plan cache. You can use the following two commands for this purpose.

Script # 3: Clear whole SQL Server plan cache
DBCC FREEPROCCACHE 
GO
Script #4: Clear SQL Server plan cache for a specific database
DBCC FLUSHPROCINDB (<dbid>)
GO
/*
You can get DBID through following command
Select dbid from sysdatabases where name = <'DBName'>
*/

Beside the above commands, the following operations will also flush the entire plan cache and new batches will require new plans.

  • Detaching any database
  • Upgrading any database to compatibility level 90 or above on SQL Server 2005 or above
  • Running ALTER DATABASE ... MODIFY FILEGROUP command for any database
  • Running ALTER DATABASE ... COLLATE command for modifying collation of any database

Altering a database with any of the following commands will remove all plans cached for that specific database.

  • ALTER DATABASE ..... MODIFY NAME
  • ALTER DATABASE ..... SET ONLINE
  • ALTER DATABASE ..... SET OFFLINE
  • ALTER DATABASE ..... SET EMERGENCY

The following operations will also remove cached plans for a specific database.

  • Dropping a database
  • Database is auto closed

It is relevant to mention here that there is no way to remove just a single query plan from the cache for SQL 2005 and below, but for SQL 2008 this is now possible.  Take a look at this article.

Next Steps

  • Start digging deeper into your database activity to see what plans are cached and how often queries are being used.
  • Stay tuned for other tips about performance tuning.
  • Take a look at these other performance tuning related tips.
Readers Who Read This Tip Also Read Free Live Webcast Comment or Ask Questions About This Tip



Get Our Tips Newsletter

We keep 50,000+ SQL Server professionals informed.



Red Gate Software - SQL Data Generator

Test your database until it cries… “Red Gate’s SQL Data Generator has overnight become the principal tool we use for loading test data to run our performance and load tests.” Grant Fritchey, FM Global.

Download now!

More SQL Server Tools
SQL Refactor

SQL Prompt

SQL secure

SQL defrag manager

SQL Data Generator


Sponsor Information
Free SQL Server performance monitoring dashboard – Idera SQL check

Increase your SQL speed and accuracy with code completion from SQL Prompt.

SQL Server Consultants - What you don't know could be your biggest asset - Guaranteed Results

Prepare for your next SQL Server interview with CareerQandA.com

Free whitepaper - Top 10 Things You Should Know About Optimizing SQL Server Performance



Copyright (c) 2006-2010 Edgewood Solutions, LLC All rights reserved
privacy statement | disclaimer | copyright | advertise | write for mssqltips | feedback | about
Some names and products listed are the registered trademarks of their respective owners.


CareerQandA.com | MSSharePointTips.com | MSSQLTips.com