Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In MySQL does a UNIQUE varchar have to be a PRIMARY KEY as well?

Tags:

sql

mysql

I have 2 unique values under 1 table in MySQL.

|id (PK)|varchar(255) UNIQUE|
-----------------------------
|   1   |      1234abcde    |
|   2   |      5678fghij    |
|   3   |      9012klmno    |

Do I have to set UNIQUE varchar as a PK or I can still use auto_incremented id (int)? Is this a good or bad practice?

like image 606
Tatarin Avatar asked Feb 04 '26 17:02

Tatarin


2 Answers

No, it doesn't have to be a primary. Primaries are unique, but not every unique is a primary.

like image 150
Refugnic Eternium Avatar answered Feb 06 '26 05:02

Refugnic Eternium


One table can have multiple keys. One of them is "primary" (PRIMARY KEY) and the rest are "alternate" (UNIQUE constraint).

But beware that under InnoDB primary key also acts as a clustered index, so choosing one key or another to be primary can have profound performance implications.

like image 26
Branko Dimitrijevic Avatar answered Feb 06 '26 05:02

Branko Dimitrijevic



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!