简体   繁体   中英

Faster row count SQL Server 2008 sys.dm_db_partition_stats with Where clase

SELECT SUM(row_count)
FROM   sys.dm_db_partition_stats
WHERE  object_id = OBJECT_ID('TableName')

People say the above query is faster than select count (*) .

I'd like to know the equivalent of select count(*) from table where name = 'awt' using sys.dm_db_partition_stats.

Thanks.

From the documentation for sys.dm_db_partition_stats :

Returns page and row-count information for every partition in the current database.

This is aggregate information that SQL Server maintains to be able to manage the structures used to hold user data. There is no information in that dynamic management view about the distribution of values in the partition. Elsewhere, so it can optimise queries, statistics are kept, but again this is aggregate data (and not maintained for each data change).

If you want to count only rows that meet some specific criterion then you are going to have to count them. (Have you considered adding an index?)

This is definitely one of the faster methods available considering the following.

  1. Collecting the statistics will take significant amount of time on larger tables

  2. Statistics need to be updated if you want the exact count all the time.

  3. If your requirement is to know a count (an estimated and approximate number) this is the best.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM