SQL,唯一鍵和主鍵

如何在SQL數據庫中創建唯一鍵和主鍵

使用通過此命令創建的表:

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

我們可以多次插入一個項目。

特別是,我們可以有重複相同值的列。

我們可以使用UNIQUE關鍵約束:

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

現在,如果您嘗試兩次添加“ Flavio”:

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

您會得到一個錯誤:

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: