7

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

2
  • 1
    Differences: Well, in a nutshell, the one is a primary key, while the other is not. Commented Oct 21, 2013 at 13:30
  • 2
    The primary key is a logical construct - the key used to uniquely and reliably identify each and every single column in a table. The clustered index is a physical implementation detail of how SQL Server handles its storage. Commented Oct 21, 2013 at 13:40

2 Answers 2

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

is that what the poster was asking?
@MitchWheat - The title seems to indicate so,
6

"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.

2 Comments

... and you can have a table without any clustered index.
indeed - called a heap.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.