How do UNIQUE and CHECK constraints work, and how do they differ from PRIMARY KEY and NOT NULL?
How do UNIQUE and CHECK constraints work, and how do they differ from PRIMARY KEY and NOT NULL?
Constraints let the database reject bad data itself. NOT NULL forbids missing values, UNIQUE forbids duplicates, CHECK enforces a rule on the value, and PRIMARY KEY combines UNIQUE and NOT NULL for the row identifier.
CREATE TABLE employees (
id BIGINT PRIMARY KEY,
email VARCHAR(255) NOT NULL UNIQUE,
phone VARCHAR(30) UNIQUE, -- nullable and unique
salary DECIMAL(10,2) NOT NULL CHECK (salary >= 0),
hired_on DATE NOT NULL,
left_on DATE,
CONSTRAINT chk_dates CHECK (left_on IS NULL OR left_on >= hired_on)
);
PRIMARY KEY |
UNIQUE |
|
|---|---|---|
| Per table | one | many |
NULL allowed |
no | yes (several in most engines; SQL Server allows one) |
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.