Question

I just executed the following script

CREATE TABLE Test
(
    ID INT IDENTITY PRIMARY KEY,
    Info nvarchar(50)
)

For my surprise, SSMS created a clustered index for the ID column. So, my question is why not a non-clustered index?

From my understanding, it would be must better to use in this case an non-clustered index, because due to the binary tree, it is much faster to look up an ID with the value of X instead of using the clustered index where the values are somehow grouped. Also, if I think about receiving data, the ID must be quickly accessed somehow. As in lot of articles written, the binary tree is the fasted way to receive a specific or multiple IDs. In addition to that, I see in most cases that the Primary Key of any Table is an ID with an autoincrementing value. So it is pretty common to use this approach of the autoincrementing principle.

So, what is the advantage of using a non-clustered key and why is this default in SSMS?

Was it helpful?

Solution

By default, the primary key of a table is backed by a clustered index - that's just a SQL Server default behavior. It can be changed, if needed:

CREATE TABLE Test
(
    ID INT IDENTITY PRIMARY KEY NONCLUSTERED,
    Info nvarchar(50)
)

but especially in the INT IDENTITY case, that's almost the perfect clustered index you could imagine on your table - so it's a "good thing" that SQL Server makes this default choice.

Every "serious" table in SQL Server ought to have a well-chosen clustered index (because the alternative - a heap - is slower and more cumbersome to fine tune in every respect) - and a small (4 byte), static (never changes), unique column like INT IDENTITY is ideally suited as the clustered index on this table.

If you want to learn more about how to choose a clustering key wisely, and why it's so important to do so, you should check out everything Kimberly Tripp has to say on the topic:

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top