Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Table Row Counts - SQL Server

RSS
Modified on Mon, Feb 24, 2014, 2:26 PM by Administrator Categorized as (Favorites), SQL Server
The following SQL view will return a record for every table in the database, indicating its name and row count. Depending on the number of rows in the tables this method can be much faster than the select count(1) from TableName method, because it is a simple lookup in a set of system tables.

SQL Server 2005

/*==================================================================================================
    OBJECT: TableRowCounts view
    SOURCE: http://www.jasinskionline.com/TechnicalWiki/TableRowCounts.ashx
==================================================================================================*/
create view dbo.TableRowCounts
as
SELECT 
     SchemaName = s.name
    ,TableName  = o.name
    ,RowQty     = sum(p.rows)  
 
FROM
    sys.objects o 

    inner join sys.schemas s
        on o.schema_id = s.schema_id

    inner join sys.partitions p 
        on p.object_id = o.object_id
        and o.type = 'U'

    LEFT JOIN  sys.allocation_units a 
        ON p.partition_id = a.container_id 

WHERE 1=1
    -- 0 = heap table, 1 = table with clustered index
    and p.index_id in (0, 1) 

    and a.type = 1 -- row-data only , not LOB
    and p.rows is not null

group by
    o.name, s.name

See Also

Database Size

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.