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.
But I have the following questions:
IsUnique
value to be "Yes",, then will there be any differences ?Unique Key: It is a constraint which imposes limitation on database. That limitation is it will not allow duplicate values . For example if you want to select one column as primary key it should be NOT NULL & UNIQUE. Unique Index: It is a index which improves the performance while executing queries on your data base.
Unique keys are indexes. If your values are guaranteed to be unique, this is the best choice. Unique Key: Unique Key enforces uniqueness of the column on which they are defined. Unique Key creates a non-clustered index on the column.
Yes, absolutely. A unique constraint creates a unique index.
Both the UNIQUE and PRIMARY KEY constraints provide a guarantee for uniqueness for a column or set of columns. A PRIMARY KEY constraint automatically has a UNIQUE constraint. However, you can have many UNIQUE constraints per table, but only one PRIMARY KEY constraint per table.
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).
One additional thing to mention, is that if you create index, you can specify included columns , this can help your sql code to work faster if there is some searching by country_name.
CREATE UNIQUE NONCLUSTERED INDEX IX_UQ_Bar ON dbo.foo ( bar ) INCLUDE (foo_other_column) GO SELECT foo_other_column FROM Foo WHERE bar = 'test'
SQL server will store "foo_other_column" in index itself. In case of unique constraint it will first find index of 'test', then will search for row in foo table and only there it will take "foo_other_column".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With