Scrivio Interview library
DebuggingIntermediate7 min read · updated 12 November 2026

A table clustered on a random UUID primary key (NEWID()) shows heavy page splits, fragmentation above 90 percent and slow inserts. What options do you have, including from a Java application?

Random keys from NEWID() land in the middle of the clustered B-tree, so full pages keep splitting, the index fragments and inserts touch pages all over the disk and buffer pool. We can make new keys arrive in order with NEWSEQUENTIALID() or with a time-ordered UUID generated in Java, as long as its time part sits where SQL Server sorts first, or we cluster on a BIGINT IDENTITY and keep the UUID as a nonclustered unique key for external use. A lower fill factor only reduces splits at the cost of size, and Hibernate's UUID generator can be configured, but check your version and test how its values sort on SQL Server.

Why this question is asked

Using a UUID as a primary key is attractive: ids can be created anywhere, they do not reveal how many orders we have, and they merge easily across systems. In SQL Server, though, the primary key is the clustered index by default, so the key decides where every row is physically stored, and a random key turns every insert into a random write. Interviewers ask this to see whether we can explain the mechanism and choose between real fixes and mitigations. In this answer, we will see why random keys split pages, then go through sequential GUIDs, a surprising catch with UUID version 7 on SQL Server, the IDENTITY plus UUID design, fill factor, and what to do in Java and Hibernate.

1Why Random Keys Split Pages

A clustered index stores rows in key order on 8 KB pages. With an ever-increasing key, every new row goes after the last one, so SQL Server fills the last page and starts a new one: no existing page is disturbed. With NEWID(), each new key is random, so it belongs somewhere in the middle of the index. When that page is full, SQL Server splits it: it allocates a new page, moves about half the rows there and links it into the chain. Each split costs extra writes and log records, and leaves two half-empty pages.

Over time the index is full of half-empty pages whose logical order no longer matches their physical order, which is what a fragmentation figure above 90 percent tells us. Worse, inserts touch random pages across the whole index, so the buffer pool must hold all of them to stay fast; once the index outgrows memory, inserts start waiting on disk reads.

SQL
SELECT avg_fragmentation_in_percent, avg_page_space_used_in_percent, page_count
FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('orders'), 1, NULL, 'SAMPLED');
-- 93.4 61.2 1840220 very fragmented, pages only 61 percent full
Where new keys land
Key sourceInsert positionEffect
BIGINT IDENTITYAlways the last pagePages fill in order, almost no splits
NEWID()Random page in the middleFrequent splits, 90+ percent fragmentation
NEWSEQUENTIALID()Near the endFew splits, except after a restart

2Fix 1: Sequential GUIDs

SQL Server's NEWSEQUENTIALID() generates GUIDs that increase on a given server, so new rows go near the end of the index, like an IDENTITY. It can only be used as a column DEFAULT, not called in a query, and after a server restart the sequence can start from a lower range, so a few splits remain. Its values are also more guessable than NEWID()'s, which matters if the id appears in URLs.

SQL
ALTER TABLE orders ADD CONSTRAINT df_orders_id DEFAULT NEWSEQUENTIALID() FOR id;

The limitation for a Java application is that the database generates the id, so the application must read it back after the insert, just like IDENTITY. If the point of using UUIDs was that the service creates the id before talking to the database, we want to generate a time-ordered UUID in Java instead.

3Fix 2: Time-Ordered UUIDs From Java, and a Catch

UUID version 7 is a standard layout whose first 48 bits are a Unix timestamp in milliseconds, followed by random bits. Compared byte by byte from the left, version 7 values increase over time, which is why they are recommended as database keys. Libraries such as java-uuid-generator or uuid-creator generate them; check whether your JDK version has built-in support.

But there is a catch on SQL Server. The uniqueidentifier type does not sort byte by byte from the left. It compares the last six bytes first, then bytes 8 and 9, then the earlier groups. In a version 7 UUID the last six bytes are random, so stored in a uniqueidentifier column, version 7 values sort almost randomly and we get the same page splits as NEWID(). Version 7 works as intended when stored as BINARY(16), or in PostgreSQL's uuid type, which compares bytes in order.

For a uniqueidentifier clustering key we need a GUID with the time in the last six bytes, the layout often called a COMB or sequential GUID. Here is a small generator that keeps random bits at the front and puts the millisecond time at the end.

Java
// Sequential for SQL Server's uniqueidentifier ordering: time in the last 6 bytes
static UUID sqlServerSequentialUuid() {
UUID random = UUID.randomUUID();
long millis = System.currentTimeMillis();
long lsb = (random.getLeastSignificantBits() & 0xFFFF_0000_0000_0000L) // keep bytes 8-9 (variant)
| (millis & 0x0000_FFFF_FFFF_FFFFL); // bytes 10-15 = time
return new UUID(random.getMostSignificantBits(), lsb);
}
UUID a = sqlServerSequentialUuid(); // ...-...-...-8f3a-0192f6a4c210
UUID b = sqlServerSequentialUuid(); // ...-...-...-b71e-0192f6a4c211 sorts after a in SQL Server

Within the same millisecond the order is random, which causes only a little local splitting. Because the driver converts between Java's UUID and SQL Server's byte layout, it is worth inserting a few thousand ids in a test and checking with ORDER BY id that they come back in creation order on your driver and version.

4Fix 3: Cluster on IDENTITY, Keep the UUID as a Unique Key

The most robust design separates the two jobs of the key. A BIGINT IDENTITY column is the clustered primary key, used internally and in foreign keys, narrow and ever-increasing. The UUID stays as a nonclustered unique index, used in APIs, URLs and messages between services.

SQL
CREATE TABLE orders (
id BIGINT IDENTITY(1,1) NOT NULL,
public_id UNIQUEIDENTIFIER NOT NULL,
-- other columns
CONSTRAINT pk_orders PRIMARY KEY CLUSTERED (id),
CONSTRAINT uq_orders_public_id UNIQUE NONCLUSTERED (public_id)
);
-- lookups by public_id: seek on uq_orders_public_id, then a key lookup by id

The nonclustered UUID index still receives random inserts, but it is small, holding only the 16-byte UUID and the 8-byte id per row, so splits there are much cheaper than splitting full data pages. Every other nonclustered index now carries an 8-byte locator instead of 16 bytes. The cost is a migration if the table already exists, and the extra lookup when we search by public_id.

5Mitigation: Fill Factor and Index Maintenance

If we cannot change the key soon, we can soften the symptoms. Rebuilding the index with a fill factor of, say, 80 leaves 20 percent free space on each page, so random inserts fit for a while before pages split again. The index becomes about 25 percent larger and must be rebuilt regularly to restore the free space. It is a mitigation, not a fix: it trades space and maintenance for fewer splits, and inserts still touch random pages.

SQL
ALTER INDEX pk_orders ON orders REBUILD WITH (FILLFACTOR = 80, ONLINE = ON); -- ONLINE needs Enterprise

6On the Java and Hibernate Side

Hibernate can generate UUIDs itself. With @UuidGenerator (Hibernate 6.2 and later) the default style is random, which behaves like NEWID(). A TIME style exists, and newer versions add further time-based styles; check your version for the exact options. Whatever style we pick, the question for SQL Server is the same as above: do its values sort in creation order as uniqueidentifier? If not, a custom generator such as the one shown, registered through Hibernate's generator API, or the IDENTITY plus UUID design is the safer path.

Java
@Entity
public class Order {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id; // clustered key
@Column(name = "public_id", nullable = false, unique = true, updatable = false)
private UUID publicId = UUID.randomUUID(); // random is fine in a small nonclustered index
}

7Follow-up questions

Is fragmentation itself the problem?

Partly. On modern SSDs the physical out-of-order pages matter less than they did on spinning disks. The bigger costs are the splits themselves, the half-empty pages that waste memory and I/O, and the random access pattern that needs the whole index in memory. Those are what slow the inserts.

Does PostgreSQL have the same problem with random UUIDs?

PostgreSQL tables are heaps, so rows are not stored in key order, but the primary key index is a B-tree with the same random insert pattern and bloat. UUID version 7 helps there directly, because PostgreSQL's uuid type compares bytes in order.

8Conclusion

In this answer, we saw that NEWID() keys land at random positions in the clustered index, causing page splits, heavy fragmentation and random I/O. We can fix it with NEWSEQUENTIALID(), with a time-ordered UUID from Java whose time is placed where SQL Server sorts first, since a standard version 7 UUID does not sort by time in a uniqueidentifier column, or by clustering on a BIGINT IDENTITY and keeping the UUID as a nonclustered unique key. A lower fill factor is only a mitigation, and Hibernate's UUID generation styles should be checked for your version and for how they sort on SQL Server.

What to say in the interviewAbout 90 seconds aloud

Open with

The cause is that the UUID is the clustered key, so its value decides where the row is stored. NEWID values are random, so each insert lands in the middle of the B-tree, full pages split in two, and we end up with pages around 60 percent full, fragmentation above 90 percent, and inserts touching random pages that must all be in memory.

Then, if they want more

I would consider three real fixes. NEWSEQUENTIALID as the column default gives increasing values, though the database then generates the id and it can restart lower after a reboot.

If the Java side must create the id, I would use a time-ordered UUID, but with one catch: SQL Server sorts uniqueidentifier by its last six bytes first, so a standard UUID version 7, which has its timestamp at the front, still sorts randomly there.

For SQL Server I would generate a sequential GUID with the time in the last six bytes, or store version 7 as binary 16, and test the order. The most robust design is a BIGINT IDENTITY clustered primary key with the UUID as a nonclustered unique column for APIs, which also makes every other index smaller.

Lowering the fill factor to around 80 and rebuilding reduces splits but costs space, so it is only a mitigation. In Hibernate, UuidGenerator defaults to random; I would check which time-based styles my version offers and how they sort on SQL Server.

About this answer

Last updated
12 November 2026
Versions it names
Hibernate 6
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A table clustered on a random UUID primary key (NEWID()) shows heavy page splits...": https://scrivio-interview-library.netlify.app/databases/oracle-and-sql-server/aee49d23e3/