Covers the B+ tree layout of SQL Server rowstore indexes, clustered indexes as the table itself, heaps and RIDs, non-clustered indexes and their row locators, and how seeks and lookups find a row.
Both are B+ trees of 8 KB pages: a root, intermediate levels and a leaf level, with leaf pages linked in key order.
To find a row SQL Server seeks from root to leaf (3–4 page reads for millions of rows). If a non-clustered index lacks a column, it does a key lookup into the clustered index. The trade-off: every extra index speeds reads and slows writes.
"Both kinds of rowstore index in SQL Server are B+ trees made of 8 KB pages. There's a root page, one or more intermediate levels, and a leaf level where the leaf pages are linked in key order so range scans can walk sideways. The difference is what sits in the leaf.
In a clustered index the leaf level is the table itself: the full rows, stored in clustered key order. That's why you can only have one. A table without a clustered index is a heap: rows go wherever there's room, and SQL Server finds them by a RID, which is file, page and slot. A non-clustered index is a separate structure holding just the index key columns, any included columns, and a row locator back to the base row. On a clustered table that locator is the clustered key; on a heap it's the RID. So if I search orders by CustomerId with a non-clustered index, SQL Server seeks down that tree, finds the matching leaf entries, and if the query needs columns the index doesn't have, it does a key lookup into the clustered index for each row.
The mistake I see is thinking indexes are free or that 'primary key' and 'clustered index' mean the same thing. By default the primary key becomes clustered, but you can choose differently, and every non-clustered index is another copy that inserts, updates and deletes must maintain. An index is a sorted copy of data you pay for on every write so that reads can skip most of the table."
| Clustered index | Non-clustered index | Heap | |
|---|---|---|---|
| Leaf contains | Whole rows | Key + included columns + row locator | Not an index: unordered data pages |
| How many | 0 or 1 | Up to 999 | n/a |
| Row locator | Clustered key | Clustered key or RID | RID (file:page:slot) |
| Range scans in key order | Yes | Yes, on its key | No order |
| Typical use | Almost every OLTP table | Supporting WHERE, JOIN, ORDER BY | Staging tables, bulk loads |
SELECT OrderDate, Total FROM dbo.Orders WHERE CustomerId = 42;
IX_Orders_CustomerId (NC) PK_Orders (clustered on OrderId)
root ─► intermediate ─► leaf ───► root ─► intermediate ─► leaf (full row)
[CustomerId=42, OrderId=1007] key lookup on OrderId=1007
Two or three page reads per tree level, so a lookup into a million-row table is roughly 3 reads for the seek plus 3 per key lookup.
| Fits | Avoid |
|---|---|
| Staging tables loaded then truncated | Tables that are updated (forwarded records) |
| Minimal-logging bulk loads | Tables read by range or joined often |
An orders table with 12 million rows had only a clustered primary key on OrderId. The "orders for this customer" query scanned the whole clustered index: about 95,000 logical reads and 400 ms. Adding a non-clustered index on CustomerId turned it into a seek plus a few key lookups: 15 logical reads and under 2 ms.
Checks that the candidate understands how SQL Server physically stores and finds rows, not just the definitions.
Green flags
Red flags
SQL Server stores data in 8 KB pages grouped into 64 KB extents. A rowstore index is a balanced B+ tree:
[ root page ]
/ | \
[intermediate] [intermediate] [intermediate]
/ \ ... \
[leaf]<->[leaf]<->[leaf]<-> ... <->[leaf] (doubly linked, key order)
Each non-leaf row holds a key value and a pointer to a child page. With a 4-byte int key, one page holds hundreds of entries, so the tree stays shallow: 3 levels covers millions of rows, 4 levels billions. That depth is the cost of a seek.
The clustered index leaf is the data. Rows are logically ordered by the clustered key (physical order on disk can drift, which is what fragmentation measures). If the key is not unique, SQL Server adds a hidden 4-byte uniquifier to duplicate values.
A heap has no order. SQL Server tracks its pages through IAM (Index Allocation Map) pages and finds free space through PFS pages. A row is addressed by its RID (file id, page id, slot). If an update makes a row too big for its page, SQL Server moves it and leaves a forwarding pointer, so later reads take an extra hop. sys.dm_db_index_physical_stats shows forwarded_record_count.
The leaf of a non-clustered index stores the key columns, any INCLUDE columns and the row locator:
When the query needs more columns, the plan shows a Key Lookup (clustered) or RID Lookup (heap) joined with Nested Loops.
The optimiser chooses by estimated cost: a seek plus 50,000 key lookups can cost more than one scan, so it sometimes scans on purpose.
An insert writes to the clustered index (or heap) and to every non-clustered index whose key it touches. Five non-clustered indexes means roughly six B-tree modifications per row, each logged.
dbo.Orders with 1 million rows clustered on OrderId. Run SET STATISTICS IO ON and query by CustomerId; note the logical reads.IX_Orders_CustomerId and rerun; compare reads and look for the Key Lookup in the actual plan.sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('dbo.Orders'), NULL, NULL, 'DETAILED') and read index_depth and page_count per level.SELECT ... INTO, update a varchar column to a much longer value and check forwarded_record_count.sys.dm_db_index_operational_stats.A clustered primary key, a supporting non-clustered index, and how to see which is used.
CREATE TABLE dbo.Orders
(
OrderId int IDENTITY NOT NULL,
CustomerId int NOT NULL,
OrderDate datetime2(0) NOT NULL,
Status tinyint NOT NULL,
Total decimal(12,2) NOT NULL,
CONSTRAINT PK_Orders PRIMARY KEY CLUSTERED (OrderId) -- leaf = the rows
);
-- Separate B+ tree: leaf = (CustomerId, OrderId) where OrderId is the row locator
CREATE NONCLUSTERED INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId);
SET STATISTICS IO ON;
-- Seek on IX_Orders_CustomerId, then a Key Lookup per row for OrderDate and Total
SELECT OrderId, OrderDate, Total
FROM dbo.Orders
WHERE CustomerId = 42;
-- Inspect structure: depth, pages per level
SELECT i.name, ps.index_level, ps.page_count, ps.index_depth
FROM sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID(N'dbo.Orders'), NULL, NULL, 'DETAILED') AS ps
JOIN sys.indexes AS i ON i.object_id = ps.object_id AND i.index_id = ps.index_id
ORDER BY i.index_id, ps.index_level DESC;
The same index declared in EF Core 10, so it is created by a migration rather than by hand.
namespace Shop.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public sealed class Order
{
public int OrderId { get; set; }
public int CustomerId { get; set; }
public DateTime OrderDate { get; set; }
public decimal Total { get; set; }
}
public sealed class OrderConfiguration : IEntityTypeConfiguration<Order>
{
public void Configure(EntityTypeBuilder<Order> b)
{
b.HasKey(o => o.OrderId); // clustered by default on SQL Server
b.HasIndex(o => o.CustomerId) // non-clustered
.HasDatabaseName("IX_Orders_CustomerId");
b.Property(o => o.Total).HasPrecision(12, 2);
}
}
STATISTICS IO.nvarchar columns. Why it is wrong: it is copied into every non-clustered index as the row locator. Instead: a narrow, unique, ever-increasing clustered key.The useful mental model is "one ordered table plus N sorted copies". Every design decision follows from it: the clustered key's width multiplies into every copy, each copy costs writes, log, maintenance and buffer pool memory, and the optimiser picks the cheapest path by estimated rows (from statistics), not by whether an index exists. The actual execution plan is where you confirm it: seek or scan, key lookups and their execution count, and Rows Read versus Actual Rows.
A seek's cost is the tree depth plus however many leaf pages the range covers plus any lookups. Depth depends on row count and key width, not on fragmentation; fragmentation and low page density mainly make range scans read more pages.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Clustered on narrow identity | Most OLTP tables | Last-page contention at extreme insert rates | Table is almost always read by another range key |
| Clustered on a range key (e.g. CreatedAt, TenantId) | Range reads dominate | Wider NC indexes, less ordered inserts | Point lookups by id dominate |
| Heap | Staging, bulk loads, truncate-and-reload | Forwarded records, RID lookups | Anything updated or queried by range |
| Extra NC index | A frequent query needs a seek | Write cost, storage, memory | Write-heavy table with rare reads on that column |
| Columnstore index | Analytics over many rows and few columns | Different storage model, slower singleton updates | Point lookups on OLTP rows |
At very large sizes, partitioning splits each index into per-partition B-trees aligned on a partition key (often a date). It helps maintenance and archiving (rebuild or switch out one partition) far more than it helps query speed; queries only benefit when they filter on the partition key.
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.
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.
Last updated 23 Nov 2026.