Find Unused Indexes In Usage Stats
List never-scanned indexes from pg_stat_user_indexes where idx_scan is zero, sized with pg_relation_size, before dropping anything that only slows writes.
Code
-- unused indexes:idx_scan = 0 表示统计重置以来从未被扫描的索引
-- usage stats 重置于服务重启或 pg_stat_reset();观察期要覆盖业务全貌
-- 每个无用索引都在拖慢每一次写入
-- 删除前先确认大小与风险:唯一索引与主键不在候选之列,它们护的是数据正确性
SELECT
schemaname,
relname AS table_name,
indexrelname AS index_name,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
-- 线上回收索引走 DROP INDEX CONCURRENTLY,避免长时间锁表How the snippet works
What runs is SELECT, with pg_stat_user_indexes as the object involved.
What the statements actually assemble: a WHERE clause that keeps only the rows a statement is meant to touch; an ORDER BY that fixes the output order.
Applying it
Run the statement against the pg_stat_user_indexes table.
Statements that matter
SELECT
schemaname,
relname AS table_name,
indexrelname AS index_name,
idx_scan,
pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE idx_scan = 0
ORDER BY pg_relation_size(indexrelid) DESC;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.SQL FormatterReformat SQL by uppercasing reserved words and breaking lines before SELECT, FROM, WHERE, and other clauses.
FAQ
- What relations does the SQL touch?
- `pg_stat_user_indexes` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.