{
    "content": [
        {
            "type": "text",
            "text": "# REINDEX(7) (man)\n\n**Summary:** REINDEX - rebuild indexes\n\n**Synopsis:** REINDEX [ ( option [, ...] ) ] { INDEX | TABLE | SCHEMA | DATABASE | SYSTEM } [ CONCURRENTLY ] name\nwhere option can be one of:\nCONCURRENTLY [ boolean ]\nTABLESPACE newtablespace\nVERBOSE [ boolean ]\n\n## Examples\n\n- `Rebuild a single index:`\n- `REINDEX INDEX myindex;`\n- `Rebuild all the indexes on the table mytable:`\n- `REINDEX TABLE mytable;`\n- `Rebuild all indexes in a particular database, without trusting the system indexes to be valid`\n- `already:`\n- `$ export PGOPTIONS=\"-P\"`\n- `$ psql brokendb`\n- `...`\n- `brokendb=> REINDEX DATABASE brokendb;`\n- `brokendb=> \\q`\n- `Rebuild indexes for a table, without blocking read and write operations on involved relations`\n- `while reindexing is in progress:`\n- `REINDEX TABLE CONCURRENTLY mybrokentable;`\n\n## See Also\n\n- CREATEINDEX(7)\n- DROPINDEX(7)\n- reindexdb(1)\n\n## Section Outline\n\n- **NAME** (2 lines)\n- **SYNOPSIS** (8 lines)\n- **DESCRIPTION** (19 lines)\n- **PARAMETERS** (52 lines)\n- **NOTES** (58 lines) — 1 subsections\n  - Rebuilding Indexes Concurrently (91 lines)\n- **EXAMPLES** (22 lines)\n- **COMPATIBILITY** (2 lines)\n- **SEE ALSO** (5 lines)\n\n## Full Content\n\n### NAME\n\nREINDEX - rebuild indexes\n\n### SYNOPSIS\n\nREINDEX [ ( option [, ...] ) ] { INDEX | TABLE | SCHEMA | DATABASE | SYSTEM } [ CONCURRENTLY ] name\n\nwhere option can be one of:\n\nCONCURRENTLY [ boolean ]\nTABLESPACE newtablespace\nVERBOSE [ boolean ]\n\n### DESCRIPTION\n\nREINDEX rebuilds an index using the data stored in the index's table, replacing the old copy\nof the index. There are several scenarios in which to use REINDEX:\n\n•   An index has become corrupted, and no longer contains valid data. Although in theory this\nshould never happen, in practice indexes can become corrupted due to software bugs or\nhardware failures.  REINDEX provides a recovery method.\n\n•   An index has become “bloated”, that is it contains many empty or nearly-empty pages. This\ncan occur with B-tree indexes in PostgreSQL under certain uncommon access patterns.\nREINDEX provides a way to reduce the space consumption of the index by writing a new\nversion of the index without the dead pages. See Section 25.2 for more information.\n\n•   You have altered a storage parameter (such as fillfactor) for an index, and wish to\nensure that the change has taken full effect.\n\n•   If an index build fails with the CONCURRENTLY option, this index is left as “invalid”.\nSuch indexes are useless but it can be convenient to use REINDEX to rebuild them. Note\nthat only REINDEX INDEX is able to perform a concurrent build on an invalid index.\n\n### PARAMETERS\n\nINDEX\nRecreate the specified index. This form of REINDEX cannot be executed inside a\ntransaction block when used with a partitioned index.\n\nTABLE\nRecreate all indexes of the specified table. If the table has a secondary “TOAST” table,\nthat is reindexed as well. This form of REINDEX cannot be executed inside a transaction\nblock when used with a partitioned table.\n\nSCHEMA\nRecreate all indexes of the specified schema. If a table of this schema has a secondary\n“TOAST” table, that is reindexed as well. Indexes on shared system catalogs are also\nprocessed. This form of REINDEX cannot be executed inside a transaction block.\n\nDATABASE\nRecreate all indexes within the current database. Indexes on shared system catalogs are\nalso processed. This form of REINDEX cannot be executed inside a transaction block.\n\nSYSTEM\nRecreate all indexes on system catalogs within the current database. Indexes on shared\nsystem catalogs are included. Indexes on user tables are not processed. This form of\nREINDEX cannot be executed inside a transaction block.\n\nname\nThe name of the specific index, table, or database to be reindexed. Index and table names\ncan be schema-qualified. Presently, REINDEX DATABASE and REINDEX SYSTEM can only reindex\nthe current database, so their parameter must match the current database's name.\n\nCONCURRENTLY\nWhen this option is used, PostgreSQL will rebuild the index without taking any locks that\nprevent concurrent inserts, updates, or deletes on the table; whereas a standard index\nrebuild locks out writes (but not reads) on the table until it's done. There are several\ncaveats to be aware of when using this option — see Rebuilding Indexes Concurrently\nbelow.\n\nFor temporary tables, REINDEX is always non-concurrent, as no other session can access\nthem, and non-concurrent reindex is cheaper.\n\nTABLESPACE\nSpecifies that indexes will be rebuilt on a new tablespace.\n\nVERBOSE\nPrints a progress report as each index is reindexed.\n\nboolean\nSpecifies whether the selected option should be turned on or off. You can write TRUE, ON,\nor 1 to enable the option, and FALSE, OFF, or 0 to disable it. The boolean value can also\nbe omitted, in which case TRUE is assumed.\n\nnewtablespace\nThe tablespace where indexes will be rebuilt.\n\n### NOTES\n\nIf you suspect corruption of an index on a user table, you can simply rebuild that index, or\nall indexes on the table, using REINDEX INDEX or REINDEX TABLE.\n\nThings are more difficult if you need to recover from corruption of an index on a system\ntable. In this case it's important for the system to not have used any of the suspect indexes\nitself. (Indeed, in this sort of scenario you might find that server processes are crashing\nimmediately at start-up, due to reliance on the corrupted indexes.) To recover safely, the\nserver must be started with the -P option, which prevents it from using indexes for system\ncatalog lookups.\n\nOne way to do this is to shut down the server and start a single-user PostgreSQL server with\nthe -P option included on its command line. Then, REINDEX DATABASE, REINDEX SYSTEM, REINDEX\nTABLE, or REINDEX INDEX can be issued, depending on how much you want to reconstruct. If in\ndoubt, use REINDEX SYSTEM to select reconstruction of all system indexes in the database.\nThen quit the single-user server session and restart the regular server. See the postgres(1)\nreference page for more information about how to interact with the single-user server\ninterface.\n\nAlternatively, a regular server session can be started with -P included in its command line\noptions. The method for doing this varies across clients, but in all libpq-based clients, it\nis possible to set the PGOPTIONS environment variable to -P before starting the client. Note\nthat while this method does not require locking out other clients, it might still be wise to\nprevent other users from connecting to the damaged database until repairs have been\ncompleted.\n\nREINDEX is similar to a drop and recreate of the index in that the index contents are rebuilt\nfrom scratch. However, the locking considerations are rather different.  REINDEX locks out\nwrites but not reads of the index's parent table. It also takes an ACCESS EXCLUSIVE lock on\nthe specific index being processed, which will block reads that attempt to use that index. In\ncontrast, DROP INDEX momentarily takes an ACCESS EXCLUSIVE lock on the parent table, blocking\nboth writes and reads. The subsequent CREATE INDEX locks out writes but not reads; since the\nindex is not there, no read will attempt to use it, meaning that there will be no blocking\nbut reads might be forced into expensive sequential scans.\n\nReindexing a single index or table requires being the owner of that index or table.\nReindexing a schema or database requires being the owner of that schema or database. Note\nspecifically that it's thus possible for non-superusers to rebuild indexes of tables owned by\nother users. However, as a special exception, when REINDEX DATABASE, REINDEX SCHEMA or\nREINDEX SYSTEM is issued by a non-superuser, indexes on shared catalogs will be skipped\nunless the user owns the catalog (which typically won't be the case). Of course, superusers\ncan always reindex anything.\n\nReindexing partitioned indexes or partitioned tables is supported with REINDEX INDEX or\nREINDEX TABLE, respectively. Each partition of the specified partitioned relation is\nreindexed in a separate transaction. Those commands cannot be used inside a transaction block\nwhen working on a partitioned table or index.\n\nWhen using the TABLESPACE clause with REINDEX on a partitioned index or table, only the\ntablespace references of the leaf partitions are updated. As partitioned indexes are not\nupdated, it is recommended to separately use ALTER TABLE ONLY on them so as any new\npartitions attached inherit the new tablespace. On failure, it may not have moved all the\nindexes to the new tablespace. Re-running the command will rebuild all the leaf partitions\nand move previously-unprocessed indexes to the new tablespace.\n\nIf SCHEMA, DATABASE or SYSTEM is used with TABLESPACE, system relations are skipped and a\nsingle WARNING will be generated. Indexes on TOAST tables are rebuilt, but not moved to the\nnew tablespace.\n\n#### Rebuilding Indexes Concurrently\n\nRebuilding an index can interfere with regular operation of a database. Normally PostgreSQL\nlocks the table whose index is rebuilt against writes and performs the entire index build\nwith a single scan of the table. Other transactions can still read the table, but if they try\nto insert, update, or delete rows in the table they will block until the index rebuild is\nfinished. This could have a severe effect if the system is a live production database. Very\nlarge tables can take many hours to be indexed, and even for smaller tables, an index rebuild\ncan lock out writers for periods that are unacceptably long for a production system.\n\nPostgreSQL supports rebuilding indexes with minimum locking of writes. This method is invoked\nby specifying the CONCURRENTLY option of REINDEX. When this option is used, PostgreSQL must\nperform two scans of the table for each index that needs to be rebuilt and wait for\ntermination of all existing transactions that could potentially use the index. This method\nrequires more total work than a standard index rebuild and takes significantly longer to\ncomplete as it needs to wait for unfinished transactions that might modify the index.\nHowever, since it allows normal operations to continue while the index is being rebuilt, this\nmethod is useful for rebuilding indexes in a production environment. Of course, the extra\nCPU, memory and I/O load imposed by the index rebuild may slow down other operations.\n\nThe following steps occur in a concurrent reindex. Each step is run in a separate\ntransaction. If there are multiple indexes to be rebuilt, then each step loops through all\nthe indexes before moving to the next step.\n\n1. A new transient index definition is added to the catalog pgindex. This definition will\nbe used to replace the old index. A SHARE UPDATE EXCLUSIVE lock at session level is taken\non the indexes being reindexed as well as their associated tables to prevent any schema\nmodification while processing.\n\n2. A first pass to build the index is done for each new index. Once the index is built, its\nflag pgindex.indisready is switched to “true” to make it ready for inserts, making it\nvisible to other sessions once the transaction that performed the build is finished. This\nstep is done in a separate transaction for each index.\n\n3. Then a second pass is performed to add tuples that were added while the first pass was\nrunning. This step is also done in a separate transaction for each index.\n\n4. All the constraints that refer to the index are changed to refer to the new index\ndefinition, and the names of the indexes are changed. At this point, pgindex.indisvalid\nis switched to “true” for the new index and to “false” for the old, and a cache\ninvalidation is done causing all sessions that referenced the old index to be\ninvalidated.\n\n5. The old indexes have pgindex.indisready switched to “false” to prevent any new tuple\ninsertions, after waiting for running queries that might reference the old index to\ncomplete.\n\n6. The old indexes are dropped. The SHARE UPDATE EXCLUSIVE session locks for the indexes and\nthe table are released.\n\nIf a problem arises while rebuilding the indexes, such as a uniqueness violation in a unique\nindex, the REINDEX command will fail but leave behind an “invalid” new index in addition to\nthe pre-existing one. This index will be ignored for querying purposes because it might be\nincomplete; however it will still consume update overhead. The psql \\d command will report\nsuch an index as INVALID:\n\npostgres=# \\d tab\nTable \"public.tab\"\nColumn |  Type   | Modifiers\n--------+---------+-----------\ncol    | integer |\nIndexes:\n\"idx\" btree (col)\n\"idxccnew\" btree (col) INVALID\n\nIf the index marked INVALID is suffixed ccnew, then it corresponds to the transient index\ncreated during the concurrent operation, and the recommended recovery method is to drop it\nusing DROP INDEX, then attempt REINDEX CONCURRENTLY again. If the invalid index is instead\nsuffixed ccold, it corresponds to the original index which could not be dropped; the\nrecommended recovery method is to just drop said index, since the rebuild proper has been\nsuccessful. A nonzero number may be appended to the suffix of the invalid index names to keep\nthem unique, like ccnew1, ccold2, etc.\n\nRegular index builds permit other regular index builds on the same table to occur\nsimultaneously, but only one concurrent index build can occur on a table at a time. In both\ncases, no other types of schema modification on the table are allowed meanwhile. Another\ndifference is that a regular REINDEX TABLE or REINDEX INDEX command can be performed within a\ntransaction block, but REINDEX CONCURRENTLY cannot.\n\nLike any long-running transaction, REINDEX on a table can affect which tuples can be removed\nby concurrent VACUUM on any other table.\n\nREINDEX SYSTEM does not support CONCURRENTLY since system catalogs cannot be reindexed\nconcurrently.\n\nFurthermore, indexes for exclusion constraints cannot be reindexed concurrently. If such an\nindex is named directly in this command, an error is raised. If a table or database with\nexclusion constraint indexes is reindexed concurrently, those indexes will be skipped. (It is\npossible to reindex such indexes without the CONCURRENTLY option.)\n\nEach backend running REINDEX will report its progress in the pgstatprogresscreateindex\nview. See Section 28.4.2 for details.\n\n### EXAMPLES\n\nRebuild a single index:\n\nREINDEX INDEX myindex;\n\nRebuild all the indexes on the table mytable:\n\nREINDEX TABLE mytable;\n\nRebuild all indexes in a particular database, without trusting the system indexes to be valid\nalready:\n\n$ export PGOPTIONS=\"-P\"\n$ psql brokendb\n...\nbrokendb=> REINDEX DATABASE brokendb;\nbrokendb=> \\q\n\nRebuild indexes for a table, without blocking read and write operations on involved relations\nwhile reindexing is in progress:\n\nREINDEX TABLE CONCURRENTLY mybrokentable;\n\n### COMPATIBILITY\n\nThere is no REINDEX command in the SQL standard.\n\n### SEE ALSO\n\nCREATE INDEX (CREATEINDEX(7)), DROP INDEX (DROPINDEX(7)), reindexdb(1), Section 28.4.2\n\n\n\nPostgreSQL 14.23                                2026                                      REINDEX(7)\n\n"
        }
    ],
    "structuredContent": {
        "command": "REINDEX",
        "section": "7",
        "mode": "man",
        "summary": "REINDEX - rebuild indexes",
        "synopsis": "REINDEX [ ( option [, ...] ) ] { INDEX | TABLE | SCHEMA | DATABASE | SYSTEM } [ CONCURRENTLY ] name\nwhere option can be one of:\nCONCURRENTLY [ boolean ]\nTABLESPACE newtablespace\nVERBOSE [ boolean ]",
        "flags": [],
        "examples": [
            "Rebuild a single index:",
            "REINDEX INDEX myindex;",
            "Rebuild all the indexes on the table mytable:",
            "REINDEX TABLE mytable;",
            "Rebuild all indexes in a particular database, without trusting the system indexes to be valid",
            "already:",
            "$ export PGOPTIONS=\"-P\"",
            "$ psql brokendb",
            "...",
            "brokendb=> REINDEX DATABASE brokendb;",
            "brokendb=> \\q",
            "Rebuild indexes for a table, without blocking read and write operations on involved relations",
            "while reindexing is in progress:",
            "REINDEX TABLE CONCURRENTLY mybrokentable;"
        ],
        "see_also": [
            {
                "name": "CREATEINDEX",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/CREATEINDEX/7/json"
            },
            {
                "name": "DROPINDEX",
                "section": "7",
                "url": "https://www.chedong.com/phpMan.php/man/DROPINDEX/7/json"
            },
            {
                "name": "reindexdb",
                "section": "1",
                "url": "https://www.chedong.com/phpMan.php/man/reindexdb/1/json"
            }
        ],
        "section_outline": [
            {
                "name": "NAME",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SYNOPSIS",
                "lines": 8,
                "subsections": []
            },
            {
                "name": "DESCRIPTION",
                "lines": 19,
                "subsections": []
            },
            {
                "name": "PARAMETERS",
                "lines": 52,
                "subsections": []
            },
            {
                "name": "NOTES",
                "lines": 58,
                "subsections": [
                    {
                        "name": "Rebuilding Indexes Concurrently",
                        "lines": 91
                    }
                ]
            },
            {
                "name": "EXAMPLES",
                "lines": 22,
                "subsections": []
            },
            {
                "name": "COMPATIBILITY",
                "lines": 2,
                "subsections": []
            },
            {
                "name": "SEE ALSO",
                "lines": 5,
                "subsections": []
            }
        ]
    }
}