Sunday, October 28, 2007

Clustered Index and primary key

Usually, the Primary Key has the clustered index. But it does not have to be that case. The following is the example to show the Clustered Index and Primary Key can be separately defined.

create table [videotitle] (
[videoid] int IDENTITY(1,1)primary key nonclustered,
[videotitle] nvarchar(100) not null ,
[description] nvarchar(255)null ,
[videolanguage] nvarchar(50) null ,
[releasedate] datetime null ,
[isbn] nvarchar(25) ,
[upc_no] nvarchar(25) ,
[format] nvarchar(25) ,
[cost] money ,
[retailprice] money);
go
create clustered index [clustered_videotitle] on [videotitle] (videotitle);

When a table has a clustered index defined, data rows in the table is sorted as shown below. Because the data rows can be sorted only in one direction, you can only have one and only one clustered index for a table.

If a table do not have a clustered index defined, the data rows are in an unordered structure called heap -- no such doubly-link chain.

For a clustered table, when a non-clustered index is created. Its leaf node contains the non-clustered index key and clustered index key, which points to the actual data row. Because all non-clustered indexes automatically include the clustered index key, you should choose the column(s) with a smaller length.