REINDEX CONCURRENTLY Index Rebuild
Rebuild a bloated index with REINDEX CONCURRENTLY: writes keep flowing while the _ccnew replacement builds, and a failed run leaves an INVALID index to drop.
Code
-- 索引因长期更新产生膨胀(bloat)后,REINDEX 原地重建(rebuild)出紧凑的物理结构;
-- 与 VACUUM FULL 相比,CONCURRENTLY 变体不阻塞并发读写:
-- 临时索引先以 _ccnew 后缀并行构建,再原子换入生效
REINDEX INDEX CONCURRENTLY products_name_trgm;
-- 一次重建一张表上的全部索引
REINDEX TABLE CONCURRENTLY products;
-- 重建中途失败会留下标记为 INVALID 的 _ccnew 索引,确认后手动清理
DROP INDEX CONCURRENTLY IF EXISTS products_name_trgm_ccnew;
-- 重建前后都用目录视图观察索引的物理大小,对比膨胀是否消除
SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE relname = 'products'
ORDER BY pg_relation_size(indexrelid) DESC;
-- 整库索引总量也可以用 pg_indexes_size 一眼看全
SELECT pg_size_pretty(pg_indexes_size('products'));What the code does
Several statements share this file — SELECT, with pg_stat_user_indexes among the objects involved.
In terms of clauses, the statements use: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.
Applying it
Run the statement against the pg_stat_user_indexes table.
Statements that matter
SELECT indexrelname, pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
WHERE relname = 'products'
ORDER BY pg_relation_size(indexrelid) DESC;
SELECT pg_size_pretty(pg_indexes_size('products'));
DROP INDEX CONCURRENTLY IF EXISTS products_name_trgm_ccnew;
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
- Which tables does the SQL touch?
- The references are `pg_stat_user_indexes`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.