################
#基本的select语句#

################

1.启动数据库
su - oracle
sqlplus / as sysdba
startup

2.对实验用户(scott)进行解锁并重置口令
SQL> conn / as sysdba
SQL> alter user scott identified by tiger account unlock;

3.登录到指定的用户(scott)
SQL> conn scott
SQL> conn scott/tiger

4.如何知道当前用户用户下拥有哪些表
SQL> select * from tab;

5.如何获得表的结构
SQL> desc BONUS

6.如何查看表重所有行所有列
select * from dept;

7.如何查看表中感兴趣的列
SQL> desc emp
SQL> select empno,ename,sal from emp;

8.select子句后面支持四则运算
SQL> select ename,sal,sal*1.1 from emp;

9.计算雇员工资与奖金的和
SQL> select ename,sal,comm,sal+comm from emp;

10.如何对列命名别名:别名中带有特殊字符要将别名放在双引号中!
SQL> select ename,sal,sal*1.1 as rise_sal from emp;
SQL> select ename,sal,sal*1.1 rise_sal from emp;
SQL> select ename,sal,sal*12 "annual sal" from emp;

11.如何将两列连接成一列显示
SQL> select ename||job from emp;
SQL> select ename||' is a '||job from emp;

12.如何将单引号连接到结果集
SMITH's salary is 800
SQL> select ename||'''s salary is '||sal from emp;

13.如何压缩重复的行
SQL> select deptno from emp;
SQL> select distinct deptno from emp;
SQL> select distinct deptno,job from emp;

14.如何使用脚本保存sql语句
vi /home/oracle/1.sql
------------------------
select * from emp;
------------------------
SQL> get /home/oracle/1.sql
SQL> @/home/oracle/1.sql

SQL> save /home/oracle/1.sql [replace]

##############
#限制和排列数据#
##############
15.如何查询10部门的雇员信息:名字、工资、工作、部门编号
SQL> select ename,sal,job,deptno from emp where deptno=10;

16.如何查询工资高于2500的雇员
SQL> select ename,sal from emp where sal>2500;

17.如何查询所有的销售员:字符作为条件时大小写敏感,并且字符串要放在单引号中!
SQL> select ename,job from emp where job='SALESMAN';

18.如何查询工资高于1000的职员
SQL> select ename,sal,job from emp where sal>1000 and job='CLERK';

19.81年9月8号参加工作的人都有谁?日期作为条件时格式敏感,日期也要放在单引号中!
SQL> select ename,hiredate from emp where hiredate='08-sep-81';

20.如何查询表中前N行记录? rownum:结果集的编号,可以等于1,可以小于一个自然数,rownum必须时从1开始的连续自然数!
select ename,sal from emp where rownum<=5;

21.如何查询名字拼写以A为前缀的人?
select ename from emp where ename like 'A%';

22.如何查询名字拼写第二个字母是L的人?
select ename from emp where ename like '_L%';

23.如何查询名字拼写第二个字母是"_"的人?
SQL> select ename from emp where ename like '_\_%' escape '\';
SQL> select ename from emp where ename like '_ _%' escape ' ';

24.查询工资介于2000和3000之间的人
SQL> select ename,sal from emp where sal>=2000 and sal<=3000;
SQL> select ename,sal from emp where sal between 2000 and 3000;

25.查询工资是1000、2000、3000的人
SQL> select ename,sal from emp where sal=1000 or sal=2000 or sal=3000;
SQL> select ename,sal from emp where sal in (1000,2000,3000);

26.查询奖金是null的人
SQL> select ename,comm from emp where comm is null;

27.查询奖金不是null的人
SQL> select ename,comm from emp where comm is not null;

28.按照工资从大到小输出雇员的信息
SQL> select ename,sal from emp order by sal desc;

29.按照奖金从大到小输出雇员的信息
SQL> select ename,comm from emp order by comm desc;
SQL> select ename,comm from emp order by comm desc nulls last;

30.按照部门和工资两列联合有序输出,部门升序,工资降序
SQL> select ename,deptno,sal from emp order by deptno,sal desc;
SQL> select ename,deptno,sal from emp order by 2,3 desc;

31.使用别名进行排序
SQL> select ename,sal*12 annual_sal from emp order by annual_sal desc;
##############
#单行函数的使用#
##############
字符函数
处理大小写转换的函数
select lower('HElloWorld') from dual;
select upper('HElloWorld') from dual;
select initcap('HElloWorld') from dual;
处理字符串的函数
select concat('Hello','World') from dual;
select substr('HelloWorld',1,5) from dual;
select substr('HelloWorld',6) from dual;
select substr('HelloWorld',-6,3) from dual;
select substr('HelloWorld',-6) from dual;
select length('HelloWorld') from dual;
select instr('HelloWorld','l') from dual;
select instr('HelloWorld','l',1,2) from dual;
select instr('HelloWorld','l',-1,2) from dual;
select * from emp where instr(ename,'L',1,1)=2;
select lpad('Hello',10,'*') from dual;
select rpad('Hello',10,'*') from dual;
select lpad(ename,10,'*') from emp;
select lpad(ename,length(ename)+5,'*') from emp;
select rpad(lpad(ename,length(ename)+5,'*'),length(lpad(ename,length(ename)+5,'*'))+5,'*') from emp;
select trim('d' from 'HelloWorldDdddddddddd') from dual;
select * from emp where trim(' ' from upper(ename))='SCOTT';
select replace('helloworld','owo','xxx') from dual;
select replace('SMITH/ALLEN/WARD/JONES','/',' ') from dual;
数字函数
select round(45.926,2) from dual;
select round(45.926,0) from dual;
select round(45.926) from dual;
select round(45.926,-1) from dual;
select trunc(45.926,2) from dual;
select trunc(45.926,0) from dual;
select trunc(45.926) from dual;
select trunc(45.926,-1) from dual;
select mod(12,5) from dual;
select ceil(0.0000000001) from dual;
select power(2,3) from dual;
select abs(-100) from dual;
日期函数
select sysdate from dual;
select sysdate+5 from dual;
select ename,sysdate-trunc(hiredate,'day') from dual;
select ename,TRUNC(sysdate,'DAY')-hiredate from emp;
select hiredate,trunc(sysdate)-hiredate from emp;
select hiredate,months_between(sysdate,hiredate) from emp;
select add_months(sysdate,6) from dual;
select next_day(sysdate,'fri') from dual;
select last_day(sysdate) from dual;
select round(sysdate,'month') from dual;
转换函数
select to_char(sysdate,'yyyy-mm-dd') from dual;
select to_char(sysdate,'yyyy-mon-dd') from dual;
select to_char(sysdate,'yyyy-month-dd') from dual;
select to_char(sysdate,'yyyy-month-dy') from dual;
select to_char(sysdate,'yyyy-month-day') from dual;
select to_char(sysdate,'year-month-day') from dual;
select to_char(sysdate,'year-month-d') from dual;
select to_char(sysdate,'yyyy-mm-dd hh24:mi:ss') from dual;
select to_char(sysdate,'fmyyyy-mm-dd hh24:mi:ss') from dual;
select to_char(sysdate,'dd "of" mon') from dual;
select to_char(sysdate,'dd "of" mon sssss') from dual;
select to_char(sal,'L999,999.99'),ename from emp;

select to_char(1194684,'xxxxxx') from dual;
select to_number('$001,600.00','L000,000.00') from dual;
select to_number('123abc','xxxxxx') from dual;

select * from emp where hiredate=to_date('1981-08-03','yyyy-mm-dd');

select
to_char(sysdate,'yyyy') curr_year,
to_char(to_date('08','yy'),'yyyy') yy08,
to_char(to_date('98','yy'),'yyyy') yy98,
to_char(to_date('08','rr'),'yyyy') rr08,
to_char(to_date('98','rr'),'yyyy') rr98
from dual;

select ename,job,sal,comm,sal+nvl(comm,0) from emp;
select ename,nvl(to_char(mgr),'No Manager') from emp;
select ename,nvl2(comm,sal+comm,sal) from emp;
select ename,sal,comm,coalesce(comm,sal,0) from emp;

CLERK --> 1.05
SALESMAN --> 1.1
ANALYST --> 1.2

select ename,job,sal,
       case job when 'CLERK' then sal*1.05
                when 'SALESMAN' then sal*1.1
                when 'ANALYST' then sal*1.2
       else sal end rise_sal
from emp;

select ename,job,sal,
       case     when job='CLERK' then sal*1.05
                when job='SALESMAN' then sal*1.1
                when job='ANALYST' then sal*1.2
                when ename='SMITH' then sal*1.5
       else sal end rise_sal
from emp;

select ename,job,sal,
       decode(job,'CLERK',sal*1.05,
                  'SALESMAN',sal*1.1,
                  'ANALYST',sal*1.2,
              sal) rise_sal
from emp;
#########
#多表连接#
#########
笛卡尔积:
select ename,loc from emp,dept;
等值连接:
select ename,loc from emp,dept where emp.deptno=dept.deptno;
外连接:
select ename,loc from emp,dept where emp.deptno(+)=dept.deptno;
对表命名别名:
select e.ename,d.loc,d.deptno from emp e,dept d where e.deptno(+)=d.deptno;
不等连接:
select e.ename,s.grade from emp e,salgrade s where e.sal between s.losal and s.hisal;
自连接:
select e.ename,m.ename from emp e,emp m where e.mgr=m.empno;
SQL99连接语法
笛卡尔积:
select e.ename,d.loc from emp e cross join dept d;
自然连接:
select e.ename,d.loc from emp e natural join dept d;
修正具有多个同名列:using
select e.ename,d.loc from emp e join dept d using (deptno);
没有同名列:on
select e.ename,d.loc from emp e join dept d on (e.deptno=d.deptno);
右外连接:
select e.ename,d.loc from emp e right outer join dept d on (e.deptno=d.deptno);

insert into emp (empno,ename) values (1,'Tom');
左外连接:
select e.ename,d.loc from emp e left outer join dept d on (e.deptno=d.deptno);
全部外连接:
select e.ename,d.loc from emp e full outer join dept d on (e.deptno=d.deptno);

#######
#组函数#
#######
select min(sal),max(sal),sum(sal),avg(sal) from emp;
select count(*) from emp;
select count(*) from emp where deptno=30;
select count(1) from emp where deptno=30;
select count(comm) from emp;
select avg(comm) from emp;
select avg(nvl(comm,0)) from emp;
select count(deptno) from emp;
select count(distinct deptno) from emp;
select sum(sal) from emp;
select deptno,sum(sal) total_sal from emp;
select deptno,sum(sal) total_sal from emp group by deptno;
select deptno,sum(sal) total_sal from emp having sum(sal)>9000 group by deptno;
select deptno,job,sum(sal) from emp group by deptno,job;
select sal,count(sal) from emp having count(sal)>1 group by sal;
#######
#子查询#
#######
1.工资高于blake的人?
select ename,sal from emp where sal>(select sal from emp where ename='BLAKE');

2.和BLAKE同一个部门工资高于MILLER的人?
select ename,sal from emp
where deptno=(select deptno from emp where ename='BLAKE')
and sal>(select sal from emp where ename='MILLER');

3.部门和工作与MARTIN相同工资高于MILLER的人?
select ename,sal from emp
where (deptno,job)=(select deptno,job from emp where ename='MARTIN')
and sal>(select sal from emp where ename='MILLER');

4.工资最少的人?
select ename,sal from emp
where sal=(select min(sal) from emp);

5.工资相同的人?
select ename,sal from emp
where sal in (select sal from emp having count(sal)>1 group by sal);

6.高于10部门最低工资的人?
select ename,sal from emp
where sal>(select min(sal) from emp where deptno=10);

select ename,sal from emp
where sal > any (select sal from emp where deptno=10);

7.每个部门工资最高的人?
select ename,sal,deptno from emp e
where sal in (select max(sal) from emp where deptno=e.deptno);

8.每个部门工资最高的前两个人?
select ename,sal,deptno from emp e
where (select count(*) from emp where deptno=e.deptno and sal>e.sal)<2;

select count(*) from emp where deptno=20 and sal>800;

select * from (select ename,sal,row_number() over (partition by deptno order by sal desc) a from emp) where a<3;

select * from (select ename,sal,rank() over (partition by deptno order by sal desc) a from emp) where a<3;

9.手下还有雇员的人?
select ename from emp where empno in (select mgr from emp);

select ename from emp e where exists (select 1 from emp where mgr=e.empno);

10.手下没有雇员的人?
select ename from emp e where not exists (select 1 from emp where mgr=e.empno);

11.工资最高的5个人?
select * from (select ename,sal from emp order by sal desc) where rownum<6;

12.工资排名6~10的人?
select * from (select rownum rn,a.* from (select ename,sal from emp order by sal desc) a) where rn between 6 and 10;

13.工资高于本部门平均工资的人?
select e.ename,e.sal,e.deptno,b.avgsal
from emp e,(select deptno,avg(sal) avgsal from emp group by deptno) b
where e.deptno=b.deptno
and e.sal>b.avgsal;

select ename,sal,deptno from emp e where sal>(select avg(sal) from emp where deptno=e.deptno);

14.scott的工资是smith的几倍?
select (select sal from emp where trim(' ' from ename)='SCOTT')/(select sal from emp where ename='SMITH') from dual;

select a.sal/b.sal from emp a,emp b where trim(' ' from a.ename)='SCOTT' and b.ename='SMITH';
#########
#替换变量#
#########
select * from emp where ename='&name';
select * from emp where empno=&employee_id;

SCOTT@ orcl> define
SCOTT@ orcl> define col=sal
SCOTT@ orcl> undefine col

select ename,&&col from emp order by &col;

select * from (select rownum rn,a.* from (select ename,sal from emp order by sal desc) a) where rn between &n*5-5+1 and &n*5;
############
#操作数据DML#
############
desc dept
insert into dept values (50,'APP','SH');
desc emp
insert into emp values (2,'Tom','CLERK',7698,sysdate,1200,null,30);
insert into emp (empno,ename) values (1,'中');
desc bonus
insert into bonus select ename,job,sal,comm from emp where comm>0;

update dept set deptno=60,... where deptno=1;
update emp set deptno=(select deptno from emp where ename='SCOTT'),
               sal=(select sal*1.1 from emp where ename='ADAMS')
where ename='SMITH';

update emp set sal=sal*1.1 where deptno=(select deptno from dept where dname='SALES');

insert into (select empno,ename,sal,deptno from emp where deptno=10 with check option)
values (1,'Tom',1300,10);

合并:
merge into e01 --目标表
using emp --数据源
on (e01.empno=emp.empno)
when matched then
  update set
  e01.ename=emp.ename,
  e01.job=emp.job,
  e01.mgr=emp.mgr,
  e01.hiredate=emp.hiredate,
  e01.sal=emp.sal,
  e01.comm=emp.comm,
  e01.deptno=emp.deptno
when not matched then
  insert (e01.empno,e01.ename,e01.job,e01.mgr,e01.hiredate,e01.sal,e01.comm,e01.deptno)
  values (emp.empno,emp.ename,emp.job,emp.mgr,emp.hiredate,emp.sal,emp.comm,emp.deptno);

select * from emp as of timestamp (sysdate-30/1440);
alter table emp enable row movement;
flashback table emp to timestamp (sysdate-30/1440);

闪回版本查询:
select
versions_startscn,
versions_endscn,
versions_operation,
ename,sal
from emp
versions between scn minvalue and maxvalue
where empno=7369;

select * from emp as of scn 1296696;
flashback table emp to scn 1296696;

commit;
rollback;

隐士提交:
create drop truncate rename alter table grant revoke exit/quite conn
隐士回退:
非正常终止sqlplus,系统宕机

阶段回退:在事务内必须设置保存点
insert into emp (empno) values (1);
savepoint a1;
insert into emp (empno) values (2);
savepoint a2;
update emp set empno=3 where empno=2;
savepoint a3;
insert into emp (empno) values (4);
rollback to a3;
查看保存点:
conn / as sysdba
grant alter session to scott;
conn scott/tiger
alter session set events 'immediate trace name savepoints level 1';
SYS@ orcl> show parameter background
/u01/app/oracle/diag/rdbms/orcl/orcl/trace
ll -rt

锁:LOCK使用队列机制
session 1: update emp set sal=sal+100 where empno=7839;
session 2: update emp set sal=200 where empno=7499;
session 1: update emp set comm=100 where empno=7499; ORA-00060: deadlock
session 2: update emp set comm=200 where empno=7839;
############
#创建和管理表#
############

create table t02 (id number(4),name varchar2(20),hire_date date default sysdate);
查看列的default值:
select COLUMN_NAME,DATA_TYPE,DATA_DEFAULT from user_tab_columns where table_name='T02';

数据字典:不是终端用户创建的,是创建数据库时创建的,是记录数据库属性、状态、对象等信息的最核心的表,
对于用户是只读的,数据字典分成两类,数据字典表和动态性能视图
数据字典表
user_xxx
all_xxx
dba_xxx

态性能视图
v$xxx
gv$xxx

所有的数据字典都使用这样一个字典来管理:
desc dictionary
使用模糊匹配查找感兴趣的数据字典
select table_name from dictinoary where table_name like '%XXXX%';
子查询建表拷贝表结构
create table t03 as select * from emp where 1=0;
子查询建表拷贝数据
create table t04 as select * from emp where deptno=30;

使用虚拟列(11g新特性):
create table t05 (id number(4),
                  name varchar2(20),
                  salary number(7,2) default 1000,
                  annual_sal as (salary*12));

insert into t05 (ID,NAME,SALARY) values (1,'TOM',1300);

创建临时表:
1.事务级临时表 : commit数据消失
create global temporary table temp01
as
select * from emp;

2.会话级临时表 : disconnect数据消失
create global temporary table temp02
on commit preserve rows
as
select * from emp;

select object_name from user_objects where object_type='TABLE' AND temporary='Y';

获得元数据
select dbms_metadata.get_ddl('TABLE','E01') from dual;

获得用户下所有表的元数据
select dbms_metadata.get_ddl('TABLE',t.table_name) from
(select table_name from user_tables) t;

修改表的结构
添加列:
alter table e01 add (loc varchar2(10));
desc e01

修改列
alter table e01 modify (loc varchar2(13));

为列添加default值
alter table e01 modify (hiredate date default sysdate);
查看列的default值
select COLUMN_NAME,DATA_TYPE,DATA_DEFAULT from user_tab_columns where table_name='E01';

重命名列
alter table e01 rename column LOC to location;

列注释
comment on column e01.ename is 'first_name';
查看列的注释
select * from user_col_comments where TABLE_NAME='E01';

删除列
alter table e01 drop (hiredate,location);

列状态置为未使用:
alter table e01 set unused column sal;
alter table e01 set unused column job;

删除未使用状态的列
alter table e01 drop unused columns;

表注释
comment on table e01 is 'emp''s copy';
查看表的注释
select * from user_tab_comments where table_name='E01';

截断表
truncate table e01;

重命名表
rename e01 to emp_copy;

删除表,进入回收站
drop table e01;
查看回收站
show recyclebin
从回收站找回删除的表
flashback table e01 to before drop;
flashback table "BIN$UBgfCuwxD6rgUwsAGax+Aw==$0" to before drop rename to e0001;
清空回收站
purge recyclebin;

绕过回收站直接删除表
drop table emp_copy purge;

找回unused状态的列:
conn / as sysdba
select * from v$log;
select * from v$logfile;
exec dbms_logmnr.add_logfile('/u01/app/oracle/oradata/db00/redo01.log',dbms_logmnr.new);
exec dbms_logmnr.start_logmnr(options=>dbms_logmnr.dict_from_online_catalog);
select sql_redo from v$logmnr_contents where lower(sql_redo) like 'alter table%' and seg_name='E01' and seg_owner='SCOTT';

alter table e01 set unused column sal;
alter table e01 set unused column job;

select object_id from dba_objects where object_name='E01';
select cols from tab$ where obj#=88648;
SELECT COL#,intcol#,NAME,property FROM COL$ WHERE OBJ#=88648;

update COL$ set COL#=INTCOL# where OBJ#=88648;
update COL$ set name='JOB' where OBJ#=88648 and col#=3;
update COL$ set name='SAL' where OBJ#=88648 and col#=6;

update tab$ set cols=cols+2 WHERE OBJ#=88648;
update col$ set property=0 WHERE OBJ#=88648;

commit;
startup force
#########
#使用约束#
#########
使用约束:
drop table t01 purge;
drop table t02 purge;
drop table t03 purge;
drop table t04 purge;
drop table t05 purge;

列级别启用约束,系统命名约束
create table t01 (id number not null);

查看约束的属性
select CONSTRAINT_NAME,CONSTRAINT_TYPE,SEARCH_CONDITION from user_constraints where TABLE_NAME='T01';
查看约束和列的对应关系
select CONSTRAINT_NAME,COLUMN_NAME from user_cons_columns where TABLE_NAME='T01';

列级别启用约束,用户命名约束
create table t01 (id number constraint nn_t01_id not null);

not null约束只能在列级别启用!

列级别启用约束,用户命名约束
create table t02 (id int,e_mail varchar2(30) constraint uk_t02_mail unique);

select CONSTRAINT_NAME,CONSTRAINT_TYPE from user_constraints where TABLE_NAME='T02';

表级别启用约束,用户命名约束
create table t02 (id int,e_mail varchar2(30),
                  constraint uk_t02_mail unique (id,e_mail));

列级别启用约束,用户命名约束
create table t03 (id int constraint pk_t03_id primary key,
                  e_mail varchar2(30) constraint uk_t03_mail unique);

列级别启用约束,用户命名约束
create table t04 (id int constraint fk_t04_id references t03,name varchar2(10));

select CONSTRAINT_NAME,CONSTRAINT_TYPE,R_CONSTRAINT_NAME from user_constraints where TABLE_NAME='T04';
查看外建所参照的主键在哪一张表
select table_name from user_constraints where constraint_name='PK_T03_ID';
查看约束作用在哪些列
select table_name,column_name from user_cons_columns where constraint_name='PK_T03_ID';

列级别启用约束,用户命名约束
create table t05 (id int,name varchar2(10),sal number(7,2) constraint ck_t05_sal check (sal>=1000 and sal is not null));

select CONSTRAINT_NAME,CONSTRAINT_TYPE,SEARCH_CONDITION from user_constraints where TABLE_NAME='T05';

删除约束:
alter table t04 drop constraint FK_T04_ID;
添加约束:
alter table t02 add constraint uk_t02_id unique (id);
参照唯一键的外键
alter table t04 add constraint FK_T04_ID foreign key (id) references t02 (id);
外键的扩展风格
alter table t04 add constraint FK_T04_ID foreign key (id) references t02 (id) on delete set null;

alter table t04 add constraint FK_T04_ID foreign key (id) references t02 (id) on delete cascade;

查看约束的状态:
select CONSTRAINT_NAME,CONSTRAINT_TYPE,SEARCH_CONDITION,STATUS,VALIDATED from user_constraints where TABLE_NAME='T01';

ENABLED   VALIDATED
ENABLED   NOT VALIDATED
DISABLED  NOT VALIDATED
DISABLED  VALIDATED (如何在不破坏子表数据的前提下重建父表!)
ORA-25128: No insert/update/delete on table with constraint (SCOTT.NN_T01_ID) disabled and validated

修改约束状态
alter table t01 modify constraint NN_T01_ID disable;
alter table t01 modify constraint NN_T01_ID enable novalidate;
alter table t01 modify constraint NN_T01_ID disable validate;

排他操作:启用约束失败,找到违反约束条件的行!CREATE SYNONYM
CREATE PUBLIC SYNONYM

alter table emp add constraint ck_emp_sal check (sal>=1000 and sal is not null);

SQL> @?/rdbms/admin/utlexcpt.sql

alter table emp add constraint ck_emp_sal check (sal>=1000 and sal is not null) exceptions into exceptions;

select ROW_ID from exceptions;

select * from emp where rowid in (select ROW_ID from exceptions);

create table t06 (x int constraint u unique);
insert into t06 values (1);
alter table t06 modify constraint u disable;
insert into t06 values (1);
create index i_t06 on t06 (x);
alter table t06 modify constraint u enable novalidate;
=======================================================
视图:
create view vu10
as
select empno,ename,sal,deptno from emp where deptno=10;

select text from user_views where view_name='VU10';

select * from vu10;

create or replace view vu10
as
select empno,ename,job,sal,deptno from emp where deptno=10;

create or replace view vu10
(employee_id,first_name,job,salary,department_id)
as
select empno,ename,job,sal,deptno from emp where deptno=10;

drop view vu10;

create or replace force view vu10
as
select empno,ename,job,sal,deptno from e01 where deptno=10;

create or replace force view vu10
as
select empno,ename,job,sal,deptno from e01 where deptno=10
with check option;

create or replace force view vu10
as
select rownum rn,ename,job,sal,deptno from e01 where deptno=10;

create or replace force view vu10
as
select distinct ename,job,sal,deptno from e01 where deptno=10;

create or replace force view vu10
as
select ename,job,sal,deptno from e01 where deptno=10;

对视图做DML操作的限制:
1.不能delete
组函数
group by
distinct
rownum
2.不能update
组函数
group by
distinct
rownum
带有计算表达式的伪列
3.不能insert
组函数
group by
distinct
rownum
带有计算表达式的伪列
基表中非空约束所在的列在视图中没有包括
===============================================================
序列:
create sequence s1;

select * from user_sequences;

create sequence seq_empno
start with 7935
increment by 1
minvalue 7935
maxvalue 9999
nocycle
cache 100;

alter sequence seq_empno increment by 2;
alter sequence seq_empno order;
alter sequence seq_empno noorder;

insert into emp (empno) values (7936);

select 'EMP'||s1.nextval from dual;
===============================================================
索引:
打开sql跟踪
set autot trace exp

create index i_e01_empno on e01 (empno);
drop index i_e01_empno;
select index_name from user_indexes where table_name='E01';
===============================================================
同义词:
create synonym emp for scott.emp;
create public synonym emp for scott.emp;
drop synonym emp;
drop public synonym emp;
私有同义词自己可用,不能和表同名
公有同义词全局可用,用户下的表如果和公有同义词同名,表名的优先级别高于公有同义词
select * from user_synonyms;
===============================================================
管理用户:
select username,account_status from dba_users;

create user tom identified by blake password expire;
授予系统权限
grant create session to tom;
--revoke CREATE SESSION from BLAKE;
conn tom/tom

查看所有的系统权限
select distinct privilege from dba_sys_privs order by 1;

grant create table,create view to tom,tom1,tom2;

查看用户被授予的系统权限
conn tom/tom
select * from session_privs;
conn / as sysdba
select privilege from dba_sys_privs where grantee='TOM';

使用角色管理权限:
create role r1;
grant create session,create table to r1;
grant r1 to blake;
角色可以被嵌套使用
create role r2;
grant r1 to r2;
grant create view to r2;
grant r2 to blake;
使用角色实现权限的动态管理:
将角色授予用户之后,角色成为用户的默认角色
默认角色:用户创建连接之后权限马上释放
非默认角色:用户创建连接之后权限不释放,需要激活角色之后权限才释放
create role r3;
grant drop any table to r3;
grant r3 to blake;
alter user blake default role all except r3;
set role r3;
set role all;
set role all except r4;
set role r2,r4;

级联授权
grant r1 to blake with admin option;
with admin option权限回收无级联

用户被授予的角色
SYS@ db00> select * from dba_role_privs where grantee='BLAKE';

GRANTEE                GRANTED_ROLE              ADM DEF
------------------------------ ------------------------------ --- ---
BLAKE                   R2                  NO  NO
BLAKE                   R1                  YES YES

BLAKE@ db00> grant r1 to tom;

角色被授予的系统权限
select * from role_sys_privs where role='R1';

create role r3;
grant create synonym to r3;
grant r3 to r2;

查看角色被授予的角色
select * from role_role_PRIVS where role='R1';

对象权限:
grant select on scott.emp to blake;
查看对象权限:
select PRIVILEGE,OWNER,TABLE_NAME from dba_tab_privs where GRANTEE='BLAKE';

列级别对象权限:
grant update (sal) on scott.emp to blake;
查看列级别对象权限:
select PRIVILEGE,OWNER,TABLE_NAME,COLUMN_NAME from dba_col_privs where GRANTEE='BLAKE';

grant select on scott.dept to r2 with grant option;
grant update (dname) on scott.dept to r3;
with grant option权限回收有级联
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
查询用户所拥有的所有权限:
conn / as sysdba

prompt *** 查看用户被授予的系统权限 ***
select privilege from dba_sys_privs where grantee=upper('&user_name');

prompt *** 查看用户被授予的对象权限 ***
select PRIVILEGE,OWNER,TABLE_NAME from dba_tab_privs where GRANTEE=upper('&user_name');

prompt *** 查看用户被授予的列级别对象权限 ***
select PRIVILEGE,OWNER,TABLE_NAME,COLUMN_NAME from dba_col_privs where GRANTEE=upper('&user_name');

prompt *** 查看用户被授予的角色 ***
select * from dba_role_privs where grantee=upper('&user_name');

prompt *** 查看角色被授予的角色 ***
select * from role_role_PRIVS where role='R1';

prompt *** 查看角色被授予的系统权限 ***
select * from role_sys_privs where role='R1';

prompt *** 查看角色被授予的对象权限 ***
select PRIVILEGE,OWNER,TABLE_NAME,COLUMN_NAME from role_tab_privs where ROLE='R2';
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
grant create procedure to blake;

PUBLIC(用户组)授权:
grant select on scott.emp to public;
revoke select on scott.emp from public;

修改用户密码:
1.> alter user blake identified by blake;
2.> password [username]

用户(user)和方案(schema):
TOM@ db00> alter session set current_schema=scott;
SYS@ db00> select username,schemaname from v$session where username='TOM';

代理用户:
SYS@ db00> alter user scott grant connect through tom;
SYS@ db00> alter user blake grant connect through tom;
SYS@ db00> alter user hr grant connect through tom;

查看代理用户信息:
SELECT * FROM DBA_PROXIES;

TOM@ db00> conn tom[scott]/tom
SCOTT@ db00> conn tom[blake]/tom

系统审核的用户:
前缀: show parameter os_authent_prefix
后缀: select distinct osuser from v$session;

create user ops$oracle identified by oracle;
grant create session to ops$oracle;

alter user scott grant connect through ops$oracle;
alter user blake grant connect through ops$oracle;
alter user hr grant connect through ops$oracle;
==========================================================================

计算1980,1981,1982年参加工作的员工数量分别时多少,结果集格式显示如下:

1980  1981  1982
----  ----  ----
   1    10     1

select
sum(decode(to_char(hiredate,'yyyy'),'1980',1)) "1980",
sum(decode(to_char(hiredate,'yyyy'),'1981',1)) "1981",
sum(decode(to_char(hiredate,'yyyy'),'1982',1)) "1982"
from emp;

select to_char(hiredate,'yyyy'),count(*) from emp group by to_char(hiredate,'yyyy');

对部门下的职员、销售员、分析员、管理者的工资求和,结果集如下:

DEPTNO    CLERK    SALESMAN    ANALYST    MANAGER
------ ---------- ---------- ---------- ----------
30      950        5600          2850
20     1900               6000      2975
10     1300                  2450

select deptno,
sum(decode(job,'CLERK',sal)) CLERK,
sum(decode(job,'SALESMAN',sal)) SALESMAN,
sum(decode(job,'ANALYST',sal)) ANALYST,
sum(decode(job,'MANAGER',sal)) MANAGER
from emp group by deptno;

创建一张表,构造重复值,尝试删除表中重复记录
create table e01 as select * from emp;
insert into e01 select * from e01 where deptno=30;
commit;

select * from e01 a where rowid in (select max(rowid) from e01 b where b.empno=a.empno and b.job=a.job);

select * from e01 a where rowid not in (select max(rowid) from e01 b where b.empno=a.empno and b.job=a.job);

delete e01 a where rowid not in (select max(rowid) from e01 b where b.empno=a.empno and b.job=a.job);

select deptno,job,sum(sal) from emp group by deptno,job
union
select deptno,null,sum(sal) from emp group by deptno
union
select null,null,sum(sal) from emp;
===========================================================================
扩展的日期和时间数据类型
select * from nls_database_parameters;
alter session set nls_date_format='yyyy-mm-dd hh24:mi:ss';

增强的时间函数:
col LOCALTIMESTAMP for a35
col CURRENT_TIMESTAMP for a35
select sysdate,current_date,localtimestamp,current_timestamp from dual;
修改会话的时区:              'tzh:tzm'
alter session set time_zone='-05:00';
查看数据库的时区和会话的时区
select dbtimezone,sessiontimezone from dual;
观察受时区影响的时间函数
select sysdate,current_date,localtimestamp,current_timestamp from dual;

时间戳:
create table t01 (x int,t_date timestamp);
create table t01 (x int,t_date timestamp (9));
全球化时间戳:
create table t01 (x int,t_date timestamp with time zone);
本地时间戳:
create table t01 (x int,t_date timestamp with local time zone);

萃取函数:
select extract(month from sysdate) from dual;
select extract(year from sysdate) from dual;

转换时间戳:
select from_tz(timestamp '2017-05-24 15:30:25.123456789','-07:00') from dual;
select from_tz(timestamp '2017-05-24 15:30:25','Australia/North') from dual;
select TZNAME,tz_offset(TZNAME) from v$timezone_names;

数据库后台的合法的地区描述
select * from v$timezone_names;
把地区描述转成时间偏移量
select tz_offset('US/SAMOA') from dual;

select from_tz(timestamp '2017-05-24 15:30:25','US/Samoa') from dual;

select to_timestamp('2017-05-24 15:30:25','yyyy-mm-dd hh24:mi:ss') from dual;
select to_timestamp('2017-05-24 15:30:25.123456789','yyyy-mm-dd hh24:mi:ss.ff') from dual;
select to_timestamp_tz('2017-05-24 15:30:25 08:00','yyyy-mm-dd hh24:mi:ss tzh:tzm') from dual;

返回时间段的函数
select sysdate,sysdate+to_yminterval('01-07') from dual;
select sysdate,sysdate+to_yminterval('01-07')+to_dsinterval('05 03:12:11') from dual;
===============================================================================
group by增强:

rollup(a,b,c) --> n+1
group by a
union all
group by a,b
union all
group by a,b,c
union all
total

rollup(deptno,job)

cube(a,b,c) --> power(2,n)
group by a
union all
group by b
union all
group by c
union all
group by a,b
union all
group by a,c
union all
group by b,c
union all
group by a,b,c
union all
total

cube(deptno,job)

select deptno,job,sum(sal),grouping(deptno),grouping(job)
from emp group by rollup(deptno,job);

select deptno,job,sum(sal),grouping(deptno),grouping(job),grouping_id(deptno,job)
from emp group by rollup(deptno,job);

DEPTNO JOB           SUM(SAL)
------ --------- ----------
10 CLERK       1300
10 MANAGER       2450
10 PRESIDENT       5000
subtotal10       8750
20 CLERK       1900
20 ANALYST       6000
20 MANAGER       2975
subtotal20      10875
30 CLERK        950
30 MANAGER       2850
30 SALESMAN       5600
subtotal30       9400
total          29025

select decode(grouping(deptno)||grouping(job),'01','subtotal'||deptno,'11','total',deptno) deptno,
job,sum(sal)
from emp group by rollup(deptno,job);

select decode(grouping_id(deptno,job),1,'subtotal'||deptno,3,'total',deptno) deptno,
job,sum(sal)
from emp group by rollup(deptno,job);

select deptno,job,mgr,sum(sal) from emp
group by grouping sets
((deptno,job),(job,mgr));

group by (deptno,job)
union
group by (job,mgr)

select deptno,job,mgr,sum(sal) from emp
group by rollup(deptno,job,mgr);

select deptno,job,mgr,sum(sal) from emp
group by rollup(deptno,(job,mgr));
                  A   ,    B
===============================================================================
select ename,sal from emp e
where sal>(select avg(sal) from emp where deptno=e.deptno);

select ename from emp where empno in (select distinct mgr from emp);

select ename from emp e where exists (select 1 from emp where mgr=e.empno);

select ename from emp where empno not in (select distinct mgr from emp);

哪一个部门的总工资高于所有部门的平均工资?
select deptno,sum(sal) total from emp group by deptno;

select deptno,total
from (select deptno,sum(sal) total from emp group by deptno)
where total>(select avg(total) avgsal from (select deptno,sum(sal) total from emp group by deptno));

减少相同子查询的重复执行!
with
a as (select deptno,sum(sal) total from emp group by deptno),
b as (select avg(total) avgsal from a)
select deptno,total from a
where total>(select avgsal from b);
===============================================================================
分级查询:

===============================================================================
拆分器:
create table e01 as select ename,job,sal from emp where 1=0;
create table e02 as select empno,ename,hiredate from emp where 1=0;

insert all
into e01 values (ename,job,sal)
into e02 values (empno,ename,hiredate)
select * from emp;

insert all
into e01 values (ename,job,sal)
into e02 values (empno,ename,hiredate)
select empno,ename,job,hiredate,sal from emp;

insert all
when sal>2000 then
into e01 values (ename,job,sal)
when deptno=30 then
into e02 values (empno,ename,hiredate)
select empno,ename,job,hiredate,sal,deptno from emp;

insert first
when sal>2000 then
into e01 values (ename,job,sal)
when deptno=30 then
into e02 values (empno,ename,hiredate)
select empno,ename,job,hiredate,sal,deptno from emp;

create table sales_source_data
(employee_id number,
week_id number,
sales_mon number,
sales_tue number,
sales_wed number,
sales_thu number,
sales_fri number);

insert into sales_source_data values (178,1,2345,1500,2000,3500,1450);
insert into sales_source_data values (156,2,1240,678,3560,2450,4000);

create table sales_info
(employee_id number,
week number,
sales number);

insert all
into sales_info values (employee_id,week_id,sales_mon)
into sales_info values (employee_id,week_id,sales_tue)
into sales_info values (employee_id,week_id,sales_wed)
into sales_info values (employee_id,week_id,sales_thu)
into sales_info values (employee_id,week_id,sales_fri)
select * from sales_source_data;

外部表:
1.在数据库中创建逻辑目录
conn / as sysdba
create or replace directory mydir as '/home/oracle/';
select * from dba_directories;
grant read,write on directory mydir to scott;

conn scott/tiger
CREATE TABLE dept_external (
   deptno     NUMBER(6),
   dname      VARCHAR2(20),
   loc        VARCHAR2(25)
)
ORGANIZATION EXTERNAL
(TYPE oracle_loader
 DEFAULT DIRECTORY mydir
 ACCESS PARAMETERS
 (
  FIELDS TERMINATED BY ","  OPTIONALLY ENCLOSED BY '"'
  (
   deptno     INTEGER EXTERNAL(6),
   dname      CHAR(20),
   loc        CHAR(25)
  )
 )
 LOCATION ('1.txt')
)
REJECT LIMIT UNLIMITED;

select * from dept_external;

Oracle---SQL语句相关推荐

  1. oracle sql语句中包含‘’ 的解决方法

    oracle sql语句中包含'&' 的解决方法 参考文章: (1)oracle sql语句中包含'&' 的解决方法 (2)https://www.cnblogs.com/hm1990 ...

  2. Oracle SQL语句执行过程

    前言 QQ群讨论的时候有人遇到这样的问题:where子句中无法访问Oracle自定义的字段别名.这篇 博客就是就这一问题做一个探讨,并发散下思维,谈谈SQL语句的执行顺序问题. 问题呈现 直接给出SQ ...

  3. Oracle查询所有序列;[oracle中如何创建表的自增ID(通过序列);oracle sql语句大全

    Oracle查询所有序列 oracle sql语句大全 oracle中如何创建表的自增ID(通过序列)

  4. oracle sql 语句如何插入全年日期?

    为什么80%的码农都做不了架构师?>>>    oracle sql 语句如何插入全年日期? create table BSYEAR (d date); insert into BS ...

  5. Oracle SQL语句执行步骤

    Oracle中SQL语句执行过程中,Oracle内部解析原理如下: 1.当一用户第一次提交一个SQL表达式时,Oracle会将这SQL进行Hard parse,这过程有点像程序编译,检查语法.表名.字 ...

  6. Oracle Sql语句定时执行

    Oracle Sql语句定时执行 本文链接:https://blog.csdn.net/qq_16979575/article/details/70169519 通过网上查询,找到一种方案,就是先在o ...

  7. sql跟踪 oracle,oracle SQL语句跟踪详解

    本文主要内容为oracle SQL语句跟踪详解,废话不多说,马上进入正题. 对于跟踪的sql语句,生成的trace 文件放在udump 下 SQL> showparameter sql NAME ...

  8. oracle sql语句中like %参数%的用法

    oracle sql语句中like %参数%的用法,在网上找了很久没找到类似的帖子,因此分享一下我的收获,希望对看到的人有帮助 今天在处理oracle数据库数据merge的时候遇到一个问题: 在mer ...

  9. oracle中子查询的执行顺序是,Oracle sql语句执行顺序

    sql语法的分析是从右到左 一.sql语句的执行步骤: 1)语法分析,分析语句的语法是否符合规范,衡量语句中各表达式的意义. 2)语义分析,检查语句中涉及的所有数据库对象是否存在,且用户有相应的权限. ...

  10. Oracle+sql+取年度,oracle SQL语句取本周本月本年的数据

    --国内从周一到周日 国外是周日到周六 select to_char(sysdate-1,'D') from dual;--取国内的星期几 去掉减一取国外的星期 --取本周时间内的数据 select ...

最新文章

  1. php生成文字闪烁,如何用jquery实现闪烁文字效果
  2. ASp.net 剖析三层架构
  3. 菜鸟教程 之 shell 脚本学习笔记 (一)
  4. SQL 性能优化梳理,干掉慢SQL!
  5. CEO 赠书 | 打破创新神话,揭示创新本质
  6. sqlmap mysql案例_sqlmap简单mysql注入演示附截图
  7. 用python处理excel 数据分析_Python应用实现处理excel数据过程解析
  8. HDU - 3126 Nova(最大流+二分+简单几何)
  9. JDK10的新特性:var和匿名类
  10. 华为:《数字化转型,从战略到执行》报告,附102页PPT下载
  11. 价格要大涨,新5G iPhone可能不会带来换机热?
  12. Serlizable序列化接口
  13. Asp.net性能优化-提高ASP.Net应用程序性能的十大方法
  14. 存储过程中ORA-01031: insufficient privileges的解决方法
  15. 8.卷1(套接字联网API)---基本UDP套接字编程
  16. Atitit 面向对象弊端与问题 坏处 缺点
  17. 流体力学有限元法(二)
  18. idea手动执行maven命令的三种方式
  19. java工具类_16 个超级实用的 Java 工具类
  20. 正则表达式学习实践心得——来源于codesheep(羊哥)

热门文章

  1. RGB颜色值与十六进制颜色码
  2. benchmark在postgresql上的安装及使用
  3. Codeforces Round #708 (Div. 2)B. M-arrays
  4. 再探JS---eval函数
  5. python openpyxl模块 合并单元格,设置行高,列宽,边框,居中,字体样式
  6. MT【299】对数型数列不等式
  7. 取MySQL结果集的第一条记录
  8. MAVEN Plugins 插件官网下载
  9. biosequence analysis using profile hidden Markov models(使用隐马尔可夫模型分析序列)
  10. 【即点即改】关于PHP即点即改的一些东西