What is the difference b/w Primary Key and Unique Key

nectar picture nectar · Jun 4, 2010 · Viewed 83.7k times · Source

I tried to find it out in google but not satisfactory answer is given out there. Can anybody explain the solid difference.

actually if Primary key is used to select data uniquely then what is the need of Unique key?

When should I use a Primary key and when to use a Unique key?

Answer

Kramii picture Kramii · Jun 4, 2010

Primary Key and Unique Key are used for different things - understanding what they are for will help you decide when to use them.

The primary key is used to identify a row of data in a table. It is used whenever you need to refer to a particular row, eg. in other tables or by application code etc. In order to identify a row, the values of a PK must be unique. Furthermore, they can't be null, because most DBMS treat null as not equal to null (since null typically means "unknown"). A table can only have one PK. All tables in your database should have a PK (although this is not enforced by most DBMS), and PK can span multiple columns.

Unique key constraints are used to ensure that data is not duplicated in two rows in the database. One row in the database is allowed to have null for the value of the unique key constraint. Although a table should have a PK, it need not have any additional unique keys. However, tables can have more than one unique key if that meets your needs. Like PKs, unique keys can span multiple columns.

It is also worth knowing that, by default, many DBMS index and physically order tables on disk using the PK. This means that looking up values by their PK is faster than using other values in a row. Typically, however, you can override this behaviour if required.