Index Review and Rebuild

Indexes speed up reads, but they must be updated on every INSERT/UPDATE/DELETE and they use space. So check two things periodically. Unused indexes are candidates to drop, and fragmented or bloated indexes are candidates to rebuild. In all three databases, usage statistics can be reset by a restart and similar events, so judge over a period long enough to include rarely run jobs such as month-end batches. Never drop indexes that back a PK, UNIQUE constraint, or foreign key, even if queries do not use them.

Oracle

Required privileges: query access to DBA_* views (SELECT_CATALOG_ROLE); rebuilding requires being the index owner or having ALTER ANY INDEX.

Unused indexes: DBA_INDEX_USAGE (12.2+)

From 12.2, index usage is recorded automatically. Collection is sampled by default and is reflected in DBA_INDEX_USAGE every 15 minutes.

SELECT i.owner, i.table_name, i.index_name, i.uniqueness,
       u.total_access_count, u.total_rows_returned, u.last_used
FROM dba_indexes i
LEFT JOIN dba_index_usage u ON u.owner = i.owner AND u.name = i.index_name
WHERE i.owner = 'APP'
  AND i.uniqueness = 'NONUNIQUE'
  AND (u.last_used IS NULL OR u.last_used < SYSDATE - 35)
ORDER BY i.table_name, i.index_name;
  • An index that has never been used has no row in DBA_INDEX_USAGE (NULL from the LEFT JOIN).
  • Collection is sampled, so very rarely used indexes can be missed. Do not drop immediately; make the index invisible first, as shown below.

Unused indexes: MONITORING USAGE (legacy method)

ALTER INDEX app.orders_status_ix MONITORING USAGE;
-- after a sufficient period
SELECT owner, index_name, table_name, monitoring, used, start_monitoring
FROM dba_object_usage;           -- 12.1+; before that, connect as the owner and use V$OBJECT_USAGE
ALTER INDEX app.orders_status_ix NOMONITORING USAGE;
  • used = 'YES' only means "used at least once". The number of uses is not available.

Hide before dropping

ALTER INDEX app.orders_status_ix INVISIBLE;   -- the optimizer ignores it; DML maintenance continues
-- if a problem occurs, revert immediately
ALTER INDEX app.orders_status_ix VISIBLE;
-- once you are certain
DROP INDEX app.orders_status_ix;

WARNING INVISIBLE takes effect immediately in the plans of all sessions. If any query was fast only because of that index, it slows down right away, so watch the top SQL after the change. A foreign key column index keeps its role of narrowing lock scope for parent table DML even when invisible. DROP removes that role too.

Health check: UNUSABLE indexes

SELECT owner, index_name, table_name, status FROM dba_indexes WHERE status = 'UNUSABLE';
SELECT index_owner, index_name, partition_name, status FROM dba_ind_partitions WHERE status = 'UNUSABLE';
  • They appear after a partition DROP/TRUNCATE or MOVE. A plan that uses an UNUSABLE index either fails (UNIQUE) or skips that index.

Structure check: ratio of deleted leaf rows

Most Oracle B-tree indexes never need a rebuild. Check only when space does not come back after a bulk delete.

ANALYZE INDEX app.orders_cust_ix VALIDATE STRUCTURE;
SELECT name, height, lf_rows, del_lf_rows,
       ROUND(del_lf_rows / NULLIF(lf_rows, 0) * 100, 1) AS del_pct, pct_used
FROM index_stats;   -- shows only the one index last analyzed in this session

WARNING VALIDATE STRUCTURE blocks DML on the table while it analyzes. VALIDATE STRUCTURE ONLINE does not block, but it does not populate INDEX_STATS. Do not use it on a live system.

Rebuild: REBUILD, COALESCE, SHRINK

ALTER INDEX app.orders_cust_ix REBUILD ONLINE;                       -- build anew
ALTER INDEX app.orders_cust_ix REBUILD PARTITION p2024 ONLINE;       -- one partition
ALTER INDEX app.orders_cust_ix COALESCE;                             -- merge adjacent leaf blocks; space stays in the segment
ALTER INDEX app.orders_cust_ix SHRINK SPACE;                         -- merge, then release space
  • REBUILD ONLINE is an Enterprise Edition feature. In Standard Edition, running it without ONLINE blocks table DML for the duration of the rebuild.
  • COALESCE and SHRINK SPACE run online and need almost no extra space.

WARNING REBUILD needs temporary space plus new segment space equal to the index size, and generates a lot of redo (more Data Guard transfer volume). Even with ONLINE it takes brief locks at the start and end, so it waits behind long transactions.

PostgreSQL

Required privileges: statistics views are open to all users; rebuilding requires being the table owner (in 17+, the MAINTAIN privilege or the pg_maintain role also works).

Unused indexes

SELECT s.schemaname, s.relname AS table_name, s.indexrelname AS index_name,
       s.idx_scan, pg_size_pretty(pg_relation_size(s.indexrelid)) AS size
FROM pg_stat_user_indexes s
JOIN pg_index i ON i.indexrelid = s.indexrelid
WHERE s.idx_scan = 0
  AND NOT i.indisunique
  AND NOT EXISTS (SELECT 1 FROM pg_constraint c WHERE c.conindid = s.indexrelid)
ORDER BY pg_relation_size(s.indexrelid) DESC;
  • idx_scan accumulates since pg_stat_database.stats_reset. In 16+, last_idx_scan also shows the last time of use.
  • Queries run on a standby are counted only in the standby's statistics. If you have read replicas, run the same query there too.
  • In 15+ statistics survive a clean shutdown, but they are reset after a crash or immediate shutdown.

INVALID indexes left by a failed concurrent build

SELECT n.nspname, c.relname AS index_name, t.relname AS table_name
FROM pg_index i
JOIN pg_class c ON c.oid = i.indexrelid
JOIN pg_class t ON t.oid = i.indrelid
JOIN pg_namespace n ON n.oid = c.relnamespace
WHERE NOT i.indisvalid;
  • They remain when CREATE INDEX CONCURRENTLY or REINDEX CONCURRENTLY fails midway. Queries do not use them, but they still incur DML maintenance cost. Leftovers from REINDEX ... CONCURRENTLY have names ending in _ccnew. Drop them with DROP INDEX CONCURRENTLY and create them again.

Finding bloated indexes

CREATE EXTENSION IF NOT EXISTS pgstattuple;
SELECT avg_leaf_density, leaf_fragmentation, pg_size_pretty(index_size) AS size
FROM pgstatindex('public.orders_customer_idx');
  • A freshly built B-tree has an avg_leaf_density of about 90. If it is much lower, a rebuild will shrink the index. This reads the whole index, so check large indexes during quiet hours.

Rebuild: REINDEX CONCURRENTLY (12+)

REINDEX INDEX CONCURRENTLY public.orders_customer_idx;
REINDEX TABLE CONCURRENTLY public.orders;      -- all indexes of that table

-- progress (12+)
SELECT pid, relid::regclass, index_relid::regclass, phase, blocks_done, blocks_total
FROM pg_stat_progress_create_index;
  • CONCURRENTLY cannot run inside a transaction block. It reads the table twice, so it takes longer than a regular REINDEX.
  • In 11 and earlier, build a new index with CREATE INDEX CONCURRENTLY, DROP INDEX CONCURRENTLY the old one, then rename.

WARNING REINDEX without CONCURRENTLY blocks writes to the table and also blocks reads that want to use that index. On a live system, always add CONCURRENTLY. During the rebuild, extra disk and WAL equal to the index size are needed.

Dropping an index

DROP INDEX CONCURRENTLY public.orders_status_idx;

WARNING A dropped index can only be recreated. Before dropping, save its definition with pg_get_indexdef('public.orders_status_idx'::regclass).

SQL Server

Required privileges: usage statistics and fragmentation DMVs require VIEW SERVER STATE (VIEW SERVER PERFORMANCE STATE in 2022+); rebuilding requires ALTER on the table.

Unused indexes

