Sql-server – What happens when you change a heap into a clustered table in SQL Server

clustered-indexheapsql server

As I understand, a heap is an unordered object. When you insert a record, SQL Server use IAM page to get the pages that belong to this heap, and use PFS page to find a particular one which has enough space to accommodate this record and insert into it.

When you create a clustered index on it, it becomes a clustered table and the clustered index itself becomes the table. But as the clustered index and the original heap are two different structures, does SQL Server create a new structure (the clustered index) and moves everything from the help to the new structure and then drops the heap?

There are a lot of stuffs that can be defined on a table, like triggers, constrains, permissions etc. If my assumption is true, that means SQL Server also moves all these stuff to the new structure. I didn't find any related information in the documentation. Is my understanding correct?

Best Answer

Yes, when you create a clustered index on a heap the rows are all sorted moved to the new clustered index. Any non-clustered indexes are rebuilt with the new clustered index key as the row locator.

It's the same table, though, so triggers, constraints, etc don't have to change.

The reverse is not true, however. When you drop a clustered index on a table, the leaf-level pages of the clustered index are left in-place and they become the new heap. Nonclustered indexes are still rebuilt as the row locator switches from the CI key to the rowid (file:page:slot).