Indexes are essential for improving PostgreSQL query performance. They help the database locate records without scanning entire tables, support sorting and filtering, and enforce uniqueness constraints.

However, indexes do not remain perfectly efficient under every workload. Database corruption, accumulated empty index pages, failed concurrent index builds, and changes to index storage parameters can create situations where rebuilding an index becomes necessary.

PostgreSQL provides the REINDEX command to rebuild indexes using the data stored in their underlying tables.

The challenge for database administrators is knowing when to use it. Rebuilding indexes unnecessarily can consume significant CPU, memory, disk I/O, and storage space. On production databases, it can also block write operations if the wrong rebuilding method is selected.

This article explains when PostgreSQL indexes should be rebuilt, how to identify invalid indexes, how to investigate index bloat, and how to choose between standard and concurrent reindexing.

What Does REINDEX Do in PostgreSQL?

The REINDEX command recreates an existing index using the data stored in the associated table.

During the operation, PostgreSQL builds a replacement index and uses it to replace the existing index.

For example, consider a table containing customer information:

SQL
CREATE TABLE customers (
    customer_id BIGINT PRIMARY KEY,
    customer_name VARCHAR(150),
    email VARCHAR(200),
    created_at TIMESTAMP
);

Suppose the application frequently searches customers by email.

You create an index:

SQL
CREATE INDEX idx_customers_email
ON customers(email);

PostgreSQL can use this index to locate matching customer records more efficiently.

Over time, the index may become corrupted, contain unnecessary empty pages, or require rebuilding after certain storage parameter changes.

You can rebuild it using:

SQL
REINDEX INDEX idx_customers_email;

PostgreSQL recreates the index from the underlying table data.

The command does not remove application records or recreate the table itself. It rebuilds the index structure.

REINDEX command options

PostgreSQL supports several levels of reindexing.

Command

Purpose

REINDEX INDEX

Rebuilds one specific index

REINDEX TABLE

Rebuilds all indexes associated with a table

REINDEX SCHEMA

Rebuilds indexes in a schema

REINDEX DATABASE

Rebuilds indexes in the current database

REINDEX SYSTEM

Rebuilds system catalog indexes

For example:

SQL
REINDEX INDEX idx_customers_email;

To rebuild all indexes associated with a table:

SQL
REINDEX TABLE customers;

To rebuild indexes in a schema:

SQL
REINDEX SCHEMA public;

To rebuild indexes across the current database:

SQL
REINDEX DATABASE application_db;

Use the narrowest appropriate operation. Rebuilding one problematic index is generally preferable to rebuilding every index in a database without evidence that they need it.

When Should You Rebuild PostgreSQL Indexes?

PostgreSQL documents several situations where REINDEX is appropriate.

The most important are index corruption, index bloat, changes to index storage parameters, and failed concurrent index creation or rebuilding.

Understanding these scenarios helps prevent unnecessary maintenance operations.

When an Index Becomes Corrupted

Index corruption occurs when an index no longer contains valid information or its internal structure becomes inconsistent.

Although PostgreSQL is designed to maintain index consistency, corruption can occur because of:

  • Hardware failures.

  • Storage problems.

  • Operating system issues.

  • Software defects.

  • Unexpected failures involving database files.

For example, an application may execute a query that uses an index but return unexpected results or encounter an index-related error.

However, an incorrect query result does not automatically mean the index is corrupted. Incorrect SQL, stale application assumptions, transaction behavior, and data problems can produce similar symptoms.

Investigate the underlying issue before rebuilding the index.

Rebuilding a corrupted index

If an index on a user table is confirmed or strongly suspected to be corrupted, you can rebuild it directly:

SQL
REINDEX INDEX idx_customers_email;

For all indexes associated with a table:

SQL
REINDEX TABLE customers;

A successful rebuild recreates the index using the table data.

However, REINDEX is not a universal solution for storage corruption. If the underlying table data, database files, or storage device are damaged, rebuilding an index may not resolve the root cause.

Investigate database logs, operating system logs, storage health, and PostgreSQL consistency checks as part of the recovery process.

For suspected corruption in system catalog indexes, the recovery procedure is more sensitive because PostgreSQL uses those indexes during normal operation. Follow the PostgreSQL documentation's specific recovery procedure rather than treating system indexes like ordinary application indexes.

When an Index Becomes Bloated

Index bloat is another reason administrators may consider REINDEX.

Index bloat refers to space consumed by an index that is no longer efficiently used for its current contents.

It can occur when indexes contain many empty or sparsely populated pages.

Consider a table where records are frequently updated and deleted.

SQL
DELETE FROM orders
WHERE order_date < DATE '2020-01-01';

PostgreSQL uses MVCC (Multi-Version Concurrency Control) to manage row versions.

When a row is updated or deleted, its previous version may remain until it is no longer visible to any active transaction and can be cleaned up.

Indexes can also retain entries associated with obsolete row versions until maintenance removes them.

Over time, certain workloads can cause B-tree indexes to contain many underutilized pages.

However, not every dead tuple or large index indicates bloat.

Why VACUUM does not always solve index bloat

PostgreSQL's VACUUM command helps reclaim space from dead tuples and makes space available for reuse.

For example:

SQL
VACUUM customers;

VACUUM performs important maintenance, but ordinary VACUUM does not generally shrink the physical size of an index file by returning its trailing space to the operating system.

It can clean up index entries and make space reusable within the index.

REINDEX takes a different approach: it builds a new index structure from the table data.

This can remove unnecessary empty or sparsely populated pages and reduce index size.

The two commands serve different purposes.

Operation

Main purpose

VACUUM

Reclaims space from dead tuples and makes it reusable

ANALYZE

Updates statistics used by the query planner

REINDEX

Rebuilds index structures

VACUUM FULL

Rewrites a table to reclaim space, requiring stronger locking

Do not run REINDEX simply because VACUUM has been executed or because a table contains dead tuples. First determine whether the index itself has a meaningful space-efficiency problem.

How to Identify Invalid Indexes

An index can become invalid when an index creation or concurrent rebuilding operation fails.

For example, a concurrent index operation may fail because of a uniqueness violation or another error.

The resulting index may remain in the system catalogs with an invalid status.

An invalid index is not usable for normal query planning, but it can still consume disk space and create maintenance overhead.

PostgreSQL stores index validity information in the pg_index system catalog.

You can inspect it using:

SQL
SELECT
    n.nspname AS schema_name,
    t.relname AS table_name,
    i.relname AS index_name,
    ix.indisvalid,
    ix.indisready,
    ix.indislive
FROM pg_index ix
JOIN pg_class i
    ON i.oid = ix.indexrelid
JOIN pg_class t
    ON t.oid = ix.indrelid
JOIN pg_namespace n
    ON n.oid = t.relnamespace
WHERE NOT ix.indisvalid
   OR NOT ix.indisready
   OR NOT ix.indislive
ORDER BY
    n.nspname,
    t.relname,
    i.relname;

The important fields are:

Column

Meaning

indisvalid

Whether the index is valid for query planning

indisready

Whether the index is ready to receive updates

indislive

Whether the index is considered live

An index with an invalid status needs investigation.

Do not assume every invalid index should immediately be rebuilt. Determine why it became invalid and whether it is an unfinished concurrent index operation.

Inspect index definitions

Once you identify a suspicious index, retrieve its definition:

SQL
SELECT
    schemaname,
    tablename,
    indexname,
    indexdef
FROM pg_indexes
WHERE indexname = 'idx_customers_email';

You can also inspect index details through psql:

Code
\d customers

Review the table's indexes and identify any that are marked INVALID.

For an invalid index left by a failed concurrent build, PostgreSQL documents recovery options that depend on the state of the replacement index.

A failed concurrent rebuild may leave an index with a suffix such as ccnew or ccold.

The recovery procedure should follow the documented state of the index. In particular, a failed replacement index may need to be dropped before attempting the rebuild again.

Do not drop the original valid index simply because another index with a similar name is invalid.

When Index Storage Parameters Change

PostgreSQL indexes support storage parameters that influence how index pages are maintained.

One example is fillfactor.

Fillfactor controls how full index pages are initially packed during index creation.

