Oracle 建表语句,表结构操作sql
创建表
创建表结构
create table test (id number(6) primary key,
name varchar2(20 char), --char类型,一个汉字占一个长度
text varchar2(30 byte), --byte类型,UTF8一个汉字占大约两个长度
createTime date,
number int not null,
state number(1) default 0 null,--默认值,如果为空就设置为0
doubl double,
age char(1),
content clob, -- clob可以直接存储文字,常用来存储文章等较长的文字内容
content_b blob --blob是按二进制格式存储的,所以经常用来存储文件、图片等二进制数据
);
comment on table "test" is '测试表';
comment on column "test"."name" is '名称';
创建表索引
索引命名规范
主键索引:应包含表名和一个后缀,如 _PK
唯一建索引:应包含表名和一个后缀,如_UKN(N为数字)
外键列上的索引:应包含外键表和一个后缀,如_FKN(N为数字)
不用约束的索引:应包含一个表名和一个数字,如_IDXN(N为数字)
- 语法
CREATE INDEX
CREATE [unique] INDEX [schema.]index
ON [schema.]table (column [ASC | DESC] [,column
[ASC | DESC] ] ... )
[CLUSTER [scheam.]cluster]
[INITRANS n]
[MAXTRANS n]
[PCTFREE n]
[STORAGE storage]
[TABLESPACE tablespace]
[NO SORT]
- 说明
schema ORACLE模式,缺省即为当前帐户
index 索引名
table 创建索引的基表名
column 基表中的列名,一个索引最多有16列,long列、long raw 列不能建索引列
DESC、ASC 缺省为ASC即升序排序
CLUSTER 指定一个聚簇(Hash cluster不能建索引)
INITRANS、MAXTRANS 指定初始和最大事务入口数
Tablespace 表空间名
STORAGE 存储参数,同create table 中的storage.
PCTFREE 索引数据块空闲空间的百分比(不能指定pctused)
NOSORT 不(能)排序(存储时就已按升序,所以指出不再排序)
- 案例
create index idx_test_name1 on test(name);
修改表
增加字段
- 语法
alter table tablename add (column datatype [default value][null/not null],….);
- 说明
alter table 表名 add (字段名 字段类型 默认值 是否为空);
- 案例
alter table test add (name varchar2(10) default '' not null);
修改字段
- 语法
alter table tablename modify (column datatype [default value][null/not null],….);
- 说明
alter table 表名 modify (字段名 字段类型 默认值 是否为空);
- 案例
alter table test modify (id number(3));
删除字段
- 语法
alter table tablename drop (column);
- 说明
alter table 表名 drop column 字段名;
- 案例
alter table test drop column name;
字段重命名
- 语法
alter table tablename rename column columnname to newcolumnname
- 说明
alter table 表名 rename column 列名 to 新列名
- 案例
alter table test rename column name to newname;
表重命名
- 语法
alter table tablename rename to newtablename
- 说明
alter table 表名 rename to 新表名
- 案例
alter table test rename to test2;
修改索引
- 语法
ALTER [UNIQUE] INDEX [user.]index
[INITRANS n]
[MAXTRANS n]
REBUILD
[STORAGE n]
- 说明
REBUILD 是 根据原来的索引结构重新建立索引,实际是删除原来的索引后再重新建立。
DBA经常用 REBUILD 来重建索引可以减少硬盘碎片和提高应用系统的性能。
- 案例
alter index idx_test_name1 rebuild storage(initial 1m next 512k);
alter index idx_test_name1 rebuild reverse;
删除索引
- 语法
drop index [schema.]indexname