SELECT OBJECT_SCHEMA_NAME(i.object_id) + '.' + OBJECT_NAME(i.object_id) AS table_name,
       i.name AS index_name, i.type_desc,
       ISNULL(u.user_seeks, 0) + ISNULL(u.user_scans, 0) + ISNULL(u.user_lookups, 0) AS reads,
       ISNULL(u.user_updates, 0) AS writes,
       u.last_user_seek, u.last_user_scan
FROM sys.indexes i
JOIN sys.objects o ON o.object_id = i.object_id AND o.type = 'U' AND o.is_ms_shipped = 0
LEFT JOIN sys.dm_db_index_usage_stats u
       ON u.database_id = DB_ID() AND u.object_id = i.object_id AND u.index_id = i.index_id
WHERE i.index_id > 1 AND i.is_unique = 0
ORDER BY reads, writes DESC;

SELECT sqlserver_start_time FROM sys.dm_os_sys_info;   -- when statistics started accumulating
  • Indexes with reads = 0 and a large writes are cleanup candidates.
  • These statistics are reset on instance restart and when the database goes offline or is detached.

Disable before dropping

ALTER INDEX ix_orders_status ON dbo.orders DISABLE;
-- to revert: it must be rebuilt to turn it back on
ALTER INDEX ix_orders_status ON dbo.orders REBUILD;

WARNING Disable only nonclustered indexes. Disabling a clustered index makes the whole table unreadable and unwritable. Disabling discards the index data, so re-enabling costs the same as a rebuild.

Fragmentation and page density

SELECT OBJECT_SCHEMA_NAME(ps.object_id) + '.' + OBJECT_NAME(ps.object_id) AS table_name,
       i.name AS index_name, ps.partition_number, ps.index_type_desc,
       ps.page_count, ROUND(ps.avg_fragmentation_in_percent, 1) AS frag_pct,
       ROUND(ps.avg_page_space_used_in_percent, 1) AS page_density_pct
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED') ps
JOIN sys.indexes i ON i.object_id = ps.object_id AND i.index_id = ps.index_id
WHERE ps.page_count > 1000 AND ps.index_id > 0
ORDER BY ps.avg_fragmentation_in_percent DESC;
  • 'LIMITED' mode is fastest, but avg_page_space_used_in_percent is NULL. 'SAMPLED' reads a sample and 'DETAILED' reads every page.
  • A common rule of thumb is REORGANIZE for 5-30% fragmentation and REBUILD above 30%. On SSDs and with large memory, page density (lots of free space means more pages to read) matters more than fragmentation. Ignore indexes under 1000 pages.

REORGANIZE and REBUILD

-- always online, all editions; if stopped midway, the work done so far is kept
ALTER INDEX ix_orders_customer ON dbo.orders REORGANIZE;

-- online rebuild: Enterprise Edition (including Developer)
ALTER INDEX ix_orders_customer ON dbo.orders
REBUILD WITH (ONLINE = ON, MAXDOP = 4, SORT_IN_TEMPDB = ON);

-- resumable rebuild (2017+, requires ONLINE)
ALTER INDEX ix_orders_customer ON dbo.orders REBUILD WITH (ONLINE = ON, RESUMABLE = ON, MAX_DURATION = 60 MINUTES);
ALTER INDEX ix_orders_customer ON dbo.orders PAUSE;
ALTER INDEX ix_orders_customer ON dbo.orders RESUME;

-- resumable operations in progress
SELECT name, state_desc, percent_complete, last_pause_time FROM sys.index_resumable_operations;
  • REBUILD updates statistics with FULLSCAN. REORGANIZE does not update statistics, so run UPDATE STATISTICS separately if needed.
  • Specifying ONLINE = ON in Standard Edition raises an error.

WARNING REBUILD without ONLINE locks the table until it finishes (for a clustered index, all reads and writes on the table are blocked). Even with ONLINE, brief schema locks are needed at the start and end, so it waits behind long transactions and other queries then queue up behind it. Avoid this with WAIT_AT_LOW_PRIORITY (MAX_DURATION = 5 MINUTES, ABORT_AFTER_WAIT = SELF). Rebuilds generate a lot of log, so in availability group or log shipping environments, watch log growth and replication lag as well.