An orders table in SQL Server is clustered on a uniqueidentifier key defaulted to NEWID() and fragments within hours of each rebuild; how do you diagnose and fix it?
answer
- inserts land anywhere in the key range
- page density, not only fragmentation
- narrow, unique, static, ever-increasing
- a separate surrogate to cluster on
basics
~20 sNEWID() values are random, so SQL Server inserts land mid-index and split full pages, leaving half-empty, out-of-order pages. Confirm it with sys.dm_db_index_physical_stats, then cluster on a bigint IDENTITY and keep the GUID as a nonclustered primary key.
solid answer
~50 sRandom `NEWID()` values put each new row somewhere in the middle of the clustered index, so full pages split: SQL Server moves about half the rows to a new page, leaving two half-full pages out of logical order. I'd confirm it with `sys.dm_db_index_physical_stats` in `SAMPLED` or `DETAILED` mode, looking for `avg_page_space_used_in_percent` falling and `avg_fragmentation_in_percent` climbing, and with `leaf_allocation_count` in `sys.dm_db_index_operational_stats`. The lasting fix is the clustering key: make the GUID primary key `NONCLUSTERED` and cluster on a narrow, unique, never-updated, ever-increasing `bigint IDENTITY`, which also shrinks the row locator in every nonclustered index from 16 bytes to 8. If the GUID has to stay the clustering key, `DEFAULT NEWSEQUENTIALID()` makes inserts mostly ascending, and a fill factor in the 70-95 range plus regular rebuilds buys headroom. The flip side is that sequential keys concentrate inserts on the last page; from SQL Server 2019, `OPTIMIZE_FOR_SEQUENTIAL_KEY = ON` helps with that.
code
sql · 12 linesCREATE TABLE dbo.Orders
(
OrderSeq bigint IDENTITY(1, 1) NOT NULL,
OrderId uniqueidentifier NOT NULL
CONSTRAINT DF_Orders_OrderId DEFAULT NEWID(),
CustomerId int NOT NULL,
CreatedAt datetime2(3) NOT NULL,
CONSTRAINT PK_Orders PRIMARY KEY NONCLUSTERED (OrderId)
);
CREATE UNIQUE CLUSTERED INDEX CIX_Orders_OrderSeq
ON dbo.Orders (OrderSeq);go deeper
Recall that a clustered index keeps rows in key order, so random keys insert in the middle and sequential keys append at the end.
Explain a page split and its two costs, low page density and fragmentation, and name the DMV and mode that measure them.
Lay out the fix with its costs: a surrogate clustering key with a nonclustered GUID primary key, NEWSEQUENTIALID's caveats, fill factor's read penalty, last-page contention, and how to make the change on a live table.
Turn this into a schema rule, such as what new tables cluster on and when a GUID may be the clustering key, so the team stops relearning it table by table.
## What NEWID() does to a clustered index A SQL Server clustered index keeps rows in clustering-key order. When the key comes from `NEWID()`, every new value is random, so each insert belongs on some page in the middle of the index. Once that page is full, the engine performs a **page split**: it allocates a new page and moves about half the rows onto it. Two consequences follow: - **Page density drops.** Both pages end up near 50% full, so the same data needs more pages, more I/O and more buffer-pool memory. - **Logical fragmentation rises.** The new page is rarely next to the old one, so range scans jump around instead of reading pages in order. A rebuild packs the pages again, and the next few hours of random inserts split them again. That is the "fragments within hours" pattern. A `uniqueidentifier` is also 16 bytes, twice a `bigint`, and the clustering key is copied into every nonclustered index as its row locator. ## Diagnosing it 1. Measure density and fragmentation with `sys.dm_db_index_physical_stats`. The default `LIMITED` mode returns `avg_page_space_used_in_percent` as NULL, so use `SAMPLED` (a 1% sample) or `DETAILED`. 2. Watch `leaf_allocation_count` in `sys.dm_db_index_operational_stats`. For an index, a leaf page allocation corresponds to a page split; that includes cheap end-of-index allocations, so compare it with the density trend rather than reading it alone. 3. Check the index definition in `sys.indexes`: a clustered primary key on a `uniqueidentifier` column with a `NEWID()` default confirms the cause. ```sql SELECT i.name, ips.index_level, ips.page_count, ips.avg_page_space_used_in_percent, ips.avg_fragmentation_in_percent FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('dbo.Orders'), NULL, NULL, 'SAMPLED') AS ips JOIN sys.indexes AS i ON i.object_id = ips.object_id AND i.index_id = ips.index_id; ``` Microsoft's maintenance guidance notes that in many workloads page density matters more than fragmentation, so read both numbers. ## Fix 1: cluster on a surrogate, keep the GUID as a key The documented properties of a good clustering key are **narrow, unique, ever-increasing, immutable, not nullable and fixed width**. A `bigint IDENTITY` column has all of them; a `NEWID()` GUID fails *narrow* and *ever-increasing*. | Property | `bigint IDENTITY` | `uniqueidentifier` from `NEWID()` | | --- | --- | --- | | Width | 8 bytes | 16 bytes | | Insert position | Always the last page | Anywhere in the index | | Unique, no uniqueifier needed | Yes | Yes | | Hard to guess when shown to clients | No | Yes | So keep the GUID as the public identifier and primary key, declared `NONCLUSTERED`, and add a unique clustered index on the surrogate. The GUID's nonclustered index still takes random inserts, but its rows are only the GUID plus the 8-byte locator, so it is small, and it is where a lower fill factor makes sense. ## Fix 2: keep the GUID, but make it sequential or give it room - `NEWSEQUENTIALID()` generates GUIDs greater than any it generated earlier on that computer since Windows started, so inserts land near the end. It can only be used in a `DEFAULT` constraint on a `uniqueidentifier` column. After a Windows restart the range can start lower, and the next value can be guessed, so the documentation warns against it where privacy matters. GUIDs generated by the application don't benefit. - **FILLFACTOR** leaves free space on each leaf page, which absorbs mid-index inserts for a while. It is applied only when the index is built, rebuilt or reorganized, and it costs reads all the time: a fill factor of 80 needs about 25% more pages for the same rows. The documentation suggests 70-95 for indexes that split heavily, and 100 (or 0, the same thing) everywhere else. ## The flip side: last-page contention An ever-increasing key sends every concurrent insert to the same last page. Under very high concurrency this shows up as `PAGELATCH_EX` waits on that page. From SQL Server 2019 the index option `OPTIMIZE_FOR_SEQUENTIAL_KEY = ON` (default `OFF`) helps improve insert throughput in that case. Diagnosing latch waits in depth belongs with wait statistics; here it is enough to know the trade you are making. ## Making the change on a live table Changing the clustered index rewrites the table and rebuilds every nonclustered index, since their locators change. The steps are: drop the clustered primary key (and any foreign keys that reference it), create the new clustered index, then re-add the primary key as `NONCLUSTERED`. Plan a window for it, or on Enterprise edition use `ONLINE = ON` for the index builds. Rehearse it on a copy, because each step can generate a lot of transaction log and needs room for a second copy of the data.
- Why does a wide or non-unique clustering key also hurt the nonclustered indexes?Every nonclustered row carries the clustering key as its row locator, plus a 4-byte uniqueifier when the clustered index isn't unique and a key repeats. A 16-byte GUID instead of an 8-byte bigint widens every nonclustered index on the table, and updating a clustering key value means updating every nonclustered index too.
- Does lowering FILLFACTOR on the GUID clustered index solve the splits?It only delays them. Fill factor is applied when the index is built, rebuilt or reorganized; inserts then use up the free space and splits resume, so it works only with regular maintenance. It also costs every read: at 80, the same rows need about 25% more pages in storage and in memory.
- Is NEWSEQUENTIALID() a good choice for identifiers that customers can see?Usually not. Each value is greater than the previous one on that machine, so the next value can be guessed, and the documentation warns against it where privacy matters. Its range can also restart lower after Windows restarts. A random GUID as a nonclustered key with a surrogate clustering key avoids both problems.
Filing folders by a random code means opening a full drawer somewhere in the middle and splitting it in two. Numbering folders in arrival order means you only ever add to the back of the last drawer, but then everyone crowds around that one drawer.
- A lower fill factor permanently stops page splits on a random key.
- NEWSEQUENTIALID() values stay ordered across servers and Windows restarts.
- The GUID must be the clustered index because it is the primary key.
- Fragmentation percentage alone shows how badly page splits hurt.
- A nightly rebuild is the fix for random-key page splits.
Assumes SQL Server 2025; the OPTIMIZE_FOR_SEQUENTIAL_KEY index option exists from SQL Server 2019 and is absent in earlier releases.