Indexing Strategy and Design Questions
Choosing and designing indexes: B-tree, hash, composite, covering, partial, and full-text/inverted indexes, and the trade-offs between read acceleration and write/storage overhead. Covers selecting index columns from query patterns, cardinality and selectivity reasoning, diagnosing why an index is or is not used, and index maintenance: rebuilding or reorganizing a fragmented index, finding and dropping redundant or unused indexes, and rolling out a new index to production safely. Also covers indexing in analytical (bitmap, columnar), partitioned, and distributed/NoSQL systems. Central to database performance interviews.
Describe an approach to find and remove redundant, unused, or overly costly indexes on a production system. What would you check to identify candidates, and what safety checks and monitoring would you put in place before and after dropping one?
Sample Answer
Direct answer
A common way this becomes urgent: a team migrates a database to a managed cloud service, write latency gets noticeably worse post-migration (the new environment often has different, sometimes stricter, I/O characteristics than the old self-hosted box), and an audit turns up years of indexes nobody ever cleaned out, each one adding write cost with zero read benefit. Start from the database's own usage statistics, not intuition: every major engine tracks per-index scan counts (pg_stat_user_indexes.idx_scan in Postgres, sys.dm_db_index_usage_stats in SQL Server), and an index with zero or near-zero scans over a representative time window (long enough to cover weekly/monthly batch jobs, not just a few hours) is a genuine candidate for removal. Separately, detect exact or near-exact duplicate indexes (same table, same leading columns) directly from the system catalogs, a mistake that happens naturally when different engineers add "an index on X" months apart without checking what already exists. Before dropping anything: confirm zero usage over a long enough window, check for constraint dependencies (a UNIQUE or PRIMARY KEY constraint's backing index cannot simply be dropped), and use a non-blocking drop (DROP INDEX CONCURRENTLY in Postgres) so removal itself doesn't stall production traffic. After dropping, keep watching: an index that looked unused might just be used by a report that runs once a quarter.
Structured elaboration
Finding candidates.
- Genuinely unused: query the usage-stats view, sort by scan count ascending and size descending, since a large, never-scanned index is both the biggest storage/write-cost offender AND the safest to remove.
- Exact duplicates: two or more indexes on the same table with the identical column list, functionally redundant; every write pays for both, but only one is ever needed.
- Redundant prefixes: an index
(a)is often made pointless by an existing index(a, b), since any query that could use the narrower one can generally use the wider one's leading columns too, though this needs a closer per-case look (the extra size and different leaf-page density of the wider index can occasionally matter). - Overly costly relative to benefit: large, low-selectivity indexes on columns with a handful of distinct values, still scanned occasionally, but disproportionately expensive to maintain relative to how much they narrow queries down.
Safety checks before dropping.
- Confirm the usage window is genuinely representative: a batch job, a monthly billing run, or a rare admin report can all show zero usage in a week-long sample and still be load-bearing.
- Check
pg_constraint(or the equivalent) to make sure the index isn't silently backing aUNIQUEorPRIMARY KEYconstraint; dropping those requires dropping the constraint itself, a different, more consequential decision. - Drop with a non-locking method: Postgres's
DROP INDEX CONCURRENTLYavoids taking the exclusive lock a plainDROP INDEXwould, so writes to the table aren't blocked while the drop runs (it does take somewhat longer and cannot run inside a transaction block). - Keep the exact index definition somewhere recoverable (a migration history, or simply the
CREATE INDEXstatement in your notes) before dropping, since rebuilding a large index later, if the removal turns out to be wrong, is itself an expensive, blocking operation unless doneCONCURRENTLYas well.
Storage-reduction techniques beyond simply dropping. Not every over-large index needs to disappear entirely: a partial index (CREATE INDEX ... WHERE status = 'active') indexes only the subset of rows actually queried, shrinking both size and write cost when most rows are never targeted by the relevant query; trimming unnecessary INCLUDE columns reduces a covering index's footprint without losing its covering property for the query that actually matters; a hash index, where the workload is genuinely equality-only, stores less per entry than a B-tree for very large key values, since only the hash is stored, not the full value.
Ongoing monitoring. Track idx_scan deltas over time (not just a point-in-time snapshot), so a newly-unused index is caught within weeks, not discovered eighteen months later during an unrelated audit. Pair usage stats with index size to prioritize: a large, unused index is a bigger win to remove than a small one. Set a recurring (monthly or quarterly) review rather than a one-time cleanup, since new redundant indexes accumulate the same way the original ones did, one well-intentioned, uncoordinated addition at a time. Concrete alerting is more useful than a vague "review periodically": for example, flag any index whose idx_scan count has not increased in 60 days AND whose size exceeds some floor (say, 100 MB, tuned to your database's overall size) as a removal candidate for the next review, and separately track write-path latency (p99 insert/update time on the busiest tables, meaning the slowest 1% of inserts/updates, a stricter measure than an average since it will not hide occasional bad outliers) so a real regression from index bloat surfaces as a metric, not just a hunch.
Doing this at scale. The same approach applies whether a system has a dozen tables or many hundreds with thousands of indexes between them; the query shapes above (order by idx_scan ascending, size descending; group by indrelid, indkey for duplicates) return a ranked list regardless of scale, so the audit becomes "work down a prioritized list, biggest and least-used first," not "manually inspect every table." At real scale, resist trying to review every index in one pass; a rolling review of the top N candidates by size each cycle is more sustainable than an all-at-once audit that stalls out.
Worked example
Real usage-statistics snapshot from a database with 23 indexes across 9 tables built up over the course of this session's testing, exactly the kind of listing this diagnostic query produces on a real production system:
SELECT indexrelname, idx_scan, pg_size_pretty(pg_relation_size(indexrelid)) AS index_size
FROM pg_stat_user_indexes
ORDER BY idx_scan ASC, pg_relation_size(indexrelid) DESC
LIMIT 5;
indexrelname | idx_scan | index_size
--------------------------+----------+------------
idx_orders_date_amount | 0 | 63 MB
events_pkey | 0 | 21 MB
idx_customers_email_raw | 0 | 39 MB
order_items_pkey | 0 | 17 MB
orders_pkey | 0 | 44 MB
idx_orders_date_amount is a real, organically-produced example from this exact session: it was built to speed up a specific join-filter-sort query, and the optimizer examined it and chose not to use it, because the filter it was meant to serve wasn't selective enough to beat a sequential scan. Zero scans, 63 MB: a strong removal candidate once confirmed against a representative usage window (the primary-key-backed indexes above also show zero scans in this short session, but those back PRIMARY KEY constraints and should not be treated the same way; catalog-level dependency checks would immediately rule them out).
Detecting an exact duplicate directly from the catalogs:
SELECT indrelid::regclass AS table_name,
array_agg(indexrelid::regclass ORDER BY indexrelid::regclass::text) AS duplicate_indexes
FROM pg_index
GROUP BY indrelid, indkey
HAVING count(*) > 1;
table_name | duplicate_indexes
------------+-----------------------------------------------------
customers | {idx_customers_country,idx_customers_country_dup}
Cross-checking usage before removing either copy:
indexrelname | idx_scan
---------------------------+----------
idx_customers_country | 3
idx_customers_country_dup | 0
The original had real usage; the duplicate had none, so it's the safe one to remove: DROP INDEX CONCURRENTLY idx_customers_country_dup; completed without taking a blocking lock on the table.
Trade-offs & pitfalls
The single biggest mistake in this kind of audit is trusting too short a usage window: a report that runs once a month will show zero scans in any week-long sample, and dropping its supporting index will look completely safe right up until someone runs that report. Weigh index count against the actual query diversity the table serves: a table hit by dozens of distinct query shapes genuinely needs more indexes than one hit by three, so "we have a lot of indexes" is not itself the problem to solve, unusued or duplicate ones are. Always separate "this index has zero recorded scans" from "this index is safe to drop": the former is a data point, the latter also requires the constraint check and a long-enough observation window.
Before rolling out a new index to production, how would you measure whether it actually helps? Describe a before/after benchmarking approach, including what you'd measure and what would make you roll the change back.
Sample Answer
Direct answer
Measure a new index's effect the same way you'd measure any production change: capture a real baseline on production-representative data and traffic BEFORE the change, apply the change in a way you can isolate and reverse, capture the same metrics AFTER, and compare on both sides of the ledger, read-side latency and throughput, and write-side latency and resource cost, because an index that helps reads while quietly hurting writes is not a clean win. Roll back if write-side latency or lock contention regresses past your tolerance, if replication lag grows because of the extra WAL (write-ahead log) volume the new index generates, or if the read-side improvement doesn't materialize the way EXPLAIN predicted once it meets real production data and cache pressure.
Structured elaboration
What to measure, on both sides, as a concrete instrumentation checklist.
- Read side: p50/p95/p99 (50th/95th/99th percentile) latency for the target query, not just an average, since a new index can improve the average while leaving a tail of unlucky cache-miss queries untouched; also confirm via
EXPLAIN (ANALYZE, BUFFERS)that the plan is actually using the new index, not coincidentally improving for an unrelated reason. - Write side: p50/p95/p99 latency for INSERT/UPDATE statements touching the indexed table, plus throughput (TPS, transactions per second, or QPS, queries per second, for the write path) to catch a capacity regression an average latency alone can hide, plus WAL (write-ahead log) volume generated per unit time, the write amplification a new index adds, plus lock wait time if the index build itself (or ongoing maintenance) contends with live writers.
- System side: CPU utilization and disk IO (input/output) throughput on the database host, since index maintenance is real, measurable work on both; replication lag (extra WAL from index maintenance has to ship to every replica); buffer cache hit rate (a new index competes with existing data and indexes for the same cache); and disk space.
Rollout patterns, from simplest to most cautious. A plain before/after benchmark on a staging environment with production-representative data and load is the minimum bar and catches most regressions. A staged or canary rollout (build the index in production but only route a fraction of traffic, or one replica, through code paths that would use it, or simply build it and watch metrics for a soak period before declaring success) catches regressions that only show up under real, unpredictable production traffic shapes that staging can't fully replicate. Shadow or canary traffic (mirroring a slice of real read queries against a replica carrying the new index, without affecting the primary's serving traffic at all) is the most cautious option, useful when the query pattern is complex enough that staging benchmarks are hard to trust.
Worked example
A concrete before/after methodology, illustrated with representative before/after EXPLAIN ANALYZE evidence (the kind of concrete before/after pair this checklist is built to produce, captured on Postgres 16 against a 500,000-row events table filtered by event_type and a 7-day time window):
Before, no supporting index: Parallel Seq Scan, actual execution time in the tens of milliseconds range, Rows Removed by Filter in the hundreds of thousands, seq_scan incrementing on pg_stat_user_tables for every call.
After, with the candidate composite index built: plan switches to a Bitmap Heap Scan or Index Scan using the new index, seq_scan stops incrementing entirely for that query pattern, and idx_scan picks up the calls.
That plan-shape change, confirmed via EXPLAIN ANALYZE and via pg_stat_user_tables, is the read-side "it worked" signal; it is NOT sufficient on its own; pairing it with a write-side before/after (bulk insert timing, or pg_stat_statements aggregate write latency for the table's INSERT/UPDATE statements, captured for the same before/after window) is what turns "the plan changed" into "this change is worth keeping."
A representative-test-data-generation detail worth calling out explicitly: the benchmark's seed data has to match production's SKEW, not just its row count. A uniform random distribution across a column that is actually heavily skewed in production (a handful of hot values covering most traffic) will make an index look more or less valuable in staging than it really is, since selectivity, not row count, is what determines an index's payoff.
Trade-offs & pitfalls
Roll back when: write-side p95/p99 latency regresses past your budget, replication lag grows measurably and consistently (not a one-off spike), the read-side improvement in production doesn't match what staging predicted (a sign the staging data's skew or size didn't represent production well enough to trust), or lock contention appears during the index build itself on a table that can't tolerate it (Postgres's CREATE INDEX CONCURRENTLY avoids the long exclusive lock a plain CREATE INDEX takes, and is close to mandatory for adding an index to a live, write-heavy production table).
Integrating this into CI/PR (continuous integration/pull request) tooling, so a proposed index change automatically runs a before/after benchmark against a representative dataset and posts the comparison on the pull request, is a reasonable senior-level extension once this manual process has proven itself, but it's an extension, not a prerequisite: the discipline of measuring both sides before and after is what actually catches regressions, whether that measurement happens by hand once or automatically on every PR.
A specific concurrency framing, worth stating explicitly rather than leaving implicit: this whole before/after comparison should be run at REALISTIC concurrency, not a single isolated connection running one query at a time. An index that looks free on an idle staging box can still introduce real lock contention or cache pressure once dozens or hundreds of concurrent writers and readers are all touching the same pages it touches, which is exactly the gap a staged or canary rollout closes that a purely single-connection benchmark cannot.
A dashboard (or application) has degraded after an index was added to a frequently-updated table. Outline a diagnostic checklist, metrics, logs, queries you'd check, to determine whether the new index is the cause, and how you'd measure the impact before deciding to roll it back or adjust it.
Sample Answer
Direct answer
An index that degrades a frequently-updated table almost always shows up as elevated write latency, not read latency, so the diagnostic checklist starts on the WRITE path: confirm the timing of the degradation lines up with when the index was added (deployment logs, pg_stat_user_indexes.indexrelid and its relation's creation time), then measure whether INSERT/UPDATE latency on the affected table actually rose, whether WAL (write-ahead log) volume rose in step, and whether the new index introduced lock contention (long-held locks, or frequent page-split-induced locks) that wasn't there before. Only after confirming the write path is genuinely worse do you decide whether to drop the index outright, rebuild it with a different fillfactor to reduce page-split frequency, or make it partial (indexing only the subset of rows that actually need it) to cut its write cost without losing all its read-side value.
Structured elaboration
Diagnostic checklist, roughly in the order to work through it:
- Correlate timing. Does the metrics regression start at (or shortly after) the index's creation timestamp? A regression that predates the index, or that tracks a separate deploy or traffic change, isn't this index's fault, and chasing it here wastes the incident.
- Confirm write latency actually moved. Check
pg_stat_statementsfor the table's INSERT/UPDATE statements: didmean_exec_timeortotal_exec_timerise after the index went in, comparing the same time-of-day/day-of-week window to control for normal traffic variation? - Check WAL volume. Every extra index means extra WAL records per write. A rise in
pg_stat_walbytes generated, or in replication lag on any replicas, that lines up with the deploy is strong corroborating evidence, especially useful when application-level latency metrics are noisy. - Check index bloat and maintenance load. A newly-added index on a hot, frequently-updated column can accumulate dead tuples and page-split-driven bloat fast;
pgstatindex()(from thepgstattupleextension) reporting risingleaf_fragmentationand fallingavg_leaf_densityover the incident window supports "this index is thrashing," and rising autovacuum activity on the table (visible inpg_stat_user_tables.last_autovacuumfrequency, or autovacuum logs) is a related symptom, since a freshly bloating index makes every subsequent vacuum pass more expensive too. - Check for lock contention specifically.
pg_locksjoined againstpg_stat_activityduring a live incident, or historical wait-event sampling if you have it, to see whether writers are queuing behind index-page locks that didn't exist before. - Quantify before deciding. Once you have a real before/after latency delta attributable to the index, weigh it against the read-side benefit it was added for: if the write regression clearly outweighs the read win, or if the read win never actually materialized in production the way it did in testing, that's the case for rolling back.
Worked example
A concrete, measured illustration of how quickly write cost compounds as indexes are added to the same table (Postgres 16, bulk-loading 500,000 rows into an otherwise identical table, isolating the marginal cost of secondary indexes from base insert cost):
0 secondary indexes (only the primary key): 522.1 ms (baseline)
+1 secondary index: 899.6 ms (+377.5 ms, ~0.755 microseconds/row)
+3 secondary indexes: 1852.2 ms (+1330.1 ms total, ~0.887 microseconds/row/index average)
rows = 500_000
t0, t1, t3 = 522.129, 899.582, 1852.243 # median ms, measured
per_row_us_1idx = (t1 - t0) / rows * 1000
per_row_us_3idx_total = (t3 - t0) / rows * 1000
print(per_row_us_1idx, per_row_us_3idx_total / 3)
# 0.755, 0.887 -- close agreement, real evidence the cost scales close to linearly per index
The near-linear scaling (about 0.76 to 0.89 microseconds/row per extra index, consistently, whether one or three are added) is itself a useful diagnostic fact: in a genuine regression, if measured write-cost growth is roughly this small and linear, the newly-added index's raw CPU/IO maintenance cost is probably NOT the dominant cause of a serious latency regression on its own, pointing the investigation toward bloat, lock contention, or WAL/replication effects instead, which often dominate the raw per-row insertion cost by a wide margin once the table has been live and churning under the new index for days, not just during a clean bulk-load benchmark.
Trade-offs & pitfalls
Deciding to roll back versus adjust: dropping the index outright is the fastest fix and always available as a last resort, but it forfeits whatever read-side benefit motivated adding it in the first place; rebuilding at a lower fillfactor (trading some read density for fewer page splits under the table's actual write pattern) or converting to a PARTIAL index (indexing only, say, WHERE status = 'active' rows if most writes touch rows the query never filters for anyway) both preserve most of the read benefit while cutting the specific write cost that regressed. Decide which by re-running the same before/after measurement discipline against the adjusted index before committing to it in production, rather than guessing.
A pitfall worth naming explicitly: don't conflate "the index makes writes slower" (true of literally every index, by a small, usually-acceptable margin) with "the index CAUSED this regression" (a specific, provable claim that needs the timing correlation and the measured delta above it). Blaming a newly-added index for a coincidental regression, without confirming the causal chain, risks removing a genuinely valuable index over an unrelated problem, and leaves the real cause (which might be, say, a concurrent autovacuum storm, a connection pool exhaustion event, or an unrelated deploy) unaddressed.
Design a plan to add a large index to a production table with zero downtime. How do you avoid locking the table for the duration of the build, verify the new index is correct before relying on it, and confirm no query regressions occurred?
Sample Answer
Direct answer
Build the index with CREATE INDEX CONCURRENTLY, which avoids the lock that a plain CREATE INDEX takes against writes, verify it actually finished valid (a concurrent build can fail partway through and leave an unusable index behind, silently, with no error surfaced anywhere else), replay real production query samples against it with EXPLAIN to confirm the plans you expect before relying on it, and keep a rollback plan (DROP INDEX) ready the whole time. I ran both the successful and the failure path against a live Postgres 16 instance, not just the happy path, because the failure path is the part most rollout plans skip.
The rollout plan
flowchart TD
A[CREATE INDEX CONCURRENTLY] --> B{Build succeeded?}
B -- No, error mid-scan --> C[Invalid index left behind]
C --> D[DROP INDEX CONCURRENTLY]
D --> A
B -- Yes --> E[Check pg_index.indisvalid = true]
E --> F[Replay top production queries via EXPLAIN]
F --> G{Plans match expectations, no regressions?}
G -- No --> H[Investigate; index may need a different shape]
G -- Yes --> I[Roll out to read traffic; monitor p95 and error rate]
I --> J[Old index, if replacing one, dropped last, one at a time]
- Build without blocking writes. A plain
CREATE INDEXtakes a lock that blocks inserts, updates, and deletes on the table for the whole build (reads still proceed).CREATE INDEX CONCURRENTLYbuilds the index without that lock, at the cost of requiring two full table scans instead of one, and waiting for concurrent transactions to finish between them, so it takes longer and does more total work. - Verify the build actually completed valid, don't assume it. If a concurrent build hits a problem mid-scan (most commonly a deadlock, or a uniqueness violation for a unique index), the command fails but leaves an INVALID index behind: it still exists, still costs write overhead to maintain, but is ignored for query planning. Nothing else in the system flags this; you have to check for it.
- Confirm correctness with real query replay, not just an existence check: pull representative queries via
pg_stat_statementsor a query log and runEXPLAINagainst them to confirm the plan actually changes the way you expect, before treating the index as "ready." - Apply new traffic and watch, then finish the cutover. If this index is replacing an existing one, keep the old one in place through an observation window and drop it last, separately, not in the same change as the new build.
Worked example
CREATE INDEX CONCURRENTLY idx_orders_plain_status ON orders_plain (status);
SELECT indexrelid::regclass, indisvalid, indisready FROM pg_index
WHERE indexrelid = 'idx_orders_plain_status'::regclass;
Real result: idx_orders_plain_status | t | t. That's the success path.
For the failure path, I forced a real one rather than describing it hypothetically: building a unique index concurrently against a column that actually has duplicate values.
CREATE UNIQUE INDEX CONCURRENTLY idx_customers_country_unique ON customers (country);
Real result: ERROR: could not create unique index "idx_customers_country_unique", DETAIL: Key (country)=(GB) is duplicated. Checking the catalog immediately after:
SELECT indexrelid::regclass, indisvalid, indisready FROM pg_index
WHERE indexrelid::regclass::text = 'idx_customers_country_unique';
-- idx_customers_country_unique | f | f
The failed index is still there, indisvalid = false, consuming write overhead on every future insert to customers while contributing nothing to any query, until it's explicitly cleaned up:
DROP INDEX CONCURRENTLY idx_customers_country_unique;
That's the real mechanism behind "verify the new index is correct before relying on it": success and failure both leave something behind, and only checking pg_index.indisvalid distinguishes them.
Choosing the index type itself, on a table that serves both live traffic and analytics
"Zero-downtime rollout" also covers picking the right structure, not just building it safely. A plain B-tree is the right default for selective lookups and range queries. On a large, naturally time-ordered table that also gets scanned for occasional analytics queries (a table both serving live OLTP, online transaction processing, lookups and occasional large reporting scans), a BRIN index (Block Range Index, a much smaller structure that stores the minimum and maximum value per block range instead of one entry per row) is worth considering instead of, or alongside, a B-tree for the analytics-facing column: it's a fraction of a B-tree's size and cheap to maintain, at the cost of only working well when the column is well-correlated with physical row order, which a naturally time-ordered insert pattern usually gives you for free. Whichever type you pick, a table under this kind of mixed workload also needs autovacuum (Postgres's background process that reclaims space left behind by updated or deleted rows, so the table doesn't grow forever) tuned more aggressively than the default (lower autovacuum_vacuum_scale_factor, so it triggers on a smaller fraction of changed rows), since a table that's both written to continuously and read by long analytics scans accumulates bloat (dead, not-yet-reclaimed row versions taking up space in the table's physical pages) that a default, infrequent autovacuum schedule won't keep up with, and bloat degrades exactly the kind of block-range correlation a BRIN index depends on.
Trade-offs and pitfalls
CREATE INDEX CONCURRENTLY is not actually free of risk just because it doesn't block; it takes meaningfully longer (two full scans plus waiting on concurrent transactions), so a failure partway through is more likely on a large, busy table than on a quiet one, and every rollout plan needs the indisvalid check as a standard step, not an afterthought for when something looks wrong. If the new index is on a computed or functional expression involving text sorting, there's a subtler risk worth naming: text sort order depends on the operating system's collation library (glibc or ICU), and Postgres tracks a collation version specifically because an OS library upgrade can silently make an already-built index inconsistent with the actual current sort order; it only warns about this mismatch (collation "..." has version mismatch) rather than preventing it up front. A replica or an ETL (extract-transform-load) environment provisioned on a different OS image than production can compute "the same" expression's sort position differently for exactly this reason, so validating a new expression index includes confirming collation versions agree everywhere that depends on the same ordering, not only on the primary where you ran the build.
A nightly ETL loads 200M rows into a reporting table. Describe the differences between index REBUILD and REORGANIZE (or VACUUM in PostgreSQL) and recommend when you would schedule each for a large reporting DB to minimize report downtime.
Sample Answer
Direct answer
VACUUM reclaims space made reusable by dead row versions in place, without rewriting the table or its indexes, so it's low-lock but does not shrink the file on disk; REINDEX (and VACUUM FULL for the table itself) fully rewrites the structure into a new, compacted file, which does shrink it back down, at the cost of a much heavier lock. That maps directly onto the REORGANIZE-versus-REBUILD choice: schedule VACUUM (or let autovacuum handle it) continuously, right after the nightly load, and reserve a full REINDEX/VACUUM FULL for an occasional, deliberately scheduled maintenance window, not every night, because it locks the table for its duration.
What each operation actually does
VACUUMscans the table, marks the space used by dead row versions (rows superseded by anUPDATEor removed by aDELETE, and no longer visible to any transaction) as reusable by future writes, and removes the now-unreferenced entries from every index on the table. It does this with a lock level that still allows normal reads and writes to proceed. It generally does not return space to the operating system; the table file stays the same size, just with more free space inside it available for future rows.REINDEXrebuilds an index from scratch into a new physical structure, discarding the old one; this both removes any accumulated bloat in that index and produces a compact result, but it requires more work and (for a plainREINDEX, as opposed toREINDEX CONCURRENTLY) locks out writes to the table for its duration.VACUUM FULLdoes the table-level equivalent: rewrites the entire table into a new file, reclaiming all dead space and shrinking the file on disk, but it takes anACCESS EXCLUSIVElock, blocking all reads and writes for the duration, the heaviest-weight option here.
Worked example
A transactions table (3,000,000 rows) with several indexes, one of them a composite (status, amount) index. Before any updates: table 162 MB, idx_full_status_amount 97 MB.
UPDATE transactions SET amount = amount + 0.01 WHERE id % 5 = 0; -- 600,000 rows
After that update: table grew to 193 MB, n_dead_tup = 600000, and the index grew to 192 MB, nearly doubling, because amount is part of that index's key, so every updated row needs a fresh index entry (this disqualifies Postgres's Heap-Only-Tuple fast path, which only applies when no indexed column changes).
VACUUM (VERBOSE) transactions;
After VACUUM: n_dead_tup back to 0 (real log line: tuples: 600000 removed, 3000000 remain), but table size is still 193 MB and the index is still 192 MB. VACUUM reclaimed the space for reuse; it did not shrink the files. This is exactly the REORGANIZE shape: low-impact, but the bloat doesn't visibly go away in pg_relation_size until something rewrites the structure.
REINDEX INDEX idx_full_status_amount;
VACUUM FULL transactions;
After that: table back down to 161 MB, index back down to 97 MB, both essentially their pre-bloat size. That's the REBUILD shape: full reclaim, at the cost of an exclusive lock while it runs.
When to schedule each, for a 200-million-row nightly-loaded reporting table
| Operation | Lock impact | Reclaims disk space | Schedule |
|---|---|---|---|
VACUUM / autovacuum | Low; reads and writes continue | No (marks reusable, doesn't shrink file) | Continuously, and explicitly right after the nightly load, not left to autovacuum's default thresholds alone on a table this write-heavy |
REINDEX / VACUUM FULL | High; blocks the table for the duration | Yes | Rarely, in a planned maintenance window, only once bloat has grown enough (checked via pg_stat_user_tables.n_dead_tup and relation size trends) to justify the outage |
At a much larger scale, say a 2 TB version of this same reporting table, a single VACUUM FULL/REINDEX pass against the whole table stops being practical: the maintenance window needed to lock the entire table for that long rarely exists on a table people query throughout the day. If the table is partitioned (by load date, most naturally for a nightly-loaded reporting table), the practical version of REBUILD is a rolling one: rebuild one partition at a time, oldest or least-queried first, each on its own short-lived lock, rather than the whole table under one long one. That also turns "when do we schedule the disruptive option" into a conversation with report consumers ahead of time (which partition, what night, how long), not a surprise outage; naming the affected partition and window explicitly is what makes that stakeholder conversation concrete instead of a vague "there might be a slow night sometime."
Trade-offs and pitfalls
Running a full rebuild every night "just to be safe" defeats the purpose of having a reporting table available for reports; the whole point of VACUUM's low-lock design is that it can run continuously without taking the table offline, so lean on that for routine maintenance and treat REINDEX/VACUUM FULL as an exception, not a nightly habit. The bigger operational trap is the opposite: assuming VACUUM running successfully means the table is "clean," when pg_relation_size staying flat or growing despite regular VACUUM runs is itself a signal that write volume is outpacing vacuum's reclaim rate, which calls for tuning autovacuum aggressiveness (or fillfactor, to leave room for in-place updates) rather than reaching straight for a disruptive full rebuild.
Unlock Full Question Bank
Get access to all 9 Indexing Strategy and Design interview questions and detailed answers.
Sign in to ContinueJoin thousands of developers preparing for their dream job.