Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between Unique Key and Primary Keys

Tags:

sql

mysql

I came across the following SQL in a book:

CREATE TABLE 'categories'(
id SMALLINT NOT NULL AUTO INCREMENT,
category VARCHAR(30) NOT NULL,
PRIMARY KEY('id'),
UNIQUE KEY 'category'('category')
)ENGINE=MyISAM DEFAULT CHARSET = utf8;

I was wondering is there a reason why I would need a PRIMARY and UNIQUE KEY in the same table? I guess, underlying that question is, what is the difference between PRIMARY and UNIQUE keys?

like image 529
locoboy Avatar asked Jun 16 '11 23:06

locoboy


People also ask

What is primary key and unique key in SQL?

The PRIMARY KEY constraint uniquely identifies each record in a table. 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).


2 Answers

The relational model says there's no essential difference between one key and another. That is, when a relation has more than one candidate key, there are no theoretical reasons for declaring that this key is more important than that key. Essentially, that means there's no theoretical reason for identifying one key as a primary key, and all the others as secondary keys. (There might be practical reasons, though.)

Many relations have more than one candidate key. For example, a relation of US states might have data like this.

State      Abbr      Postal Code
--
Alabama    Ala.      AL
Alaska     Alaska    AK
Arizona    Ariz.     AZ
...
Wyoming    Wyo.      WY

It's clear that values in each of those three columns are unique--there are three candidate keys.

If you were going to build a table in SQL to store those values, you might do it like this.

CREATE TABLE states (
  state varchar(15) primary key,
  abbr varchar(10) not null unique,
  postal_code char(2) not null unique
);

And you'd do something like that because SQL doesn't have any other way to say "My table has three separate candidate keys."

I didn't have any particular reason for choosing "state" as the primary key. I could have just as easily chosen "abbr" or "postal_code". Any of those three columns can be used as the target for a foreign key reference, too.

And as far as that goes, I could have built the table like this, too.

CREATE TABLE states (
  state varchar(15) not null unique,
  abbr varchar(10) not null unique,
  postal_code char(2) not null unique
);
like image 113
Mike Sherrill 'Cat Recall' Avatar answered Oct 05 '22 11:10

Mike Sherrill 'Cat Recall'


I'm surprised that nobody mentionned that a primary key can be referenced as foreign key into other tables.

Also an unique constraint allows NULL values.

like image 41
Luc M Avatar answered Oct 05 '22 10:10

Luc M