Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Counting rows for all tables at once

I'm using SQL Server 2005 and would like to know how I can get a list of all tables with the number of records in each.

I know I can get a list of tables using the sys.tables view, but I'm unable to find the count.

Thank you

like image 946
Allain Lalonde Avatar asked Jan 09 '09 15:01

Allain Lalonde


People also ask

How can I count total rows in SQL?

SQL COUNT(), AVG() and SUM() FunctionsThe COUNT() function returns the number of rows that matches a specified criterion.

How do I count rows in a GROUP BY?

To count the number of rows, use the id column which stores unique values (in our example we use COUNT(id) ). Next, use the GROUP BY clause to group records according to columns (the GROUP BY category above). After using GROUP BY to filter records with aggregate functions like COUNT, use the HAVING clause.

How do I get all rows to count all tables?

To get the count of all the records in MySQL tables, we can use TABLE_ROWS with aggregate function SUM. The syntax is as follows. mysql> SELECT SUM(TABLE_ROWS) ->FROM INFORMATION_SCHEMA.


2 Answers

From here: http://web.archive.org/web/20080701045806/http://sqlserver2000.databases.aspfaq.com:80/how-do-i-get-a-list-of-sql-server-tables-and-their-row-counts.html

SELECT 
    [TableName] = so.name, 
    [RowCount] = MAX(si.rows) 
FROM 
    sysobjects so, 
    sysindexes si 
WHERE 
    so.xtype = 'U' 
    AND 
    si.id = OBJECT_ID(so.name) 
GROUP BY 
    so.name 
ORDER BY 
    2 DESC
like image 79
brian Avatar answered Sep 20 '22 18:09

brian


For what it's worth, the sysindexes system table is deprecated in SQL 2008. The above still works, but here's query that works going forward with SQL 2008 system views.

select
schema_name(obj.schema_id) + '.' + obj.name,
row_count
from (
    select
        object_id,
        row_count = sum(row_count)
    from sys.dm_db_partition_stats
    where index_id < 2  -- heap or clustered index
    group by object_id
) Q
join sys.tables obj on obj.object_id = Q.object_id
like image 35
Tom Wilson Avatar answered Sep 20 '22 18:09

Tom Wilson