Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is it proper to use unique key in a table than a primary key?

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.

like image 825
Kester Soriano Avatar asked Mar 07 '12 03:03

Kester Soriano


People also ask

Can I use unique key instead of primary key?

Primary key will not accept NULL values whereas Unique key can accept NULL values. A table can have only one primary key whereas there can be multiple unique key on a table. A Clustered index automatically created when a primary key is defined whereas Unique key generates the non-clustered index.

What's the difference between a primary key and a unique key?

A primary key can constitute one or more fields of a table to identify records in a table uniquely. On the other hand, a unique key prevents two rows from having duplicate entries in a column. A table cannot have more than one primary key in a relational database, while there can be multiple unique keys per table.

Why must a primary key be unique?

Purpose: Primary Key is used to uniquely identify a row but a unique key is used to prevent duplicate values in a column. Existence: A table can have only one primary key but it can have multiple unique keys.

What is true about unique and primary key?

What is true about Unique and primary key? a) Unique can have multiple NULL values but Primary can't have. b) Unique can have single NULL value but Primary can't have even single. Explanation: Primary key doesn't allow Null values and Unique key allows Null value, but only one Null value.


1 Answers

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)

like image 73
Sanjay Goswami Avatar answered Oct 12 '22 22:10

Sanjay Goswami