Friday, November 12, 2010

Finding the size of Index in SQL Server 2005/2008

sp_spaceused gives the size of table and index but it gives the sum of size of all indexes on a table.What if you need to capture size of individual index on a table.Thats where the DMF sys.dm_db_index_physical_stats
comes handy.

This DMF will return lot of values but if the last parameter to the DMF is 'detailed' then you get two columns that can be used to find the size of each index.They  are avg_record_size_in_bytes   and record_count.
If these columns are multiplied the resultant is the size of  that index.

The query given below returns the name of Database,ObjectId,Objectname,IndexId,IndexDescription,Size of Index in MB,Last Updated Statistics Date and Avg Fragmentation.

select DatabaseName,ObjectId,ObjectName,IndexId,Index_Description,CONVERT(DECIMAL(16,1),(sum(avg_record_size_in_bytes * record_count)/ (1024.0 * 1024)))as [Size of Index(MB)]
,last_updated as [Statistic last Updated],Avg_Fragmentation_In_Percent
from ( SELECT Distinct DB_Name(Database_id) as'DatabaseName',Object_ID as ObjectId,Object_Name(Object_id) as ObjectName,Index_ID as IndexId,Index_Type_Desc as Index_Description,avg_record_size_in_bytes , record_count,STATS_DATE(object_id,index_id) as 'last_updated',Convert(Varchar,round(Avg_Fragmentation_In_Percent,3)) as 'Avg_Fragmentation_In_Percent'FROM sys.dm_db_index_physical_stats (db_id('PM_Db'), NULL, NULL, NULL, 'detailed')
Where Object_id is not null and Avg_Fragmentation_In_Percent <> 0) T
group by DatabaseName,ObjectId,ObjectName,IndexId,Index_Description,last_updated,Avg_Fragmentation_In_Percent

No comments:

Post a Comment