Random Musings of Jeremy Jameson

Counting Rows in All Database Tables in SQL Server

Here is yet another of the SQL scripts that I like to keep handy in my toolbox: Count Records in All Tables.sql

Sometimes when I get "dropped into" a consulting situation with a new customer, I need to quickly get acquainted with one or more of their SQL Server databases. One of the first things I usually like to know is: "What are the largest tables in the database in terms of the number of rows?"

While you could certainly craft some SQL to SELECT COUNT(*) from each user table, this is very inefficient. A much better way is to simply query the system tables as shown below:

SELECT
    sysobjects.Name
    , sysindexes.Rows
FROM
    sysobjects
    INNER JOIN sysindexes
    ON sysobjects.id = sysindexes.id
WHERE
    type = 'U'
    AND sysindexes.IndId < 2
ORDER BY
    sysobjects.Namecode
Published Friday, May 30, 2008 7:56 AM by Jeremy Jameson
Filed under:

Comments

 

Weekly Link Post 45 &laquo; Rhonda Tipton&#8217;s WebLog said:

June 8, 2008 5:20 PM
 

sidsan2k said:

Thanks for the query .. I was looking for this , got after extreme search from you. good

thanks once again

sanjeev

July 7, 2008 9:49 AM
Anonymous comments are disabled

© 2009 Microsoft Corporation. All rights reserved. Terms of Use  |  Trademarks  |  Privacy Statement
Microsoft
Page view tracker