使用子查询创建表
在创建表的同时,可以将子查询的结果直接插入其中:
1. 新建表与子查询结果的字段列表必须匹配
create table A (名字,年龄) as select name,age from B
2. 新建表的字段列表可以缺省
create table A as select name,age from B
创建表:
create table A
(
name varchar2(10),
age number(3) default 18,
ttime date default sysdate
)
修改表:alter table
1. 添加字段
alter table A
add(
email varchar2(20),
phone number()
);
//注释
comment on column ASA10_11_TEMP.IMP_SIGN
is '导入状态';
2.修改字段
alter table A
add/modify/drop(
email varchar2(50),
phone number(11)
)
3.删除字段
alter table A
add/modify/drop(
email,
phone
)
清空表中数据
1. 清除表中所有记录
2. 释放表的存储空间
3. 为DDL 语句,一经执行不可撤消
truncate table A
删除表
1. 表中所有数据将被删除
2. 此前未完成的事务将被提交
3. 所有相关的索引被删除
4. 为DDL 语句,一经执行不可撤消
drop table A
重命名表/视图/序列/同义词等
rename old_name to new_name
约束:
1. 非空约束
create table A
(
name varchar2(10) not null ,
age number(3) default 18,
ttime date default sysdate constraint A_ttime_nn not null
)
2. 唯一性约束
create table A
(
name varchar2(10) unique ,
age number(3) default 18
)
create table B
(
name varchar2(10) ,
age number(3) default 18,
constraint B_name_un unique(name)
)
3. 主键约束
create table A
(
name varchar2(10) primary key ,
age number(3) default 18
)
create table B
(
name varchar2(10) ,
age number(3) default 18,
constraint B_name_pk primary key(name)
)
4. 外键约束
create table A
(
id varchar2(50) references 主表名(主表的主键或唯一性字段),
name varchar2(10),
age number(3) default 18
)
create table B
(
id varchar2(50),
name varchar2(10) ,
age number(3) default 18,
constraint B_name_fk foreign key(id) references 主表名(主表的主键或唯一性字段)
)
5. 检查约束
create table A
(
id varchar2(50),
name varchar2(10),
age number(3) default 18 check(age>=0 and age<=120)
)
视图
创建:
create or replace view B(name,age) as select ename,eage from C
删除
drop view B
索引
创建/删除索引
create index myindex on A(id)
drop index myindex
创建索引的原则
1. 字段取值分布范围很广
2. 字段中包含大量空值
3. 字段经常出现在where 子句或连接条件中
4. 表经常被访问、数据量很大,且通常每次访问的数据量小于记录总量的2%~4%
下列情况不适合创建索引
1. 表很小
2. 字段不经常出现在where 子句中
3. 每次访问的数据量大于记录总量的2%~4%
4. 表经常更新
5. 被索引的字段作为表达式的一部分被引用
序列
创建:
create sequence A
increment by n
//n为递增值,默认是1start with n
//初始值,默认是1maxvalue n
//最大值,默认是nomaxvalueminvalue n
//取小值,默认是nominvaluecycle|nocycle
//是否循环(超过上限后,重新开始),默认值nocyclecache n
//缓存数,默认值20order|noorder
//请求顺序
nextval/currval伪列
nextval 指定的序列数值中取出下一个值
currval 指定序列的当前值
insert into A values(序列名.nextval);