本教程将演示如何使用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
值。