Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 594
nectar Avatar asked Jun 04 '10 10:06

nectar


People also ask

What is difference between a primary key and 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.

What is the difference between primary key and unique key Class 11?

The primary key is accepted as a unique or sole identifier for every record in the table. In the case of a primary key, we cannot save NULL values. In the case of a unique key, we can save a null value, however, only one NULL value is supported.

What is primary and unique key in SQL?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


1 Answers

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.

like image 130
Kramii Avatar answered Sep 18 '22 09:09

Kramii