15.9.08

List out all tables and row count in sql server

How to list down all the tables and its row count in SQL Server:

SQL Server will hold all the tables and its row count in a special table named sysindexes.
Below is the query to fetch all the information,

select distinct convert(varchar(30),object_name(a.id)) [Table Name], a.rows from sysindexes a inner join sysobjects b on a.id = b.id

To list out the information for a particular database, you can use the below query.

select distinct convert(varchar(30),object_name(a.id)) [Table Name], a.rows
from sysindexes a inner join sysobjects b on a.id = b.id
inner join INFORMATION_SCHEMA.TABLES c on c.[TABLE_NAME]=convert(varchar(30),object_name(a.id))
where c.Table_catalog='Database Name'

Happy Learning!!!
Regards,
Venkatesan Prabu .J

8 comments:

  1. Very good work Venkatesan...

    I have to build a report for my client that does a row count for all tables in all databases, so instead of running this manually for each databases, is there a way to do this with one routine?

    Paul

    ReplyDelete
  2. Venkat,

    The query to display the record counts for all tables returns duplicate table names, one with 0 records and another with actual count.

    ReplyDelete
  3. Excellent Work. Works Perfect.
    Thanks buddy.

    ReplyDelete
  4. And idea on the duplication of tables (as mentioned by 'anonymous')?

    Rich

    ReplyDelete
  5. Just what I needed. Thank you!

    ReplyDelete
  6. Works perfect, thanks buddy.

    ReplyDelete
  7. The only stmt missing is that the query has to be run on the database where the row count information is being requested; running it from master will produce a different dataset than running it from AdventureWorks.

    The second query, requesting the catalog or database name does not work across DBs.

    ReplyDelete
  8. solution for the duplicate 0-records:

    add "where a.name like 'PK_%'" at the end of the query.

    this works if each table ha a self-generated primary key.

    ReplyDelete