MySQL学习笔记:非空约束、默认约束

**

1. --非空约束

**

–修饰的字段不能为空 NULL

create table user6(
	id int,
	name varchar(20) not null
);
+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(20) | NO   |     | NULL    |       |
+-------+-------------+------+-----+---------+-------+
2 rows in set (0.00 sec)

插入语句必须提供非空字段的值:

insert into user6 values(1,'张三');
insert into user6 (name) values('李四’)
  1. 默认约束

默认约束是当插入字段值如果没有传值,就会使用默认值。

create table user7(
	id int,
	name varchar(20),
	age int default 10
);

+-------+-------------+------+-----+---------+-------+
| Field | Type        | Null | Key | Default | Extra |
+-------+-------------+------+-----+---------+-------+
| id    | int(11)     | YES  |     | NULL    |       |
| name  | varchar(20) | YES  |     | NULL    |       |
| age   | int(11)     | YES  |     | 10      |       |
+-------+-------------+------+-----+---------+-------+
3 rows in set (0.00 sec)
insert into user7  (id,name)  values(1,'张三');
+------+------+------+
| id   | name | age  |
+------+------+------+
|    1 | 张三 |   10 |
+------+------+------+
1 row in set (0.00 sec)
insert into user7  (id,name,age)  values(1,'李四',25);
+------+------+------+
| id   | name | age  |
+------+------+------+
|    1 | 张三 |   10 |
|    1 | 李四 |   25 |
+------+------+------+
2 rows in set (0.00 sec)

总结

非空约束和默认约束 同样支持下列方法对表进行更改。

alter table ... add 

alter table modify ...

你可能感兴趣的:(MySQL)