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

📚 Interview question

How do you choose a primary key and clustered key for a SQL Server table? Compare int and bigint identity with GUIDs (NEWID, NEWSEQUENTIALID and version 7), natural versus surrogate keys, and explain what makes a good clustered index key.

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).

Mid-Level Theory Intermediate clustered-index database-design guid identity primary-keys sql-server

🎯 Key points

  • Primary key (logical identity) and clustered key (physical order) are separate choices
  • Good clustered key: narrow, unique, static, ever-increasing
  • Clustered key is copied into every non-clustered index as the row locator
  • int (4 bytes, 2.1 billion) vs bigint (8 bytes): plan for exhaustion
  • NEWID causes page splits and fragmentation; NEWSEQUENTIALID only as a DEFAULT
  • Version 7 GUIDs (Guid.CreateVersion7, .NET 9+) are time-ordered but SQL Server sorts uniqueidentifier from the last 6 bytes, so they insert randomly
  • Surrogate key plus a unique constraint on the natural key
  • Do not expose sequential ints publicly; last-page contention fix OPTIMIZE_FOR_SEQUENTIAL_KEY

⏱ 30-second answer

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.

  • int/bigint IDENTITY: 4 or 8 bytes, ordered inserts; the default for most OLTP tables. Watch int exhaustion at about 2.1 billion.
  • GUIDs: 16 bytes, generated anywhere. 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.
  • Natural keys change; I use a surrogate key plus a unique constraint on the natural key.

Trade-off: ordered keys insert cheaply but can create last-page contention and are guessable.

🗣 Full answer (senior)

How I would answer this in an interview

"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 options

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

When the PK should not be clustered

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

Production example

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.

🔍 What the interviewer is checking

Checks whether the candidate understands the physical consequences of key choice in SQL Server, not just "int or GUID" preferences.

Green flags

  • Separates primary key from clustered key
  • Explains the clustered key being copied into every NC index
  • Knows NEWID page splits and the NEWSEQUENTIALID / v7 ordering nuance
  • Uses surrogate keys with unique constraints on natural keys

Red flags

  • "Always use GUIDs, they're unique"
  • Natural keys like email as the PK
  • No awareness of int exhaustion

📚 Learn in depth

1. The clustered key is everywhere

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.

2. Ever-increasing vs random inserts

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.

3. How SQL Server orders uniqueidentifier

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.

4. Last-page insert contention

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.

5. Natural vs surrogate

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.

6. Exposing IDs

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.

Try it yourself

  1. Create two tables with 1 million rows: one clustered on int IDENTITY, one on NEWID(). Compare page counts and avg_fragmentation_in_percent in sys.dm_db_index_physical_stats.
  2. Insert 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.
  3. Repeat with NEWSEQUENTIALID() as a default.
  4. Add three non-clustered indexes to each table and compare their total size.
  5. Check the current identity value against the type's maximum with IDENT_CURRENT for every table in a database you know.

💻 Code

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();
    }
}

⚠ Common mistakes

  • Mistake: Clustering on 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.
  • Mistake: Assuming 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.
  • Mistake: Using an email, ABN or Medicare number as the primary key. Why it is wrong: natural keys change and spread personal data into every child table. Instead: surrogate key plus a unique constraint.
  • Mistake: Choosing 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.
  • Mistake: A wide composite clustered key (e.g. three 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.
  • Mistake: Exposing sequential IDs and relying on obscurity. Why it is wrong: enumeration is trivial. Instead: proper authorisation checks, optionally a separate public identifier.
  • Mistake: Expecting identity values to be gap-free. Why it is wrong: rollbacks and identity caching leave gaps. Instead: never use identity for invoice numbers that must be contiguous.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions page splits from random GUIDs. Why: Checks they can measure the damage with DMVs.
    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 EF Core value generation or HiLo. Why: Checks the EF Core side of key generation.
    How to answer

    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.

    • EF Core's SQL Server provider generates sequential GUIDs client-side by default, ordered the way SQL Server compares 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.
    • Composite keys (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.

🛠 Real-world problems: how you handle them

Int identity about to overflow on an event table
Situation
An audit events table in a [payments] platform on Azure SQL used `int IDENTITY` and had grown to [1.9 billion] rows over [6] years, with [15] million inserts a day.
Signals
A weekly capacity query showed `IDENT_CURRENT` at [89]% of 2,147,483,647; projection gave about [16] days before inserts would fail with arithmetic overflow error 8115.
Investigation
Checked every table with `sys.identity_columns`, found [3] child tables with FKs to the key, and measured the table size with `sp_spaceused`. Tested `ALTER COLUMN` to bigint on a restored copy: it took hours and held a schema modification lock.
Resolution
Immediate: reseeded to negative values (`DBCC CHECKIDENT ... RESEED, -2147483648`) after confirming no code assumed positive IDs, buying years. Long-term: created a new bigint table, dual-wrote through the app, backfilled in batches, then swapped with `sp_rename` in a short window.
Prevention
A daily alert at 70% of any identity type's maximum; a design checklist rule: bigint for append-only tables; a test that fails if a new migration adds an int identity to an events table.

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.

↩ Usually asked after

More in Database Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me