DBA Scripts: Get Heaps

🔧Part of the DBA-Tools Project, copy/paste SQL Server scripts and health checks.In: Maintenance & Automation › Index Maintenance

A heap is a table with no clustered index. Non-covering lookups scan the whole table, updates that grow a row leave forwarded records, and deleted space is not reclaimed until a rebuild.

This script lists every heap across the online user databases, tables with no primary key first and then largest first, so you can see which ones are worth fixing. Small, static lookup tables can stay heaps; anything else deserves review.


The Script

Run the following script against your SQL Server instance. It is read-only and needs VIEW DATABASE STATE in each user database it iterates.

/*
Script Name : Get-Heaps
Category    : performance
Purpose     : Tables with no clustered index (heaps) across all online user databases.
Author      : Peter Whyte (https://sqldba.blog/dba-scripts-get-heaps/)
Requires    : VIEW DATABASE STATE (iterates each user database)
Notes       : Prioritise by reserved_mb and forwarded_fetch_count (resets on restart).
              has_primary_key = 0 means no PK at all: the first to address.
*/
-- SAFE:ReadOnly
-- IMPACT:Low
SET NOCOUNT ON;

CREATE TABLE #heaps (
    database_name           sysname       NOT NULL,
    schema_name             sysname       NOT NULL,
    table_name              sysname       NOT NULL,
    row_count               BIGINT        NOT NULL,
    reserved_mb             DECIMAL(10,2) NOT NULL,
    forwarded_fetch_count  BIGINT        NOT NULL,
    has_primary_key         BIT           NOT NULL
);

DECLARE @sql NVARCHAR(MAX) = N'';

SELECT @sql += N'
USE ' + QUOTENAME(name) + N';
INSERT INTO #heaps (database_name, schema_name, table_name, row_count, reserved_mb, forwarded_fetch_count, has_primary_key)
SELECT
    DB_NAME(),
    s.name,
    t.name,
    SUM(p.rows),
    CAST(SUM(a.total_pages) * 8.0 / 1024 AS DECIMAL(10,2)),
    ISNULL(SUM(ios.forwarded_fetch_count), 0),
    CASE WHEN EXISTS (
        SELECT 1 FROM sys.indexes pk
        WHERE pk.object_id = t.object_id AND pk.is_primary_key = 1
    ) THEN 1 ELSE 0 END
FROM sys.tables        t
JOIN sys.schemas       s   ON  t.schema_id   = s.schema_id
JOIN sys.indexes       i   ON  t.object_id   = i.object_id AND i.type = 0
JOIN sys.partitions    p   ON  i.object_id   = p.object_id AND i.index_id = p.index_id
JOIN sys.allocation_units a ON p.partition_id = a.container_id
LEFT JOIN sys.dm_db_index_operational_stats(DB_ID(), NULL, NULL, NULL) ios
    ON  ios.object_id = i.object_id AND ios.index_id = i.index_id
WHERE t.is_ms_shipped = 0
GROUP BY s.name, t.name, t.object_id
HAVING SUM(p.rows) > 0;
'
FROM sys.databases
WHERE state_desc  = 'ONLINE'
AND database_id > 4;

IF LEN(@sql) > 0
    EXEC sys.sp_executesql @sql;

SELECT
    database_name,
    schema_name,
    table_name,
    row_count,
    reserved_mb,
    forwarded_fetch_count,
    has_primary_key
FROM   #heaps
ORDER BY has_primary_key ASC, reserved_mb DESC;

DROP TABLE #heaps;

It queries every online user database, finds tables with no clustered index, and returns row counts, reserved size, forwarded-record activity, and whether a primary key exists.


Example Output

Five SQL Server heap tables of 781.38 MB each with has_primary_key of 0 and forwarded_fetch_count of 0, returned by the Get-Heaps script in SSMS

Run against the lab instance. It returns five heaps of about the same size, and has_primary_key reads 0 on every one of them. Size together with no primary key is the combination worth queueing.

Run it from the DBA Tools repo
git clone https://github.com/peterwhyte-lgtm/dba-tools
cd dba-tools
.\Initialize-Environment.ps1
.\run.ps1 Get-Heaps

Add -ServerInstance SQLSERVER01 to run against another server. Script file: Get-Heaps.sql


Understanding the Results

database_name
schema_name
table_name
Where the heap lives. The script loops every ONLINE database with database_id > 4, so system databases are out of scope.
row_count
Rows in the heap, summed across its partitions. Heaps with no rows are filtered out, so every row in the result has data behind it.
reserved_mb
Total reserved size in megabytes, from sys.allocation_units. After has_primary_key this is what the results are sorted by.Act when a large heap is also written to often. Size is what turns a missing clustered index from a schema detail into measurable IO.
forwarded_fetch_count
How many rows were fetched through a forwarding record, from sys.dm_db_index_operational_stats, where it is documented as applying to heaps only and is still present in SQL Server 2025 (sys.dm_db_index_operational_stats).

The counter is not simply reset at restart: it is zeroed whenever the metadata for the heap is brought into the cache, so a low number can mean not measured rather than not happening.Act when this is high on a heap you update frequently. A rebuild clears the forwarding records; a clustered index stops them being created.
has_primary_key
Set when a primary key constraint exists on the table, 0 when there is none at all. A heap can still carry a nonclustered primary key, so a 1 here does not mean the table is fine.

Results sort 0 first.Act when this reads 0. A table with neither a clustered index nor a primary key has no dependable way to address a single row.

How to Fix Heaps

If the table has a natural key:

ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (YourNaturalKey);

If the table has no natural key:

ALTER TABLE dbo.YourTable
ADD YourIdentity BIGINT IDENTITY(1,1);

ALTER TABLE dbo.YourTable
ADD CONSTRAINT PK_YourTable PRIMARY KEY CLUSTERED (YourIdentity);

Rebuilding the table removes forwarded records and reclaims space.

Docs: Microsoft’s reference covers sys.indexes, sys.tables and sys.partitions in full.

Frequently Asked Questions

Are heaps always bad?

No, tiny, static lookup tables can be heaps safely. Anything large or frequently updated should not be.

Was forwarded_fetch_count removed in SQL Server 2025?

No. It is still a returned column of sys.dm_db_index_operational_stats, and Microsoft still documents it for SQL Server 2025.

A value of 0 on every heap is a real reading, not a missing column: the counter is zeroed when the heap’s metadata is brought into cache, so on a recently restarted instance it means not measured yet rather than no forwarded records.

What is a heap?

A heap is a table without a clustered index. SQL Server stores its rows without any guaranteed order, which leads to full scans, forwarded records, and poor delete behaviour.

Why do forwarded records matter?

They force SQL Server to perform extra IO to chase pointers, slowing down lookups and scans.

Which heaps should I fix first?

Start with large heaps that are written to often, especially ones with no primary key or a high forwarded_fetch_count. Small, static lookup tables can stay as heaps.


Related Scripts

You may also find these scripts useful:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *