约束
约束用于限制加入表的数据的类型。
可以在创建表时规定约束(通过 CREATE TABLE 语句),或者在表创建之后也可以(通过 ALTER TABLE 语句)。
我们将主要探讨以下几种约束:
- NOT NULL
- UNIQUE
- PRIMARY KEY
- FOREIGN KEY
- CHECK
- DEFAULT
这里我们详解建表之后创建约束:
1.主键约束:
格式为:
alter table 表格名称 add constraint 约束名称 增加的约束类型 (列名)
例子:
alter table emp add constraint ppp primary key (id);
2.check约束:就是给一列的数据进行了限制
格式:
alter table 表名称 add constraint 约束名称 增加的约束类型 (列名)
例子:
alter table emp add constraint xxx check(age>20);
3.unique约束:这样的约束就是给列的数据追加的不重复的约束类型
格式:
alter table 表名 add constraint 约束名称 约束类型(列名)
例子:
alter table emp add constraint qwe unique(ename);
4.默认约束:意思很简单就是让此列的数据默认为一定的数据
格式:
alter table 表名称 add constraint 约束名称 约束类型 默认值) for 列名
例子:
alter table emp add constraint jfsd default 10000 for gongzi;
5.外键约束:
格式:
alter table 表名 add constraint 约束名称 约束类型 (列名) references 被引用的表名称 (列名)
例子:
alter table emp add constraint jfkdsj foreign key (did) references dept (id);
6.not null约束(不接受null值):
UNIQUE 约束唯一标识数据库表中的每条记录。
UNIQUE 和 PRIMARY KEY 约束均为列或列集合提供了唯一性的保证。
PRIMARY KEY 拥有自动定义的 UNIQUE 约束。
请注意,每个表可以有多个 UNIQUE 约束,但是每个表只能有一个 PRIMARY KEY 约束。
撤销约束(除开default):
alter table table_name
drop constraint key_name;
撤销default约束:
alter table table_name
alter column 列名 drop default
索引
您可以在表中创建索引,以便更加快速高效地查询数据。
用户无法看到索引,它们只能被用来加速搜索/查询。
注释:更新一个包含索引的表需要比更新一个没有索引的表更多的时间,这是由于索引本身也需要更新。因此,理想的做法是仅仅在常常被搜索的列(以及表)上面创建索引。
建立索引:
在表上创建一个简单的索引。允许使用重复的值:
create index index_name
on table_name(column_name)
在表上创建一个唯一的索引。唯一的索引意味着两个行不能拥有相同的索引值
create unique index index_name
on table_name (column_name1)
若索引不止一个列,则:
create inde index_name
on table(lastname,first name)
删除索引:
drop index table_name.index_name