Get row count of table – SQL Server

There are times when as a DBA or developer you want to get the count of a table. To get the current count you can simply do:
SELECT COUNT(*) FROM [table_name]

Which works fine, when tables are small or medium size, but for large table (10 millions rows or above) this can take a while to return. If the count is for getting a “close enough” number, then sys.partitions can be used for getting this count quickly. sys.partitions keeps track of indexes for each table and rows contain within each index. The row count may be little off, depending on when the query is executed (pending commits etc), but for a “good enough” number count using sys.partitions is a faster option.

SELECT OBJECT_NAME(object_id), rows FROM sys.partitions WHERE index_id = 1

OBJECT_NAME will return the table name and index_id = 1 will return single row for tables with multiple indexes.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>