Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unique index or unique key?

What is the diffrence between a unique index and a unique key?

like image 464
fariba Avatar asked Sep 25 '10 16:09

fariba


People also ask

What is a unique index?

Unique indexes are indexes that help maintain data integrity by ensuring that no rows of data in a table have identical key values. When you create a unique index for an existing table with data, values in the columns or expressions that comprise the index key are checked for uniqueness.

Does unique key automatically create index?

Yes, absolutely. A unique constraint creates a unique index.

What is the difference between key and index?

A key uniquely identifies a row in a table. An index is the order of rows based a field in a table. A table can have multiple indexes, because an index can just be a certain order of a set fields the system uses to search on and then looks up the actual row.

Is unique key same as unique constraint?

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.


2 Answers

The unique piece is not where the difference lies. The index and key are not the same thing, and are not comparable.

A key is a data column, or several columns, that are forced to be unique with a constraint, either primary key or explicitly defined unique constraint. Whereas an index is a structure for storing data location for faster retrieval.

From the docs:

Unique Index

Creates a unique index on a table or view. A unique index is one in which no two rows are permitted to have the same index key value. A clustered index on a view must be unique

Unique key (Constraint)

You can use UNIQUE constraints to make sure that no duplicate values are entered in specific columns that do not participate in a primary key. Although both a UNIQUE constraint and a PRIMARY KEY constraint enforce uniqueness, use a UNIQUE constraint instead of a PRIMARY KEY constraint when you want to enforce the uniqueness of a column, or combination of columns, that is not the primary key.

like image 122
Dustin Laine Avatar answered Oct 08 '22 12:10

Dustin Laine


This MSDN article comparing the two is what you're after. The terminology is such that "constraint" is ANSI, but in SQL Server you can't disable a Unique Constraint...

For most purposes, there's no difference - the constraint is implemented as an index under the covers. The MSDN article backs this up--the difference is in the meta-data, for things like:

  • tweaking FILLFACTOR
  • INCLUDE provides more efficient covering indexes (composite constraint)
  • A filtered index is like a constraint over a subset of rows/ignore multiple null etc.
like image 34
OMG Ponies Avatar answered Oct 08 '22 14:10

OMG Ponies