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.
Other than the excellent answers above, I'd add my 2 cents here.
Unique key is a constraint and it uses unique index to enforce itself. Just as primary key is usually enforced by a clustered unique index. Logically speaking, a constraint and an index are two different things. But in RDBMS, a constraint can be physically implemented through an index.
If a table is created with an unique constraint in sql server, you will see both a constraint object and a unique index
create table dbo.t (id int constraint my_unique_constraint unique (id));
select [Constraint]=name from sys.key_constraints
where parent_object_id = object_id('dbo.t');
select name, index_id, type_desc from sys.indexes
where object_id = object_id('dbo.t')
and index_id > 0;
we will get the following (a constraint and an index)
However, if we do not create a constraint but just a unique index as the following
create table dbo.t2 (id int );
create unique index my_unique_constraint on dbo.t2 (id);
select [Constraint]=name from sys.key_constraints
where parent_object_id = object_id('dbo.t2');
select name, index_id, type_desc from sys.indexes
where object_id = object_id('dbo.t2')
and index_id > 0
You will see there is NO constraint object created (only an index created).
From "theoretical" perspective, in SQL Server, a constraint is an object with object_id value and is schema-bound, while an index is not an object and has no object_id value and no schema related.