// SQL snippet

Find the largest indexes in PostgreSQL

Before you tune an index, find out how big it is. This ranks every index on a user table by the space it takes on disk.

Main statement
PostgreSQL
Deckt außerdem ab
SQL Server

The task

A large index competes with table data for shared_buffers, makes every index scan touch more pages and adds to base backup size. Some of the biggest are accidental: a multi-column index on a wide text column, or an index that bloated after years of updates. Ranking by size tells you where REINDEX or a redesign would pay off.

The snippet

Written for PostgreSQL. Versions for SQL Server are under Variations.

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

So funktioniert es

pg_stat_user_indexes carries the index OID (indexrelid), so pg_relation_size returns each index's on-disk size, empty and half-empty pages included. Note the column names: this view uses relname and indexrelname, while the pg_indexes view uses tablename and indexname. The ORDER BY uses the byte count, not the pg_size_pretty text. idx_scan sits beside the size so a large index with few scans stands out.

Variations

Largest indexes in SQL Server

SQL Server
SELECT TOP 25
    OBJECT_SCHEMA_NAME(i.object_id) AS schema_name,
    OBJECT_NAME(i.object_id) AS table_name,
    i.name AS index_name,
    CAST(SUM(ps.used_page_count) * 8 / 1024.0 AS DECIMAL(12,1)) AS size_mb,
    ISNULL(us.user_seeks + us.user_scans + us.user_lookups, 0) AS total_reads
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
LEFT JOIN sys.dm_db_index_usage_stats us
  ON us.object_id = i.object_id AND us.index_id = i.index_id AND us.database_id = DB_ID()
WHERE i.index_id > 1
  AND OBJECTPROPERTY(i.object_id, 'IsUserTable') = 1
GROUP BY i.object_id, i.name, us.user_seeks, us.user_scans, us.user_lookups
ORDER BY size_mb DESC;

Check a single index for bloat with pgstatindex

CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT index_size, avg_leaf_density, leaf_fragmentation
FROM pgstatindex('public.orders_created_at_idx');

Questions that come up

An index is huge but has high idx_scan. Should I drop it?

No. A high idx_scan means queries depend on it. Check whether it is bloated instead: pgstatindex reports avg_leaf_density, which sits near 90 percent for a freshly built B-tree (the default fillfactor). If it is far below that, REINDEX INDEX CONCURRENTLY rebuilds it without blocking writes.

Why does my index have half-empty pages after a bulk load?

Inserting keys in random order (random UUIDs, shuffled ids) splits full leaf pages in half, and the halves fill back up slowly. Loading in key order, or creating the index after the load instead of before, gives densely packed leaf pages.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.