SQL Server Heap


This entry is part 4 of 5 in the series SQL Server Data Structures

Preliminary Information

A table can be organized one of two ways: heap or B-tree. If a table has a clustered index on it then it is organized as a B-tree and where there is no clustered index defined on it, it is organized as a heap.

You can create a clustered index on a table when you define a primary key constraint on it, unless you specify the NONCLUSTERED keyword explicitly, or a clustered index already exists on a table. When you define a primary key constraint , SQL Server enforces it with a clustered index by default. You can create a clustered index directly using the CREATE CLUSTERED INDEX command. Another way is to use an inline clustered index definition INDEX CLUSTERED, starting with SQL Server 2014.

When you add a unique constraint to a table, SQL Server will enforce it using a nonclustered index unless you specify the CLUSTERED keyword.

Generally, it is better to have a table organized as a B-tree rather than a heap, however there are exceptions to that rule.

Nonclustered Indexes

You can have zero, one or many nonclustered indexes defined on it. Nonclustered indexes are objects that exist apart from the table itself, but are assocaiated with the table. Nonclustered indexes are always organized as B-trees.

Heap

A heap is a table in SQL Server that has no clustered index. It is called a heap because it is not organized in any order. It is a big pile of pages and extents. How does SQL Server map the data in the table? It does so with one or more bitmap pages called index allocation maps (IAMS).

The header of the IAM page has pointers to the first 8 pages that SQL Server allocated for the heap from mixed extents. The header also has a pointer to a starting location of a range of 4 GB that the IAM page maps in the data file.

You can see internal pointers to the first IAM page in the system view sys.system_internals.

Since a heap does not maintain the data in a table in any particular order, SQL Server needs to keep track of available free space using bitmap pages called page free space (PFS).

Series Navigation<< SQL Server B-TreeSQL Server Access Methods >>