SQL分為5大類:
DDL:數據定義語言
DCL:數據控制語言
DML:數據操縱語言
DTL:數據事務語言
DQL:數據查詢語言
?
1、DDL(data definition language):create,drop,alter,rename to
數據類型
①、數字類型,可以數學運算
number(4)代表整數,最大4位數,也就是9999
number(7,2)代表小數,總長度7位,小數2位,整數5位
②、字符型,可以拼接
char(20), 固定長度,不管里面多少內容,只要小于20,輸出結果就是20個字符
varchar2(20),不固定長度,最長20個字符
在數據庫中要用 ' ' 標注字符串
③、日期類型,可以加減運算
date 年月日時分秒
time 時分秒
timestamp ?年月日時分秒,還有小時位,如1.2秒
④、大數據類型
clob character large object 大字符型對象,最大可存4G
blob binary large object 大二進制對象,最大可存4G
注意:大數據類型不支持查看結果
?
約束(constraint)
作用:約束表格中是數據,相對于數據類型而言,用來進一步限定表中的數據,使得添加到表中的數據都是合法有效的,符合業務需求的數據,不會出現無效數據
2、oracle中的5種約束
primary key PK 含義:主鍵
not null NN 含義:非空
unique UK 含義:唯一
check ??CK 含義:自定義約束,相當于添加條件
foreign key FK 含義:外鍵
?
3、創建表格
create table abc(
id number(4),
name varchar2(10),
title varchar2(10),
constraint abc_id_pk primary key(id),
constraint abc_name_nn check(name is not null),
constraint abc_title_nn check(title is not null)
);
create table bcd(
id number(4),
name varchar2(10),
manager_id number(4),
constraint bcd_id_pk primary key(id),
constraint bcd_name_nn check(name is not null),
constraint bcd_manager_id_fk foreign key(manager_id) references abc(id)
↑ ?↑ ? ?↑
外鍵的列 主鍵表 ? 主鍵id
);
?
創建表格的另一種方法,就是把已有的表復制過來
--復制某張表中的指定列,構建一張新的表格(拷貝了數據)
create table 新表格名 as select 列,列,列from原表格;
例:創建一張表格,表格中只有s_emp表中的id,first_name,salary三列數據
create table new_emp as select id,first_name,salary from s_emp;
--復制了某張表格的指定列,構建一張新表格(不拷貝數據,取表結構)
create table 新表格名 as select 列,列,列from原表格 where 恒假條件;
例:創建一張表格,表格中只有s_emp表中的id,first_name,salary三列數據
create table new_emp as select id,first_name,salary from s_emp where 1=2;
注意:此處1=2表示恒false,則數據庫不會被拷貝,只能得到一張空表
?
4、刪除表格
drop table 表名
注意約束,外鍵
?
5、修改表格
--列相關
1.添加列
alter table 表名 add 列名 數據類型 [default默認值] 約束;
例:--給tbl_user表添加一列年齡
alter table tbl_user add age number(3) default 18 not null;
2.刪除列
alter table 表名 drop column 列名;【注意關鍵字column】
例:刪除tbl_user表中age列
alter table tbl_user drop column age;
3.修改列(修改列數據類型和約束)
alter table 表名 modify 原列名 新數據類型 新約束;
例:修改tbl_user表中password列為char(6)默認值‘000000’非空
alter table tbl_user modify password default'000000' not null;
4.修改列名
alter table 表名 rename column 原列名 to 新列名;
--修改tbl_user表中password列名為pwd
alter table tbl_user rename column password to pwd;
--約束相關
1.添加約束
alter table 表名 add constraint 約束名 約束類型(列名)
注意:如果是添加非空約束,則:
alter table 表名 add constraint 表名_列名_nn check (is not null)
注意:所有的DDL語句都是自動提交事務的,所以語句是不能回滾的
2.刪除約束
alter table 表名 drop constraint 約束名;
3.使約束生效
alter table 表名 enable constraint 約束名
4.使約束失效
alter table 表名 disable constraint 約束名