In PostgreSQL, how does CLUSTER differ from VACUUM FULL, and how much free disk should you plan for each while it runs?
answer
- one reorders, one only compacts
- the order is not maintained
- index scan, or seqscan plus sort
- sort files add to the peak
- indisclustered remembers the index
basics
~20 sBoth rewrite the table into new files under an ACCESS EXCLUSIVE lock and rebuild every index. CLUSTER also orders rows by a chosen index, once only, and its sort can need about twice the table plus indexes; VACUUM FULL just compacts.
solid answer
~40 s`VACUUM FULL` and `CLUSTER table USING index` share one implementation: copy the rows that are live or visible to an open snapshot into a new heap, rebuild every index and swap the files at commit, all under `ACCESS EXCLUSIVE`, with progress in `pg_stat_progress_cluster`. `VACUUM FULL` copies rows in their current physical order with a sequential scan. `CLUSTER` writes them in index order, choosing between an index scan, which needs free disk of at least the table plus its indexes, and, for a B-tree, a sequential scan plus sort, whose temporary files push the peak toward twice the table plus its indexes. The order is not maintained afterwards; PostgreSQL remembers the index (`pg_index.indisclustered`) so a bare `CLUSTER` can redo it, and you should `ANALYZE` afterwards because the planner's correlation statistic has changed.
code
sql · 14 lines-- Order payroll rows by employee and pay period, once
CREATE INDEX payroll_ledger_employee_period_idx
ON payroll_ledger (employee_id, pay_period);
SET maintenance_work_mem = '1GB';
CLUSTER (VERBOSE) payroll_ledger USING payroll_ledger_employee_period_idx;
ANALYZE payroll_ledger;
-- Later: recluster with the remembered index
CLUSTER payroll_ledger;
SELECT indexrelid::regclass AS cluster_index
FROM pg_index
WHERE indrelid = 'payroll_ledger'::regclass AND indisclustered;go deeper
Recall that CLUSTER physically sorts a table by an index once, while VACUUM FULL only compacts it, and that both lock the table completely while they run.
Explain the shared rewrite path, CLUSTER's two read methods, and why the sort method can need about twice the table plus its indexes in free disk.
Show judgment: when ordering by an index pays off for range scans, how to cap disk with enable_sort off, and why you ANALYZE afterwards and expect the order to decay.
Weigh whether physical order is worth a recurring exclusive-lock maintenance job, or whether index design or partitioning gives the same locality without rewrites.
## One implementation, two commands `VACUUM FULL` and `CLUSTER` run the same code in PostgreSQL. Both copy the table into a new heap file, keep every tuple that is live or still visible to an open snapshot, rebuild all of the table's indexes, swap the new files in at commit and release the old ones. Both hold an **`ACCESS EXCLUSIVE`** lock for the entire run, so neither is an online operation, and both report progress in `pg_stat_progress_cluster`. The difference is the order in which rows land in the new file. | | `VACUUM FULL` | `CLUSTER table USING index` | |---|---|---| | Purpose | Compact the table | Compact it and physically order it by an index | | How rows are read | Sequential scan, physical order | Index scan, or for a B-tree a sequential scan plus sort | | Index required | No | Yes: valid, not partial, of an access method that supports clustering (B-tree or GiST; not hash, GIN, BRIN or SP-GiST) | | Peak extra disk | Roughly the table's size (new heap plus rebuilt indexes) | At least table plus indexes; up to about twice the table plus indexes with the sort method | | Remembered for next time | No | Yes: the index is marked `pg_index.indisclustered` | | Lock | `ACCESS EXCLUSIVE` | `ACCESS EXCLUSIVE` | ## Planning the disk The old files cannot be dropped until the new ones are complete, so free space must cover the new copy: 1. **`VACUUM FULL`**: the compacted table plus its rebuilt indexes; the manual's rule of thumb is extra space roughly equal to the table's size. 2. **`CLUSTER` with an index scan**: a temporary copy of the table in index order plus temporary copies of each index, so at least the table size plus the index sizes. 3. **`CLUSTER` with a sequential scan and sort**: the sort also writes temporary files, so the peak can reach about **twice the table size plus the index sizes**. This method is often faster, and the planner picks it from its cost estimates. If the disk cannot take it, `SET enable_sort = off` in the session before `CLUSTER` rules it out. Raising `maintenance_work_mem` for the session (default `64MB`) helps both the sort and the index rebuilds. `CLUSTER (VERBOSE)` prints which method it chose, for example a line ending in `using sequential scan and sort`. ## The order does not last `CLUSTER` is a one-time sort, not a clustered index that keeps the table ordered: - New rows, and new versions of updated rows, go wherever the free space map finds room, so the physical order decays with every write. - A `fillfactor` below 100 slows the decay, because updated versions can then stay on their original page; how fillfactor and HOT updates work is a storage subject of its own. - PostgreSQL remembers the index, so a bare `CLUSTER payroll_ledger` reclusters with it, and `CLUSTER` with no table name reclusters every previously clustered table you are allowed to cluster; that form cannot run inside a transaction block. `ALTER TABLE ... CLUSTER ON` and `SET WITHOUT CLUSTER` change or clear the remembered index without rewriting anything. - Run `ANALYZE` afterwards: the correlation statistic for the indexed column has changed, and stale statistics can keep the planner from choosing the newly cheap index range scans. ## Choosing between them For a payroll ledger that doubled on disk after a one-off backfill, the question is whether order buys anything: - If reports read one employee's entries across many pay periods, `CLUSTER payroll_ledger USING payroll_ledger_employee_period_idx` puts those rows on a few adjacent pages, so the same rewrite also cuts the I/O of every such range scan. - If access is by single-row key lookups, order is irrelevant and `VACUUM FULL` is the simpler rewrite, with no sort files to plan disk for. - If neither exclusive lock is acceptable, both are ruled out, and an online tool such as `pg_repack`, which can also order by an index or by columns, is the usual route. On a partitioned table, `CLUSTER` processes each partition using its partition of the named partitioned index; the index cannot be omitted there, and that form cannot run in a transaction block either.
- How do you cap CLUSTER's peak disk use in PostgreSQL when the sort method would not fit on the volume?Run `SET enable_sort = off` in the session before `CLUSTER`. The planner can then not choose the sequential-scan-and-sort method, so `CLUSTER` reads the table through the index and needs about the table plus its indexes instead of up to twice the table plus its indexes. The index-scan method is often slower, especially when the current physical order is far from index order.
- Why does CLUSTER refuse some indexes in PostgreSQL?The index must be valid, must not be partial, and its access method must support clustering: B-tree and GiST do, while hash, GIN, BRIN and SP-GiST do not. The errors read `cannot cluster on partial index`, `cannot cluster on invalid index` or `access method does not support clustering`. A bare `CLUSTER table` also fails with `there is no previously clustered index` if no index was ever marked.
- CLUSTER keeps the table sorted as new rows arrive, like a clustered index
- CLUSTER runs online because it reads the table through an index
- VACUUM FULL also reorders the rows by primary key
- CLUSTER and VACUUM FULL always need the same free disk
- No ANALYZE is needed after CLUSTER because the data did not change