Unique key vs. unique index on SQL Server 2008

前端 未结 7 1510
抹茶落季
抹茶落季 2021-02-01 00:59

I have a table called countries and I define the country_name column to be unique by creating a “Index/Key” of type “Unique Key” on SQL Server 2008 R2.

相关标签:
7条回答
  • 2021-02-01 01:37

    A unique constraint is implemented behind the scenes as a unique index, so it doesn't really matter how you specify it. I tend to implement it simply as:

    ALTER TABLE dbo.foo ADD CONSTRAINT UQ_bar UNIQUE(bar);
    

    Some people create a unique index instead, e.g.

    CREATE UNIQUE INDEX IX_UQ_Bar ON dbo.foo(bar);
    

    The difference is in the intent - if you are creating the constraint to enforce uniqueness/business rules, you create a constraint, if you are doing so to assist query performance, it might be more logical to create a unique index. Again, under the covers it's the same implementation, but the road you take to get there may help document your intent.

    I think there are multiple options to adhere to both previous Sybase functionality as well as to adhere to the ANSI standard (even though unique constraints don't adhere to the standard 100%, since they only allow one NULL value - a unique index, on the other hand, can work around this by adding a WHERE clause (WHERE col IS NOT NULL) on SQL Server 2008 and greater).

    0 讨论(0)
提交回复
热议问题