Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save stevewithington/d4935afba10cfdd3f95d704c04b9952b to your computer and use it in GitHub Desktop.
Save stevewithington/d4935afba10cfdd3f95d704c04b9952b to your computer and use it in GitHub Desktop.
SQL: Get total and average row count per table and/or database
/* SQL: Get total and average row count per table and/or database */
USE SomeDB;
GO
CREATE TABLE #counts
(
table_name varchar(255),
row_count int
)
EXEC sp_MSForEachTable @command1='INSERT #counts (table_name, row_count) SELECT ''?'', COUNT(*) FROM ?'
-- Row count per table
SELECT table_name, row_count FROM #counts ORDER BY table_name, row_count DESC
-- Total DB row count
SELECT SUM(row_count) AS total_row_count FROM #counts
-- Average DB row count
SELECT AVG(row_count) AS average_row_count FROM #counts
DROP TABLE #counts
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment