In SQL Server, how do ALTER INDEX REBUILD and ALTER INDEX REORGANIZE differ, and which would you run on a busy table?
answer
- re-create versus tidy the leaf
- which one is always online
- the statistics side effect
- pausing a long rebuild
basics
~20 sREORGANIZE reorders and compacts only the leaf level, is always online and keeps its progress if stopped. REBUILD re-creates the whole index and refreshes its statistics, but blocks the table unless run with ONLINE = ON, an Enterprise feature.
solid answer
~50 s`ALTER INDEX ... REORGANIZE` puts leaf pages back in logical order and compacts them to the index's fill factor. It is always online, holds only short-lived locks, keeps its progress if you cancel it, and doesn't update statistics. `ALTER INDEX ... REBUILD` builds a new copy of the index: it removes fragmentation at every level, can set a new `FILLFACTOR`, needs room for two copies, and updates the index's statistics with the equivalent of a full scan. Offline, a rowstore rebuild holds a schema-modification (`Sch-M`) lock that blocks all access for the whole run. `ONLINE = ON`, available in Enterprise edition, keeps the table usable and needs short locks only at the start and end, and `RESUMABLE = ON` lets you pause and resume it. On a busy table I'd start with `REORGANIZE`, which Microsoft's guidance prefers unless there's a specific reason to rebuild, and check whether the real win was fresh statistics.
code
sql · 15 lines-- First choice: always online, keeps progress if cancelled
ALTER INDEX IX_Orders_CustomerId ON dbo.Orders REORGANIZE;
-- Online rebuild that waits politely for its locks (Enterprise edition)
ALTER INDEX IX_Orders_CustomerId ON dbo.Orders
REBUILD WITH (ONLINE = ON (WAIT_AT_LOW_PRIORITY (MAX_DURATION = 5 MINUTES, ABORT_AFTER_WAIT = SELF)));
-- Large index: resumable, pauses itself after four hours
ALTER INDEX PK_Orders ON dbo.Orders
REBUILD WITH (ONLINE = ON, RESUMABLE = ON, MAX_DURATION = 240);
-- From another session
ALTER INDEX PK_Orders ON dbo.Orders PAUSE;
SELECT name, state_desc, percent_complete FROM sys.index_resumable_operations;
ALTER INDEX PK_Orders ON dbo.Orders RESUME;go deeper
Know that SQL Server has two maintenance commands, that REORGANIZE is lighter and always online, and that REBUILD re-creates the index.
Compare them on scope, locking, interruption, statistics and fill factor, and explain why an offline rebuild blocks the table.
Plan maintenance for a live system: measure before acting, try statistics first, use ONLINE with WAIT_AT_LOW_PRIORITY and RESUMABLE for large indexes, and know the edition limits.
Replace blanket nightly rebuilds with a measured policy: which indexes earn maintenance, how much log and replica lag it may cost, and how its effect on queries is checked.
## What each statement does Both statements reduce **fragmentation** (pages out of logical order) and raise **page density** (how full pages are), but they work very differently. | | `REORGANIZE` | `REBUILD` | | --- | --- | --- | | Method | Reorders and compacts existing leaf pages | Builds a new copy, then drops the old one | | Levels fixed | Leaf level only | Every level | | Online | Always | Only with `ONLINE = ON` | | If cancelled | Work done so far is kept | Rolled back, unless resumable | | Statistics | Not updated | Updated, as with a full scan | | Fill factor | Compacts to the existing one | Can set a new `FILLFACTOR` | | Extra space | A few work pages in the same file | Room for a second copy of the index | For heaps, neither applies: a heap is rebuilt with `ALTER TABLE ... REBUILD`, which also removes forwarded records. ## Locks: offline, online and the moment at the end - **Offline rebuild** of a clustered or nonclustered rowstore index takes a schema-modification (`Sch-M`) lock for its whole duration. Nobody can read or write the table, whatever their isolation level. - **Online rebuild** (`ONLINE = ON`, default `OFF`) holds only an intent-shared (`IS`) lock during the main phase. It needs a short shared (`S`) lock at the start and a short `Sch-M` lock at the end. Meanwhile every change to the indexed columns is applied to both copies, so writes get somewhat slower while it runs. - Even a short `Sch-M` request has to wait for running transactions on the table, and requests that arrive behind it wait too. `WAIT_AT_LOW_PRIORITY (MAX_DURATION = n MINUTES, ABORT_AFTER_WAIT = NONE | SELF | BLOCKERS)` lets the rebuild wait at low priority and then keep waiting, give up, or kill the blockers. Online index create and rebuild, and resumable operations, are **Enterprise edition** features (also in the Developer and Evaluation editions built on it); Standard and Express can rebuild only offline. `REORGANIZE` is online in every edition. ## Resumable rebuilds `RESUMABLE = ON` (SQL Server 2017 and later for rebuild; 2019 and later for `CREATE INDEX`) makes an online rebuild pausable: 1. It requires `ONLINE = ON`, can't be used with `ALL`, doesn't support `SORT_IN_TEMPDB = ON`, and can't run inside an explicit transaction. 2. `MAX_DURATION = n MINUTES` (up to 10,080, one week) pauses it automatically when the time runs out. 3. `ALTER INDEX ... PAUSE`, `RESUME` and `ABORT` control it; `sys.index_resumable_operations` shows its `state_desc` and `percent_complete`. 4. Statistics are updated with default sampling, not a full scan. 5. While it's paused, writes still maintain both copies and both use disk space, so the documentation says to abort a resumable operation you don't intend to finish rather than leave it paused. ## Choosing on a busy table Microsoft's current guidance is explicit: reorganize is the preferred method unless there's a specific reason to rebuild, and maintenance decisions shouldn't rest on fixed fragmentation thresholds alone. In practice: - **Measure first** with `sys.dm_db_index_physical_stats`, and check that queries actually got slower. - **Try `UPDATE STATISTICS`** before rebuilding. A rebuild's benefit is often its full-scan statistics update and the recompiles that follow, which costs minutes instead of hours. - **Reorganize** the indexes the slow queries use. It can be stopped and restarted; it needs `ALLOW_PAGE_LOCKS = ON` and free space in the data file that holds the index (otherwise error 1105). - **Rebuild online** when you need every level fixed or a new fill factor or compression setting, with `WAIT_AT_LOW_PRIORITY` and, for large indexes, `RESUMABLE = ON`. On a partitioned index, rebuild only the partition that needs it. ## Details that catch people - Rebuilding the **clustered** index doesn't rebuild the nonclustered indexes; creating or dropping a clustered index does. - `ALTER INDEX ALL ... REBUILD` drops and rebuilds every index on the table in one operation. - An **offline** rebuild can sometimes repair an inconsistent nonclustered index; an online rebuild can't, because it builds from the existing index. - For **columnstore** indexes, `REORGANIZE` also compresses closed delta rowgroups (all of them with `COMPRESS_ALL_ROW_GROUPS = ON`) and removes deleted rows, which makes a rebuild rarely necessary. A rule like "rebuild over 30%, reorganize over 5%" is the classic thing to say in an interview; the current documentation expects you to measure instead.
- Why does an index rebuild often seem to fix a slow query, and what should you try first?A rowstore rebuild updates the index's statistics by scanning every row, like UPDATE STATISTICS WITH FULLSCAN, and plans that use those statistics recompile. The improvement is often the better plan, not the defragmented pages. Updating statistics gives the same benefit in minutes, so try it first and measure before and after.
- What does ONLINE = ON still lock, and how do you keep it from hurting the workload?It takes a short S lock at the start and a short Sch-M lock at the end. Those requests queue behind running transactions, and new requests queue behind them. WAIT_AT_LOW_PRIORITY with MAX_DURATION and ABORT_AFTER_WAIT lets the rebuild wait at low priority, then give up (SELF), kill blockers (BLOCKERS) or keep waiting (NONE).
- How do you defragment a heap in SQL Server?Not with ALTER INDEX, which works on indexes. Use ALTER TABLE ... REBUILD, which rewrites the heap, compacts its pages and removes forwarded records left by updates that outgrew their pages. Creating and then dropping a clustered index has the same effect but rebuilds the nonclustered indexes twice.
- REORGANIZE locks the table, so it needs a maintenance window.
- REBUILD WITH (ONLINE = ON) takes no locks at all.
- Always rebuild above 30% fragmentation and reorganize between 5% and 30%.
- REORGANIZE updates statistics just like REBUILD does.
- Rebuilding the clustered index also rebuilds every nonclustered index.