Covers surrogate versus natural keys, identity integers versus GUID variants, why SQL Server's uniqueidentifier sort order matters for v7 GUIDs, and the properties of a good clustered key (narrow, unique, static, ever-increasing).
I separate two decisions: the primary key (logical identity) and the clustered key (physical row order). A good clustered key is narrow, unique, static and ever-increasing, because it is copied into every non-clustered index.
NEWID() is random and causes page splits; NEWSEQUENTIALID() is ordered but only as a column default. .NET's Guid.CreateVersion7() is time-ordered, but SQL Server sorts uniqueidentifier starting from the last six bytes, so v7 values still insert randomly.Trade-off: ordered keys insert cheaply but can create last-page contention and are guessable.
"I treat it as two decisions. The primary key is the logical identity of the row; the clustered index decides how rows are physically ordered. By default SQL Server makes the primary key clustered, which is usually right, but not always. A good clustered key is narrow, unique, static and ever-increasing, because SQL Server copies it into every non-clustered index as the pointer back to the row. A 16-byte key on a table with six indexes costs real memory and I/O compared with a 4-byte int.
For most OLTP tables I use int or bigint identity. Inserts go to the end of the B-tree, pages fill to 100%, and the key is tiny. I pick bigint when the table might pass about two billion rows in its lifetime, because changing it later is a painful migration. GUIDs make sense when IDs are generated outside the database, like offline clients, merging data from several sources, or when the API needs non-guessable IDs. The catch is NEWID, which is random: inserts land on random pages, cause page splits and fragmentation and hurt buffer pool locality. NEWSEQUENTIALID fixes the ordering but only works as a column default. And there's a subtle trap with .NET 9's Guid.CreateVersion7: it's time-ordered as a string, but SQL Server compares uniqueidentifier starting from the last six bytes, so those values arrive in effectively random order in a clustered index.
The mistake I see is using a natural key like email or ABN as the primary key. Those change, and every foreign key has to change with them. I use a surrogate key and a unique constraint on the natural key. For example, at [company] we [moved a 300 million row table off a NEWID clustered key to bigint identity], and [index size dropped by 40% and insert p95 halved]. Choose the clustered key for the engine; expose a different identifier to users if you need to."
| Key | Size | Insert pattern | Pros | Cons |
|---|---|---|---|---|
int IDENTITY |
4 B | Append | Smallest, fast joins | ~2.1 billion limit, guessable |
bigint IDENTITY |
8 B | Append | Effectively unlimited | Guessable |
SEQUENCE |
4–8 B | Append | Value known before insert, shareable across tables | Gaps on cache and rollback (like identity) |
NEWID() / Guid.NewGuid() |
16 B | Random | Generate anywhere, non-guessable | Page splits, fragmentation, wide NC indexes |
NEWSEQUENTIALID() |
16 B | Mostly append | Ordered | Default only; ordering can restart after a server reboot; partly guessable |
Guid.CreateVersion7() |
16 B | Random in SQL Server's order | Time-ordered elsewhere (Postgres, logs) | Not ordered for SQL Server's uniqueidentifier comparison |
| Natural key (email, ABN) | Varies | Random | Meaningful | Changes, often wide, sometimes personal data |
| Situation | Choice |
|---|---|
| GUID PK you cannot change | Non-clustered GUID PK + clustered index on an identity or date column |
Table almost always read by a range (e.g. TenantId, CreatedAt) |
Cluster on the range key, keep PK non-clustered |
| Very high insert rate on identity (last-page latch contention) | OPTIMIZE_FOR_SEQUENTIAL_KEY = ON (SQL Server 2019+), or hash partitioning |
A telemetry table [you can describe] used a random GUID clustered PK: [300 million] rows, 99% fragmentation within days, and inserts at [25] ms p95 under load. Re-clustering on bigint IDENTITY with the GUID kept as a non-clustered unique key cut index storage by about [40]% and insert p95 to [6] ms.
Checks whether the candidate understands the physical consequences of key choice in SQL Server, not just "int or GUID" preferences.
Green flags
Red flags
In a clustered table the leaf level of the clustered index is the table. Every non-clustered index leaf row stores the clustered key to find the row (a key lookup). So the clustered key's width is multiplied by the number of rows times the number of non-clustered indexes.
NC index IX_Orders_CustomerId leaf: [CustomerId | OrderId] ──key lookup──► Clustered index on OrderId
4 B 4 B (int) vs 16 B (GUID)
If the clustered key is not unique, SQL Server adds a hidden 4-byte uniquifier to duplicates, another reason to choose a unique key.
Identity: [page 1 full][page 2 full][page 3 full][page 4 ← new rows]
Random GUID:[page 1 ← split][page 2 ← split][page 3 ← split] ... every page half full
A random insert into a full page triggers a page split: half the rows move to a new page, both pages are logged, and the index ends up around 50–70% full. More pages mean more reads and more buffer pool memory. Fill factor can soften it but not remove it.
SQL Server compares uniqueidentifier by byte groups in this order: bytes 10–15 (the last 12 hex digits) first, then 8–9, 6–7, 4–5 and finally 0–3. NEWSEQUENTIALID() and EF Core's SequentialGuidValueGenerator produce values that increase in that order. A version 7 GUID puts a 48-bit Unix timestamp in the first 12 hex digits and random bits at the end, so SQL Server effectively sorts it by its random part. If you want v7 for other reasons, generate SQL Server-ordered sequential GUIDs for the clustered key, or cluster on something else.
The flip side of ordered keys: at thousands of inserts per second, every session needs an exclusive latch on the same last page (PAGELATCH_EX waits). SQL Server 2019 added OPTIMIZE_FOR_SEQUENTIAL_KEY = ON on the index, which manages the flow of threads to reduce the convoy. Most line-of-business systems never hit this.
Natural keys (email, ABN, Medicare number) are meaningful but change, can be wide, and may be personal information under the Privacy Act 1988, which you then copy into every child table and log line. A surrogate key plus UNIQUE on the natural key gives stable references and still enforces the business rule.
Sequential integers in URLs invite enumeration (/orders/1001, /orders/1002). Authorisation must stop access anyway, but many teams add a public identifier (a GUID or a short random code) as a separate unique column while keeping the int as the internal key.
int IDENTITY, one on NEWID(). Compare page counts and avg_fragmentation_in_percent in sys.dm_db_index_physical_stats.Guid.CreateVersion7() values from a .NET console app in order and SELECT ... ORDER BY Id: see that SQL Server's order is not insert order.NEWSEQUENTIALID() as a default.IDENT_CURRENT for every table in a database you know.A surrogate clustered key, a natural key enforced as unique, and a public GUID that is not the clustered key.
CREATE TABLE dbo.Customers
(
CustomerId bigint IDENTITY NOT NULL,
PublicId uniqueidentifier NOT NULL
CONSTRAINT DF_Customers_PublicId DEFAULT NEWSEQUENTIALID(), -- only usable as a DEFAULT
Abn char(11) NULL,
Email nvarchar(256) NOT NULL,
CONSTRAINT PK_Customers PRIMARY KEY CLUSTERED (CustomerId),
CONSTRAINT UQ_Customers_PublicId UNIQUE NONCLUSTERED (PublicId),
CONSTRAINT UQ_Customers_Email UNIQUE NONCLUSTERED (Email)
);
-- "Unique when present" for an optional natural key.
CREATE UNIQUE INDEX UX_Customers_Abn ON dbo.Customers (Abn) WHERE Abn IS NOT NULL;
-- How close is each identity to overflow?
SELECT t.name, c.name AS column_name, ty.name AS type_name, IDENT_CURRENT(t.name) AS current_value
FROM sys.identity_columns AS c
JOIN sys.tables AS t ON t.object_id = c.object_id
JOIN sys.types AS ty ON ty.user_type_id = c.user_type_id;
EF Core: keep the long internal key, and let EF generate SQL Server-ordered GUIDs if a GUID must be the key.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Microsoft.EntityFrameworkCore.ValueGeneration;
public sealed class Customer
{
public long CustomerId { get; set; }
public Guid PublicId { get; set; }
public required string Email { get; set; }
}
public sealed class CustomerConfiguration : IEntityTypeConfiguration<Customer>
{
public void Configure(EntityTypeBuilder<Customer> b)
{
b.HasKey(c => c.CustomerId); // bigint identity, clustered
b.HasIndex(c => c.PublicId).IsUnique(); // what the API exposes
// Ordered for SQL Server's uniqueidentifier comparison, unlike Guid.CreateVersion7().
b.Property(c => c.PublicId).HasValueGenerator<SequentialGuidValueGenerator>();
b.HasIndex(c => c.Email).IsUnique();
}
}
NEWID() / Guid.NewGuid(). Why it is wrong: random inserts cause page splits, fragmentation and wide non-clustered indexes. Instead: identity or a SQL Server-ordered sequential GUID, or a non-clustered GUID PK.Guid.CreateVersion7() is sequential in SQL Server. Why it is wrong: SQL Server sorts uniqueidentifier from the last six bytes, where v7 is random. Instead: NEWSEQUENTIALID() or EF Core's SequentialGuidValueGenerator for clustered keys.int for a high-volume event table. Why it is wrong: hitting 2,147,483,647 stops inserts (arithmetic overflow) and changing the type is a big migration. Instead: bigint from day one where growth is plausible, and monitor IDENT_CURRENT.nvarchar columns). Why it is wrong: copied into every non-clustered index. Instead: a narrow surrogate clustered key with a unique index on the composite.The senior move is separating logical identity from physical order and being explicit about both. Most tables want bigint IDENTITY clustered; GUIDs are a deliberate choice for distributed generation or public IDs, with the ordering trap understood.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| bigint IDENTITY clustered | Default OLTP table | Guessable, last-page contention at extreme insert rates | IDs must be created offline or across databases |
| Sequential GUID clustered | IDs created by the app before insert, merged data | 16 B per index row | Tables with many NC indexes and huge row counts |
| GUID PK non-clustered + identity clustered | Existing GUID API contract | Extra index, key lookups via the GUID | Simple internal tables |
| Cluster on (TenantId, CreatedAt) | Range-heavy reads per tenant | Random-ish inserts across tenants | Single-row lookups dominate |
Measure with sys.dm_db_index_physical_stats (page count, fragmentation), sys.dm_db_index_operational_stats (page splits via leaf_allocation_count) and PAGELATCH_EX waits.
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.
Identity int/bigint keys are small (4/8 bytes) and always increasing, so inserts append to the end of the clustered index; the downside is the value only exists after the INSERT. GUIDs can be created anywhere (offline clients, merges, ids before saving) but are 16 bytes, and random GUIDs as a clustered key cause page splits and fragmentation.
uniqueidentifier.Guid.CreateVersion7() is time-ordered by .NET's byte order, but SQL Server compares the last 6 bytes first, so it is not sequential in a SQL Server index.HasKey(x => new { x.A, x.B })), alternate keys (unique, can be FK targets), sequences and HiLo (UseHiLo()) cover the rest.The trade-off: identity is simplest and smallest; GUIDs buy distribution at the cost of size and care with clustering.
How to tell it (STAR)
**S:** At [company] our audit events table was on an int identity and close to two billion rows. **T:** I had to make sure inserts didn't start failing, with about [16] days of headroom. **A:** I checked every identity column against its maximum, tested an in-place ALTER on a restored copy and found it would block for hours, so I reseeded to negative values as a safe stopgap, then led a dual-write migration to a bigint table with a batched backfill. **R:** No insert failed, the cut-over took [4] minutes, and we added an alert at 70% for every identity column.
Last updated 23 Nov 2026.