Query to Display Tables with Row Counts
February 25th, 2009 by Andrew Chen
A query to display all user tables in a database and sort them by decending order according to row counts is very useful when it comes to research and
For SQL server 2000:
SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
FROM
sysobjects so,
sysindexes si
WHERE
so.xtype = ‘U’
AND
si.id = OBJECT_ID(user_name(uid)+’.'+so.name)
GROUP BY
so.name
ORDER BY
2 DESC
For SQL Server 2005
–SQL 2005
SELECT
[TableName] = so.name,
[RowCount] = MAX(si.rows)
FROM
sys.tables so,
sys.sysindexes si
WHERE
so.type = ‘U’
AND
si.id = OBJECT_ID(schema_name(schema_id)+’.'+so.name)
GROUP BY
so.name
ORDER BY
2 DESC
SELECT OBJECT_NAME(st.OBJECT_ID) TableName, st.row_count
FROM sys.dm_db_partition_stats st
join sys.objects tb on st.object_id=tb.object_id
and objectproperty(tb.object_id, ‘isUserTable’)=1
WHERE st.index_id < 2
and st.row_count>0
ORDER BY st.row_count DESC


No comments yet.