Skip to content

Instantly share code, notes, and snippets.

@karenpayneoregon
Last active March 9, 2024 16:03
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 karenpayneoregon/bdef046fe7ad80a3d38d30529ebff3ad to your computer and use it in GitHub Desktop.
Save karenpayneoregon/bdef046fe7ad80a3d38d30529ebff3ad to your computer and use it in GitHub Desktop.
Get table names and row count for a SQL-Server database

First statement concatenates schema with table name while the second statement separates schema name and table name.

SELECT QUOTENAME(SCHEMA_NAME(item.schema_id)) + '.' + QUOTENAME(item.name) AS TableName,
SUM(parts.rows) AS [RowCount]
FROM sys.objects AS item
INNER JOIN sys.partitions AS parts
ON item.object_id = parts.object_id
WHERE item.type = 'U'
AND item.is_ms_shipped = 0x0
AND parts.index_id < 2
AND item.name <> 'sysdiagrams'
GROUP BY item.schema_id,
item.name
ORDER BY [TableName];
SELECT TableSchema = s.name,
Name = t.name,
[RowCount] = p.rows
FROM sys.tables t
INNER JOIN sys.schemas s
ON t.schema_id = s.schema_id
INNER JOIN sys.indexes i
ON t.object_id = i.object_id
INNER JOIN sys.partitions p
ON i.object_id = p.object_id
AND i.index_id = p.index_id
WHERE t.is_ms_shipped = 0 AND t.name <> 'sysdiagrams'
GROUP BY t.name,
s.name,
p.rows
ORDER BY s.name,
t.name;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment