Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 993
mr_dunski Avatar asked Oct 01 '09 18:10

mr_dunski


3 Answers

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
like image 132
Chris Ballance Avatar answered Sep 19 '22 14:09

Chris Ballance


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;
like image 25
Kenny Evitt Avatar answered Sep 19 '22 14:09

Kenny Evitt


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

like image 39
jerryhung Avatar answered Sep 22 '22 14:09

jerryhung