📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

What is index fragmentation in SQL Server, and what does fill factor do? Explain page splits, logical fragmentation versus page density, rebuild versus reorganise, whether fragmentation still matters on SSDs and Azure SQL, and what index maintenance strategy you would actually run.

Covers page splits, logical fragmentation and low page density, fill factor trade-offs, REBUILD versus REORGANIZE (online, resumable, statistics side effects), why fixed 5%/30% thresholds are outdated on SSD storage, and a measured maintenance strategy for SQL Server and Azure SQL.

Mid-Level Theory Intermediate azure-sql fill-factor fragmentation index-maintenance indexes sql-server

🎯 Key points

  • Page split: inserting into a full page moves about half its rows to a new page; logged and costly
  • Logical fragmentation = pages out of key order; page density = how full pages are
  • On SSDs logical fragmentation matters little; low page density still wastes I/O and buffer pool memory
  • Fill factor 0 and 100 are equivalent (pages filled completely, the default); it is applied only at create or rebuild
  • Lower fill factor (e.g. 85-90) only for indexes with measured mid-page splits: random keys, rows widened by updates
  • REORGANIZE: always online, interruptible, compacts leaf pages, does not update statistics
  • REBUILD: recreates the index, updates statistics with full scan; ONLINE and RESUMABLE in Enterprise and Azure SQL
  • No fixed 5%/30% thresholds: measure density and query impact; statistics usually matter more

⏱ 30-second answer

Fragmentation comes from page splits: inserting into a full page moves about half its rows to a new page. You end up with logical fragmentation (pages out of key order) and low page density (half-empty pages).

On modern SSD storage, out-of-order pages barely matter; page density does, because half-empty pages mean more reads and more buffer pool memory for the same rows.

  • Fill factor leaves free space at rebuild time to absorb inserts; the default (0/100%) is right for ever-increasing keys.
  • REORGANIZE is online and interruptible but doesn't update statistics; REBUILD recreates the index and updates statistics, online and resumable in Enterprise and Azure SQL.

Trade-off: maintenance costs log, I/O and time; I measure the benefit rather than rebuilding on fixed 5%/30% thresholds, and I prioritise statistics updates.

🗣 Full answer (senior)

How I would answer this in an interview

"Fragmentation mostly comes from page splits. If a row has to go into a page that's already full, which happens with random keys like NEWID, or when updates make rows wider, SQL Server allocates a new page, moves roughly half the rows across, and fixes up the links. That's expensive and fully logged, and it leaves two kinds of damage. Logical fragmentation means the next page in key order isn't the next page physically. Low page density means pages are only half full.

The old advice was reorganise above 5% fragmentation and rebuild above 30%, every night. On spinning disks out-of-order pages broke read-ahead, so it made sense. On SSDs and in Azure SQL, logical fragmentation barely affects performance. Page density still matters: a table at 50% density takes twice the pages, twice the reads for a scan and twice the buffer pool memory. Microsoft's current guidance reflects that: don't run maintenance on fixed thresholds, measure whether it actually helps. REORGANIZE compacts and reorders leaf pages, is always online and can be stopped, but doesn't update statistics. REBUILD recreates the index from scratch and updates its statistics with a full scan; it can be online and resumable on Enterprise edition and Azure SQL.

The mistake I see is nightly rebuilds of everything, which burn log, inflate backups, push secondaries behind and mostly 'fix' performance by accidentally refreshing statistics. Lowering fill factor everywhere is the other one: 80% on an identity-keyed index just makes it 20% bigger for nothing. For example, at [company] we [replaced nightly rebuilds of everything with statistics updates plus targeted rebuilds of a few low-density indexes, and cut the maintenance window from hours to minutes]. Keep statistics fresh, keep density high where it matters, and stop defragmenting for its own sake."


Two kinds of fragmentation

Logical fragmentation Low page density
What it is Pages out of key order Pages partly empty
Measured by avg_fragmentation_in_percent avg_page_space_used_in_percent (SAMPLED/DETAILED mode)
Hurts on HDD Yes (breaks sequential read-ahead) Yes
Hurts on SSD / Azure SQL Little Yes: more pages to read and cache
Fixed by REORGANIZE or REBUILD REORGANIZE (compacts) or REBUILD

REORGANIZE vs REBUILD

