维护表的完整性
可以用约束,触发器,应用程序(过程,函数)三种方法实现
而约束作为首选
约束包括not null,nuique,primary key ,foreign key ,check
注意一个表只有一个主键,主键可以有多个列,不可为空。
age number(3) check (age > 0),
name varchar2(20) not null,
mother varchar2(20) nuique,
sex char(2) default '男' check(sex in('男','女')),
categoryId number reference categroy(categoryid),
unms check(sums between 1 and 66)
忘记了约束,可以建表后使用alter table ,但是not null约束需要用
modify选项,其他四种可以使用add 选项
alter table xxx modify name not null;
alter table xxx add constraint useridnuique unique(userid)
// userid 增加不重复约束
删除约束 alter table 表名 drop constraint 约束名
强制删除,主从关系删除 alter table 表名 dropprmary key cascade;
显示约束信息
select constraint_name ,constraint_type,status,validated form
user_constraints where table_name = '表名';
显示约束列
select column_name,position from user_cons_consmns
where constaint_name = '表名' ;
表级定义 列级定义
表定义,定义了之后,在定约束
create table a (id number constraint a_pk primary key,name varchar2(20))
create table b (id number,name varchar2(20),
constraint a_pk primary key(id))
建立索引为什么加了索引,i/o 性能会提高很多。索引不是随意建的,创建的不好反而相反影响性能。
创建索引
单列索引
create index nameindex on 表(name)
联合索引(复合索引)
create index nameindex on 表(字段1,字段2)
-- 注意顺序,一下帅选很多的字段放到后面,因为sql语句的扫描是从后往前扫描的
使用原则
1 大表上建
2 where 子句经常用到
3 索引的层次不要超过4层
索引的缺点:
先天不足:
1:创建索引,系统要占用大约为表的1.2倍的硬盘盒内存空间来
保存空间。
2 更新数据的时候,系统要占额外的时间来同时对索引更新。
什么时候不适合用索引
1 很少或者从不引用的字段
2 男或女
管理索引
按照数据存储方式,可以分为
B* 树,反向索引,位图索引
按照索引的个数分类,可以分为单列索引,复合索引;
按照索引列值的唯一性,可以分为唯一索引和非唯一索引;
此外还有函数索引,全局索引,分区索引。
在不同的情况我们会再不同的列上建立索引,可能是不同种类的索引
,如B*树索引建立在重复值很少的列上,而位图索引则建立在重复值很多,不同值相对固定的列上。
显示表的所有索引,通过dba_indexs,和user_indexs,可以显示索引信息
select index_name,index_type from user_indexs where table_name = '表名';
通过查询数据字典视图user_ind_columns 可以显示索引对应的列的信息
select table_name ,column_name from user_ind_columns where
index_name = 'IND_ENAME'