A complete index rebuild means dropping and recreating every index on a table (or across a database), which removes fragmentation and refreshes index statistics. The key condition is that "complete" rarely means "all at once": on SQL Server, Oracle, PostgreSQL, and MySQL the safest complete rebuild is a planned, logged, per-table sequence with tested backups, maintenance-window limits, and a rollback path. The exact commands differ by engine and version, so you check your engine's current documentation before running anything against production.
Indexes are separate physical structures that point back to table rows. Over time, inserts, updates, and deletes leave gaps, out-of-order pages, and stale statistics. A rebuild recreates the structure from scratch, which typically produces tightly packed pages and fresh optimizer statistics. That can speed up reads and shrink index size on disk, but it also takes time proportional to table size, consumes transaction log or write-ahead log space, and can block writers or readers depending on engine and options. The "complete" part of the request is where most incidents happen, because rebuilding every index on a large database in one pass can exhaust disk, logs, or your maintenance window.
What a complete rebuild actually changes, and what it doesn't
Before touching a production system, separate three things people often blend together:
Defragmentation. Rebuilding reclaims empty space inside index pages and reorders pages. The benefit is largest when fragmentation is high and the index is read often. Statistics refresh. A rebuild normally recomputes index statistics, which can change query plans. That's a benefit for stale plans and a risk for plans that were previously stable. Physical layout. Rebuilds can change page density and fill factor, which affects future fragmentation and write cost.
What a rebuild does not do: fix missing indexes, correct bad schema design, or guarantee faster queries. If the workload is dominated by scans on a table with no useful index, a rebuild changes little. Treat the rebuild as maintenance, not tuning.
Fragmentation thresholds are engine-specific and debated. A common practical rule is to reorganize lightly fragmented indexes and rebuild heavily fragmented ones, but the threshold depends on page count, workload, and engine. Small tables often show high fragmentation percentages that are meaningless because they occupy few pages. Filter by page count before deciding what to rebuild.
Prerequisites and a recovery plan before any DDL
Complete these before the first rebuild statement:
1: Confirm backups are recent and restorable. A rebuild that fails mid-way on a large table can leave you waiting on rollback. Verify a restore, not just a backup job's green checkmark. 2: Capture the current index definitions and settings. Script out index definitions, included columns, filters, compression, and fill factor. You need this to prove the rebuild recreated what you intended and to recover from a partial failure. 3: Inventory indexes by size and write activity. Rank tables by total index size and by write volume. The biggest, busiest tables deserve the most caution and the longest window. 4: Check free space in the data file, tempdb or temp tablespace, and the log. Rebuilds can need working space roughly comparable to the index being rebuilt; online rebuilds may need more. Confirm headroom before starting, not during. 5: Choose the window and the concurrency mode. Decide whether the engine supports online rebuilds and whether your edition licenses that feature. Offline rebuilds block access to the table; online rebuilds reduce but don't eliminate blocking. 6: Freeze schema changes and coordinate with application owners. A rebuild that races a deployment or a partition switch creates confusing failures. 7: Set a stop condition. If log usage crosses a threshold you set, or a rebuild runs past its window, stop and reassess rather than pushing through.
The ordered procedure: rebuild one table at a time
The following sequence is engine-neutral in structure; the commands are engine-specific and must be checked against your version's documentation. The point of the order is to make every step reversible and observable.
1: Pick the first target table, smallest meaningful index first. Starting small proves your script, permissions, logging, and monitoring on a low-risk object. A complete rebuild of the whole database is a loop over tables, not a single statement. 2: Script the existing indexes to a file using your engine's metadata views or a schema comparison tool. Read the output; confirm filtered indexes, included columns, and compression settings are captured. 3: Record a baseline. Note index size, fragmentation, and the top queries against the table with their current plans. You'll compare after the rebuild to see whether plans changed. 4: Run the rebuild for that table's indexes, one index or one table at a time. On SQL Server the pattern is ALTER INDEX ... ON ... REBUILD with options for online operation, fill factor, and parallelism; Oracle uses ALTER INDEX ... REBUILD with online and tablespace options; PostgreSQL's REINDEX rebuilds indexes and has a concurrent variant; MySQL and InnoDB rebuild indexes through table rebuild operations or online DDL, depending on version. Use the syntax your documentation specifies for your version. 5: Watch log growth, temp space, blocking, and elapsed time while it runs. If you hit your stop condition, cancel and let the engine roll back cleanly before investigating. 6: Verify the index exists and is valid. Query the catalog for the index, its columns, and its status. Confirm statistics were updated if your process expects that. 7: Compare after-state to baseline. Check size and fragmentation, and compare the captured plans for your top queries. Investigate plan regressions before proceeding to the next table. 8: Repeat for the next table, moving from small to large and from low-write to high-write. Update your run log with elapsed time and space used so you can forecast the remaining tables. 9: Run a final validation pass across the database: all expected indexes present, no invalid or disabled indexes, statistics fresh where required, and application smoke tests passing.
Success looks like this: every index in your inventory exists and is valid, the run log shows each table completed within its window, log and temp usage stayed under your thresholds, and your top-query plans either held steady or improved. A simple check is to re-run the inventory query and diff it against the pre-change scripted definitions; any missing or altered index is a failure to investigate, not a rounding error.
Engine differences that change the plan
The same word, "rebuild," maps to different mechanics and risks:
SQL Server distinguishes reorganize from rebuild. Rebuilds can be offline (blocking) or online (edition-dependent), and partition-level rebuilds are possible. Rebuilding a clustered index rebuilds the table's physical order, which can be a large operation; rebuilding nonclustered indexes separately has different cost. Fill factor and SORT_IN_TEMPDB choices affect tempdb pressure. Oracle supports ALTER INDEX ... REBUILD with ONLINE, and rebuilding can move an index to a different tablespace. Rebuilding a partitioned index has per-partition options, and global versus local indexes behave differently during partition maintenance. PostgreSQL uses REINDEX, which takes locks that block writes for the duration unless you use the concurrent form (REINDEX ... CONCURRENTLY), which is slower and can fail partway, leaving an invalid index that must be dropped and rebuilt. It also can't run inside a transaction block. Version matters: newer releases have expanded concurrent options for different object types. MySQL/InnoDB rebuilds indexes as part of table rebuild operations; online DDL support and the exact locking behavior depend on version and operation. Some rebuilds copy the table, which needs free disk roughly equal to the table size.
A "complete" rebuild script written for one engine will not transfer cleanly to another. Port the sequence, not the syntax.
Online versus offline: the trade-off that decides your window
Offline rebuilds are simpler and often faster per index, but they take locks that block reads or writes on the table. Online rebuilds keep the table available for most operations, at the cost of longer runtime, more log and temp usage, and residual blocking during phases that still require brief locks.
| Criterion | Offline rebuild | Online rebuild |
|---|---|---|
| Table availability | Blocked for the duration | Mostly available; brief locks possible |
| Runtime | Usually shorter per index | Usually longer |
| Log and temp pressure | Lower | Higher |
| Licensing/edition limits | Usually available | Edition- or feature-gated on some engines |
| Failure behavior | Rolls back; window lost | Can leave intermediate state to clean up |
Choose offline when the table is small, the window is generous, and downtime is acceptable. Choose online when availability dominates and you've confirmed your edition supports it. Neither option removes the need to test on a copy first.
Space, log, and time: a worked estimate
Rebuilds are resource events, so estimate before you run. The inputs you need are the index size, your engine's space behavior for rebuilds, your log growth rate, and your measured throughput from the first table.
As an illustrative calculation, suppose an index is 40 GB, your engine's online rebuild needs working space roughly equal to the index, and your log grows at about the rate the rebuild writes pages. If you measured 200 MB per minute of rebuild throughput on a smaller index, the 40 GB index could take roughly 200 minutes (40 GB divided by 0.2 GB per minute) before accounting for slowdowns from concurrency. Free space should cover the working copy plus headroom, and log capacity should cover the same window with a margin. Label these numbers as estimates from your own measurements; actual throughput varies with hardware, concurrency, and index shape.
Run the arithmetic for the largest three tables before scheduling, and set your stop condition as a percentage of available log or temp space. If the estimate exceeds your window, split the work across nights by table rather than shrinking the safety margin.
Failure modes and how to recover
Log or temp space exhausted mid-rebuild. The statement fails and rolls back; rollback itself can take time. Free space, reduce batch size to fewer or smaller indexes per run, and retry. Invalid index after a failed concurrent rebuild. Drop and rebuild the affected index; don't assume the engine cleaned up. Plan regressions after statistics refresh. Compare captured plans and consider whether updated statistics changed a plan for the worse. You can address this with plan guides, query tuning, or targeted statistics handling depending on engine, but investigate before mass-rebuilding more tables. Blocking incidents. Identify the blocking session and the rebuild phase; if it's an offline rebuild, you may need to cancel and reschedule into a quieter window. Rebuild recreated an index with the wrong settings. Restore from your scripted definitions. This is why step 2 exists.
Stop condition: if a rebuild on a production table runs past its window, or log/temp usage passes your threshold, cancel and roll back rather than letting it run into business hours. If you cannot restore a verified backup or cannot explain a plan regression, stop the rollout and involve your database administrator or the engine vendor's support before continuing.
For very large tables, partitioning changes the calculus: rebuilding partition by partition keeps each operation smaller, and some engines let you switch partitions in and out. That's an advanced pattern worth planning with someone who knows your schema.
Frequently asked questions
Do I need to rebuild every index to consider maintenance "complete"? No. Completing a maintenance cycle means every index in your inventory has been assessed and either rebuilt, reorganized, or deliberately skipped with a reason. Rebuilding low-fragmentation, small, or write-heavy indexes can cost more than it saves.
Can I rebuild indexes while users are working? Often yes, with online rebuilds where your engine and edition support them, but expect longer runtime and some blocking phases. Test on a copy at realistic concurrency first.
How often should a complete rebuild run? There's no universal schedule. Base it on measured fragmentation, page counts, workload, and window capacity, and review after each cycle rather than fixing a calendar interval in advance.
Does a rebuild always improve performance? No. It can refresh statistics and tighten pages, but it can also change plans. Measure before and after with captured plans and query timings.