简体   繁体   中英

Getting table row count

The following query can be used to find the total row count for a specific table in a database

SELECT COUNT(*) AS [TotalRowCount] FROM table_name; 

It is also possible to get the row count for all tables by joining back to the table's partition based off the tables' HEAP (index_id = 0) or cluster clustered index (index_id = 1) using the following script:

SELECT [Tables].name AS [TableName],
SUM( [Partitions].[rows] ) AS [TotalRowCount] 
FROM sys.tables AS [Tables] 
JOIN sys.partitions AS [Partitions] 
   ON [Tables].[object_id] = [Partitions].[object_id] 
   AND [Partitions].index_id IN ( 0, 1 )
 --WHERE [Tables].name = N'table name' we uncomment for a specific table
GROUP BY [Tables].name; 

If someone can please explain this code, if we can get the count by simply using count() , why do we use the second code?

You can use the second code because you can parameterize the table name, so you can get the counts for multiple tables at the same time.

In the first code, you would have to use dynamic SQL.

In addition, the second code is much faster, because it doesn't actually read any data from the table. I do think there are some circumstances where the results may not be exactly the same due to locking on the table. That is usually not important because it only affects a handful of rows.

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