Beyondrelational

Wednesday, June 9, 2010

How to obtain quick counts of rows in all tables?

The following SQL Server T-SQL queries will yield fast (not real time) row counts in each table in the database:

-- SQL quick table row counts - SQL Server 2005, SQL Server 2008
USE AdventureWorks2008;

SELECT   TableName = SCHEMA_NAME(schema_id)+'.'+o.name,
         Rows = max(i.rows)
FROM     sys.sysobjects o
         INNER JOIN sys.sysindexes i
           ON o.id = i.id
         INNER JOIN sys.objects oo
           ON o.id = oo.object_id
WHERE    xtype = 'u'
         AND OBJECTPROPERTY(o.id,N'IsUserTable') = 1
GROUP BY schema_id, o.name
ORDER BY Rows DESC
GO
/* Partial results

TableName                                 Rows
Sales.SalesOrderDetail                    121317
Production.TransactionHistory             113443
Production.TransactionHistoryArchive      89253
Production.WorkOrder                      72591
Production.WorkOrderRouting               67131
Sales.SalesOrderHeader                    31465
Sales.SalesOrderHeaderSalesReason         27647
Person.BusinessEntity                     20777
Person.EmailAddress                       19972
Person.Password                           19972
Person.Person                             19972
Person.PersonPhone                        19972
Sales.Customer                            19820
*/

No comments:

Post a Comment