NOT NULL 與 UNIQUE 限制

SQL 關聯式資料庫入門

Timo Grossenbacher

Data Journalist

NOT NULL 限制

  • 不允許某欄位為 NULL
  • 當前狀態必須成立
  • 未來狀態也必須成立
SQL 關聯式資料庫入門

NULL 代表什麼?

  • 未知
  • 不存在
  • 不適用
SQL 關聯式資料庫入門

NULL 的例子

CREATE TABLE students (
 ssn integer not null,
 lastname varchar(64) not null,
 home_phone integer,
 office_phone integer
);
NULL != NULL
SQL 關聯式資料庫入門

如何新增或移除 NOT NULL 限制

建立資料表時…

CREATE TABLE students (
 ssn integer not null,
 lastname varchar(64) not null,
 home_phone integer,
 office_phone integer
);

建立後…

ALTER TABLE students 
ALTER COLUMN home_phone 
SET NOT NULL;
ALTER TABLE students 
ALTER COLUMN ssn 
DROP NOT NULL;
SQL 關聯式資料庫入門

UNIQUE 限制

  • 不允許欄位出現重複值
  • 當前狀態必須成立
  • 未來狀態也必須成立

SQL 關聯式資料庫入門

新增 UNIQUE 限制

CREATE TABLE table_name (
 column_name UNIQUE
);
ALTER TABLE table_name
ADD CONSTRAINT some_name UNIQUE(column_name);
SQL 關聯式資料庫入門

把這些套用到資料庫吧!

SQL 關聯式資料庫入門

Preparing Video For Download...