SQL, unique key and primary key

How to create unique key and primary key in SQL database

Use the table created by this command:

CREATE TABLE people (
  age INT NOT NULL,
  name CHAR(20) NOT NULL
);

We can insert an item multiple times.

In particular, we can have columns that repeat the same value.

We can useUNIQUEKey constraints:

CREATE TABLE people (
  age INT NOT NULL,
  name CHAR(20) NOT NULL UNIQUE
);

Now, if you try to add "Flavio" twice:

INSERT INTO people VALUES (37, 'Flavio');
INSERT INTO people VALUES (20, 'Flavio');

You will get an error:

ERROR:  duplicate key value violates unique constraint "people_name_key"
DETAIL:  Key (name)=(Flavio) already exists.

A primary key is a unique key that has another property: it’s the primary way we identify a row in the table.

CREATE TABLE people (
  age INT NOT NULL,
  name CHAR(20) NOT NULL PRIMARY KEY
);

The primary key can be an email in a list of users, for example.

The primary key can be a unique id that we assign to each record automatically.

Whatever that value is, we know we can use it to reference a row in the table.


More database tutorials: