Quantcast
Viewing latest article 9
Browse Latest Browse All 10

Finding the Size of SQL Azure Database Tables

Recently I needed to know exactly how much storage a SQL Azure database was consuming. I was also interested in seeing the usage on a per-table basis, to see which tables were contributing most to the size.

I came up with the following query:

WITH 
[TableSize] AS 
(
   SELECT 
          sys.objects.name AS [TableName]
          ,SUM(reserved_page_count) * 8.0 / 1024 AS [SizeMB]
     FROM sys.dm_db_partition_stats, sys.objects
    WHERE sys.dm_db_partition_stats.object_id = sys.objects.object_id
      AND reserved_page_count > 0
      AND sys.objects.is_ms_shipped = 0
 GROUP BY sys.objects.name
),
[Total] AS
(
   SELECT SUM([SizeMB]) AS [TotalMB] FROM [TableSize]
)
SELECT [TableName]
       ,[SizeMB]
       ,([SizeMB] / (SELECT [TotalMB] FROM [Total])) * 100.0 AS [Percent]
       FROM [TableSize]
UNION ALL
  SELECT 'Total', (SELECT [TotalMB] FROM [Total]), 100.0

On a sidenote, CTEs (Common Table Expressions) are my new favorite tool when writing SQL statements. They allow one to “refactor” common segments of code into a named expression that can be re-used later on. Using CTEs makes for much more readable (and maintainable) SQL code. Just like in C# when I am considering copy/pasting a piece of code and decide to refactor it into a method instead, when considering copy/pasting segments of a SQL query I’ve found that refactoring those segments into a CTE is a good move.

Image may be NSFW.
Clik here to view.

Viewing latest article 9
Browse Latest Browse All 10

Trending Articles