database: primary key, Clustered or NonClustered

混江龙づ霸主 提交于 2019-11-30 12:28:11

问题


I am creating a database in SQL server 2008,

CREATE TABLE Users
(
    U_Id INT NOT NULL
    FirstName VARCHAR(50) NOT NULL,
    LastName VARCHAR(50) NOT NULL,
    Email VARCHAR(200)
    Password VARCHAR(50)
)

I want to make U_Id the primary key. I would like to ask what is the difference between

 CONSTRAINT pk_UserID PRIMARY KEY (U_Id)

this

 CONSTRAINT pk_UserID PRIMARY KEY CLUSTERED (U_Id)

and this

CONSTRAINT pk_UserID PRIMARY KEY NONCLUSTERED (U_Id)

When to use each?

I read some article but it is still unclear to me. Can someone give me a quick explanation?


回答1:


The following statement:

CONSTRAINT pk_UserID PRIMARY KEY (U_Id)

Is the same as this one:

CONSTRAINT pk_UserID PRIMARY KEY CLUSTERED (U_Id)

You can only have the table data physicality ordered by one of the indexes, and by default that index is the one used for the primary key (the primary key unique constraint is always supported by an index).

If you want to leave the order of the table data to be stored according to some other index then you should create the primary key with:

CONSTRAINT pk_UserID PRIMARY KEY NONCLUSTERED (U_Id)

And then create the clustered index with:

CREATE CLUSTERED INDEX ix_Email ON Users (Email); 


来源:https://stackoverflow.com/questions/10706992/database-primary-key-clustered-or-nonclustered

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!