简体   繁体   中英

MySQL PRIMARY KEY vs UNIQUE constraints

According to the MySQL documentation, the difference between PRIMARY KEY constraint and UNIQUE constraint is that PK constraint DOES NOT allow NULL values while UQ constraint DOES allow NULL values. In MySQL table one can create both PK and UQ for one the same column!

  • What's the point or reasoning of creating UNIQUE constraint for a column already having a PK constraint!?
  • Why MySQL does allow creating a unique constraint for column which already has a PK constraint?

As a preface, note that a Primary Key does not need to be a single column: it can be comprised of multiple columns: this is known as a Composite Key. Also note that not every table has an AUTO_INCREMENT / IDENTITY column at all, and you can have a UNIQUE constraint on a single column inside a composite-key anyway.

  1. There is none - but it doesn't make sense for a DBMS to prohibit such redundancy either because you'd need added logic and complexity to handle that condition, whereas there's no real harm done by having both (besides the performance impact of having to maintain two indexes).

  2. As said above: because the opportunity cost of detecting and preventing that redundancy isn't worth it.

Another thing to consider is that the primary-key definition of a table is not immutable and therefore is subject to change. A table might already have columns with a UNIQUE constraint set-up and then the database-designer decides to include that in a new definition of the primary-key - it would be a user-unfriendly to require the old constraint be removed first, especially if other parts of their application system depend on that UNIQUE constraint being there (eg a 1:0..1 relationship definition).

(Also, AUTO_INCREMENT is not mutually-inclusive with UNIQUE or PRIMARY KEY : you can use AUTO_INCREMENT with non-unique columns (eg if AUTO_INCREMENT is added after a table already contains data), and contrarywise a PRIMARY KEY can use unique values sourced from elsewhere, such as another identity column as a foreign key (composite primary keys can contain foreign keys!) or a "natural" data source, such as using a US Social Security Number as a Primary Key (of course you should never do this in reality)).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM