Geeks With Blogs

Bill Osuch - Random geek notes

Among the many useful SQL snippets I regularly use is this little bit that will return row counts in a table:

SELECT as TableName, MAX(si.rows) as [RowCount]
FROM sysobjects so
JOIN sysindexes si ON = OBJECT_ID(
WHERE so.xtype = 'U'

This is handy to find tables that have grown wildly, zero-row tables that could (possibly) be dropped, or other clues into the data.

Right off the bat you may spot some "non-ideal" code - I'm using sysobjects rather than sys.objects. What's the difference? In SQL Server 2005 and later, sysobjects is no longer a table, but a "compatibility view", meant for backward compatibility only. SELECT * from each and you'll see the different data that each returns.

Microsoft advises that sysindexes could be removed in a future version of SQL Server, but this has never really been an issue for me since my company is still using SQL 2000. However, there are murmurs that we may actually migrate to 2008 some year, so I might as well go ahead and start using an updated version of this snippet on the servers that can handle it:

SELECT as TableName, ddps.row_count as [RowCount]
FROM sys.objects so
JOIN sys.indexes si ON si.OBJECT_ID = so.OBJECT_ID
JOIN sys.dm_db_partition_stats AS ddps ON si.OBJECT_ID = ddps.OBJECT_ID  AND si.index_id = ddps.index_id
WHERE si.index_id < 2  AND so.is_ms_shipped = 0
ORDER BY ddps.row_count DESC

Posted on Friday, January 28, 2011 10:33 AM SQL | Back to top

Comments on this post: Getting SQL table row counts via sysindexes vs. sys.indexes

# re: Getting SQL table row counts via sysindexes vs. sys.indexes
Requesting Gravatar...
Thanks, very helpful.

Have you gone to 2k8 yet?

Left by Victor Brink on Oct 06, 2014 6:27 AM

Your comment:
 (will show your gravatar)

Copyright © Bill Osuch | Powered by: