When should we use a unique key


SQL UNIQUE Constraint

The UNIQUE constraint ensures that all values in a column are different.

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.


======================== Q and A

Question Since primary key and unique is similar. I have trouble grasping the concept of the two. I know primary key doesnt accept null and unique key accepts a null once. Since a null value is a unique value so it can be only accepted once. But the idea of primary key is having a uniqueness in every row. which a unique key also do. thats why im asking when is it proper to use primary key over unique key and vice versa.

Answer
A UNIQUE constraint is similar to PRIMARY key, but you can have more than one UNIQUE constraint per table.

When you declare a UNIQUE constraint, SQL Server creates a UNIQUE index to speed up the process of searching for duplicates. In this case the index defaults to NONCLUSTERED index, because you can have only one CLUSTERED index per table.
  • The number of UNIQUE constraints per table is limited by the number of indexes on the table i.e 249 NONCLUSTERED index and one possible CLUSTERED index.
Contrary to PRIMARY key UNIQUE constraints can accept NULL but just once. If the constraint is defined in a combination of fields, then every field can accept NULL and can have some values on them, as long as the combination values is unique.
Also Refer other link (MSDN)


=========================

primary and unique key comparison

=========================

So when should you use a primary key?
Always!  In my book, every table should have a primary key.  It provides the main way (primary) to identify each row.
When should you use a unique key?
I would use a unique key when you have columns you know shouldn’t contain duplicates.  This becomes a great way to ensure data validation. 

Comments

Popular posts from this blog

Tree view in winforms using c#

how to Replace null value with 0 Using C#

how to fetch all HTML Table Records and modify all records accordingly using jquery and Javascript