To retrieve the total number of records (rows) for each table in a SQL Server database, you can use the sys.tables
and sys.dm_db_partition_stats
views. Here's a query to accomplish this:
Query to Get Row Counts for All Tables
SELECT
t.name AS TableName,
SUM(p.rows) AS TotalRecords
FROM
sys.tables t
INNER JOIN
sys.partitions p ON t.object_id = p.object_id
WHERE
p.index_id IN (0, 1) -- 0 = Heap, 1 = Clustered index
GROUP BY
t.name
ORDER BY
TotalRecords DESC;
Explanation of Query:
sys.tables
: Contains information about all tables in the database.sys.partitions
: Provides information about partitions of tables and indexes. Therows
column contains the number of rows for each partition.index_id IN (0, 1)
: Ensures you count rows only for heap (no clustered index) or clustered index partitions.
Sample Output:
TableName | TotalRecords |
---|---|
Customers | 1200 |
Orders | 450 |
Products | 150 |
No comments:
Post a Comment