sql server table size code example

Example 1: sql server table size

/******* Calcula tamany de totes les taules  *********/
SELECT 
    s.Name AS SchemaName,
    t.NAME AS TableName,
    p.rows AS RowCounts,
    CAST(ROUND(((SUM(a.total_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS TotalSpaceMB,
    CAST(ROUND(((SUM(a.used_pages) * 8) / 1024.00), 2) AS NUMERIC(36, 2)) AS UsedSpaceMB, 
    CAST(ROUND(((SUM(a.total_pages) - SUM(a.used_pages)) * 8) / 1024.00, 2) AS NUMERIC(36, 2)) AS UnusedSpaceMB,
    SUM(a.total_pages) * 8 AS TotalSpaceKB, 
    SUM(a.used_pages) * 8 AS UsedSpaceKB, 
    (SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM 
    sys.tables t
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
INNER JOIN 
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN 
    sys.schemas s ON t.schema_id = s.schema_id
WHERE 
    t.NAME NOT LIKE 'dt%' 
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255 
GROUP BY 
    t.Name, s.Name, p.Rows
ORDER BY 
      TotalSpaceMB desc
;


/************ Calcula tamany dels indexos ****************/
SELECT
      OBJECT_NAME(i.OBJECT_ID)     AS NomTaula
    , i.name                       AS NomIndex
    , SUM(a.used_pages) * 8 / 1024 AS TamanyMB
FROM
	  sys.indexes          AS i
	, sys.partitions       AS p
	, sys.allocation_units AS a
WHERE
	  i.OBJECT_ID     = p.OBJECT_ID
  AND i.index_id      = p.index_id
  AND p.partition_id  = a.container_id
  AND i.is_primary_key = 0 -- excloure PK's
GROUP BY
      i.OBJECT_ID
    , i.index_id
    , i.name
ORDER BY
	TamanyMB DESC,
    NomTaula,
    i.index_id
;

Example 2: check size of table sql

SELECT pg_size_pretty( pg_total_relation_size('tablename') );
(postgres)

Tags:

Sql Example