非空约束(Not Null Constraint)指字段的值不能为空。对于使用了非空约束的字段,如果用户在添加数据时没有指定值,数据库系统就会报错。
在创建表时设置非空约束
创建表时可以使用 NOT NULL 关键字设置非空约束,具体的语法规则如下:<字段名> <数据类型> NOT NULL;
【实例 1】创建数据表 tb_dept4,指定部门名称不能为空,输入的 SQL 语句和运行结果如下所示。mysql> CREATE TABLE tb_dept4 -> ( -> id INT(11) PRIMARY KEY, -> name VARCHAR(22) NOT NULL, -> location VARCHAR(50) -> ); Query OK, 0 rows affected (0.37 sec) mysql> DESC tb_dept3; +----------+-------------+------+-----+---------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+---------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(22) | NO | | NULL | | | location | varchar(50) | YES | | NULL | | +----------+-------------+------+-----+---------+-------+ 3 rows in set (0.06 sec)
在修改表时添加非空约束
修改表时设置非空约束的语法规则如下: ALTER TABLE <数据表名>
CHANGE COLUMN <字段名>
<字段名> <数据类型> NOT NULL;
mysql> ALTER TABLE tb_dept4 -> CHANGE COLUMN location -> location VARCHAR(50) NOT NULL; Query OK, 0 rows affected (0.15 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC tb_dept4; +----------+-------------+------+-----+----------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+----------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(22) | NO | | NULL | | | location | varchar(50) | NO | | NULL | | +----------+-------------+------+-----+----------+-------+ 3 rows in set (0.00 sec)
删除非空约束
修改表时删除非空约束的语法规则如下: ALTER TABLE <数据表名>
CHANGE COLUMN <字段名> <字段名> <数据类型> NULL;
mysql> ALTER TABLE tb_dept4 -> CHANGE COLUMN location -> location VARCHAR(50) NULL; Query OK, 0 rows affected (0.15 sec) Records: 0 Duplicates: 0 Warnings: 0 mysql> DESC tb_dept4; +----------+-------------+------+-----+----------+-------+ | Field | Type | Null | Key | Default | Extra | +----------+-------------+------+-----+----------+-------+ | id | int(11) | NO | PRI | NULL | | | name | varchar(22) | NO | | NULL | | | location | varchar(50) | YES | | NULL | | +----------+-------------+------+-----+----------+-------+ 3 rows in set (0.00 sec)