REORGANIZE REBUILD
Online Always ONLINE = ON (Enterprise, Azure SQL)
Interruptible Yes, keeps work done RESUMABLE = ON (2017+, Azure SQL)
Statistics Not updated Updated with full scan
Fill factor Uses the existing setting Applies a new one
Log Can generate more log on heavily fragmented indexes Minimal logging possible in SIMPLE/BULK_LOGGED (offline)
Columnstore Compresses delta stores, merges rowgroups Full recreate

Production example

A nightly job rebuilt every index over 30% fragmentation: 3 hours, 400 GB of log, and availability group secondaries lagging into business hours. Replacing it with statistics updates on changed tables plus REBUILD only for indexes under 70% page density cut the job to 20 minutes and log to 25 GB, with no measurable change in query durations in Query Store.

🔍 What the interviewer is checking

Checks whether the candidate understands what fragmentation physically is and has an evidence-based, modern maintenance approach rather than a folklore schedule.

Green flags

  • Explains page splits and distinguishes logical fragmentation from page density
  • Knows why SSDs changed the advice
  • Knows REORGANIZE vs REBUILD differences including statistics
  • Uses fill factor selectively and measures splits

Red flags

  • "Rebuild above 30%, reorganise above 5%, every night" with no nuance
  • Sets fill factor to 80 everywhere
  • Unaware of the lock and log impact of rebuilds

📚 Learn in depth

1. What a page split does

Before: page 100 [A B C D E F G H] full     Insert 'D2'
After:  page 100 [A B C D D2]  --next--> page 731 [E F G H]  --next--> page 101
         ~55% full                        ~50% full    (731 is physically elsewhere)

The split allocates a new page, moves rows, updates the parent level and the prev/next links, all logged. Appending at the end of an ever-increasing key is a cheap 'good split' (new empty page); splits in the middle are the costly ones.

2. Measuring

sys.dm_db_index_physical_stats in LIMITED mode reads only upper levels and returns avg_fragmentation_in_percent; SAMPLED or DETAILED also returns avg_page_space_used_in_percent (density). Mid-page splits show up in sys.dm_db_index_operational_stats.leaf_allocation_count (which includes end-of-index allocations) or precisely via Extended Events on sqlserver.transaction_log with operation = LOP_DELETE_SPLIT.

3. Fill factor

Fill factor (1-100, 0 = 100) is applied only when an index is created or rebuilt. 90 leaves 10% free per leaf page to absorb inserts into the middle. It costs space and reads everywhere, all the time, so lower it only on indexes with measured mid-page splits (random keys, wide updates), and check the effect after a week. PAD_INDEX = ON applies it to intermediate levels too.

4. Why SSDs changed the advice

On HDDs, fragmentation broke large sequential read-ahead I/Os into random seeks. SSDs and cloud storage have near-uniform random access, so out-of-order pages cost little. What remains is page count: a scan of a 50% dense index reads twice the pages and holds twice the memory. That is why Microsoft's guidance (updated 2021) says to measure the benefit of maintenance rather than apply 5%/30% thresholds.

5. Side effects people attribute to defragmenting

A REBUILD updates the index's statistics with a full scan and causes recompilation of plans that use the table. A query that 'got faster after the rebuild' was often fixed by the new statistics or a new plan, not by page order. Test by updating statistics alone first.

6. Azure SQL specifics

Azure SQL Database has no SQL Agent on single databases; schedule maintenance with Elastic Jobs or Azure Automation. Online and resumable operations are available on all tiers. Heavy rebuilds consume log rate, which is capped per service objective, so they can throttle the workload.

Try it yourself

  1. Load 1 million rows into a table clustered on NEWID() and another on IDENTITY; compare fragmentation and density in DETAILED mode.
  2. Rebuild the GUID table with FILLFACTOR = 80, insert 200,000 more rows and compare splits using the Extended Events session below.
  3. Run the same range scan with STATISTICS IO on a 50%-dense and a 100%-dense copy.
  4. Run REORGANIZE and check whether sys.dm_db_stats_properties.last_updated changed; then REBUILD and check again.
  5. Try ALTER INDEX ... REBUILD WITH (ONLINE = ON, RESUMABLE = ON), pause it and resume it.

💻 Code

Measure density and fragmentation, then maintain only what is worth it.

-- Density matters more than order on SSD storage. SAMPLED mode returns page space used.
SELECT OBJECT_NAME(ps.object_id) AS table_name, i.name AS index_name,
       ps.page_count,
       CAST(ps.avg_fragmentation_in_percent  AS decimal(5,1)) AS frag_pct,
       CAST(ps.avg_page_space_used_in_percent AS decimal(5,1)) AS density_pct,
       i.fill_factor
FROM sys.dm_db_index_physical_stats(DB_ID(), NULL, NULL, NULL, 'SAMPLED') AS ps
JOIN sys.indexes AS i ON i.object_id = ps.object_id AND i.index_id = ps.index_id
WHERE ps.page_count > 1000 AND ps.index_level = 0
ORDER BY ps.avg_page_space_used_in_percent;

-- Low density on a large index: rebuild online and resumable (Enterprise / Azure SQL)
ALTER INDEX IX_Orders_CustomerId ON dbo.Orders
    REBUILD WITH (ONLINE = ON, RESUMABLE = ON, MAX_DURATION = 60 MINUTES);

-- Fill factor only where mid-page splits are measured (random-key index)
ALTER INDEX IX_Devices_DeviceGuid ON dbo.Devices REBUILD WITH (FILLFACTOR = 85, ONLINE = ON);

-- Statistics usually matter more than page order
UPDATE STATISTICS dbo.Orders WITH FULLSCAN;
-- Count mid-page (bad) splits per index for an hour
CREATE EVENT SESSION track_page_splits ON SERVER
ADD EVENT sqlserver.transaction_log
(
    WHERE operation = 11   -- LOP_DELETE_SPLIT
      AND database_id = 5  -- replace with DB_ID()
)
ADD TARGET package0.histogram (SET filtering_event_name = 'sqlserver.transaction_log',
                               source_type = 0, source = 'alloc_unit_id');
ALTER EVENT SESSION track_page_splits ON SERVER STATE = START;

In Azure SQL Database there is no SQL Agent, so a small .NET job (run by Elastic Jobs, an Azure Function or a container job) can drive the same logic.

namespace Maintenance;

using Microsoft.Data.SqlClient;

public sealed record IndexTarget(string Schema, string Table, string Index);

public sealed class IndexMaintenance(string connectionString)
{
    // Rebuild only large indexes with low page density; ONLINE and RESUMABLE keep the workload running.
    public async Task RebuildAsync(IEnumerable<IndexTarget> targets, CancellationToken ct)
    {
        await using var conn = new SqlConnection(connectionString);
        await conn.OpenAsync(ct);
        foreach (var t in targets)
        {
            var sql = $"ALTER INDEX {Quote(t.Index)} ON {Quote(t.Schema)}.{Quote(t.Table)} " +
                      "REBUILD WITH (ONLINE = ON, RESUMABLE = ON, MAX_DURATION = 30 MINUTES);";
            await using var cmd = new SqlCommand(sql, conn) { CommandTimeout = 0 };
            await cmd.ExecuteNonQueryAsync(ct);
        }
    }

    // Names come from sys.indexes, but quote them anyway: DDL cannot be parameterised.
    private static string Quote(string name) => "[" + name.Replace("]", "]]") + "]";
}

⚠ Common mistakes

  • Mistake: Rebuilding every index nightly on 5%/30% thresholds. Why it is wrong: on SSD storage it burns log, I/O and AG bandwidth for little gain. Instead: measure density and query impact; maintain selectively.
  • Mistake: Lowering fill factor server-wide. Why it is wrong: every page carries empty space permanently, so all reads and memory grow. Instead: only on indexes with measured mid-page splits.
  • Mistake: Setting fill factor below 100 on identity-keyed indexes. Why it is wrong: inserts go to the end, so the free space is never used. Instead: leave it at 100 (0).
  • Mistake: Crediting a rebuild for a speed-up. Why it is wrong: the rebuild also updated statistics and invalidated plans. Instead: test a statistics update alone first.
  • Mistake: Running REORGANIZE and assuming statistics are fresh. Why it is wrong: REORGANIZE does not update statistics. Instead: pair it with UPDATE STATISTICS where needed.
  • Mistake: Offline rebuilds during business hours. Why it is wrong: they take a schema-modification lock that blocks every query on the table. Instead: ONLINE = ON, RESUMABLE = ON, WAIT_AT_LOW_PRIORITY.
  • Mistake: Only checking avg_fragmentation_in_percent. Why it is wrong: it ignores page density, which is what costs memory on SSDs. Instead: use SAMPLED mode and look at avg_page_space_used_in_percent.
  • Mistake: Defragmenting tiny indexes. Why it is wrong: under about 1,000 pages fragmentation is noise. Instead: filter by page count.

