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
SQL COUNT(), AVG() and SUM() FunctionsThe COUNT() function returns the number of rows that matches a specified criterion.
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.
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.
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With