Table and Index Sizes, Top Objects

Commands for finding which object grew when space suddenly increases, and which tables are worth cleaning up. In all three databases, object size is based on allocated space. Deleting rows usually does not shrink allocated space right away, so look separately at the gap between the actual data volume and the allocated size (wasted space).

Oracle

Required privileges: query access to DBA_SEGMENTS, DBA_INDEXES, DBA_LOBS (SELECT_CATALOG_ROLE).

Largest segments

SELECT owner, segment_name, partition_name, segment_type, tablespace_name,
       ROUND(bytes / 1024 / 1024) AS size_mb
FROM dba_segments
ORDER BY bytes DESC
FETCH FIRST 20 ROWS ONLY;   -- 12c+
  • Segments exist separately for each table, index, LOB, and partition. LOB segments appear as SYS_LOB... and LOB indexes as SYS_IL....
  • A table that never had a row inserted has no segment because of deferred segment creation (11.2+), so it does not appear in the list.

Total per table: data + indexes + LOB

WITH seg AS (
  SELECT owner, segment_name AS table_name, 'TABLE' AS kind, bytes
  FROM dba_segments
  WHERE segment_type IN ('TABLE', 'TABLE PARTITION', 'TABLE SUBPARTITION')
  UNION ALL
  SELECT i.table_owner, i.table_name, 'INDEX', s.bytes
  FROM dba_indexes i
  JOIN dba_segments s ON s.owner = i.owner AND s.segment_name = i.index_name
  WHERE i.index_type <> 'LOB'
  UNION ALL
  SELECT l.owner, l.table_name, 'LOB', s.bytes
  FROM dba_lobs l
  JOIN dba_segments s ON s.owner = l.owner AND s.segment_name IN (l.segment_name, l.index_name)
)
SELECT owner, table_name,
       ROUND(SUM(CASE kind WHEN 'TABLE' THEN bytes ELSE 0 END) / 1048576) AS table_mb,
       ROUND(SUM(CASE kind WHEN 'INDEX' THEN bytes ELSE 0 END) / 1048576) AS index_mb,
       ROUND(SUM(CASE kind WHEN 'LOB'   THEN bytes ELSE 0 END) / 1048576) AS lob_mb,
       ROUND(SUM(bytes) / 1048576) AS total_mb
FROM seg
WHERE owner NOT IN ('SYS', 'SYSTEM')
GROUP BY owner, table_name
ORDER BY total_mb DESC
FETCH FIRST 20 ROWS ONLY;
  • If the indexes are larger than the table, check for duplicate or unused indexes (see 12-index-maintenance).

Size per LOB column

SELECT l.owner, l.table_name, l.column_name, l.securefile,
       ROUND(s.bytes / 1024 / 1024) AS lob_mb
FROM dba_lobs l
JOIN dba_segments s ON s.owner = l.owner AND s.segment_name = l.segment_name
WHERE l.owner = 'APP'
ORDER BY s.bytes DESC;
  • LOBs of 4000 bytes or less are stored inside the table row by default (ENABLE STORAGE IN ROW), so they do not show up in LOB segments.

Estimating wasted space

Compute the "actual data volume" from statistics and compare it with the allocated size. This is meaningful only when statistics are current.

SELECT t.owner, t.table_name, t.num_rows, t.avg_row_len,
       ROUND(t.blocks * ts.block_size / 1048576) AS alloc_mb,
       ROUND(t.num_rows * t.avg_row_len / 1048576) AS data_mb,
       t.last_analyzed
FROM dba_tables t
JOIN dba_tablespaces ts ON ts.tablespace_name = t.tablespace_name
WHERE t.owner = 'APP' AND t.blocks > 1000
ORDER BY t.blocks * ts.block_size - t.num_rows * t.avg_row_len DESC;
  • data_mb does not subtract block headers or PCTFREE, so even a healthy table has an alloc_mb about 20-30% larger. A difference of two times or more makes the table a cleanup candidate.
  • For more accurate figures, use the Segment Advisor (DBMS_SPACE).

Reclaiming space

ALTER TABLE app.orders MOVE ONLINE;            -- 12.2+, indexes are maintained too

-- or (ASSM tablespace)
ALTER TABLE app.orders ENABLE ROW MOVEMENT;
ALTER TABLE app.orders SHRINK SPACE CASCADE;

WARNING MOVE without ONLINE blocks DML during the move and makes indexes UNUSABLE (add UPDATE INDEXES or rebuild them later). MOVE ONLINE is an Enterprise Edition feature. Both methods use a lot of redo and temporary space. SHRINK SPACE changes ROWIDs, so do not use it if any application stores ROWIDs.

PostgreSQL

Required privileges: size functions are available to all users. pgstattuple requires superuser or pg_stat_scan_tables.

The PostgreSQL size functions each cover a different scope.

FunctionScope included
pg_relation_size(t)Table body (main fork) only
pg_table_size(t)Body + TOAST + FSM/VM (excludes indexes)
pg_indexes_size(t)All indexes of that table
pg_total_relation_size(t)All of the above combined

Largest tables

SELECT n.nspname AS schema, c.relname AS table_name,
       pg_size_pretty(pg_total_relation_size(c.oid)) AS total,
       pg_size_pretty(pg_relation_size(c.oid)) AS heap,
       pg_size_pretty(pg_table_size(c.oid) - pg_relation_size(c.oid)) AS toast_etc,
       pg_size_pretty(pg_indexes_size(c.oid)) AS indexes,
       c.reltuples::bigint AS est_rows
FROM pg_class c
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE c.relkind IN ('r', 'm')
  AND n.nspname NOT IN ('pg_catalog', 'information_schema')
