Module 1 · Foundations · Lesson 1 of 17
How SQL Server Stores a Table: Heaps, Clustered Indexes and B+ Trees
SQL Server stores a table as a heap without key order, or as a clustered index with its rows at the leaves of a B+ tree. Both use 8 KB pages.
This lesson covers rowstore tables, which store a row’s columns together, rather than grouping values by column. These principles apply to SQL Server and Azure SQL Database.
You will learn how SQL Server finds rows, why a primary key is not the same thing as clustered storage, and how your choice of clustered key affects other indexes.
How do 8 KB pages and B+ trees store rows?
A page is an 8 KB unit that SQL Server uses to store and read data. Several small rows can share one page.
An index is a structure that helps SQL Server find rows without examining every row. Its index key is the column, or combination of columns, used to organize its entries.
A clustered rowstore index is a B+ tree: a branching search structure with the table’s in-row data at the bottom. “In-row” means the data stored as part of the row itself; some large values can be stored separately.
The tree has three kinds of levels:
- The root is the starting page.
- Intermediate levels, when present, contain keys and pointers that direct a search toward the correct lower page.
- The leaf level is the bottom level. In a clustered index, these pages contain the table’s in-row data.
Here is part of an illustrative tree, not a fixed layout for every table:
flowchart TD
R["Root page"] -->|routes search to| I["Intermediate page"]
I -->|routes lower keys to| L1["Leaf: OrderId 1–100"]
I -->|routes higher keys to| L2["Leaf: OrderId 101–200"]
L1 -->|links to next leaf| L2
The upper pages guide searches, while linked leaf pages hold the rows in logical key order.
For a point search such as WHERE OrderId = 125, SQL Server can follow the relevant branch to the leaf containing 125. For WHERE OrderId BETWEEN 125 AND 150, it can locate the start and then follow the leaf entries through the range.
An index seek uses index keys to navigate to a value or range. A scan walks through pages or entries in the selected table or index rather than locating a starting point through a search key. A seek can still read many rows; a scan can be sensible when a query needs much of the table.
A table can have only one clustered index, because its in-row data forms the leaf level of that one tree.
Three different kinds of “order” matter here:
- Logical key order is the order maintained by the index structure.
- Physical page placement is where pages happen to be located in database files. Neighboring keys do not promise neighboring physical pages.
- Query-result order is guaranteed only when your query specifies
ORDER BY; see the ORDER BY reference.
In an interview, say: “A clustered rowstore index is a B+ tree whose leaves hold the table’s in-row data, so there is only one per table. Searches follow root and intermediate pages to the leaves; ranges continue through linked leaves. Only ORDER BY guarantees result order.”
What is a heap, and when should you use one?
A heap is a table without a clustered index. SQL Server places its rows where space is available, without maintaining a logical key order.
For example, a staging table temporarily holds incoming data before another step validates or moves it:
CREATE TABLE dbo.ImportStage
(
ExternalOrderId int NOT NULL,
Description varchar(200) NOT NULL
);
INSERT dbo.ImportStage (ExternalOrderId, Description)
VALUES (200, 'Second order'), (100, 'First order');
SELECT ExternalOrderId, Description
FROM dbo.ImportStage
ORDER BY ExternalOrderId;There is no clustered index declaration, so this table is a heap.
A heap row has an 8-byte RID, or row identifier. It contains the file number, page number and slot number. A slot identifies an entry on that page.
A heap can still have nonclustered indexes, which are separate search structures. Their row locator, the information used to find the underlying table row, is the heap RID. Without any suitable index, a search by a column value must scan the heap.
Heaps can suit staging workflows and bulk loads: loading many rows in one large operation, for example with SqlBulkCopy or BULK INSERT. These workflows can insert unordered rows, process them, then empty and reload the table.
Updates create another trade-off. If an update makes a heap row wider and it no longer fits on its page, SQL Server can move it. A forwarded record results: a pointer at the original location leads to the moved row. Following that pointer can add page reads.
Microsoft’s heap guidance recommends a carefully chosen clustered index for most tables unless there is a reason to use a heap.
In an interview, say: “A heap is a table without a clustered index. It can have nonclustered indexes using RID locators. Frequently reloaded staging tables and bulk loads can suit heaps, but unindexed searches scan, and widening updates can create forwarded records that add reads.”
Is a primary key always the clustered index?
No. A primary key constraint enforces unique, non-null key values. Clustering determines how SQL Server organizes the table’s row storage. These are separate decisions.
By default, SQL Server creates a clustered index to enforce a primary key when no clustered index already exists. If one already exists, the primary key defaults to nonclustered. You can also request NONCLUSTERED explicitly:
CREATE TABLE dbo.OrderKeyExample
(
OrderId int NOT NULL,
CreatedAt datetime2 NOT NULL,
CONSTRAINT PK_OrderKeyExample
PRIMARY KEY NONCLUSTERED (OrderId)
);
CREATE CLUSTERED INDEX CX_OrderKeyExample_CreatedAt
ON dbo.OrderKeyExample (CreatedAt);The first statement creates a nonclustered primary key on OrderId. At that point, the table is a heap. The second statement organizes the table as a clustered index on CreatedAt.
This example separates the concepts; it is not a recommendation to cluster every orders table by creation time.
By default, the EF Core SQL Server provider creates primary keys without specifying CLUSTERED or NONCLUSTERED. SQL Server’s default then applies: the primary key becomes clustered if the table has no clustered index. You can change this in the model. For example, HasKey(...).IsClustered(false) makes the primary key nonclustered, and HasIndex(...).IsClustered() can configure a different clustered index.
In an interview, say: “No. A primary key enforces uniqueness and non-null values; clustering determines storage. SQL Server defaults the primary key to clustered when no clustered index exists, but I can declare it NONCLUSTERED. EF Core normally leaves that choice unspecified, so SQL Server’s default applies; I can override it in the model.”
How does a nonclustered index find the table row?
A nonclustered rowstore index is a separate B+ tree containing its own index keys and a row locator. A table can have several nonclustered indexes, each offering a different way to find rows.
Consider this complete example:
CREATE TABLE dbo.CustomerOrderExample
(
OrderId int NOT NULL,
CustomerId int NOT NULL,
Total decimal(12, 2) NOT NULL,
CONSTRAINT PK_CustomerOrderExample
PRIMARY KEY CLUSTERED (OrderId)
);
CREATE NONCLUSTERED INDEX IX_CustomerOrderExample_CustomerId
ON dbo.CustomerOrderExample (CustomerId);
INSERT dbo.CustomerOrderExample (OrderId, CustomerId, Total)
VALUES (1, 42, 25.00), (2, 7, 80.00), (3, 42, 60.00);
SELECT OrderId, CustomerId, Total
FROM dbo.CustomerOrderExample
WHERE CustomerId = 42
ORDER BY OrderId;The clustered tree holds the complete in-row order data at its leaves, organized by OrderId. The nonclustered tree is organized by CustomerId, and its row locator is the clustered key, OrderId.
When the index lacks a column the query needs, SQL Server must go back to the table row for it. The next index lesson covers these key lookups and covering indexes.
In an interview, say: “A clustered index holds the table’s in-row data at its leaves. A nonclustered index is a separate tree containing index columns and a row locator: the clustered key for a clustered table, or a RID for a heap. It may need another retrieval if it lacks requested columns.”
What makes a good clustered key, and why can random GUIDs hurt?
A good starting choice is narrow, unique, stable and preferably increasing:
- Narrow keys use fewer bytes, including when carried as row locators in nonclustered indexes. For 1 million rows and 3 nonclustered indexes, a 16-byte GUID rather than a 4-byte
intadds about 36 MB of locator bytes: 1,000,000 × 3 × (16 − 4). That means more pages to read and keep in memory, before considering other overhead. - Unique keys identify rows without SQL Server adding an internal value to distinguish duplicates.
- Stable keys rarely change. Changing a clustered key value requires moving the row to its new place in key order. SQL Server must also update that key in every nonclustered index, because each stores it as its row locator.
- Increasing keys tend to place new entries at the end of the key range rather than throughout it.
An int or bigint with IDENTITY is a common candidate. IDENTITY generates numeric values for inserted rows; the primary key or a unique index supplies uniqueness enforcement.
A GUID is a 16-byte identifier, stored in SQL Server as uniqueidentifier. A random GUID spreads inserts throughout the key range. When the target index page lacks room for a new row, SQL Server can perform a page split: allocate another page and redistribute rows, often roughly half to each page.
Splits add work recorded in SQL Server’s transaction log, which records database changes for recovery. They can also lower page density, the proportion of page space occupied by data, and increase fragmentation, where logical index order differs from physical page order.
This is not unique to GUIDs. Other inserts, and updates that enlarge rows, can also require splits.
One alternative separates the storage key from the identifier used outside the database:
CREATE TABLE dbo.PublicOrderExample
(
OrderId bigint IDENTITY(1, 1) NOT NULL,
PublicId uniqueidentifier NOT NULL DEFAULT NEWID(),
CONSTRAINT PK_PublicOrderExample
PRIMARY KEY CLUSTERED (OrderId),
CONSTRAINT UQ_PublicOrderExample_PublicId
UNIQUE NONCLUSTERED (PublicId)
);Here, the table clusters on the increasing integer. NEWID() generates the GUID, whose uniqueness is enforced by a separate nonclustered index. That GUID index still has random-insert costs; the design does not make them disappear. It keeps the clustered locator narrower, at the cost of an additional identifier and index.
Another option is a sequential GUID. New rows then go near the end of the index, on the same few pages, instead of being spread throughout it. SQL Server’s NEWSEQUENTIALID() works only in a column DEFAULT; its values increase on one machine until Windows restarts, and they are guessable. It remains a 16-byte key.
For GUID primary keys generated on add, EF Core’s SQL Server provider generates sequential GUID values on the application side. That is distinct from asking SQL Server to use NEWSEQUENTIALID(); see provider value generation.
In an interview, say: “I usually want a narrow, unique, stable, increasing clustered key. Random GUIDs are wide and can cause scattered inserts into full pages, producing splits and lower density. Sequential GUIDs place new entries near the end of the index; an integer clustered key plus a separate GUID is another trade-off.”
How can you compare a heap and a clustered table with STATISTICS IO?
The useful comparison keeps the columns, rows and queries identical, changing only the storage structure.
SET STATISTICS IO reports page access for executed statements. Logical reads count pages read from the in-memory data cache; physical reads count pages read from disk. A cached query can therefore have zero physical reads while still doing substantial work.
In SQL Server Management Studio, enable Include Actual Execution Plan before running the queries if you want to compare their access paths.
Run the following SQL in a disposable database on SQL Server 2025 or 2022. It drops and recreates the two named lesson tables. It requires a real SQL Server connection, not the page’s C# runner.
Before running, predict which query pair will need to inspect more pages.
DROP TABLE IF EXISTS dbo.StorageLessonHeap;
DROP TABLE IF EXISTS dbo.StorageLessonClustered;
CREATE TABLE dbo.StorageLessonHeap
(
OrderId int NOT NULL,
CustomerId int NOT NULL,
Total decimal(12, 2) NOT NULL,
Notes char(180) NOT NULL
);
CREATE TABLE dbo.StorageLessonClustered
(
OrderId int NOT NULL,
CustomerId int NOT NULL,
Total decimal(12, 2) NOT NULL,
Notes char(180) NOT NULL
);
CREATE UNIQUE CLUSTERED INDEX CX_StorageLessonClustered
ON dbo.StorageLessonClustered (OrderId);
;WITH Digits AS
(
SELECT n
FROM (VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9)) AS d(n)
), Numbers AS
(
SELECT 1 + a.n + 10 * b.n + 100 * c.n + 1000 * d.n AS n
FROM Digits AS a
CROSS JOIN Digits AS b
CROSS JOIN Digits AS c
CROSS JOIN Digits AS d
)
INSERT dbo.StorageLessonHeap (OrderId, CustomerId, Total, Notes)
SELECT n, n % 100, CAST(n % 500 AS decimal(12, 2)), 'lesson row'
FROM Numbers;
INSERT dbo.StorageLessonClustered (OrderId, CustomerId, Total, Notes)
SELECT OrderId, CustomerId, Total, Notes
FROM dbo.StorageLessonHeap;
SET STATISTICS IO ON;
SELECT OrderId, CustomerId, Total, Notes
FROM dbo.StorageLessonHeap
WHERE OrderId = 5000
ORDER BY OrderId;
SELECT OrderId, CustomerId, Total, Notes
FROM dbo.StorageLessonClustered
WHERE OrderId = 5000
ORDER BY OrderId;
SELECT OrderId, CustomerId, Total, Notes
FROM dbo.StorageLessonHeap
WHERE OrderId BETWEEN 5000 AND 5020
ORDER BY OrderId;
SELECT OrderId, CustomerId, Total, Notes
FROM dbo.StorageLessonClustered
WHERE OrderId BETWEEN 5000 AND 5020
ORDER BY OrderId;
SET STATISTICS IO OFF;There are no nonclustered indexes to provide another search route.
The heap searches require a table scan; the clustered tree provides a seek route to the requested key or range. Confirm the operations actually chosen in your plans.
Compare each statement’s logical reads in the Messages tab: expect hundreds of page reads for each heap query and a handful for each clustered seek.
The STATISTICS IO reference defines the fields. Continue with reading actual execution plans and logical reads for detailed plan interpretation.
In an interview, say: “I compare identical data and queries, inspect the chosen access paths, and measure logical reads with STATISTICS IO. An unindexed heap search scans; a clustered key offers a seek route. The returned data can be identical while the work differs.”
Check yourself
A table has a PRIMARY KEY NONCLUSTERED on OrderId and a clustered index on CreatedAt. Which statement is correct?
Show answer
Correct answer: D
The primary key enforces the key rules independently of clustered storage. The clustered index organizes the table's in-row data, and nonclustered indexes use its key as their row locator. Query-result order still requires ORDER BY.
Why might an integer clustered key plus a separate random GUID column be preferable to clustering directly on the random GUID?
Show answer
Correct answer: A
The integer can provide a narrow, increasing clustered key. A separate indexed GUID still uses space and can experience random-insert page splits. The design moves and limits some costs; it does not remove them.
Going deeper
Nonunique clustered keys need an extra distinction. SQL Server adds an internal 4-byte value, called a uniqueifier, where needed to distinguish duplicate clustered key values. This can add overhead to the clustered structure and nonclustered row locators, as explained in the index design guide. It is one reason uniqueness is a useful clustered-key property.
Increasing keys have a different pressure point. Many concurrent inserts can compete to update the same last leaf page. That competition is called last-page insert contention.
Sources
- Clustered and Nonclustered Indexes - SQL Server | Microsoft Learn: Clustered and nonclustered structures, one clustered index per table, row locators, primary-key defaults and constraints.
- Index Architecture and Design Guide - SQL Server | Microsoft Learn: Rowstore B+ tree levels and linked pages; clustered-key properties, key width, uniqueifiers, page splits and increasing-key insertion trade-offs.
- Page and Extent Architecture Guide - SQL Server | Microsoft Learn: 8 KB pages, logical versus physical row organization, in-row limits and separately stored large values.
- Heaps (Tables Without Clustered Indexes) - SQL Server | Microsoft Learn: Heap definition, 8-byte RIDs, staging and bulk-load use cases, unindexed scans and forwarded records.
- SET STATISTICS IO (Transact-SQL) - SQL Server | Microsoft Learn: STATISTICS IO syntax, logical and physical reads, and the distinction between scan count and plan operator names.
- sys.dm_db_index_physical_stats (Transact-SQL) - SQL Server | Microsoft Learn: Inspecting index depth, page counts, density, fragmentation and forwarded records, with scan-mode qualifications.
- Indexes - EF Core | Microsoft Learn: SQL Server’s primary-key clustering default and the provider’s configurable IsClustered settings.
- Value Generation - EF Core | Microsoft Learn: Application-side sequential GUID generation for GUID primary keys generated on add.
- NEWSEQUENTIALID (Transact-SQL) - SQL Server | Microsoft Learn: Database-side sequential GUID defaults and locality compared with random GUIDs.
- SELECT - ORDER BY Clause (Transact-SQL): The requirement to specify ORDER BY for guaranteed result order.
- Primary and foreign key constraints: Primary-key uniqueness and non-null values.
- Execution plans: The operations SQL Server chooses to execute a query.
- Showplan logical and physical operators reference: Seek and scan operations, key lookups and RID lookups.
Practice
Checked before publishing: links opened, reviewed while it was written and read in full. How lessons are checked
Updated 30 Nov 2026 ·