How to get list of Tables and count of rows from table

Raj0125 511 Reputation points
2022-05-24T13:12:23.947+00:00

Hi,

How to get list of Tables and count of rows from table by writing single Query.

Expected O/P as below

205106-image.png

Azure SQL Database
{count} votes

Accepted answer
  1. Dan Guzman 9,236 Reputation points
    2022-05-24T13:43:54.417+00:00

    Below is an example using the object catalog views:

    SELECT s.name AS SchemaName, t.name AS TableName, SUM(p.rows) AS TableRowCount
    FROM sys.schemas AS s
    JOIN sys.tables AS t ON t.schema_id = s.schema_id
    JOIN sys.partitions AS p ON p.object_id = t.object_id
    GROUP BY s.name, t.name
    ORDER BY SchemaName, TableName;
    
    2 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Sreedhar V 0 Reputation points
    2024-06-26T21:45:50.16+00:00

    It will give wrong results in case you have PK and Unique key scenarios.

    Add Index_ID as 1, 0 clause; 1 = table with PK, 0 = table without PK. Corrected query:

    SELECT s.name AS SchemaName, t.name AS TableName, SUM(p.rows) AS TableRowCount

    FROM sys.schemas AS s

    JOIN sys.tables AS t ON t.schema_id = s.schema_id

    JOIN sys.partitions AS p ON p.object_id = t.object_id

    where p.index_id IN (1, 0)

    GROUP BY s.name, t.name

    ORDER BY 3 desc, SchemaName, TableName;

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.