Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 

A faster way to count rows in a table

By Cade Bryant, 2013/05/19

SQL Server includes the COUNT function for counting a table's rows - however, it can be slow.  Although querying the "rows" column from the sysindexes table is faster, it is not always accurate (e.g., if a bulk load process has recently taken place).  In addition, you would not be able to use this method in conjunction with a GROUP BY...HAVING construct, as you would if you were using the COUNT function.

Here is a better way: it involves adding an extra column to your tables and giving it a default value of 1.  You then use the SUM function on that column to obtain the row count (if you need to exclude rows that have a NULL value for any given column(s), you can add a WHERE clause specifying "WHERE  IS NOT NULL").

In my tests on a table with 9999 rows, a statement using "SELECT SUM(counter) FROM test" took only 7 ms to run (compared to 11 ms when "SELECT COUNT(*)" was used).  And since SUM is an aggregate function, you can use it with GROUP BY...HAVING, just as you would with COUNT.

Total article views: 358 | Views in the last 30 days: 2
 
Related Articles
FORUM

Adding a column header on count function

Adding a column header on count function

FORUM

Count Function

Count Function with condition

FORUM

COUNT and NULL

how to use the COUNT Function

FORUM

user defined functions & columns

user defined functions & columns

FORUM

Counting non-blank columns

How can I count the number of rows that have non-blank columns across a table?

Tags
miscellaneous    
t-sql    
 
Contribute

Join the most active online SQL Server Community

SQL knowledge, delivered daily, free:

Email address:  

You make SSC a better place

As a member of SQLServerCentral, you get free access to loads of fresh content: thousands of articles and SQL scripts, a library of free eBooks, a weekly database news roundup, a great Q & A platform… And it’s our huge, buzzing community of SQL Server Professionals that makes it such a success.

Join us!

Steve Jones
Editor, SQLServerCentral.com

Already a member? Jump in:

Email address:   Password:   Remember me: Forgotten your password?
Steve Jones