Click here to Skip to main content
Click here to Skip to main content

Number of different ways to get total number of rows from tables

By , 21 Jun 2010
Rate this:
Please Sign up or sign in to vote.

Problem


Sometimes there is a need to get record counts from every table in your database. One way of doing this is to do a SELECT count(*) on all of your tables, but this could create a lot of overhead especially for large databases and large tables. If you don't require an exact answer, it isn't necessary to use a SELECT count(*) query on the rows in a table to get the row count.
 

Possible Solutions

Following are the different ways to get the number of records in a table:
 

First

List all tables of the database with row counts.
SELECT
Table_Name = object_name(object_id),
Total_Rows = SUM(st.row_count)
FROM
sys.dm_db_partition_stats st
GROUP BY
object_name(object_id)
HAVING
SUM(st.row_count) <> 0
ORDER BY
object_name(object_id)

 

 

Second

List table with the number of rows in table.
SELECT sysobjects.[name], max(sysindexes.[rows]) AS TableRows
FROM sysindexes INNER JOIN sysobjects ON sysindexes.[id] = sysobjects.[id]
WHERE sysobjects.xtype = 'U' and sysobjects.[name]='App3_Employee'
GROUP BY sysobjects.[name]
ORDER BY max(rows) DESC
GO 
 

 

Third

List table with row count.
SELECT
Total_Rows= SUM(st.row_count)
FROM
sys.dm_db_partition_stats st
WHERE
object_name(object_id) = 'app3_employee' 
 

 

Fourth

List rows with the row count.
SELECT PKEY, FIRSTNAME, LASTNAME, ROW_NUMBER() OVER (ORDER BY PKEY) AS Position, 
COUNT(*) OVER () AS TotalRows
FROM app_employee
 

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Pranay Rana
Software Developer (Senior) GMind Solusion
India India

Microsoft C# MVP (12-13)

 
Hey, I am Pranay Rana, working as a ITA in MNC. Web development in Asp.Net with C# and MS sql server are the experience tools that I have had for the past 5.5 years now.
 
For me def. of programming is : Programming is something that you do once and that get used by multiple for many years
 

You can visit my blog

StackOverFlow - http://stackoverflow.com/users/314488/pranay
My CV :- http://careers.stackoverflow.com/pranayamr
 
Awards:


Follow on   Twitter   LinkedIn

Comments and Discussions

 
GeneralReason for my vote of 5 Nice Work.... PinmemberPravin Patil, Mumbai7-Oct-11 8:59 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 21 Jun 2010
Article Copyright 2010 by Pranay Rana
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid