Skip to content

Repair and Rebuild Indexes

Find indexes that are invalid or bloated on a Managed PostgreSQL service, rebuild them without blocking the application, and clear the duplicate rows that prevent a unique index from being built.

When an Index Needs Rebuilding

  • A concurrent build failed. CREATE INDEX CONCURRENTLY and REINDEX ... CONCURRENTLY that fail, because of duplicate keys, a lock timeout, a cancel or a lost connection, leave an invalid index behind. The planner ignores it, but every write still maintains it and it uses disk.
  • The index is bloated. B-tree indexes on tables with many updates and deletes accumulate half-empty pages and grow beyond what the data needs.
  • The collation changed. Text indexes are sorted by the collation in force when they were built. If the operating system’s collation library changes its sort order, existing indexes can return wrong results until they are rebuilt.

Find Invalid Indexes

SELECT i.indexrelid::regclass AS index_name,
       i.indrelid::regclass   AS table_name,
       i.indisvalid,
       i.indisready,
       pg_size_pretty(pg_relation_size(i.indexrelid)) AS size
FROM pg_index i
WHERE NOT i.indisvalid OR NOT i.indisready;

A name ending in _ccnew is the replacement built by an interrupted REINDEX ... CONCURRENTLY; one ending in _ccold is the original index, left behind when the swap had already happened. In both cases the index without the suffix is the one to keep. Drop the leftover:

DROP INDEX CONCURRENTLY public.orders_customer_id_idx_ccnew;

An invalid index without a suffix is the result of a failed CREATE INDEX CONCURRENTLY. Drop it and create it again, or rebuild it with REINDEX INDEX CONCURRENTLY.

Measure Index Bloat

pgstatindex() from the pgstattuple extension describes a B-tree index. avnadmin can create the extension and call it:

CREATE EXTENSION IF NOT EXISTS pgstattuple;

SELECT tree_level,
       pg_size_pretty(index_size)            AS index_size,
       leaf_pages,
       round(avg_leaf_density::numeric, 1)   AS avg_leaf_density,
       round(leaf_fragmentation::numeric, 1) AS leaf_fragmentation
FROM pgstatindex('public.orders_customer_id_idx');

A freshly built B-tree has an avg_leaf_density of about 90. Updating a third of the rows of the indexed column brings it to about 80; when it falls towards 50 or below, about half of the index is empty space and a rebuild is worthwhile. pgstatindex() reads the whole index: run it outside peak hours on large indexes.

A cheaper first pass compares index and table sizes:

SELECT s.indexrelid::regclass                         AS index_name,
       s.relid::regclass                              AS table_name,
       s.idx_scan                                     AS scans,
       pg_size_pretty(pg_relation_size(s.indexrelid)) AS index_size,
       pg_size_pretty(pg_table_size(s.relid))         AS table_size
FROM pg_stat_user_indexes s
ORDER BY pg_relation_size(s.indexrelid) DESC
LIMIT 20;

Important

The amcheck extension, which verifies the structure of indexes and tables, cannot be used to check for corruption. On PostgreSQL 18 it can be created, but avnadmin gets permission denied for function bt_index_check, and the same for bt_index_parent_check and verify_heapam. If you suspect corruption rather than bloat, contact Exoscale support.

Check for a Collation Version Change

PostgreSQL records the collation version a database and its collations were created with. Compare it with the version the server provides now:

SELECT datname, datcollversion,
       pg_database_collation_actual_version(oid) AS actual_version
FROM pg_database
WHERE datname = current_database();

SELECT collname, collversion, pg_collation_actual_version(oid) AS actual_version
FROM pg_collation
WHERE collversion IS NOT NULL
  AND collversion IS DISTINCT FROM pg_collation_actual_version(oid);

If the versions differ, PostgreSQL also warns when you connect. Rebuild every index on text columns that uses the affected collation, then record the new version:

ALTER DATABASE DATABASE_NAME REFRESH COLLATION VERSION;

Parameters:

  • DATABASE_NAME: the database whose indexes you rebuilt. When the version has not changed, PostgreSQL answers NOTICE: version has not changed.

Refresh only after the rebuild. Refreshing first silences the warning and leaves the wrongly sorted indexes in place.

Rebuild an Index

REINDEX CONCURRENTLY

REINDEX INDEX CONCURRENTLY public.orders_customer_id_idx;
REINDEX TABLE CONCURRENTLY public.orders;

