A quick way to count each table row in SQL Server _mssql

Source: Internet
Author: User
Tags rowcount

We all know the number of rows that can be counted with the aggregate function count (). The count () function must generate a dynamic SQL statement for each table and execute it to get results if you need to count the number of rows per table for the database (which the DBA might need). Previously seen on the internet has a very good solution, forget the source, write down and share.

This method utilizes the Rows field provided by the sysindexes system table. The Rows field records the number of rows at the data level of the index. The code for the workaround is as follows:

Copy Code code as follows:

Select Schema_name (t.schema_id) as [schema], t.name as tablename,i.rows as [rowcount]

From Sys.tables as T, sysindexes as I

where t.object_id = I.id and I.indid <=1


This method connects the Sys.tables view, finds the table name and schema_id, and then obtains the schema name of the table through the Schema_name function. Filter Criteria I.indid <=1 Select only the clustered index or heap, each table has at least one heap, or a clustered index, ensuring that a row is returned for each table. The following are some of the results returned by running this query in my AdventureWorks database:
Copy Code code as follows:

Schema TableName ROWCOUNT
——————– ——————– ———–
Sales Store 701
Production ProductPhoto 101
Production ProductProductPhoto 504
Sales storecontact 753
Person Address 19614
Production ProductReview 4
Production TransactionHistory 113443
Person AddressType 6

The advantages of this method are:

1. Run very fast.
2. Because the user table is not accessed, locks are not placed on the user table and the performance of the user table is not affected.
3. The query can be written as a subquery, a CTE, or a view, in conjunction with other queries.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.