Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIQUE and PRIMARY KEY

Tags:

sql

mysql

Is declaring an attribute of a table as UNIQUE equivalent to declaring it as PRIMARY KEY?

thanks a lot!

like image 856
ultrajohn Avatar asked Mar 16 '10 05:03

ultrajohn


People also ask

Which is a unique key?

A unique key is a set of one or more than one fields/columns of a table that uniquely identify a record in a database table. You can say that it is little like primary key but it can accept only one null value and it cannot have duplicate values.

Does Unique mean primary key?

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.

Can a key be both primary and unique?

yes, you can have primary key and unique key in the same MySQL table.


2 Answers

The different is: Primary key will create clustered index by default and only one PK can exist in one table. Primary key can cover multiple columns (composite key)

like image 188
heisthedon Avatar answered Oct 04 '22 02:10

heisthedon


UNIQUE can still be NULL.

PRIMARY KEY means UNIQUE and NOT NULL and there can be only one PRIMARY KEY per table.

like image 20
Thilo Avatar answered Oct 04 '22 04:10

Thilo