MySql - Is primary key unique by default?

北战南征 提交于 2019-12-03 10:26:20

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.

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

Note that composite keys may lead to confusion : indeed a primary key can be a composite key, and DESCRIBE will show all of the composite key components as primary keys :

> DESCRIBE foobar;
+----------------------+------------------+------+-----+---------+-------+
| Field                | Type             | Null | Key | Default | Extra |
+----------------------+------------------+------+-----+---------+-------+
| column_A             | int(10) unsigned | NO   | PRI | NULL    |       |
| column_B             | int(10) unsigned | NO   | PRI | NULL    |       |
+----------------------+------------------+------+-----+---------+-------+

However SHOW CREATE TABLE will show the reality :

> SHOW CREATE TABLE foobar;
+--------+---------------------------…+
| Table  | Create Table              …|
+--------+---------------------------…+
| foobar | CREATE TABLE `foobar` (
  `column_A` int(10) unsigned NOT NULL,
  `column_B` int(10) unsigned NOT NULL,
  PRIMARY KEY (`column_A`,`column_B`),
  KEY `column_B` (`column_B`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 |
+--------+---------------------------…+
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!