Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql - Is primary key unique by default?

If I define a column as a primary key in MySQL, is it also unique key by default or do I need to also define it as unique key (in case I want it to be unique)?

I saw this question What is the difference b/w Primary Key and Unique Key that explain the difference between the two, but doesn't exactly answer my question.

Does PK is UK by default or I need to explicitly define it?

like image 855
Roee Gavirel Avatar asked Jun 18 '15 09:06

Roee Gavirel


People also ask

Does primary key have to be unique?

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).

Is unique key created automatically?

There is an automatically defined unique key constraint within a primary key constraint. There may be many unique key constraints for one table, but only one PRIMARY KEY constraint for one table.


2 Answers

Primary key is always unique in every SQL. You dont have to explicitly define it as UNIQUE.

On a side note: You can only have onePrimary key in a table and it never allows null values. Also you can have only one primary key constraint in the table(as the point of creating a primary key is to uniquely identify the row in your table) but you can more than one unique key constraint in your table.

Example:

An employee details table having EmpID as Primary key and EmpPhoneNo as unique key.

like image 116
Rahul Tripathi Avatar answered Oct 21 '22 07:10

Rahul Tripathi


Primary key is always unique by definition. Not only in MySQL. So you don't need any additional unique key.

like image 7
Jakub Matczak Avatar answered Oct 21 '22 07:10

Jakub Matczak