非空与唯一性约束

SQL 关系型数据库入门

Timo Grossenbacher

Data Journalist

非空约束

  • 禁止某列出现 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 关系型数据库入门

如何添加或移除非空约束

创建表时…

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 关系型数据库入门

唯一性约束

  • 禁止列中出现重复值
  • 对当前状态必须成立
  • 对未来任何状态必须成立

SQL 关系型数据库入门

添加唯一性约束

CREATE TABLE table_name (
 column_name UNIQUE
);
ALTER TABLE table_name
ADD CONSTRAINT some_name UNIQUE(column_name);
SQL 关系型数据库入门

将其应用到数据库!

SQL 关系型数据库入门

Preparing Video For Download...