The concurrent form builds a new index next to the old one and swaps them, while the table stays readable and writable. What to expect:

  • It scans the table twice and takes longer than a plain REINDEX.
  • It needs disk space for a second copy of the index while it runs. On a service short of space, see Prevent a full disk.
  • It waits for every transaction that started before it to finish, so an old idle in transaction session makes it wait indefinitely.
  • It cannot run inside a transaction block.

Set a lock_timeout so that the rebuild gives up instead of waiting behind an old transaction:

SET lock_timeout = '5s';
REINDEX INDEX CONCURRENTLY public.orders_customer_id_idx;

If it times out, it fails with ERROR: canceling statement due to lock timeout and can leave a _ccnew or _ccold index behind: run the invalid-index query above and drop the leftover.

Plain REINDEX

REINDEX INDEX public.orders_customer_id_idx;

REINDEX without CONCURRENTLY blocks writes to the table, and queries that would use the index, until it finishes. Use it on small indexes or in a maintenance window.

Build and Swap by Hand

You can also build the replacement under another name, drop the old index, and rename:

CREATE INDEX CONCURRENTLY orders_customer_id_idx_new ON public.orders (customer_id);
DROP INDEX CONCURRENTLY public.orders_customer_id_idx;
ALTER INDEX public.orders_customer_id_idx_new RENAME TO orders_customer_id_idx;

This does not work for an index that backs a primary key or unique constraint, which cannot be dropped on its own. Use REINDEX ... CONCURRENTLY for those.

Speed Up a Rebuild

Index builds use maintenance_work_mem and can use parallel workers. avnadmin can raise both for the session that rebuilds:

SET maintenance_work_mem = '512MB';
SET max_parallel_maintenance_workers = 2;
REINDEX INDEX CONCURRENTLY public.orders_customer_id_idx;

Each autovacuum worker can also use up to maintenance_work_mem. Keep large values to the session that needs them and size them against the memory of your plan.

Rebuild a Bloated Table and Its Indexes

If the table itself is bloated, rebuilding only its indexes is not enough. pg_repack rewrites a table and its indexes while keeping it available: see Use pg_repack.

Clear Duplicates That Block a Unique Index

A unique index cannot be built, or rebuilt, while the table contains duplicate keys. The build fails and names one of them:

ERROR:  could not create unique index "memberships_team_user_key"
DETAIL:  Key (team_id, user_id)=(12, 40651) is duplicated.

With CONCURRENTLY, the failed build also leaves an invalid index behind. Take this table, which should hold one row per team and user:

CREATE TABLE public.memberships (
    team_id  bigint,
    user_id  bigint,
    role     text,
    added_at timestamptz DEFAULT now()
);

List the duplicated keys, grouping on exactly the columns of the index:

SELECT team_id, user_id, count(*) AS copies
FROM public.memberships
GROUP BY team_id, user_id
HAVING count(*) > 1
ORDER BY copies DESC;

Look at the rows themselves, using ctid, the physical row address, to tell copies apart:

SELECT ctid, team_id, user_id, role, added_at
FROM public.memberships
WHERE (team_id, user_id) IN (
    SELECT team_id, user_id
    FROM public.memberships
    GROUP BY team_id, user_id
    HAVING count(*) > 1
)
ORDER BY team_id, user_id, ctid;

If the copies differ in other columns, here role, decide by hand which values to keep. If they are true copies, keep one row per key:

DELETE FROM public.memberships a
USING public.memberships b
WHERE a.team_id = b.team_id
  AND a.user_id = b.user_id
  AND a.ctid > b.ctid;

Then drop the invalid index left by the failed build and build it again:

DROP INDEX CONCURRENTLY public.memberships_team_user_key;
CREATE UNIQUE INDEX CONCURRENTLY memberships_team_user_key
    ON public.memberships (team_id, user_id);

What avnadmin Can Rebuild

REINDEX needs ownership of the table or index, or the MAINTAIN privilege on the table (PostgreSQL 17 and later):

  • Tables owned by avnadmin, and tables owned by roles that avnadmin created. A role created by avnadmin is automatically granted to it with INHERIT, so avnadmin has that role’s privileges.

  • Tables of other roles fail with permission denied for index ... unless the owner grants the privilege:

    GRANT MAINTAIN ON TABLE public.orders TO avnadmin;
  • REINDEX SYSTEM DATABASE_NAME works in a database that avnadmin owns. REINDEX TABLE on an individual system catalog, for example pg_catalog.pg_class, fails with permission denied for table pg_class.

Related Pages

Last updated on