Difference between primary key and unique key
Asked Answered
R

15

302

I'm using a MySQL database.

In which situations should I create a unique key or a primary key?

Rew answered 5/3, 2012 at 11:39 Comment(2)
wrt null-ability a good way to distinguish b/w them is PRIMARY KEY = UNIQUE KEY + Not Null CONSTRAINTIden
Take a look at dba.stackexchange.com/questions/15572/…. And #1402072Handpick
T
284

Primary Key:

  • There can only be one primary key constraint in a table
  • In some DBMS it cannot be NULL - e.g. MySQL adds NOT NULL
  • Primary Key is a unique key identifier of the record

Unique Key:

  • Can be more than one unique key in one table
  • Unique key can have NULL values
  • It can be a candidate key
  • Unique key can be NULL ; multiple rows can have NULL values and therefore may not be considered "unique"
Telemeter answered 12/11, 2012 at 18:15 Comment(14)
i) Can only one in a table /// sorry but you can have PFK its not same as PK but both have PK identifierAscogonium
Also want to add on that primary key can be created on multiple columns, e.g. Primary key (CustomerID, ProductID). This is called composite primary key. This is to clarify the first point, as it might be take as it is (read one key => one column ) by new comer to sql : )Tullis
passionforsql.com/… here is the link with detailed description.Limnetic
What is your mean of 'can be a candidate key' ?Entablement
"only single null is allowed" - this is not true, at least not for MySQL.Yvor
Unique key can be null and may not be unique Means ??Bonacci
@PratikCJoshi He probably means that the can be multiple rows with null on the otherwise unique key.Tiki
@LoveForDroid Of course not. That's why it's called a unique key.Incipient
@Incipient I knew that. I was asking whether it is possible rather than should I do that. The reason why asked that is, in one of my app, there was a bug where same record was saved twice with same unique key.Earldom
@Earldom strange - what DBMS were you using, and was the constraint definitely correct? it certainly sounds like there was a bug in the DBMS if so.Incipient
@Incipient It was sqlite3 I was accidentally saving the record twice, hence it was creating same record twice.Earldom
@ken: So, means, first diff. is incorrect. As both PK and UK can consist of multiple columns.Leavelle
@Mr. KB : So, means, first diff. is incorrect. As both PK and UK can consist of multiple columns.Leavelle
The info here applies whether the PK (or UNIQUE) is a single column or multiple columns ("composite" key).Panama
O
91

Unique Key (UK): It's a column or a group of columns that can identify a uniqueness in a row.

Primary Key (PK): It's also a column or group of columns that can identify a uniqueness in a row.

So the Primary key is just another name for unique key, but the default implementation in SQL Server is different for Primary and Unique Key.

By Default:

  1. PK creates a Clustered index and UK creates a Non Clustered Index.
  2. PK is not null, but UK allows nulls (Note: By Default)
  3. There can only be one and only one PK on a table, but there can be multiple UK's
  4. You can override the default implementation depending upon your need.

It really depends what is your aim when deciding whether to create a UK or PK. It follows an analogy like "If there is a team of three people, so all of them are peers, but there will be one of them who will be a pair of peers: PK and UK has similar relation.". I would suggest reading this article: The example given by the author may not seem suitable, but try to get an overall idea.

http://tsqltips.blogspot.com/2012/06/difference-between-unique-key-and.html

