Brian's Blog

items I see across my tribes

SQL Server: Row Count for Large Tables

February 21
by briancarter 21. February 2010 08:56

When working on tables with a large number of records, one must be careful using a simple statements like SELECT COUNT(*) FROM[Table_Name]; especially when you are bulk inserting items into a table and want to get a count. 

The simple count statement takes forever to return row count on large tables. Its because it uses full table scan to count number of rows. A better approach to get the row count on any table is to query new Dynamic Management Views (DMV) in SQL Server 2005+ sys.dm_db_partition_stats. DMV contains row count and page counts for any table including all the partitions. Please note that if you did not create partitions for your table, your table still going to be created on single default partition; so you are using partitions.

The statement below will provide the total number of rows – very quickly:

SELECT
  Total_Rows= SUM(st.row_count)
FROM
  sys.dm_db_partition_stats st
WHERE
  object_name(object_id) = '!!YOUR TABLE!!'
  and (index_id <2)

Categories:

Comments

5/25/2010 7:19:20 AM #

Excellent trick.. I was looking for something like this. When I do a simple select count(*), it takes 6 minutes and now with this trick, it takes less than a second!
Thanks for sharing this trick.

Asif United States


 Questions or Feedback, my contact information is located on my About page.


The opinions, thoughts, and comments made in these blog posts are solely my own (unless otherwise stated). They do not reflect the opinions, thoughts or practices of my employer, my universities, my family, or anyone else. Also, I retain the right to change my mind about anything I publish here without having to go back and edit posts that occurred in the past. 

These are my opinions, or just as likely, someone else's opinions that I leveraged for my own.