How To Retrieve Table List With Number of Rows In SQL

Introduction

This article shows a quick way to list tables with the number of rows in a database. The script is particularly useful for analyzing which tables are larger, and the results could be saved to a regular table to track growth against time.

Script

The script is divided into four steps. First, it creates a memory table named rcount (#rcount) that consists of two fields. A VARCHAR to store table names and an INT that will expose the rows count.

Using the sp_MSForEachTable Stored Procedure (a function in the master database, in Programmability > Stored Procedure > System Stored Procedure section), the instruction referenced by the variable @command1 will be executed. It will insert a record with the table name as the first field, whereas the second one will be the number of records in that specific table obtained through the COUNT(*) function.

CREATE TABLE #rcount(table_name varchar(255), row_count int)  
EXEC sp_MSForEachTable @command1='INSERT #rcount (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'  
SELECT REPLACE(REPLACE(table_name, '[dbo].[', ''), ']', ''), row_count FROM #rcount ORDER BY row_count DESC  
DROP TABLE #rcount  

At the end of this process, the next SELECT retrieves the records stored in our memory table, sorting them by descending values of the row_count field (in other words, the record with the highest number of rows being the first). Since the field that represents the table name will be exposed in the [dbo].[Table_Name] form, we apply, using the REPLACE function, a cleansing of the field to show the bare table name, without other indicators.

Finally, once the data is displayed, the temporary table is deleted.

References


Similar Articles