Sunday, 16 July 2017

How to Get Row Count Of All The Tables In SQL Server Database

Sometimes we want to get the Row Count quickly for all the tables in our Database for analysis. There are multiple ways to do that. We can use TSQL Cursor to loop through all the tables and use count(*) to get the row count.

I am using Catalog views to get this information by using below query. This is a quick way to find the row count for all the tables in a database. The Cursor with Count(*) can be slow as it has to count rows for each of the tables.

USE DBName
GO
SELECT OBJECT_NAME(id) AS TableName,
       rowcnt          AS [RowCount]
FROM   sysindexes s
       INNER JOIN sys.tables t
               ON s.id = t.OBJECT_ID
WHERE  s.indid IN ( 0, 1, 255 )
       AND is_ms_shipped = 0 order by [RowCount] DESC