Sql Server唯一键也是索引吗?
我在表中有一列(例如用户名),我想确保它是唯一的。 因此,我为该列创建一个唯一键并将其命名为 IX_Users_UserName。
现在,如果我根据用户名进行大量搜索用户,我想确保该字段有一个索引。
我是否需要创建单独的索引,或者唯一键也被视为索引,就像主键是聚集唯一键一样?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
基本上,在SQL Server中,唯一约束确实是通过唯一索引来实现的。
UNIQUE 约束和 UNIQUE INDEX 之间的区别确实非常微妙。 如果创建 UNIQUE INDEX,则可以在另一个表的外键约束中引用它(如果创建 UNIQUE 约束则不起作用......)。
那么有什么区别呢? 好吧 - 唯一约束实际上更像是表上的逻辑事物 - 您想要表达给定列(或列组)的内容是唯一的意图。
唯一索引(像大多数索引一样)更多的是“幕后”实现细节。
从我的角度来看,除非你确实有问题,否则我总是使用唯一索引 - 成为引用完整性约束一部分的好处是非常有效的,并且在某些情况下非常有用。 从功能上讲,在实践中,使用唯一约束与唯一索引实际上没有区别。
Basically, in SQL Server, a unique constraint is indeed realized by means of a unique index.
The differences between a UNIQUE constraint and a UNIQUE INDEX are quite subtle, really. If you create a UNIQUE INDEX, you can reference that in a foreign key constraints from another table (doesn't work if you create a UNIQUE constraint....).
So what's the difference? Well - a unique constraint really is more of a logical thing on a table - you want to express the intent that the contents of a given column (or group of columns) is unique.
A unique index (like most indices) is more of a "behind-the-scenes" implementation detail.
From my point of view, unless you really have a problem with it, I'd always use a UNIQUE INDEX - the benefit of being part of a referential integrity constraint is quite valid and can be very useful in certain cases. Functionally, in practice, there's no difference between using a Unique Constraint vs. Unique Index, really.
我怀疑几乎每个数据库产品都有一个唯一的键是索引。 必须如此,否则数据库将很难执行它:当您插入一个值时,数据库必须回答“该值是否已经存在?” 明智的方法是查阅索引。
我面前没有可供测试的 SQL Server,但如果没有,我会感到震惊。
A unique key is an index in I suspect almost every database product. It has to be, otherwise the database would have a hard time enforcing it: when you insert a value, the database has to answer, "does that value already exist?" The sane way to do that is consult an index.
I don't have a SQL Server in front of me to test, but I'd be shocked if it didn't.
来源
更多信息来自 MSDN。
FWIW - 如果您的约束不创建索引,我会避免将其命名为 IX_,因为通常会假定它与一个(IX = 索引)相关联。
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).