Displaying row count for all tables

In: SQL Server
Written by: Taylor Gerring


1 Oct 2008

Anyone who has worked with a database for even a short amount of time has undoubtedly checked the number of rows in a table with a statement akin to this:

SELECT COUNT(*) FROM dbo.TableName

It’s quick and easy, but is expensive in terms of logical reads. Also, things get complicated when you want to check the numbers of rows for all user tables in an entire database – you might think about resorting to cursors and dynamic SQL.

Fortunately, SQL Server 2005 shipped with a whole slew of Dynamic Management Views that make monitoring your database much simpler. With a quick query, we can view the rowcount for all tables in a database – and no table scan required.

select s.name [SchemaName], t.name [TableName], sum(st.row_count) [RowCount]
from sys.tables t
inner join sys.schemas s on t.schema_id = s.schema_id
inner join sys.indexes i on t.object_id = i.object_id
inner join sys.dm_db_partition_stats st on t.object_id = st.object_id and i.index_id = st.index_id
where i.index_id < 2
group by s.name, t.name
order by s.name, t.name

Turn that into a handy view and you’ll always know where you stand on rows per table.

Comment Form

@TaylorGerring


Unless specified otherwise, this website is licensed under a Creative Commons Attribution-ShareAlike 3.0 United States.
Stop SOPA
Unless specified otherwise, this website is licensed under a Creative Commons Attribution-ShareAlike 3.0 United States.