本教程将演示如何使用sql not null约束来强制列存储null值。
not null约束是一个列约束,它定义将列限制为仅具有非null值的规则。
这意味着当使用insert语句向表中插入新行时,必须指定not null列的值。以下语句是not null约束语法。 它强制column_name不能接受null值。
create table table_name(
...
column_name data_type not null,
...
);
逻辑上,not null约束等同于check约束,因此,上述语句等效于以下语句。
create table table_name (
...
column_name data_type,
...
check (column_name is not null)
);
例如,以下语句创建一个名称为training表,表中有带一个not null约束的taken_date列。
create table training (
employee_id int,
course_id int,
taken_date date not null,
primary key (employee_id , course_id)
);
大多数关系数据库管理系统默认情况下会自动将not null约束添加到主键列,因此不必明确指定它。
以下insert语句违反了not null约束。
insert into training(employee_id,course_id)
values(1,1);
上面插入语句中,taken_date列未指定值,因此默认使用null值,但是taken_date列指定了not null约束,所以插入数据时会出现错误。
通常,在创建表时为列定义not null约束。 但是,有时希望更改列的约束以接受null值。
要进行更改以接受null值,可参考以下两个步骤:
首先,使用update语句将所有当前null值更新为非null值。
update table_name
set column_name = 0
where
column_name is null;
请注意,在where子句中使用is null运算符来查找column_name为null的行。
其次,使用alter table语句将not null约束添加到列
alter table table_name
modify column_name data_type not null;
假设training表的taken_date列为null,想将它更改为not null。
首先,将taken_date列中的所有null值更新为特定日期,例如:当前日期。
update training
set taken_date = current_date ()
where
taken_date is null;
其次,将take_date列更改为not null约束。
alter table training
modify taken_date date not null;
在本教程中,讲解了not null约束的概念,并演示了如何使用not null约束将列约束为仅接受非null值。