Search Blog

HOW TO count all rows in each table in a database in MS-SQL

Ever tried running "select count(*)" on a table with millions of rows? Or being asked to find that out for every table in a huge database? I had to count all rows in every table in a database at work today. With quite a few  tables having upwards of 50 million rows, and with 100s of tables in the db, getting all results using the plain vanilla "select count(*) would take all day.

Here is a super efficient SQL query that counts all rows in every table in a database, and FAST. Tested on MS SQL:-

SELECT  [TableName] = so.name,  [RowCount] = MAX(si.rows)  FROM sysobjects so, sysindexes si  WHERE
so.xtype = 'U'  AND si.id = OBJECT_ID(so.name)
GROUP BY  so.name
ORDER BY 2 DESC

No comments:

Post a Comment