Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between primary key (cluster) and clustered unique index in SQL Server

I understand what is primary key and unique clustered index my question is why primary key is required when we define unique clustered index. Just considering performance good database design.

As per my understanding when we define a clustered unique index it sorts the data physically and which is required for table performance and it is immaterial whether we define primary key or not

like image 413
user2903263 Avatar asked Oct 21 '13 13:10

user2903263


2 Answers

There is no practical difference between a unique index on non nullable columns and a PK as far as SQL Server is concerned.

Both enforce uniqueness, can be clustered or non clustered, and can be referenced by a foreign key constraint.

Some tools may expect there to be a primary key defined though.

Regarding your point that a clustered index "sorts the data physically" this is a bit of a misconception.

This is only true if the CI has zero fragmentation. For example after page splits it is perfectly possible for the clustered index pages to be out of order in the file.

like image 76
Martin Smith Avatar answered Oct 05 '22 16:10

Martin Smith


"why primary key is required when we define unique clustered index "

It is not.

By default, when you declare a table with a primary key in SQL Server, it adds a clustered index on the primary key (if you do not specify a separate clustered index).

But the clustered index does not have to be on the columns that comprise the table's primary key.

You can create a table where the primary key has a unique non-clustered index, and the clustered index is elsewhere.

like image 42
Mitch Wheat Avatar answered Oct 05 '22 14:10

Mitch Wheat