Olen answered 26/6, 2012 at 0:14 Comment(3)
read around 10 webpages, which say, PK can contain more than one column. Then how can there be one and only one PK on a table?Leavelle
@android A PK with more than one column acts as a single column with respect to the uniqueness. In PostgreSQL at least, this means that a new column (with default name [table_name]_pkey) is added to the table (I've heard this referred to as a surrogate key). Source: postgresqltutorial.com/postgresql-primary-key I'm new to all this so I'd appreciate a more knowledgeable poster to point out the nuances I missed.Nelidanelie
Okay, it's not a column. I misread. It's a contraint, not a column. There's still the clustered index, but it's over two columns instead of one. And each column in it is not a primary key on its own, instead the whole set is a primary key. So there are not more than one PK in these instances.Nelidanelie
P
51

For an organization or a business, there are so many physical entities (such as people, resources, machines, etc.) and virtual entities (their Tasks, transactions, activities). Typically, business needs to record and process information of those business entities. These business entities are identified within a whole business domain by a Key.

As per RDBMS prospective, Key (a.k.a Candidate Key) is a value or set of values that uniquely identifies an entity.

For a DB-Table, there are so many keys are exist and might be eligible for Primary Key. So that all keys, primary key, unique key, etc are collectively called as Candidate Key. However, DBA selected a key from candidate key for searching records is called Primary key.

Difference between Primary Key and Unique key

1. Behavior: Primary Key is used to identify a row (record) in a table, whereas Unique-key is to prevent duplicate values in a column (with the exception of a null entry).

2. Indexing: By default SQL-engine creates Clustered Index on primary-key if not exists and Non-Clustered Index on Unique-key.

3. Nullability: Primary key does not include Null values, whereas Unique-key can.

4. Existence: A table can have at most one primary key, but can have multiple Unique-key.

5. Modifiability: You can’t change or delete primary values, but Unique-key values can.

For more information and Examples:

http://dotnetauthorities.blogspot.in/2013/11/Microsoft-SQL-Server-Training-Online-Learning-Classes-Integrity-Constraints-PrimaryKey-Unique-Key_27.html

Proud answered 10/1, 2014 at 16:40 Comment(3)
In 5th point you say we can't change or delete primary values. we for sure can change the primary values in the table by using an update statement.Peper
@Peper doing so beats the whole purpose of using a primary key.Sulfamerazine
clustered index: the rows are stored physically on the disk in the same order as the indexAfrika
K
27

A primary key must be unique.

A unique key does not have to be the primary key - see candidate key.

That is, there may be more than one combination of columns on a table that can uniquely identify a row - only one of these can be selected as the primary key. The others, though unique are candidate keys.

Knighton answered 5/3, 2012 at 11:42 Comment(0)
H
21
Primary Key Unique Key
A primary key can't accept NULL values Unique key can accept NULL values, so problematic in the context of being unique
A primary key cannot contain duplicate values A unique key also cannot contain duplicate values
We can have only one primary key in a table We can have more than one unique key in a table
We can make a primary key from one or more table fields We can also make a unique key from one or more table fields
By default, a primary key creates a clustered index By default, a unique key creates a non-clustered unique index
It is used to identify each record in the table It prevents storing duplicate entries in a column
Houseraising answered 16/11, 2015 at 20:31 Comment(1)
Yeah, "only one null value per column" is SQL Server but non-standard SQL. PS I converted to markdown table format.Doi
B
17

A primary key has the semantic of identifying the row of a database. Therefore there can be only one primary key for a given table, while there can be many unique keys.

Also for the same reason a primary key cannot be NULL (at least in Oracle, not sure about other databases)

Since it identifies the row it should never ever change. Changing primary keys are bound to cause serious pain and probably eternal damnation.

Therefor in most cases you want some artificial id for primary key which isn't used for anything but identifying single rows in the table.

Unique keys on the other hand may change as much as you want.

Bucktooth answered 5/3, 2012 at 11:44 Comment(2)
+1 for mentioning risk of eternal damnation. It's time to introduce theology into relational database theory.Emilyemina
PK cannot be NULL in SQL Server as wellCapacitate
E
9

A Primary key is a unique key.

Each table must have at most ONE primary key but it can have multiple unique key. A primary key is used to uniquely identify a table row. A primary key cannot be NULL since NULL is not a value.

Esp answered 5/3, 2012 at 11:47 Comment(0)
E
9

Explaining why rather than how:

Purpose of Primary Key: To identify a row in a database uniquely => A row represents a single instance of the entity type modeled by the table. A primary key enforces integrity of an entity, AKA Entity Integrity. Primary Key would be a clustered index i.e. it defines the order in which data is physically stored in a table.

Purpose of Unique Key: Ok, with the Primary Key we have a way to uniquely identify a row. But I have a business need such that, another column/a set of columns should have unique values. Well, technically, given that this column(s) is unique, it can be a candidate to enforce entity integrity. But for all we know, this column can contain data originating from an external organization that I may have a doubt about being unique. I may not trust it to provide entity integrity. I just make it a unique key to fulfill my business requirement.

Exogamy answered 27/12, 2018 at 5:30 Comment(0)
G
8
  • Think the table name is employe.
  • Primary key
  • Primary key can not accept null values. primary key enforces uniqueness of a column. We can have only one Primary key in a table.
  • Unique key
  • Unique key can accept null values. unique key also enforces uniqueness of a column.you can think if unique key contains null values then why it can be unique ? yes, though it can accept null values it enforces uniqueness of a column. just have a look on the picture.here Emp_ID is primary and Citizen ID is unique. Hope you understand. We can use multiple unique key in a table. enter image description here
Gammer answered 19/11, 2017 at 13:15 Comment(3)
we can't insert more than one null values in Unique key and it will not allow duplicates also.Fanfare
@mahedi-hasan Isn't Unique key column should have only one NULL value? How come last two rows in Citizen ID NULL? Am I missing something here?Eaglestone
Just got answer to my own comment above. Looks like MySQL allows multiple NULL in unique also so looks like @Mahedi_Hasan used MySQL. #3712722Eaglestone
C
1

If your Database design is such that their is no need of foreign key, then you can go with Unique key( but remember unique key allow single null value ).

If you database demand foreign key then you leave with no choice you have to go with primary key.

To see the difference between unique and primary key visit here

Conni answered 17/4, 2016 at 7:49 Comment(1)
Unique constraint can be referenced from foreign key. Primary key is not mandatory.Standby
M
1

Unique key:

It should be used when you have to have a unique value. In the case of unique key it means null values are also allowed. Unique keys are those keys which are unique and not similar in that column. For example your pet name. It can be nothing, like null, and if you are asking in context of a database then every null is different from another null in the database. (EXCEPT SQL Server where null=null is true.)

Primary key:

It should be used when you have to give uniquely identify a row. A primary is a key which is unique for every row in a database and doesn't allow null. So you might have seen that the database has a column which is auto incremented and it is the primary key of the table. It can be used as a foreign key in another table. For example: orderId on an order Table, billId in a bill Table.

When to use:

Use a primary key in the column which cannot be null in the table that you are using as foreign key in another table for creating a relationship.

Use a unique key in a table where it doesn't affect whether you take the null for the particular column in the table or in the whole database. For example snacks in the restaurant when it is possible you don't take snacks in a restaurant

Mo answered 24/7, 2018 at 9:52 Comment(0)
D
1

difference between Primary Key and Unique Key

Both Primary key and Unique Key are used to uniquely define of a row in a table. Primary Key creates a clustered index of the column whereas a Unique creates an unclustered index of the column.

A Primary Key doesn’t allow NULL value, however a Unique Key does allow one NULL value.

Dispermous answered 26/11, 2018 at 13:3 Comment(0)
C
0

Simply Primary Key is a unique and can't be null, unique can be null and may not be unique.

Copp answered 11/11, 2014 at 9:50 Comment(1)
"unique can be null and may not be unique". What does may not be unique means here?Moria
G
0

Primary Keys

The main purpose of the primary key is to provide a means to identify each record in the table.

The primary key provides a means to identity the row, using data within the row. A primary key can be based on one or more columns, such as first and last name; however, in many designs, the primary key is an auto-generated number from an identity column.

A primary key has the following characteristics:

  1. There can only be one primary key for a table.
  2. The primary key consists of one or more columns.
  3. The primary key enforces the entity integrity of the table.
  4. All columns defined must be defined as NOT NULL.
  5. The primary key uniquely identifies a row.
  6. Primary keys result in CLUSTERED unique indexes by default.

Unique Keys

A unique key is also called a unique constraint. A unique constraint can be used to ensure rows are unique within the database.

Don’t we already do that with the primary key? Yep, we do, but a table may have several sets of columns which you want unique.

In SQL Server the unique key has the following characteristics:

  1. There can be multiple unique keys defined on a table.
  2. Unique Keys result in NONCLUSTERED Unique Indexes by default.
  3. One or more columns make up a unique key.
  4. Column may be NULL, but on one NULL per column is allowed.
  5. A unique constraint can be referenced by a Foreign Key Constraint.

source : here

Goalie answered 24/7, 2018 at 9:58 Comment(0)
S
0

A primary key’s main features are:

It must contain a unique value for each row of data. It cannot contain null values. Only one Primary key in a table.

A Unique key’s main features are:

It can also contain a unique value for each row of data.

It can also contain null values.

Multiple Unique keys in a table.

Swish answered 27/6, 2019 at 17:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.