For a B-tree index, the default fillfactor is generally 90.

You can change the setting:

SQL
ALTER INDEX idx_customers_email
SET (fillfactor = 80);

However, changing the storage parameter does not immediately rebuild the existing index pages.

To ensure that the new setting takes effect throughout the index, rebuild it:

SQL
REINDEX INDEX idx_customers_email;

Fillfactor is a workload-dependent setting.

For example, a workload with frequent inserts and updates may benefit from leaving additional space on index pages, depending on the access pattern.

Do not reduce fillfactor without testing. A lower value can increase index size and memory requirements.

How to Investigate Index Bloat

Index bloat should be measured or investigated rather than assumed from the index's physical size.

A large index is not necessarily bloated. It may simply contain many valid entries because the table itself is large.

Start by checking index sizes.

SQL
SELECT
    schemaname,
    tablename,
    indexname,
    pg_size_pretty(
        pg_relation_size(indexrelid)
    ) AS index_size
FROM pg_stat_user_indexes
ORDER BY pg_relation_size(indexrelid) DESC;

This query helps identify the largest indexes in the current database.

Large indexes deserve attention when they are associated with performance problems or unusual space growth.

Check index usage statistics

PostgreSQL provides pg_stat_user_indexes for monitoring index activity.

For example:

SQL
SELECT
    schemaname,
    relname AS table_name,
    indexrelname AS index_name,
    idx_scan,
    idx_tup_read,
    idx_tup_fetch,
    pg_size_pretty(
        pg_relation_size(indexrelid)
    ) AS index_size
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC;

Important columns include:

  • idx_scan: Number of index scans initiated.

  • idx_tup_read: Number of index entries returned by scans.

  • idx_tup_fetch: Number of live table rows fetched through the index.

This information helps identify indexes that may have low observed usage.

However, low usage does not prove that an index is unnecessary or bloated.

The statistics are collected since the statistics counters were last reset, and an index may support infrequent but important reporting or maintenance operations.

An index used by a monthly report may appear unused during a short monitoring window.

Always review the workload period and business requirements before removing or rebuilding indexes.

Use pgstattuple for detailed inspection

PostgreSQL provides the pgstattuple extension for examining table and index storage characteristics.

Where supported, pgstatindex can provide useful information about B-tree index structure.

First, enable the extension:

SQL
CREATE EXTENSION IF NOT EXISTS pgstattuple;

Then inspect a B-tree index:

SQL
SELECT *
FROM pgstatindex('idx_customers_email');

The output can include:

Metric

Purpose

tree_level

Height of the B-tree

index_size

Physical index size

leaf_pages

Number of leaf pages

empty_pages

Number of empty pages

deleted_pages

Number of deleted pages

avg_leaf_density

Average leaf-page density

leaf_fragmentation

Measure of leaf-page fragmentation

Average leaf density can help indicate how full the leaf pages are.

For example, a low density may suggest that an index contains considerable unused space.

However, do not treat one density value as a universal rebuild threshold.

Index structure depends on fillfactor, data distribution, index workload, and expected future growth.

The pgstattuple extension also has operational considerations. Some inspection methods scan substantial portions of an index, so use them carefully on large production databases.

Choosing Between REINDEX and REINDEX CONCURRENTLY

One of the most important decisions during production index maintenance is choosing the appropriate rebuilding method.

A standard REINDEX operation and REINDEX CONCURRENTLY both rebuild indexes, but they have different locking and operational characteristics.

Standard REINDEX

A normal index rebuild is straightforward:

SQL
REINDEX INDEX idx_customers_email;

PostgreSQL rebuilds the index while holding locks that prevent concurrent writes to the associated table.

Other sessions can generally continue reading the table, but INSERT, UPDATE, and DELETE operations can be blocked until the rebuild completes.

This approach is useful when:

  • The table is not receiving production traffic.

  • A maintenance window is available.

  • The index is small.

  • Faster rebuilding is more important than allowing concurrent writes.

  • The operation is part of a controlled recovery procedure.

For a large production table, the write-blocking behavior can be disruptive.

REINDEX CONCURRENTLY

