mr_dunski
mr_dunski

Reputation: 451

SQL Server 2008 - find table with most rows

Is there a way in SQL Server 2008 to find the table with the most rows in the database?

Upvotes: 21

Views: 22113

Answers (3)

Kenny Evitt
Kenny Evitt

Reputation: 9791

Here's basically the same T-SQL that Chris Ballance provided, but using the new Object Catalog Views instead of the compatability views:

SELECT  SchemaName = schemas.[name],
        TableName = tables.[name],
        IndexName = indexes.[name],
        IndexType =
            CASE indexes.type
                WHEN 0 THEN 'Heap'
                WHEN 1 THEN 'Clustered'
            END,
        IndexPartitionCount = partition_info.PartitionCount,
        IndexTotalRows = partition_info.TotalRows
FROM    sys.tables
        JOIN sys.indexes
            ON  tables.object_id = indexes.object_id
                AND indexes.type IN ( 0, 1 )
        JOIN (  SELECT object_id, index_id, PartitionCount = COUNT(*), TotalRows = SUM(rows)
                FROM sys.partitions
                GROUP BY object_id, index_id
        ) partition_info
            ON  indexes.object_id = partition_info.object_id
                AND indexes.index_id = partition_info.index_id
        JOIN sys.schemas ON tables.schema_id = schemas.schema_id
ORDER BY SchemaName, TableName;

Upvotes: 12

jerryhung
jerryhung

Reputation: 1111

I just customize my SSMS 2008 to show the following additional columns for tables - Row Count - Data Space Used (KB)

for databases - Primary Data Location - Last Backup Date - Created Date ....

Works quicker for me most of the time without opening a query, I just click on the column header to go ASC or DESC

Upvotes: 1

Chris Ballance
Chris Ballance

Reputation: 34337

This will get you close:

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

Upvotes: 50

Related Questions