Sql Server 唯一键也是索引吗?

2021-12-21 00:00:00 indexing sql-server unique-key

我在表中有一列(例如用户名),我想确保它是唯一的.因此,我为该列创建了一个唯一键并将其命名为 IX_Users_UserName.

现在,如果我根据用户名进行大量用户搜索,我想确保该字段有索引.

我是否需要创建单独的索引,还是唯一键也被视为索引,就像主键是聚集唯一键一样?

解决方案

唯一键:唯一键强制执行它们所在的列的唯一性被定义.唯一键创建一个列上的非聚集索引.唯一键只允许一个 NULL 值.

Alter table 添加唯一约束到列:

ALTER TABLE 作者添加约束IX_Authors_Name UNIQUE(Name) GO

来源

更多信息来自 MSDN.>

FWIW -- 如果您的约束没有创建索引,我会避免将其命名为 IX_,因为这通常被认为与一个 (IX = Index) 相关联.

I've got a column in a table (eg. UserName) which I want to make sure is unique. So I create a unique key for that column and call it IX_Users_UserName.

Now, if I do lots of searching for users based on their username I want to make sure there is an index for that field.

Do I need to create a separate index, or is the unique key also considered an index, just like the primary key is a clustered unique key?

解决方案

Unique Key: Unique Key enforces uniqueness of the column on which they are defined. Unique Key creates a non-clustered index on the column. Unique Key allows only one NULL Value.

Alter table to add unique constraint to column:

ALTER TABLE Authors ADD CONSTRAINT IX_Authors_Name UNIQUE(Name) GO

Source

More information from MSDN.

FWIW -- if your constraint doesn't create an index, I would avoid naming it IX_ as that would typically be assumed to be associated with one (IX = Index).

相关文章