PostgreSQL provides REINDEX CONCURRENTLY to rebuild an index while allowing normal INSERT, UPDATE, and DELETE operations to continue.

For example:

SQL
REINDEX INDEX CONCURRENTLY idx_customers_email;

The operation uses a more involved process than standard REINDEX.

It performs multiple phases, including multiple table scans, and waits for transactions that could affect the rebuild.

This makes the operation more expensive in terms of total work and elapsed time.

However, it reduces the need to block ordinary writes during the rebuild.

Standard versus concurrent reindexing

Factor

Standard REINDEX

REINDEX CONCURRENTLY

Rebuild process

Direct rebuild

Multi-phase rebuild

Concurrent reads

Generally allowed

Allowed

Concurrent writes

Blocked by the required table lock

Allowed

Execution time

Often shorter

Often longer

Resource usage

Depends on index and workload

Additional work and resource consumption

Transaction block

Supported for ordinary index and table cases, subject to restrictions

Not allowed

Production suitability

Best with a maintenance window

Useful when writes must continue

CONCURRENTLY does not mean that the operation has no impact on production.

It can still consume significant CPU, memory, disk I/O, and storage space. It can also wait for long-running transactions and interfere with other maintenance work.

Only one concurrent index build can run on a table at a time, and other schema modifications may be restricted during the operation.

Choose the method based on table size, workload, maintenance requirements, and acceptable locking.

Rebuilding a Specific Index Safely

For a production application, start with the individual index rather than rebuilding an entire table.

Suppose the index is:

SQL
CREATE INDEX idx_orders_customer_id
ON orders(customer_id);

First, inspect the index:

SQL
SELECT
    schemaname,
    tablename,
    indexname,
    indexdef
FROM pg_indexes
WHERE indexname = 'idx_orders_customer_id';

Check its size:

SQL
SELECT
    pg_size_pretty(
        pg_relation_size(
            'idx_orders_customer_id'
        )
    ) AS index_size;

Check whether it is valid:

SQL
SELECT
    indexrelid::regclass AS index_name,
    indisvalid,
    indisready
FROM pg_index
WHERE indexrelid =
    'idx_orders_customer_id'::regclass;

If a rebuild is justified and production writes must continue:

SQL
REINDEX INDEX CONCURRENTLY
idx_orders_customer_id;

After the operation, verify the index status and review query performance.

Also compare the physical size before and after the rebuild.

A smaller index may indicate that unused space was removed, but size reduction alone does not prove that application performance improved.

Rebuilding All Indexes on a Table

Sometimes the problem affects several indexes on the same table.

For example, a table may have indexes on customer_id, order_date, and order_status.

You can rebuild all its indexes using:

SQL
REINDEX TABLE orders;

For a production table where concurrent writes must continue:

SQL
REINDEX TABLE CONCURRENTLY orders;

This can be useful when several indexes require rebuilding.

However, rebuilding every index on a table can generate substantial I/O and storage activity.

Before using this approach, identify which indexes actually need attention.

A table may contain many healthy indexes, and rebuilding them unnecessarily increases maintenance time.

Monitoring REINDEX Progress

Large index rebuilds may take a considerable amount of time.

PostgreSQL provides the pg_stat_progress_create_index system view for monitoring index creation and reindexing operations.

For example:

SQL
SELECT
    pid,
    datname,
    relid::regclass AS table_name,
    index_relid::regclass AS index_name,
    command,
    phase,
    lockers_total,
    lockers_done,
    blocks_total,
    blocks_done,
    tuples_total,
    tuples_done
FROM pg_stat_progress_create_index;

The view provides information about active index operations.

Important fields include:

Field

Meaning

pid

Process ID executing the operation

command

CREATE INDEX or REINDEX operation

phase

Current stage of the operation

blocks_total

Total blocks to process in the current phase

blocks_done

Blocks processed so far

tuples_total

Estimated or known tuples to process

tuples_done

Tuples processed so far

lockers_total

Transactions or sessions that must be waited for

lockers_done

Lockers already processed

Progress information is particularly useful when a concurrent rebuild appears to be waiting.

For example, PostgreSQL may need to wait for transactions that could still use the old index.

