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

📚 Interview question

What is the difference between a clustered and a non-clustered index in SQL Server? Explain the B+ tree structure, what a heap is, and how SQL Server finds a row through each.

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.

Junior Theory Beginner b-tree clustered-index heap indexes non-clustered-index sql-server

🎯 Key points

  • Rowstore indexes are B+ trees of 8 KB pages: root, intermediate and leaf levels
  • Clustered index leaf level is the table data itself; only one per table
  • Heap = table with no clustered index; rows located by RID (file:page:slot)
  • Non-clustered index leaf holds the key plus a row locator (clustered key or RID)
  • Seek cost = index depth (3-4 levels for millions of rows) plus leaf pages read; range size and lookups drive the total
  • Key lookup (or RID lookup) fetches missing columns from the base table
  • Write amplification: every insert/delete touches every NC index, updates touch those containing the changed columns
  • Primary key is clustered by default but the two are separate choices

⏱ 30-second answer

Both are B+ trees of 8 KB pages: a root, intermediate levels and a leaf level, with leaf pages linked in key order.

  • A clustered index is the table: its leaf pages hold the full rows, sorted by the clustered key. There is only one per table.
  • A table with no clustered index is a heap; rows sit wherever there is space and are found by a RID (file, page, slot).
  • A non-clustered index is a separate, sorted copy of some columns. Its leaf holds the index key plus a row locator: the clustered key, or the RID on a heap.

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.

🗣 Full answer (senior)

How I would answer this in an interview

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


Side by side

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

How a lookup works

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.

When a heap is acceptable

Fits Avoid
Staging tables loaded then truncated Tables that are updated (forwarded records)
Minimal-logging bulk loads Tables read by range or joined often

Production example

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.

🔍 What the interviewer is checking

Checks that the candidate understands how SQL Server physically stores and finds rows, not just the definitions.

Green flags

  • Describes the B+ tree, leaf level and linked leaf pages
  • Knows the clustered leaf is the data and the NC leaf holds a row locator
  • Explains heaps, RIDs and key lookups
  • Mentions write cost of each index

Red flags

  • "Clustered means sorted on disk" with no nuance
  • Thinks PK and clustered index are the same thing
  • No idea what a key lookup is

📚 Learn in depth

1. Pages and the B+ tree

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.

2. Clustered index = the table

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.

3. Heaps and RIDs

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.

4. Non-clustered indexes and row locators

The leaf of a non-clustered index stores the key columns, any INCLUDE columns and the row locator:

  • On a clustered table: the clustered key (so a wide clustered key widens every non-clustered index).
  • On a heap: the RID.

When the query needs more columns, the plan shows a Key Lookup (clustered) or RID Lookup (heap) joined with Nested Loops.

5. Seek versus scan

  • Index seek: navigate root to leaf for a value or range, then read only the matching leaf pages.
  • Index scan: read every leaf page in order (or allocation order).

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.

6. Write cost

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.

Try it yourself

  1. Create dbo.Orders with 1 million rows clustered on OrderId. Run SET STATISTICS IO ON and query by CustomerId; note the logical reads.
  2. Add IX_Orders_CustomerId and rerun; compare reads and look for the Key Lookup in the actual plan.
  3. Query sys.dm_db_index_physical_stats(DB_ID(), OBJECT_ID('dbo.Orders'), NULL, NULL, 'DETAILED') and read index_depth and page_count per level.
  4. Make a heap copy with SELECT ... INTO, update a varchar column to a much longer value and check forwarded_record_count.
  5. Insert 1,000 rows and count index operations in sys.dm_db_index_operational_stats.

💻 Code

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

⚠ Common mistakes

  • Mistake: Saying the primary key and the clustered index are the same thing. Why it is wrong: the PK is a logical constraint; clustering is physical storage, and they can be on different columns. Instead: choose them separately, even if they usually coincide.
  • Mistake: Believing a clustered index keeps rows physically contiguous on disk. Why it is wrong: it guarantees logical order through page links; pages can be scattered (fragmentation). Instead: describe it as logical key order.
  • Mistake: Leaving busy, updated tables as heaps. Why it is wrong: forwarded records and no order make reads and space reuse worse. Instead: give OLTP tables a clustered index; keep heaps for staging.
  • Mistake: Adding a non-clustered index for every column. Why it is wrong: each one is maintained on every write and uses buffer pool memory. Instead: index for real query patterns and remove unused indexes.
  • Mistake: Assuming a seek is always cheaper than a scan. Why it is wrong: a seek followed by thousands of key lookups can read more pages than one scan. Instead: compare logical reads in STATISTICS IO.
  • Mistake: Using a wide clustered key such as several 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.

🏛 Senior insight: trade-offs

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.

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions the clustered key being copied into non-clustered indexes. Why: Checks they can choose a good clustered key.
    How to 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.

  2. When: Candidate mentions GUID primary keys. Why: Checks they understand page splits from random keys.
    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.

↩ Usually asked after

More in Indexes

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me