惯用SQL笔记总结
常用SQL笔记总结
DDL(data definition language)创建和管理表
1.创建表
-
1.直接创建
例如: create table emp( name varchar(20), salary int default 1000, id int, hire_date date );
-
2.通过子查询的方式创建
例如: create table emp1 as select name n_name,id n_id,hire_date from emp;
2.修改表
-
1.增加新的列
alter table emp add(birthday date);
-
2.修改现有的列
alter table emp alter column name set default "abc"
-
3.重命名现有的列
alter table emp change salary sal int;
-
4.删除现有的列
alter table emp drop column birthday;
-
3.清空表中的数据
truncate table emp1;
-
4.重命名表
alter table emp1 rename emp2;
-
5.删除表
drop table emp2;
DML(data manipulation language)数据处理
1.INSERT 增
-
1.增添一条记录
insert into [表名](,,,,,) values(,,,,,)
-
2.从其它表中拷贝数据
insert into [表名] select .... from [另一个表] where ....
2.UPDATE 改
-
1.更新数据
update [表名] set ..... where ....
3.DELETE 删
-
1.删除数据
delete from [表名] where ....
4.SELECT 查
-
1.查询数据
select .... from … where …. group by … having … order by ….
约束(oracle)
1.创建表的同时,添加对应属性的约束
-
1.表级约束 & 列级约束
create table emp( employee_id number(8), salary number(8), --列级约束 hire_date date not null, dept_id number(8), email varchar2(8) constraint emp_email_uk unique, name varchar2(8) constraint emp_name_uu not null, first_name varchar2(8), --表级约束 constraint emp_emp_id_pk primary key(employee_id), constraint emp_fir_name_uk unique(first_name), constraint emp_dept_id_fk foreign key(dept_id) references departments(department_id) ON DELETE CASCADE );
2.只有 not null 只能使用列级约束。其他的约束两种方式皆可
2.添加和删除表的约束--在创建表以后,只能添加和删除,不能修改
-
1.添加
alter table emp add constraint emp_sal_ck check(salary > 0);
对于 not null 来讲,不用 add,需要使用 modify:
alter table emp modify (salary not null);
-
2.删除
alter table emp drop constraint emp_sal_ck;
-
3.使某一个约束失效:此约束还存在于表中,只是不起作用
alter table emp disable constraint emp_email_uk;
-
4.使某一个约束激活:激活以后,此约束具有约束力
alter table emp enable constraint emp_email_uk;