PostgreSQL Rebuild Indexes
This article describes how to rebuild indexes in PostgreSQL.
You can rebuild indexes when they are damaged or contain bad data. PostgreSQL provides the REINDEX statement to rebuild one or more indexes.
PostgreSQL REINDEX syntax
Here is the syntax of the PostgreSQL REINDEX statement:
REINDEX
[ ( VERBOSE ) ]
[ ( CONCURRENTLY [ boolean ] ) ]
[ ( TABLESPACE new_tablespace ) ]
{ INDEX | TABLE | SCHEMA | DATABASE | SYSTEM } name;
Explanation:
- The
VERBOSEkeyword are optional. If this keyword is provided, progress will be displayed while the index is being rebuilt. - The
CONCURRENTLYkeyword is optional. With it, PostgreSQL will not block any operations on the table while the index is being rebuilt. - The
TABLESPACE new_tablespaceis optional. With it, PostgreSQL will rebuild indexes on the new tablespace. - The
{ INDEX | TABLE | SCHEMA | DATABASE | SYSTEM } nameis used to specify the index object to rebuild.INDEX: Rebuild the specified index.TABLE: Rebuild all indexes in the specified table.SCHEMA: Rebuild all indexes in the specified schema.DATABASE: Rebuild all indexes in the specified database.SYSTEM: Rebuild all indexes in the system catalog of the specified database.- The
namespecifies the name of the object.
Here are some specific usages:
-
To rebuild a single index, use the
INDEXkeyword and specify the index name:REINDEX INDEX index_name; -
To rebuild all indexes in a table, use the
TABLEkeyword and specify the name of the table:REINDEX TABLE table_name; -
To rebuild all indexes in a schema, use the
SCHEMAkeyword and specify the name of the schema:REINDEX SCHEMA schema_name; -
To rebuild all indexes in a database, use the
DATABASEkeyword and specify the database name:REINDEX DATABASE database_name; -
To rebuild all indexes on the system catalog in one data, use the
SYSTEMkeyword and specify the database name:REINDEX SYSTEM database_name;
REINDEX vs DROP INDEX and CREATE INDEX
The process of rebuilding an index is equivalent to dropping the index first and creating an index with the same definition. That is: REINDEX equivalent to a combination of DROP INDEX and CREATE INDEX statements. It also has some differences between them:
-
REINDEXStatement:- Locks writes but not reads of the table to which the index belongs.
- Takes an exclusive lock on the index being processed, which prevents reads attempting to use the index. unless you specify
CONCURRENTLYkeywords.
-
DROP INDEXandCREATE INDEXstatements:- The
DROP INDEXstatement locks writes and reads of the table to which the index belongs by acquiring an exclusive lock on the table. - The
CREATE INDEXstatement locks writes but not reads in the index’s parent table. However, reads during index creation is expensive.
- The
Conclusion
This article describes how to use the REINDEX statement in PostgreSQL.