Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the `primary key` keyword relate to clustered indexes in SQL Server?

How does the PRIMARY KEY keyword relate to clustered indexes in SQL Server?

(Some people seem to want to answer this question instead of a different question I asked, so I am giving them a better place to do so.)

like image 762
bbadour Avatar asked Sep 07 '10 19:09

bbadour


3 Answers

How does the PRIMARY KEY keyword related to clustered indexes in MS SqlServer?

By default, a PRIMARY KEY is implemented as a clustered index. However, you can back it by an unclustered index as well (specifying NONCLUSTERED options to its declaration)

A clustered index is not necessarily a PRIMARY KEY. It can even be non-unique (in this case, a hidden column called uniqueifier is added to each key).

Note that a clustered index is not really an index (i. e. a projection of a table ordered differently, with the references to original records). It is the table itself, with the original records ordered.

When you create a clustered index, you don't really "create" anything that you can drop apart from the table. You just rearrange the table itself and change the way the records are stored.

like image 200
Quassnoi Avatar answered Nov 20 '22 23:11

Quassnoi


The clustered index of a table is normally defined on the primary key columns.

This, however is not a strict requirement.

From MSDN:

When you create a PRIMARY KEY constraint, a unique clustered index on the column or columns is automatically created if a clustered index on the table does not already exist and you do not specify a unique nonclustered index.

And:

You can create a clustered index on a column other than primary key column if a nonclustered primary key constraint was specified.

like image 43
Oded Avatar answered Nov 20 '22 21:11

Oded


A primary key is, as the name implies, the primary unique identifier for a row in your table. A clustered index physically orders the data according to the index. Although SQL Server will cluster a primary key by default, there is no direct relationship between the two.

like image 4
Joe Stefanelli Avatar answered Nov 20 '22 23:11

Joe Stefanelli