REINDEX(7)
π REINDEX(7) β the PostgreSQL 16.15 documentation glow-up
okay so bestie, welcome to REINDEX, from the PostgreSQL 16.15 docs, and I promise this is gonna be more fun than it sounds π«Ά
β¨ NAME β¨
REINDEX β rebuild indexes. that's it, that's the whole vibe. it's giving "spring cleaning but for your index files" π§Ήπ
πΈ SYNOPSIS πΈ
REINDEX [ ( option [, ...] ) ] { INDEX | TABLE | SCHEMA } [ CONCURRENTLY ] name
REINDEX [ ( option [, ...] ) ] { DATABASE | SYSTEM } [ CONCURRENTLY ] [ name ]
where option can be one of:
CONCURRENTLY [ boolean ]
TABLESPACE new_tablespace
VERBOSE [ boolean ]
like, look at her go. two whole forms, and a little menu of options. icon behavior honestly π
π¦ DESCRIPTION π¦
so REINDEX rebuilds an index using the data stored in the index's table β it literally replaces the old copy of the index with a fresh new one. main character energy: out with the old, in with the new π
β¨
there are several scenarios where you'd wanna use REINDEX, and yes we're listing all of them because every single one matters:
- an index has become corrupted and no longer contains valid data. and like, in theory this should never happen?? but in practice indexes can become corrupted due to software bugs or hardware failures π and
REINDEXprovides a recovery method. it's the "have you tried turning it off and on again" of indexes fr fr. - an index has become "bloated" β meaning it contains many empty or nearly-empty pages. this can occur with B-tree indexes in PostgreSQL under certain uncommon access patterns.
REINDEXprovides a way to reduce the space consumption of the index by writing a new version of the index without the dead pages π see Section 25.2 for more information. - you've altered a storage parameter (such as
fillfactor) for an index, and you wish to ensure that the change has taken full effect. no cap, sometimes you gotta rebuild so the change actually lands π― - if an index build fails with the
CONCURRENTLYoption, this index is left as "invalid". such indexes are useless but it can be convenient to useREINDEXto rebuild them. heads up though: note that onlyREINDEX INDEXis able to perform a concurrent build on an invalid index. that's a very specific little detail and we are NOT skipping it π
π PARAMETERS π
the big four (plus a couple friends)
INDEXβ recreate the specified index. this form ofREINDEXcannot be executed inside a transaction block when used with a partitioned index. so like, partitioned index? no transaction block for you, bestie π«TABLEβ recreate all indexes of the specified table. if the table has a secondary "TOAST" table, that is reindexed as well π (yes it's called TOAST, we love her). this form ofREINDEXcannot be executed inside a transaction block when used with a partitioned table.SCHEMAβ recreate all indexes of the specified schema. if a table of this schema has a secondary "TOAST" table, that is reindexed as well. indexes on shared system catalogs are also processed. and β say it with me β this form ofREINDEXcannot be executed inside a transaction block π«DATABASEβ recreate all indexes within the current database, except system catalogs. indexes on system catalogs are not processed. this form ofREINDEXcannot be executed inside a transaction block either. the pattern is patterning πSYSTEMβ recreate all indexes on system catalogs within the current database. indexes on shared system catalogs are included. indexes on user tables are not processed. and yep, this form ofREINDEXcannot be executed inside a transaction block. it's giving "no transaction blocks allowed, periodt" π
name
the name of the specific index, table, or database to be reindexed. index and table names can be schema-qualified β¨ presently, REINDEX DATABASE and REINDEX SYSTEM can only reindex the current database. their parameter is optional, and it must match the current database's name. so if you're gonna pass a name, it better be the right one, iykyk π
CONCURRENTLY
when this option is used, PostgreSQL will rebuild the index without taking any locks that prevent concurrent inserts, updates, or deletes on the table β whereas a standard index rebuild locks out writes (but not reads) on the table until it's done π₯ that's the whole selling point honestly.
but bestie, there are several caveats to be aware of when using this option β see Rebuilding Indexes Concurrently below π (we'll get there, don't worry)
also for temporary tables, REINDEX is always non-concurrent, as no other session can access them, and non-concurrent reindex is cheaper. so like, don't fight it π
TABLESPACE
specifies that indexes will be rebuilt on a new tablespace. new location, new vibes, same index energy β¨
VERBOSE
prints a progress report as each index is reindexed. literally the "are we there yet" of reindexing ππ
boolean
specifies whether the selected option should be turned on or off. you can write TRUE, ON, or 1 to enable the option, and FALSE, OFF, or 0 to disable it. the boolean value can also be omitted, in which case TRUE is assumed. so VERBOSE with no argument? that's a yes from her π
new_tablespace
the tablespace where indexes will be rebuilt. that's the spot, bestie π―
β¨ NOTES β¨
okay so first thing first π if you suspect corruption of an index on a user table, you can literally just rebuild that index, or all indexes on the table, using REINDEX INDEX or REINDEX TABLE. slay, easy.
things get way more stressful if you need to recover from corruption of an index on a system table. in that case it's genuinely important that the system has not used any of the suspect indexes itself. (and yeah, in this sort of scenario you might find server processes crashing immediately at start-up, due to reliance on the corrupted indexes. π) to recover safely, the server must be started with the -P option, which prevents it from using indexes for system catalog lookups.
one way to do this is to shut down the server and start a single-user PostgreSQL server with -P included on its command line. then REINDEX DATABASE, REINDEX SYSTEM, REINDEX TABLE, or REINDEX INDEX can be issued, depending on how much you want to reconstruct. if in doubt, use REINDEX SYSTEM to select reconstruction of all system indexes in the database. then quit the single-user server session and restart the regular server. see the postgres(1) reference page for more information about how to interact with the single-user server interface π«Ά
alternatively, a regular server session can be started with -P included in its command line options. the method for doing this varies across clients, but in all libpq-based clients, it is possible to set the PGOPTIONS environment variable to -P before starting the client. note that while this method does not require locking out other clients, it might still be wise to prevent other users from connecting to the damaged database until repairs have been completed. safety first, bestie π
REINDEX is similar to a drop and recreate of the index in that the index contents are rebuilt from scratch. however, the locking considerations are rather different. REINDEX locks out writes but not reads of the index's parent table. it also takes an ACCESS EXCLUSIVE lock on the specific index being processed, which will block reads that attempt to use that index. in particular, the query planner tries to take an ACCESS SHARE lock on every index of the table, regardless of the query, and so REINDEX blocks virtually any queries except for some prepared queries whose plan has been cached and which don't use this very index. in contrast, DROP INDEX momentarily takes an ACCESS EXCLUSIVE lock on the parent table, blocking both writes and reads. the subsequent CREATE INDEX locks out writes but not reads; since the index is not there, no read will attempt to use it, meaning that there will be no blocking but reads might be forced into expensive sequential scans. the way locking just changes the whole vibe π
reindexing a single index or table requires being the owner of that index or table. reindexing a schema or database requires being the owner of that schema or database. note specifically that it's thus possible for non-superusers to rebuild indexes of tables owned by other users. however, as a special exception, when REINDEX DATABASE, REINDEX SCHEMA or REINDEX SYSTEM is issued by a non-superuser, indexes on shared catalogs will be skipped unless the user owns the catalog (which typically won't be the case). of course, superusers can always reindex anything. main character superuser energy π
reindexing partitioned indexes or partitioned tables is supported with REINDEX INDEX or REINDEX TABLE, respectively. each partition of the specified partitioned relation is reindexed in a separate transaction. those commands cannot be used inside a transaction block when working on a partitioned table or index. π¦
when using the TABLESPACE clause with REINDEX on a partitioned index or table, only the tablespace references of the leaf partitions are updated. as partitioned indexes are not updated, it is recommended to separately use ALTER TABLE ONLY on them so as any new partitions attached inherit the new tablespace. on failure, it may not have moved all the indexes to the new tablespace. re-running the command will rebuild all the leaf partitions and move previously-unprocessed indexes to the new tablespace. π¦
if SCHEMA, DATABASE or SYSTEM is used with TABLESPACE, system relations are skipped and a single WARNING will be generated. indexes on TOAST tables are rebuilt, but not moved to the new tablespace. not the TOAST tables catching strays π
π¦ Rebuilding Indexes Concurrently π¦
rebuilding an index can interfere with regular operation of a database. normally PostgreSQL locks the table whose index is rebuilt against writes and performs the entire index build with a single scan of the table. other transactions can still read the table, but if they try to insert, update, or delete rows in the table they will block until the index rebuild is finished. this could have a severe effect if the system is a live production database. very large tables can take many hours to be indexed, and even for smaller tables, an index rebuild can lock out writers for periods that are unacceptably long for a production system. genuinely terrifying for prod π
PostgreSQL supports rebuilding indexes with minimum locking of writes. this method is invoked by specifying the CONCURRENTLY option of REINDEX. when this option is used, PostgreSQL must perform two scans of the table for each index that needs to be rebuilt and wait for termination of all existing transactions that could potentially use the index. this method requires more total work than a standard index rebuild and takes significantly longer to complete as it needs to wait for unfinished transactions that might modify the index. however, since it allows normal operations to continue while the index is being rebuilt, this method is useful for rebuilding indexes in a production environment. of course, the extra CPU, memory and I/O load imposed by the index rebuild may slow down other operations. trade-offs are real, but it's giving production-friendly β¨
the following steps occur in a concurrent reindex. each step is run in a separate transaction. if there are multiple indexes to be rebuilt, then each step loops through all the indexes before moving to the next step.
- a new transient index definition is added to the catalog
pg_index. this definition will be used to replace the old index. aSHARE UPDATE EXCLUSIVElock at session level is taken on the indexes being reindexed as well as their associated tables to prevent any schema modification while processing. - a first pass to build the index is done for each new index. once the index is built, its flag
pg_index.indisreadyis switched totrueto make it ready for inserts, making it visible to other sessions once the transaction that performed the build is finished. this step is done in a separate transaction for each index. - then a second pass is performed to add tuples that were added while the first pass was running. this step is also done in a separate transaction for each index.
- all the constraints that refer to the index are changed to refer to the new index definition, and the names of the indexes are changed. at this point,
pg_index.indisvalidis switched totruefor the new index and tofalsefor the old, and a cache invalidation is done causing all sessions that referenced the old index to be invalidated. - the old indexes have
pg_index.indisreadyswitched tofalseto prevent any new tuple insertions, after waiting for running queries that might reference the old index to complete. - the old indexes are dropped. the
SHARE UPDATE EXCLUSIVEsession locks for the indexes and the table are released.
if a problem arises while rebuilding the indexes, such as a uniqueness violation in a unique index, the REINDEX command will fail but leave behind an βinvalidβ new index in addition to the pre-existing one. this index will be ignored for querying purposes because it might be incomplete; however it will still consume update overhead. the psql \d command will report such an index as INVALID:
postgres=# \d tab
Table "public.tab"
Column | Type | Modifiers
--------+---------+-----------
col | integer |
Indexes:
"idx" btree (col)
"idx_ccnew" btree (col) INVALID
if the index marked INVALID is suffixed _ccnew, then it corresponds to the transient index created during the concurrent operation, and the recommended recovery method is to drop it using DROP INDEX, then attempt REINDEX CONCURRENTLY again. if the invalid index is instead suffixed _ccold, it corresponds to the original index which could not be dropped; the recommended recovery method is to just drop said index, since the rebuild proper has been successful. a nonzero number may be appended to the suffix of the invalid index names to keep them unique, like _ccnew1, _ccold2, etc. π₯
regular index builds permit other regular index builds on the same table to occur simultaneously, but only one concurrent index build can occur on a table at a time. in both cases, no other types of schema modification on the table are allowed meanwhile. another difference is that a regular REINDEX TABLE or REINDEX INDEX command can be performed within a transaction block, but REINDEX CONCURRENTLY cannot. π§
like any long-running transaction, REINDEX on a table can affect which tuples can be removed by concurrent VACUUM on any other table.
REINDEX SYSTEM does not support CONCURRENTLY since system catalogs cannot be reindexed concurrently.
furthermore, indexes for exclusion constraints cannot be reindexed concurrently. if such an index is named directly in this command, an error is raised. if a table or database with exclusion constraint indexes is reindexed concurrently, those indexes will be skipped. (it is possible to reindex such indexes without the CONCURRENTLY option.) exclusion constraints said not today π
each backend running REINDEX will report its progress in the pg_stat_progress_create_index view. see Section 28.4.4 for details. β
β¨ EXAMPLES β¨
rebuild a single index:
REINDEX INDEX my_index;
rebuild all the indexes on the table my_table:
REINDEX TABLE my_table;
rebuild all indexes in a particular database, without trusting the system indexes to be valid already:
$ export PGOPTIONS="-P"
$ psql broken_db
...
broken_db=> REINDEX DATABASE broken_db;
broken_db=> \q
rebuild indexes for a table, without blocking read and write operations on involved relations while reindexing is in progress:
REINDEX TABLE CONCURRENTLY my_broken_table;
π COMPATIBILITY π
there is no REINDEX command in the SQL standard. not a single one, bestie periodt π
π SEE ALSO π
CREATE INDEX (CREATE_INDEX(7))DROP INDEX (DROP_INDEX(7))reindexdb(1)Section 28.4.4
xoxo from the PostgreSQL 16.15 girlies, dated 2026, on the REINDEX(7) page ππ«Άβ¨
π¦ where this page comes from
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql16 16.15-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms