Monday, February 6, 2012

Getting a quicker SQL row count

Credit goes to Rick Caminiti at http://rickcaminiti.com/tips/alternative-efficient-tables-rowcount-sql/


SELECT COUNT(*) statements make a full table scans to return the total table’s row count, it can take a lot of time and a lot of “energy” for a large table.
There is another way to determine the total row count in a table by using the sysindexes system table. There is a column (ROWS) in it that contains the total row count for each table in your database.
You can use the syntax below to speed up the query by several times.  You can see this by setting statistics on, as shown below.


SET STATISTICS IO ON
GO
SELECT count(*) FROM tbTest
GO
SELECT rows FROM sysindexes WHERE id = OBJECT_ID('tbTest') AND indid < 2
GO
SET STATISTICS IO OFF
GO



I tried my own test, and here are my results:


(1 row(s) affected)
Table 'myTable'. Scan count 1, logical reads 116, physical reads 1, read-ahead reads 176, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

(1 row(s) affected)
Table 'sysidxstats'. Scan count 1, logical reads 5, physical reads 0, read-ahead reads 0, lob logical reads 0, lob physical reads 0, lob read-ahead reads 0.

No comments:

Post a Comment