🏛 Senior insight: trade-offs

Index maintenance is a cost that has to earn its keep. I start with statistics (they change plans), then page density on large, frequently scanned indexes, and only then logical fragmentation if storage is still spinning disk. I also check the operational side: log generation, AG redo queues and Azure SQL log rate caps.

Option When it fits Cost When not to
Statistics updates only Most OLTP databases on SSD Small Density has dropped badly on large scanned indexes
REORGANIZE Moderate density loss, no Enterprise online rebuild Online, can be stopped; no stats update Severe fragmentation on huge indexes (slow, log-heavy)
REBUILD ONLINE RESUMABLE Large, low-density indexes; Azure SQL or Enterprise Log, tempdb, CPU Small indexes or during peak load
Lower fill factor Measured mid-page splits on random keys Permanent extra space Ever-increasing keys
Fix the key (sequential instead of random) Splits are the root cause Schema migration Key is a fixed external contract

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions random GUID keys causing page splits. Why: Checks they connect fragmentation to the key choice that causes it.
    How to answer

    A clustered index stores rows in key order. A random Guid.NewGuid() key sends every insert to a random page, so full pages split (half the rows move to a new page, both writes are logged), page density drops towards ~50–70%, and the index is fragmented. More pages means more I/O and buffer-pool memory for every scan and range seek, and inserts touch pages spread over the whole index instead of a hot last page that stays in cache. Measure it with sys.dm_db_index_physical_stats (avg_fragmentation_in_percent, avg_page_space_used_in_percent, page_count), the Page Splits/sec counter, transaction log growth and insert latency in Query Store. Fixes: an IDENTITY/bigint clustered key, sequential GUIDs (EF Core's default SequentialGuidValueGenerator for SQL Server, NEWSEQUENTIALID(), or Guid.CreateVersion7()), or keep the random GUID as a non-clustered unique key and cluster on something else.

  2. When: Candidate mentions that a rebuild also updates statistics. Why: Checks they understand why statistics often matter more than page order.
    How to answer

    Selectivity is the fraction of rows a predicate returns: OrderId = 5 is highly selective, IsActive = 1 matching 95% of rows is not. Density is 1 / distinct values for a column (or column prefix); a column with 4 statuses has density 0.25.

    SQL Server keeps both in statistics: a header, a density vector for each key prefix, and a histogram of up to 200 steps on the leading column. The optimiser uses the histogram for literals and sniffed parameters and falls back to density for local variables and unknown values.

    An index on a low-selectivity column is often ignored because a seek plus thousands of key lookups costs more than one scan. Trade-off: such columns are useful as part of a composite or filtered index, rarely alone.

🛠 Real-world problems: how you handle them

Nightly index rebuild job overrunning into business hours
Situation
An [insurance claims] system on SQL Server 2022 Enterprise ([2 TB], Always On availability group with a synchronous secondary in [Australia Southeast]) ran a nightly maintenance plan rebuilding every index over 30% fragmentation.
Signals
The job started taking [3+] hours and ran past 7 am; the AG redo queue grew to [40] GB; morning users saw blocking and timeouts, and the log backup chain and storage costs grew.
Investigation
Reviewed job history and `sys.dm_db_index_physical_stats` in SAMPLED mode: most rebuilt indexes were on identity keys with high density, so the work achieved little. Query Store showed no regression on nights when the job failed. A handful of GUID-keyed indexes had 50-55% density and real mid-page splits, confirmed with an Extended Events session on `LOP_DELETE_SPLIT`.
Resolution
Immediate: disabled the rebuild step and kept the statistics step. Real fix: replaced the plan with a job that updates statistics on tables over a modification threshold, and rebuilds online and resumable only indexes over [10,000] pages with density under [70]%, with fill factor 85 on the GUID-keyed ones.
Prevention
Weekly report of index density and job duration; alert on AG redo queue size; Query Store comparison before and after maintenance changes; an ADR documenting the maintenance policy.

How to tell it (STAR)

**S:** At [company] our nightly index maintenance was running past 7 am and backing up the availability group. **T:** I needed to cut the job without making queries slower. **A:** I measured page density instead of just fragmentation, showed with Query Store that nights without rebuilds had no regressions, kept statistics updates, and replaced blanket rebuilds with online, resumable rebuilds of the few low-density GUID indexes, which I gave a lower fill factor. **R:** The job went from [3] hours to [20] minutes, log generation dropped by about [90]%, and query durations didn't change.

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me