sql语句介绍
- 数据定义语言(ddl),包括 create、 alter、 drop等。
- 数据操纵语言(dml),包括 insert、 update、 delete、 select … for update等。
- 数据查询语言(dql),包括基本查询语句、 order by 子句、 group by 子句等。
- 事务控制语言(tcl),包括 commit、 savepoint、rollback。
- 数据控制语言(dcl), grant、 revoke。
字段类型
varchar2(length)
字符串类型:存储可变的长度的字符串,length是字符串的最大长度,默认是1,最大不超过4000。
char(length)
字符串类型:存储固定长度的字符串,length字符串的固定长度,默认是1,最大不超过2000。
number(a,b)
数值类型:存储数值类型,可以存整数和浮点型。a代表数值的最大位数,包含小数位和小数点;b代表小数的位数。例子:
number(6,2),输入123.12345,实际存入:123.12 。
number(4,2),输入12312.345,提示不能存入,超过存储的指定的精度。
data
时间类型:存储的是日期和时间,包括年、月、日、时、分、秒。
内置函数sysdate获取的就是data类型。
timestamp
时间类型:存储的不仅是日期和时间,还包含了时区。
内置函数systimestamp获取的就是timestamp类型。
clob
大字段类型:存储大文本,大于4000长度的字符串。
blob
二进制类型:存储的是二进制对象,比如图片、视频、声音等转换过来的二进制对象。
创建表
-- stuinfo学生信息表
create table student.stuinfo
(
stuid varchar2(11) not null,--学号
stuname varchar2(50) not null,--学生姓名
sex char(1) not null, --性别
age number(2) not null, --年龄
classno varchar2(7) not null, --班号
stuaddress varchar2(100) default '未录入', --地址
grade char(4) not null, --年级
enroldate date, --入学时间
idnumber varchar2(18) default '身份证未采集' not null --身份证
)
-- stuinfo存储的表空间是users
-- storage表示存储参数
-- initial表示区段(extent)一次扩展64k
-- minextents最小区段数为1
-- maxextents最大的区段数不限制
tablespace users
storage
(
initial 64k
minextents 1
maxextents unlimited
);
-- add comments to the table
comment on table student.stuinfo
is '学生信息表';
-- add comments to the columns
comment on column student.stuinfo.stuid
is '学号';
comment on column student.stuinfo.stuname
is '学生姓名';
comment on column student.stuinfo.sex
is '学生性别';
comment on column student.stuinfo.age
is '学生年龄';
comment on column student.stuinfo.classno
is '学生班级号';
comment on column student.stuinfo.stuaddress
is '学生住址';
comment on column student.stuinfo.grade
is '年级';
comment on column student.stuinfo.enroldate
is '入学时间';
comment on column student.stuinfo.idnumber
is '身份证号';
添加约束
-- 创建/重建主键索引、唯一索引、外键索引 -- 把 stuid 设为主键,主键字段的数据必须是唯一性的(学号是唯一的) alter table student.stuinfo add constraint pk_stuinfo_stuid primary key (stuid); -- 创建/重建检查约束 -- 年龄age添加约束,学生的年龄只能0-50岁之间 alter table student.stuinfo add constraint ch_stuinfo_age check (age>0 and age<=50); alter table student.stuinfo add constraint ch_stuinfo_sex check (sex='1' or sex='2'); alter table student.stuinfo add constraint ch_stuinfo_grade check (grade>='1900' and grade<='2999');