ORDER BY pg_total_relation_size(c.oid) DESC
LIMIT 20;
  • reltuples is an estimate from the last ANALYZE/VACUUM. If the table has never been analyzed it is -1 (14+).
  • The parent of a partitioned table (relkind = 'p') has no storage, so it shows 0. Get the partition total as follows (12+).
SELECT pg_size_pretty(SUM(pg_total_relation_size(relid))) AS total
FROM pg_partition_tree('public.orders');

Largest indexes

SELECT schemaname, relname AS table_name, indexrelname AS index_name,
       pg_size_pretty(pg_relation_size(indexrelid)) AS size, idx_scan
FROM pg_stat_user_indexes
ORDER BY pg_relation_size(indexrelid) DESC
LIMIT 20;

TOAST size

Long text, jsonb, and bytea values (rows over roughly 2KB) are compressed or stored separately in a TOAST table.

SELECT c.relname, t.relname AS toast_table,
       pg_size_pretty(pg_relation_size(c.reltoastrelid)) AS toast_size
FROM pg_class c
JOIN pg_class t ON t.oid = c.reltoastrelid
WHERE c.relkind = 'r'
ORDER BY pg_relation_size(c.reltoastrelid) DESC
LIMIT 20;

Measuring bloat (pgstattuple)

Tables with heavy UPDATE/DELETE activity accumulate dead rows and free space. pgstattuple is a contrib extension and is usually included in the server package.

CREATE EXTENSION IF NOT EXISTS pgstattuple;

SELECT * FROM pgstattuple_approx('public.orders');   -- fast estimate using the visibility map
SELECT * FROM pgstattuple('public.orders');          -- reads the whole table
SELECT avg_leaf_density, leaf_fragmentation FROM pgstatindex('public.orders_pkey');
  • A high dead_tuple_percent means VACUUM is not keeping up. A high free_percent (approx_free_percent for approx) means VACUUM ran but the space remains inside the file.
  • The avg_leaf_density of a B-tree index is about 90 when freshly built. Consider a rebuild if it falls below 50.

WARNING pgstattuple reads the entire table, so it puts heavy I/O load on large tables. During business hours, use pgstattuple_approx first.

Reclaiming space

VACUUM (VERBOSE) public.orders;   -- marks free space as reusable (the file barely shrinks)
VACUUM FULL public.orders;        -- rewrites the table to shrink the file

WARNING VACUUM FULL holds an ACCESS EXCLUSIVE lock until it finishes, blocking even reads, and needs free disk equal to the table size. On a live system, use the pg_repack extension (installed separately), which rewrites the table while holding only short locks.

SQL Server

Required privileges: sys.dm_db_partition_stats requires VIEW DATABASE STATE.

Largest tables

SELECT TOP (20) s.name AS schema_name, t.name AS table_name,
       SUM(CASE WHEN ps.index_id IN (0, 1) THEN ps.row_count ELSE 0 END) AS row_count,
       SUM(ps.reserved_page_count) * 8 / 1024.0 AS reserved_mb,
       SUM(CASE WHEN ps.index_id IN (0, 1)
                THEN ps.in_row_data_page_count + ps.row_overflow_used_page_count + ps.lob_used_page_count
                ELSE 0 END) * 8 / 1024.0 AS data_mb,
       SUM(CASE WHEN ps.index_id > 1 THEN ps.used_page_count ELSE 0 END) * 8 / 1024.0 AS index_mb,
       SUM(ps.lob_used_page_count) * 8 / 1024.0 AS lob_mb,
       SUM(ps.reserved_page_count - ps.used_page_count) * 8 / 1024.0 AS unused_mb
FROM sys.dm_db_partition_stats ps
JOIN sys.tables  t ON t.object_id = ps.object_id
JOIN sys.schemas s ON s.schema_id = t.schema_id
GROUP BY s.name, t.name
ORDER BY reserved_mb DESC;
  • index_id 0 is a heap, 1 is the clustered index (= the table data), and 2 or higher are nonclustered indexes. Rows are counted only for 0/1.
  • Row and page counts are metadata values, so they return immediately. The table is not scanned.

Size per index

SELECT OBJECT_SCHEMA_NAME(i.object_id) + '.' + OBJECT_NAME(i.object_id) AS table_name,
       i.name AS index_name, i.type_desc,
       SUM(ps.used_page_count) * 8 / 1024.0 AS used_mb,
       SUM(ps.row_count) AS row_count
FROM sys.indexes i
JOIN sys.dm_db_partition_stats ps ON ps.object_id = i.object_id AND ps.index_id = i.index_id
WHERE OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
GROUP BY i.object_id, i.name, i.type_desc
ORDER BY used_mb DESC;

One table: sp_spaceused

EXEC sp_spaceused N'dbo.orders';
  • reserved, data, index_size, and unused are returned in KB. To look at many tables at once, the DMV query above is better.

Estimating compression savings

Large tables with space problems can be shrunk with page compression. Data compression is available in Standard Edition from 2016 SP1+.

EXEC sp_estimate_data_compression_savings
     @schema_name = N'dbo', @object_name = N'orders',
     @index_id = NULL, @partition_number = NULL, @data_compression = N'PAGE';
  • This procedure compresses a sample in tempdb and estimates the result. Actually applying it (ALTER TABLE ... REBUILD WITH (DATA_COMPRESSION = PAGE)) is a rebuild, so follow the cautions in 12-index-maintenance.

WARNING Compression reduces space and read I/O at the cost of more CPU. For write-heavy tables, ROW compression or no compression may be better.