Investigate long-running sessions before assuming that the rebuild is stuck.

What Happens When REINDEX CONCURRENTLY Fails?

A concurrent rebuild can fail because of:

  • Duplicate values in a unique index.

  • Deadlocks.

  • Cancellation.

  • Resource exhaustion.

  • Other concurrent database problems.

When the operation fails, PostgreSQL may leave behind an invalid replacement index.

For example, psql may display:

Code
Indexes:
    "idx_orders_customer_id" btree (customer_id)
    "idx_orders_customer_id_ccnew" btree (customer_id) INVALID

The invalid replacement index is not used for normal query planning, but it can still consume storage and create update overhead.

First, identify which index is invalid:

SQL
SELECT
    indexrelid::regclass AS index_name,
    indrelid::regclass AS table_name,
    indisvalid,
    indisready
FROM pg_index
WHERE NOT indisvalid;

Then investigate the failed operation.

If the invalid index is the temporary replacement left by a failed concurrent rebuild, the documented recovery method is generally to drop that invalid replacement and retry the rebuild.

For example:

SQL
DROP INDEX CONCURRENTLY
idx_orders_customer_id_ccnew;

Then retry:

SQL
REINDEX INDEX CONCURRENTLY
idx_orders_customer_id;

The exact cleanup action depends on the state and identity of the invalid index.

Do not blindly drop indexes based only on their names. Verify that the original valid index remains available and that the object being removed is the failed replacement.

Common Mistakes During PostgreSQL Index Maintenance

Mistake

Why it causes problems

Better approach

Rebuilding every index regularly

Consumes resources without proving a need

Rebuild only when justified

Treating every large index as bloated

Large indexes may contain valid data

Inspect index structure and workload

Assuming VACUUM rebuilds indexes

Ordinary VACUUM does not generally shrink index files

Use the appropriate maintenance operation

Using standard REINDEX during peak traffic

Writes can be blocked

Consider concurrent rebuilding

Assuming REINDEX CONCURRENTLY has no impact

It still consumes resources and has locking phases

Monitor workload and active transactions

Ignoring invalid indexes

They can consume storage and create write overhead

Inspect pg_index

Dropping an index before checking dependencies

Can break query performance or constraints

Verify index purpose and constraints

Rebuilding without a recovery plan

Operational failures may be difficult to resolve

Prepare backups and a maintenance procedure

Best Practices for PostgreSQL Index Maintenance

A reliable index maintenance strategy should focus on evidence rather than fixed schedules.

Follow these practices:

  • Monitor index sizes and query performance.

  • Investigate invalid indexes promptly.

  • Use pg_stat_user_indexes to understand index activity.

  • Use pgstattuple where detailed index inspection is necessary.

  • Distinguish table bloat from index bloat.

  • Run ANALYZE when planner statistics need refreshing.

  • Use standard REINDEX when write blocking is acceptable.

  • Prefer REINDEX CONCURRENTLY when production writes must continue.

  • Monitor long-running transactions before concurrent rebuilds.

  • Review disk capacity because rebuilding requires additional temporary space.

  • Verify index validity after maintenance.

  • Measure application performance after rebuilding.

  • Investigate the underlying cause if corruption or unusual bloat occurs repeatedly.

Do not make REINDEX a routine replacement for VACUUM or ANALYZE. Each command addresses a different database maintenance requirement.

Conclusion

REINDEX is an important PostgreSQL maintenance command, but it should be used when there is a clear reason to rebuild an index.

Common reasons include index corruption, significant index bloat, changes to storage parameters, and invalid indexes left behind by failed concurrent operations.

Start by inspecting index validity, physical size, usage statistics, and query behavior. Use pgstattuple when a deeper investigation of B-tree structure is necessary.

For production systems, choose between standard REINDEX and REINDEX CONCURRENTLY based on the impact of write blocking, available resources, and maintenance requirements.

Most importantly, rebuilding an index should be part of a broader database maintenance strategy. Monitor the database, investigate the root cause of index problems, and verify the results after every rebuild.

This approach helps maintain index health without introducing unnecessary resource consumption or production disruption.