Você está na página 1de 67

sql 1)DDL ---constraints 2)DML 3)savepoint,commit,rollback

2/7/2013 -- DDL--- auto commit create table, alter,drop,rename,truncat SQL dataTypes 1)number 2)char 3)varchar 4)date 5)raw 6)long 7)LOB ---Internal LOB(CLOB,BLOB) resume clob ---External LOB(BFile) pic bfile 1)number empID number salary number(5,2) 456 345.7 ,457.90 deptno number(3) 2, 12, 123

2)char-- fixed datatype name char(5) abc, d , yyy, 3)varchar--variable length datatype name varchar(5) abc, d , yyy, ertyu 4)date DOB date hireDate date -- c, y, m,d,hr ,mi ,ss default display formate of date is dd-mon-rr 5)raw, long TextContext long

create table tableName(colNAme datatype, colname2 datatype,....colN datatype);

TWO TYPES OF TABLES 1)SYSTEM TABLES ---dd select * from dict

--USER_OBJECTS

2)USER DEFINED TABLES create table emp(empid number(3), ename varchar(20),hiredaTE DATE, ALARY NUMBER(5,1)); ---------------------------------------------------------------------drop objectType objectName; drop table emp; drop table emp purge ; alter table tableName [add/ modify/drop] columnname dataype; ------------------------------------------alter table tableName add columnname datType; alter table emp add emailid vachar2(30); -------------------------------------------------alter table tableName add (columnname datType, col2 datatype); alter table emp add(emailid varchar2(30), address varchar(20)); ---------------------------------------------------------alter table tableName drop column columnname ; S

alter table emp drop column address ; --------------------------------------------------------alter table tableName drop ( columnname1, colname2) ; alter table emp drop (emailid,hiredaTE) ; -----------------------------------------------------------alter table tableName modify columname datatype; alter table emp modify empid varchar2(30) --------------------------------------------------------------alter table tableName modify (columname datatype, column2 datatype); alter table emp modify (empid number,ename varchar2(30)) --------------------------------------------------------------to rename column name

alter table tableName rename column oldName to newName; alter table emp rename column empid to empNo --------------------------------------------------------------to rename table rename oldTableNAme to NewTableName; desc Emp rename emp to newEmp; desc newEmp ----------------------------------------------------------------truncate table TableNAme; truncate table newEMp; ----------------------------------------------------------------Constraints 1)primary key [not null+ unique] 2)unique 3)foreign key 4)not null --applied only at column level 5)check constraints applied at 1)table level (constraint name is must) 2)column level (you can ommit constraint name) Sys_cn dd---user_constraints, user_cons_columns select * from user_constraints select * from user_cons_columns ----------------------------------------------------------column level ---no constraint name create table empTest(empid number primary key, ename varchar2(30) not null, emailid varchar2(30) unique, salary number(5,2) check(salary>0), deptno number(4) references departments(DEPARTMENT_ID)); -----------------------------------------------------------------------column level --provide constraint name create table empTest(empid number constraint empid_pk1 primary key, ename varchar2(30) constraint ename_notnull1 not null, emailid varchar2(30) constraint idUq unique, salary number(5,2) constraint chk12 check(salary>0), deptno number(4) constraint deptno_FK12 references departments(DEPART MENT_ID)); ----------------------------------------------------------------------table level create table empTest(empid number , ename varchar2(30) constraint ename_notnull1 not null, emailid varchar2(30) ,

salary number(5,2) , deptno number(4) , constraint deptno_FK12 foreign key(deptno)references departments(DEPARTMENT_ID) , constraint empid_pk1 primary key(empid), constraint idUq unique(emailid), constraint chk12 check(salary>0)); --------------------------------------------------------------------create table empTest(empid number , ename varchar2(30) , emailid varchar2(30) , salary number(5,2) , deptno number(4) ); alter table empTest modify ename varchar2(30) not null; alter table tableNAme add constraint constraintName constraintType(columnNAme); alter table empTest add constraint Cons_pk primary key(empid,ename); alter table empTest add constraint deptno_FK12 foreign key(deptno)references departments(DEPARTMENT _ID) on delete cascade ---------------------------------------------------------------------alter table tableNAme drop constraint constraintName ; alter table empTest drop constraint deptno_FK12 ; alter table empTest drop primary key ; ----------------------------------------------------------------------alter table TableName enable constraint constraintName; alter table empTest1 enable constraint SYS_C004062; alter table TableName disable constraint constraintName;

alter table empTest1 disable constraint SYS_C004062; --------------------------------------------------------------create table empTest1(empid number primary key, ename varchar2(30) not null, emailid varchar2(30) unique, salary number(5,2) check(salary>0), deptno number(4) references departments(DEPARTMENT_ID) on delete casca

de); create table empTest1(empid number primary key, ename varchar2(30) not null, emailid varchar2(30) unique, salary number(5,2) check(salary>0), deptno number(4) references departments(DEPARTMENT_ID) on delete set n ull); FK -- on delete cascade -- on delete set null emp empid 100 102 101 dept deptno 10 20 30

ename AA BB CC

deptno 10 20 10

dname IT Sales HR

Drop table---constraints,indexes , triggers ---what is not dropped is view and synonym DML --non auto commit insert into tableNAme values(val1,val2,...valN); insert into tableNAme(col1, col2,..colN) values(val1,val2,...valN); create table empTest1(empid number primary key, ename varchar2(30) not null, emailid varchar2(30) unique, salary number(5,2) check(salary>0), deptno number(4) references departments(DEPARTMENT_ID) on delete set n ull); --------------------------------------------------------------------insert into tableNAme values(val1,val2,...valN); insert into empTest1 values(1,'fff','fff@gmail.com',500.89,20); insert into empTest1 values(11,'fff','fff33@gmail.com'null,null); -------------------------------------------------------------------insert into tableNAme(col1, col2,..colN) values(val1,val2,...valN); insert into empTest1(empid,ename) values(12,'ddfff'); --------------------------------------------------------------------delete [from] tableNAme[where condition] delete from empTest1; delete empTest1; delete from empTest1 where deptno=20; where clause used to apply limitations on rows sql comparision operators > < >= <= = <> commit

rollback; transcation --- any DML --- commit, rollback, DDl savepoint -----------------------------------------------------------------update tableName set Col1=val1, col2=val2,....colN=valN [where condition] update empTest1 set salary=salary+2000; update empTest1 set salary=2000; -----------------------------------------------------------------create table empTest1(empid number primary key, ename varchar2(30) not null, emailid varchar2(30) unique, salary number(5,2) default 10 check(salary>0), deptno number(4) references departments(DEPARTMENT_ID) on delete set n ull); alter table empTest1 add gender varchar2(10) check (gender in ('female','male' )) insert into empTest1(empid,ename) values(12,'ddfff'); val for salary col is 10 insert into empTest1 values(1,'fff','fff@gmail.com',default,20); insert into empTest1 values(1,'fff','fff@gmail.com',null,20);

create table empTest1(empid number primary key, ename varchar2(30) not null, emailid varchar2(30) unique, salary number(5,2) check(salary>0), deptno number(4) references departments(DEPARTMENT_ID) on delete set n ull);

insert into empTest1(empid,ename) values(12,'ddfff'); null for salary value

alter table EMpTest1 add salary default 20;

insert into empTest1(empid,ename) values(12,'ddfff'); 20 for salary value -----------------------------------------------------------------------4/7/2013 SELECT FIRST_NAME, SALARY SAL FROM EMPLOYEES SELECT FIRST_NAME, SALARY AS SAL FROM EMPLOYEES SELECT FIRST_NAME, SALARY+100 + - / * SELECT FIRST_NAME ||' '|| LAST_NAME "full Name" FROM EMPLOYEES SELECT FIRST_NAME ||' '|| LAST_NAME Name FROM EMPLOYEES SELECT FIRST_NAME ||' EARNS '|| SALARY "full Name" FROM EMPLOYEES SELECT DISTINCT DEPARTMENT_ID, JOB_id FROM EMPLOYEES "saL result" FROM EMPLOYEES

SELECT DEPARTMENT_ID, JOB_id FROM EMPLOYEES --------------------------------------------------------------------cOMPARISION OPERATORS > < <= >= = <> LOGICAL OPERATORS AND OR NOT --WHERE USED TO APPLY RESTRICTIONS ON ROWS SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID=10; SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID=90; SELECT * FROM EMPLOYEES WHERE SALARY >5000 SELECT * FROM EMPLOYEES WHERE HIRE_DATE <'21-SEP-89' OR SALARY >5000 SELECT * FROM EMPLOYEES WHERE HIRE_DATE <'21-SEP-89' AND SALARY >5000 SELECT * FROM EMPLOYEES WHERE HIRE_DATE <'21-SEP-89' OR SALARY >5000 AND DEPARTMENT_ID=90 SELECT * FROM EMPLOYEES WHERE (HIRE_DATE <'21-SEP-89' OR SALARY >5000) AND DEPARTMENT_ID=90

ORDER BY-- BY DEFAULT IT SORTS IN ASCENDING ORDER BY COLUMNNAME DESC; SORTS IN DESCENDING

SELECT * FROM EMPLOYEES ORDER BY SALARY SELECT * FROM EMPLOYEES ORDER BY SALARY DESC

COLUMNNAME, NUMBER, ALIAS

1) SELECT EMPLOYEE_ID ,SALARY, SALARY+100 SAL FROM EMPLOYEES ORDER BY SAL; 2)SELECT EMPLOYEE_ID ,SALARY, SALARY+100 SAL FROM EMPLOYEES ORDER BY 3 BOTH 1 AND 2 WILL GIVE SAME O/P 1)IN 2)IS NULL 3) IS NOT NULL 4)LIKE _ % 5)BETWEEN ... AND .... SELECT * FROM EMPLOYEES WHERE SALARY IN(2000,9000,17000) SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID IN(10,40,80) SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID IN(20,90) AND SALARY>5000 SELECT * FROM EMPLOYEES WHERE MANAGER_ID IS NULL SELECT * FROM EMPLOYEES WHERE MANAGER_ID IS NOT NULL SELECT * FROM EMPLOYEES WHERE COMMISSION_PCT IS NULL SELECT * FROM EMPLOYEES WHERE COMMISSION_PCT IS NOT NULL LIST EMPLOYEES WHOES NAME STARTS WITH A SELECT * FROM EMPLOYEES WHERE FIRST_NAME LIKE 'A%' LIST EMPLOYEES WHOES NAME STARTS WITH A OR a SELECT * FROM EMPLOYEES WHERE FIRST_NAME LIKE 'a%' OR FIRST_NAME LIKE 'A%' LIST EMPLOYEES WHOES NAME ENDS WITH A SELECT * FROM EMPLOYEES WHERE FIRST_NAME LIKE '%A' LIST EMPLOYEES WHOES NAME CONTAINS SECOND CAHACTER AS A

SELECT * FROM EMPLOYEES WHERE FIRST_NAME LIKE '_A%' LIST EMPLOYEES WHOES NAME CONTAINS SECOND LAST CAHACTER AS S SELECT * FROM EMPLOYEES WHERE FIRST_NAME LIKE '%S_' LIST EMPLOYEES WHOES NAME CONTAINS thrid LAST CAHACTER AS P SELECT * FROM EMPLOYEES WHERE FIRST_NAME LIKE '%p__'

SELECT * FROM EMPLOYEES WHERE salary between 10000 and 20000 SELECT * FROM EMPLOYEES WHERE salary >= 10000 salary <= 20000 sql 1)single row function 2)multiple row function -------------------------------------character function select lower('ABCDg') from dual; select upper('ABCDg') from dual; select initCap('ABCDg') from dual; SELECT employee_id, last_name, department_id FROM employees WHERE upper(last_name) = 'HIGGINS'; select concat('Hello', 'world') from dual;-->Helloworld select concat(concat('Hello', 'world'),'hhhh') from dual; -->Helloworldhhhh select 'Hello'|| 'world' ||'hhhh' from dual;-->Helloworldhhhh select concat(FIRST_NAME,PHONE_NUMBER)from employees select FIRST_NAME, length(FIRST_NAME)from employees select length('abcdef') from dual select concat(FIRST_NAME,PHONE_NUMBER), length(concat(FIRST_NAME,PHONE_NUMBER))f rom employees select lpad(23234,5,'$') from dual---> 23234 select rpad(23,5,'$') from dual--->23$$$ select lpad(23,5,'$') from dual--->$$$23 select trim('H' from 'Hello World') from dual;-->ello World select trim('H' from 'HelloHWorldH') from dual;-->elloHWorld select trim('H' from 'HHHelloHWorldHHH') from dual;-->elloHWorld select trim(leading 'H' from 'HHHelloHWorldHHH') from dual -->elloHWorldHHH

select trim(trailing 'H' from 'HHHelloHWorldHHH') from dual; --->HHHelloHWorld

Select substr('Hello world',1,7) from dual;-->Hello w Select substr('Hello world',1,2) from dual--->He Select substr('Hello world',7) from dual;--> world ------------------------------------Select instr('Hello Hi worldHi','hi',8) from dual; -->0 Select instr('Hello Hi worldHi','Hi',8) from dual;-->15 Select instr('Hello Hi worldHi','Hi') from dual;-->7 Select instr('Hello Hi worldHi','Hi',1,2) from dual;--->15 Select instr('Hello Hi worldHi','Hi',10,2) from dual;--->0 Select instr('Hello Hi worldHi','Hi',10) from dual; -->15 Select replace('Hello World','He','D') from dual;-->Dllo World

Select replace('Hello World','H','D') from dual;-->Dello World Select replace('Hello World','H','De') from dual;-->Deello World SELECT employee_id, CONCAT(first_name, last_name) NAME, job_id, LENGTH (last_name), last_name, INSTR(last_name, 'a') "Contains 'a'?" FROM employees WHERE SUBSTR(job_id, 4) = 'REP';

select select select select select select select select select select

round(45.34) from dual;-->45 round(45.54) from dual;-->46 round(45.34,1) from dual;-->45.3 round(45.356,2) from dual;-->45.36 trunc(45.34) from dual;-->45 trunc(45.3467) from dual-->45 trunc(45.64) from dual;-->45 trunc(45.34,1) from dual;--->45.3 trunc(45.37,1) from dual;-->45.3 trunc(45.356,2) from dual;-->45.35

select mod(4,2) from dual;-->0 select mod(5,2) from dual;-->1 select round(45.356,-1) from dual;-->50

select round(44.356,-1) from dual;-->40 select round(45.356,-2) from dual;-->0 select round(44.356,-2) from dual;-->0 select round(145.356,-2) from dual;--->100 select round(144.356,-2) from dual;-->100 select round(145.356,-1) from dual;-->150 select round(144.356,-1) from dual;-->140 select trunc(145.356,-1) from dual;-->140 select trunc(144.356,-1) from dual;-->140 select trunc(52.356,-1) from dual;-->50 select trunc(56.356,-1) from dual;-->50 select salary, mod(salary,2000) from employees select sysdate from dual select months_between(sysdate,'7-jul-12') from dual-->12.05 select select select select months_between('7-jul-12',sysdate) from dual-->-12.05 add_months(sysdate,2) from dual-->8-sep-13 add_months(sysdate,-2) from dual--> 8-May-13 add_months(sysdate,10) from dual--->08-MAY-14

select next_day(sysdate,'Tuesday') from dual---> select next_day(sysdate,'Tuesday') from dual--> 9-jul-13 select next_day(sysdate,'Monday') from dual-->15-JUL-13 select last_day(sysdate) from dual-->31-jul-13 select last_day('24-Jun-13') from dual--->30-jun-13 select round(sysdate, 'year') from dual;--->1-jan-14 select round(sysdate, 'month') from dual;-->1-jul-13 select to_char(sysdate,' Year') from dual; select to_char(sysdate,' ddspth "of" Month Year') from dual;-->eighth of July Tw enty Thirteen select to_char(sysdate,' ddspth "of" Month Year HH12:MI:SS Pm') from dual;-->eig hth of July Twenty Thirteen 03:28:07 Pm select to_char(2345,'$9,999') from dual;-->$2,345 select to_char(2345,'$99,999') from dual;-->$2,345 select to_char(2345,'$00,999') from dual;-->$02,345 select to_number('2345',9990)+10 from dual;-->2355 select '2345'+10 from dual;-->2355

select SALARY, COMMISSION_PCT, SALARY +nvl(COMMISSION_PCT,0) "Sal+Comm" from employees 1)nvl nvl(COMMISSION_PCT,0) select SALARY, COMMISSION_PCT, SALARY +nvl(COMMISSION_PCT,0) "Sal+Comm" from employees

2)nvl2 nvl2(COMMISSION_PCT,'sal+com','sal') select SALARY, COMMISSION_PCT, nvl2(COMMISSION_PCT,'earns sal+com','earns onlysa l') "Sal+Comm" from employees 3)nullif select nullif('aa','aa') from dual;--->null select nullif('ata','aa') from dual;-->ata select length(FIRST_NAME) ,length(LAST_NAME) ,nullif(length(FIRST_NAME), length( LAST_NAME)) from employees 4)case select case '2' when '1' then 1 when '2' then 2 else 999 end from dual--->2

select case '13' when '1' then 'one' when '2' then 'two' else '999' end from dual ---> 999

select case '1' when '1' then 'one' when '2' then 'two' else '999' end from dual ---> one

SELECT last_name, job_id, salary, case job_id when 'IT_PROG' then 1.10*salary when 'ST_CLERK' then 1.15*salary when 'SA_REP' then 1.20*salary else salary end REVISED_SALARY from employees

5)decode select decode('3' , '1' , 'one', '2' , 'two', '3','three', '999' ) from dual-->three select decode('13' , '1' , 'one', '2' , 'two', '3','three', '999' ) from dual--->999

SELECT last_name, job_id, salary, DECODE(job_id, 'IT_PROG', 1.10*salary, 'ST_CLERK', 1.15*salary, 'SA_REP', 1.20*salary, salary) REVISED_SALARY 6)coalsce --- n number of parameters -- first not null value SELECT coalesce(null,null,'22') from dual;-->22 SELECT coalesce(null,'66',null,'22') from dual;-->66 select MANAGER_ID,COMMISSION_PCT,salary, coalesce(COMMISSION_PCT,MANAGER_ID,sala ry) from employees

multiple row function avg,sum , count,max min select max(salary) from employees select department_id , Avg(salary) from employees group by department_id select department_id , Avg(salary) from employees group by department_id select department_id , Avg(salary),Max(salary),min(salary) from employees group by department_id select sum(salary) from employees

select count(*) from employees-->107 select count(department_id) from employees-->106

select count(distinct department_id) from employees-->11

select count(*) + count(distinct department_id) from employees-->118

emp empid 100 101 102

ename A B C

sal 4000 2000

deptno 10 20 10

select count(sal) +count(ename) from emp;-->5 select count(distint deptno) +count(sal) from emp;-->4 select max(sal) from emp group by deptno; 4000 2000 select deptno,avg(nvl(sal,0)) from emp group by deptno; deptno avg(nvl(sal,0)) 10 2000 20 2000 select min(max(salary)) from employees group by department_id select department_id, max(salary) from employees group by department_id having max(salary)<10000 select department_id, max(salary) from employees group by department_id having max(salary)>10000

select department_id, max(salary) from employees where department_id<>100 having max(salary)>10000 group by department_id order by 1 desc select department_id,count(employee_id) from employees group by department_id having count(employee_id)>3 -----------------------------------------------------------------------joins fetch data from more than one table

1)equi join 2)self join 3)outer join(+) 4)non-equi join

select * from employees,departments; ---cross product is generated when u ommit join condition or worngly specify joi n condition 1)equi join select last_name ,salary,e.department_id,department_name from employees e,depart ments d where e.department_id=d.department_id --------------------------------------------------------------------emp empid 100 101 102 103 104 ename salary deptno A 1000 B 2000 10 C 4000 20 D 2300 30 E 1000 dept deptno dname 20 sales 10 IT 30 Hr 40 marketing

select ename,salary,emp.deptno, dname from emp , dept where emp.deptno=dept.deptno; ename salary emp.deptno dname B 2000 10 IT C 4000 20 sales D 2300 30 hr ------------------------------------------------------------------outer join (+) emp dept empid ename salary deptno deptno dname 100 A 1000 20 sales 101 B 2000 10 10 IT 102 C 4000 20 30 Hr 103 D 2300 30 40 marketing 104 E 1000 select ename,salary,emp.deptno, dname from emp , dept where emp.deptno=dept.deptno(+); o/p ename salary emp.deptno dname B 2000 10 IT C 4000 20 Sales D 2300 30 Hr A 1000 E 1000 -

emp empid 100 101 102 103 104

ename salary deptno A 1000 B 2000 10 C 4000 20 D 2300 30 E 1000

dept deptno dname 20 sales 10 IT 30 Hr 40 marketing

select ename,salary,emp.deptno, dname from emp , dept where emp.deptno(+)=dept.deptno; o/p ename salary emp.deptno dname B 2000 10 IT C 4000 20 Sales D 2300 30 Hr marketing

----------------------------------------------------------------------outer join (+) emp dept empid ename salary deptno deptno dname 100 A 1000 20 sales 101 B 2000 10 10 IT 102 C 4000 10 30 Hr 103 D 2300 40 marketing 104 E 1000 30 50 payroll select ename,salary,emp.deptno, dname from emp , dept where emp.deptno=dept.deptno(+);

select ename,salary,emp.deptno, dname from emp , dept where emp.deptno(+)=dept.deptno; o/p ename salary emp.deptno dname B 2000 10 IT C 4000 10 IT E 1000 30 Hr sales marketing payroll ------------------------------------------------------------------------self join emp empid(pk) 100 101 102

ename A B C

salary deptno mgrid (fk) 1000 2000 10 100 4000 10 100

103 104

D E

2300 1000

30

101 103

select w.ename ||' works for '||m.ename result from emp w, emp m where w.mgrid=m.empid; o/p result B works for A c works for A D works for B e works for D emp empid(pk) 100 101 102 103 104 105

ename A B C D E F

salary deptno mgrid (fk) 1000 2000 10 100 4000 10 2300 101 1000 30 30 100

select w.ename ||' works for '||m.ename result from emp w, emp m where w.mgrid=m.empid; o/p result B works for A D works for B F works for A ----------------------------------------------------------------------non-equi join emp empid(pk) 100 101 102 103 104 105 ename salary AA 9000 BB 2800 CC 4023 DD 2300 Ee 3000 FF salgrade grade A B c D lowsal 8001 4001 2001 100 hisal 10000 8000 4000 2000

select ename, salary, grade from emp e,salgrade g where salary between lowsal and hisal; o/p ename AA BB CC DD Ee salary 9000 2800 4023 2300 3000 grade A C B C C

---------------------------------------------------------------------non-equi join

select ename, salary, grade from emp e,salgrade g where salary >=lowsal and salary<= hisal ; emp empid(pk) 100 101 102 103 ename AA BB DD salgrade grade A B c D

ename salary AA 9000 BB 2800 CC DD 8000 grade A C B

lowsal 8001 4001 2001 100

hisal 10000 8000 4000 2000

salary 9000 2800 8000

select ename, salary, grade from emp e,salgrade g where salary >=lowsal and salary<= hisal and salary>4000; ename salary grade AA 9000 A DD 8000 B ----------------------------------------------------------------------1)cross join select last_name,department_name from employees cross join departments

-----------------------------------------------------------------------2)natural join emp empid 100 101 102 103 104 ename salary deptno A 1000 B 2000 10 C 4000 10 D 2300 E 1000 30 dept deptno dname 20 sales 10 IT 30 Hr 40 marketing 50 payroll

select ename,salary,deptno, dname from emp natural join dept o/p ename salary deptno dname B 2000 10 IT C 4000 10 IT E 1000 30 Hr

emp empid ename salary deptno mgr

dept deptno dname

mgr

100 101 102 103 104

A B C D E

1000 2000 4000 2300 1000

10 10 30

100 101 101 101

20 10 30 40 50

sales IT Hr marketing payroll

102 100 101 101

select ename,salary,deptno, dname from emp natural join dept; ename salary deptno dname B 2000 10 IT E 1000 30 Hr

test(t1 number, t2 number) test2(t1 number, t2 char, t3 number) select t1,t2 from test1 natural join test2;---error select t1,t2 from test1 join test2 using(t1,t2)--error select t1,t2 from test1 join test2 using(t1)--correct

--------------------------------------------------------------select last_name ,salary,department_id,department_name from employees natural j oin departments select last_name ,salary,department_id,department_name from employees e, departments d where e.department_id=d.department_id and e.manager_id=d.manager_i d -----------------------------------------------------------------------3)using clause select ename,salary,deptno, dname from emp join dept using(deptno) -----------------------------------------------------------------------select last_name ,salary,department_id,department_name from employees join dep artments using(department_id) select last_name ,salary,department_id,department_name from employees artments using(department_id,manager_id) -----------------------------------------------------------------------4)on clause select ename,salary,e.deptno, dname from emp e join dept d on(e.deptno=d.deptno) -----------------------------------------------------------------select last_name ,salary,e.department_id,department_name , city from employees join dep

e join departments d on(e.department_id=d.department_id) join locations l on(l.location_id=d.location_id) -----------------------------------------------------------------------5) left outer,right outer,full outer select last_name ,salary,e.department_id,department_name , city from employees e left outer join departments d on(e.department_id=d.department_id) ------------------------------------------select last_name ,salary,e.department_id,department_name from employees e right outer join departments d on(e.department_id=d.department_id) ----------------------------------------------select last_name ,salary,e.department_id,department_name from employees e full outer join departments d on(e.department_id=d.department_id) -----------------------------------------------------------------------n tables n-1 join conditions---- if single col pk

----------------------------------------------------------------------set operations(union, union all, intersect, minus) 1)union all select department_id, JOB_ID from employees union all select department_id, JOB_ID from JOB_HISTORY ----------------------------------------------2)union select department_id, JOB_ID from employees union select department_id, JOB_ID from JOB_HISTORY ----------------------------------------------3)intersect select department_id, JOB_ID from employees intersect select department_id, JOB_ID from JOB_HISTORY --------------------------------------------4)minus select department_id, JOB_ID from employees minus select department_id, JOB_ID from JOB_HISTORY ------------------------------------------------------------------

DCL (grant revoke) privilages --- System (by DBA) eg -->create user, create table,create view ,resource ect ---Object (by owner of object) object is table ----select, insert, update, delete object is view ----select, insert, update, delete object is procedure ,function -- excecute

create user uerNAme identified by password; --logined as dba and created user cmc1 create user cmc1 identified by cmc1; --- give privilages to cmc1 user grant create table,resource to cmc1; ---to give privilages revoke create table,resource from cmc1;---to take back the privilages

object login as hr grant pr1,pr2... on objectName t0 user; grant select on employees to cmc1; grant select,insert, update on employees to cmc1; grant select on employees to cmc1 with grant option; hr---with grant option->cmc1--->abc cmc1-with grant option-->cmc2--->other user

revoke select on employees from cmc1; role create role roleName; grant pr1,pr2,..prn on TableNAme to roleNAme;

grant roleNAme to user1,user2....userN; create role Roletest; grant select, update on emplyees to Roletest; revoke update on employees from roletest; grant Roletest to cmc1,cmc2; revoke roletest from cmc2; ---------------------------------------------------------------------11/7/2013 -- subquery select colname from tableName where colnameX=(select colnameX from tableNAme where cond ) and col2=(select col2 from tableNAme where cond ) two type of subqueries 1)Single row Subquery 2)multiple row subquery --single row subquery operates returns a single value select first_name , salary from employees where salary >(select salary from employees where first_name='Nancy')

select first_name , salary from employees where department_id=(select department_id from employees where last_name='K ochhar') select first_name , salary,department_id from employees where salary >17000 and department_id=(select department_id from employees where last_name='Kochhar') select first_name , salary,department_id from employees where department_id=(select department_id from employees where last_name=' Kochhar') and salary >(select salary from employees where last_name='De Haan')

select first_name , salary from employees where department_id=(select department_id from employees where last_name='K ochhar')

select first_name , salary,department_id from employees where job_id=(select job_id from employees where last_name='Hunold') and s alary =(select salary from employees where last_name='Hunold')

select first_name , salary,department_id from employees where (job_id,salary)=(select job_id,salary from employees where last_name ='Hunold')

single row subquery operator are > ,< ,>=, <=, = ,<>

-------------------------------------------------------------multiple row subquery returns multiple values or returns more than one values multiple row operator are in ,any ,all < all means less than minval > all means more than maxval <any means less than maxval >any means more than minval

SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary < any (SELECT salary FROM employees WHERE job_id = 'IT_PROG')

SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary <(select max(salary) FROM employees WHERE job_id = 'IT_PROG')

SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary < all (SELECT salary FROM employees WHERE job_id = 'IT_PROG') SELECT employee_id, last_name, job_id, salary FROM employees WHERE salary > all (SELECT salary FROM employees WHERE job_id = 'IT_PROG')

-----------------------------------------------------------------advacnce subquery Inlineview subquery SELECT a.last_name, a.salary, a.department_id, b.salavg FROM employees a, (SELECT department_id, AVG(salary) salavg FROM employees GROUP BY department_id) b WHERE a.department_id = b.department_id AND a.salary > b.salavg;

--------------------------------------------------------------Top n analysis subquery top data select rownum, last_name,salary from (select last_name,salary from employees o rder by salary desc) where rownum <= 3 bottom data select rownum, last_name,salary from (select last_name,salary from employees order by salary ) where rownum <=3

----------------------------------------------------------------exists sub query SELECT employee_id, last_name FROM employees outer WHERE EXISTS ( SELECT 'X' FROM employees WHERE manager_id = outer.employee_id); empid lastname salary 100 AAA 2000 101 DDD 4000 102 FFF 8000 103 CCC 4000 managerid 100 100 101

o/p empid lastname 100 AAA

101

DDD

SELECT employee_id, last_name FROM employees outer WHERE not EXISTS ( SELECT 'X' FROM employees WHERE manager_id = outer.employee_id); empid lastname salary 100 AAA 2000 101 DDD 4000 102 FFF 8000 103 CCC 4000 managerid 100 100 101

o/p empid lastname 102 FFF 103 CCC -------------------------------------------------------corelated subquery--- for each row SELECT column1, column2, ... FROM table1 WHERE column1 operator (SELECT colum1, column2 FROM table2 WHERE expr1 = table1.expr2); SELECT FROM WHERE FROM WHERE last_name, salary, department_id employees outer salary >(SELECT AVG(salary) employees department_id = outer.department_id) ; departmentid 20 10 10 20

empid lastname salary 100 AAA 2000 101 DDD 4000 102 FFF 8000 103 CCC 4000 o/p lastname salary FFF 8000 CCC 4000

departmentid 10 20

--------------------------------------------------------------SELECT last_name, salary, department_id FROM employees o WHERE salary <(SELECT AVG(salary) FROM employees

WHERE department_id = o.department_id) ; 10---> 5000.3 20-->2000 empid lastname salary 100 AAA 2000 101 DDD 4000 102 FFF 8000 103 CCC 4000 o/p last_name salary department_id DDD 4000 10 CCC 4000 10 ----------------------------------------------------------------------index,sequence,synom --On PK & unique automatically unique index is generated create Index indexName on TableName(columnName); create index ind12 on Employees(FIRST_NAME); dd--user_indexes drop index indexName; drop index ind12 function based index create index ind12 on Employees(upper(FIRST_NAME)); DD---select * from user_indexes ----------------------------------------------------------------------CREATE SEQUENCE sequence [INCREMENT BY n] [START WITH n] [{MAXVALUE n | NOMAXVALUE}] [{MINVALUE n | NOMINVALUE}] [{CYCLE | NOCYCLE}] [{CACHE n | NOCACHE}]; CREATE SEQUENCE seq1 INCREMENT BY 1 start with 1 maxvalue 5 minvalue 0;

departmentid 20 10 10 10

seq1.curval seq1.nextval

alter SEQUENCE seq1 maxvalue 25 INCREMENT BY 2 cycle cache 2 drop SEQUENCE seq1; CREATE SEQUENCE seq2 INCREMENT BY 1 start with 1 maxvalue 5 minvalue 0 cycle CACHE 4;

CREATE SEQUENCE seq3 INCREMENT BY -1 start with 2 maxvalue 5 minvalue 0; CREATE SEQUENCE seq3 INCREMENT BY -1 start with 2 maxvalue 5 minvalue 0 cycle cache 4 after creating sequence use nextval as nextval is used to generate sequence valu es --currval gives current value select seq1.nextval from dual; select seq1.currval from dual;

CREATE SEQUENCE seq1 INCREMENT BY 1 start with 1 maxvalue 10 minvalue 0; create table test1(a number primary key); insert into test1 values(seq1.nextval)

drop sequence sequenceNAme dd---user_sequences --------------------------------------------------------------------SYNONYM CREATE SYNONYM synonymName FOR object; CREATE SYNONYM emp for employees; select * from emp update emp set salary=salary+1000; using emp you can perform DML operation as you have create sysnonm for table obj ect if employees table is dropped then status of emp will be invalid drop SYNONYM tt; CREATE SYNONYM tt for test1 dependent oject tt referenced object test1

local dependencies are automatically managed by oracle server

----------------------------------------------------------------------views view is based on table create [force/noforce] view viewName as [Subquery] select [with check option] [with read only] views are of two types --simple --complex(join) --simple create view vEmp as select * from employees where department_id=90;

select * from user_views ---dd select * from vEmp update vemp set salary=salary-200 ;

--simple create view vEmp1 as select first_name,department_id from employee where department_id=90 DD--user_views

DMl operation can be performed on simple view insert into vemp values(1,2,3,4,5...10);

create force view vEmp111 as select * from abc --force option creates view even if abc table is not present in database

-------------------------------------------------------------create or replace view vEmp as select * from employees where department_id=90 with read only ----dml operations cannot be performed

-----------------------------------------------------------create or replace view vEmp as select * from employees where department_id=90

create table test12(a number, b number)

create or replace view vtest12 as select * from test12 where b=10; insert into vtest12 values(1,1);

create or replace view vtest123 as select * from test12 where b=10 with check option

---------------------------------------------------------complex view create view v1 as select employee_id, last_name,salary,department_name from employees e, depar tments d where e.department_id=d.department_id create view v11 as select min(salary) minsal,department_id from employees group by department_id select * from v11; ---------------------------------------------------------drop view ViewName; drop view v1; ------------------------------------------------------------view vemp--constraint update trigger --on table update trigger --on view table Employees

SELECT [LEVEL], column, expr... FROM table [WHERE condition(s)] [START WITH condition(s)] [CONNECT BY PRIOR condition(s)];

CONNECT BY PRIOR Column1 = Column2 Top down Column1 = Parent Key Column2 = Child Key Bottom up

Column1 = Child Key Column2 = Parent Key SELECT employee_id, last_name, job_id, manager_id FROM employees START WITH employee_id = 101 CONNECT BY PRIOR manager_id = employee_id;

SELECT last_name||' reports to '|| PRIOR last_name "Walk Top Down" FROM employees START WITH last_name = 'King' CONNECT BY PRIOR employee_id = manager_id;

101 108 109 110 111 112 113 200 203 204 205 206

----drops a single row 205 SELECT employee_id, last_name, job_id, manager_id FROM employees where last_nama<>'Higgins' START WITH employee_id = 101 CONNECT BY PRIOR employee_id=manager_id

---drops complete brach from 205, 206 SELECT employee_id, last_name, job_id, manager_id FROM employees START WITH employee_id = 101 CONNECT BY PRIOR employee_id=manager_id and last_name <>'Higgins' drop delete truncate

-----------------------------------------****************************************** -----------------------------------------PLSQL two types

-unnamed block -Named block eg-procedure,

function,package, triggers (pcode)

unnamed block declare -----begin ----exception ----end; SQL datatype is vaild in plSQL pLSQL --boolean,integer single row functions can be used as plsql statements < > <= >= <> = comparision operators and or variableName dataype; a number; //vaild a, b, c number;// invalid sataement a number;//vaild b number;//vaild c number;//vaild -----------------------------------------

begin dbms_output.put_line('Hello World'); end;

dbms_output---package Name put_line---function

SQL command prompt set serveroutput on begin dbms_output.put_line('Hello World'); end; / /*

*/ ----------------------------------------Assignment operator := -----------------------------------------declare a number:=10; --vaild b number:=10; --vaild c number; --vaild begin c:=a+b; dbms_output.put_line('addition is '|| c); end; if (condition) then ----end if; if (condition) then ----else ---end if;

if (condition) and (condition) then ----elsif (condition) and (condition) then ----elsif (condition) then -----else ----end if; -----------------------------------------declare a number:=128; --vaild b number:=100; --vaild begin if(a>b) then dbms_output.put_line(a||'is greater'); else dbms_output.put_line(b||'is greater'); end if; end; -----------------------------------------declare

a number:=128; --vaild b number:=100; --vaild c number:=10; begin if(a>b) and (a>c)then dbms_output.put_line(a||'is greater'); elsif(b>c) then dbms_output.put_line(b||'is greater'); else dbms_output.put_line(c||'is greater'); end if; end; declare a number:=127; begin if(mod(a,2)=0)then dbms_output.put_line(a||' is even number'); else dbms_output.put_line(a||' is odd number'); end if; end; variableName datatype not null :=value; variableName constant datatype :=value; declare a number not null:=10; c constant number :=11; begin a:=a+c; dbms_output.put_line('a '||a ||' c: '||c) ; end; -----------------------------------------****************************************** --------------------------------------------------------------------------------loops 1)basic loop 2)while loop 3) for loop 1)basic loop loop ----exit when(condition); --end loop; declare a number:=1; begin

loop dbms_output.put_line(a); a:=a+1; exit when(a>5); end loop; end; 2)while loop declare a number:=1; begin while(a<=5) loop dbms_output.put_line(a); a:=a+1; end loop; end; -----------------------------------------3)for loop increments only by 1 for countervariable in lowerlimit..upperlimit loop ----end loop; begin for i in 1..5 loop dbms_output.put_line(i); end loop; end; ----------------------------------------begin for i in 1..5 loop dbms_output.put_line(i); i:=i+2; end loop; end; error: expression 'I' cannot be used as an assignment target --------------------------------------begin for i in reverse 1..5 loop dbms_output.put_line(i); end loop; end; -----------------------------------------------------------------------------------

****************************************** -----------------------------------------CASE variableNAme WHEN expression1 THEN result1 WHEN expression2 THEN result2 ... WHEN expressionN THEN resultN [ELSE result;] END; in command prompt declare variable as follows variable a vachar2(30); DECLARE v_grade CHAR(1) := UPPER('G'); v_appraisal VARCHAR2(20); BEGIN v_appraisal := CASE v_grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade ); DBMS_OUTPUT.PUT_LINE('Appraisal ' || v_appraisal); END; ---------------------------------------SQL command prompt DECLARE v_grade CHAR(1) := UPPER('&p'); v_appraisal VARCHAR2(20); BEGIN v_appraisal := CASE v_grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good' ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade ); DBMS_OUTPUT.PUT_LINE('Appraisal ' || v_appraisal); END; --every time it will take value for p DECLARE v_grade CHAR(1) := UPPER('&&p'); v_appraisal VARCHAR2(20); BEGIN v_appraisal := CASE v_grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Very Good' WHEN 'C' THEN 'Good'

ELSE 'No such grade' END; DBMS_OUTPUT.PUT_LINE ('Grade: '|| v_grade ); DBMS_OUTPUT.PUT_LINE('Appraisal ' || v_appraisal); END; only once it will take value for p -----------------------------------------****************************************** -----------------------------------------into clause declare name varchar2(30); a number:=100; begin select last_name into name from employees where employee_id=a; DBMS_OUTPUT.PUT_LINE('Emp Name is '||name); end; ----------------------------------------find error declare name varchar2(30); a number:=105; begin select last_name into name from employees; DBMS_OUTPUT.PUT_LINE('Emp Name is '||name); end; ORA-01422: exact fetch returns more than requested number of rows ------------------------------------------find error declare name varchar2(30); a number:=105; begin select last_name into name from employees where employee_id=10; DBMS_OUTPUT.PUT_LINE('Emp Name is '||name); end; as employee_id 10 is not their in database error:ORA-01403: no data found -----------------------------------------****************************************** -----------------------------------------a tableNAme.columnNAme%type; rec table%rowtype; declare name employees.last_name%type; a number:=100; begin select last_name into name from employees where employee_id=a;

DBMS_OUTPUT.PUT_LINE('Emp Name is '||name); end; -----------------------------------------****************************************** -----------------------------------------declare name employees.last_name%type; dnum employees.department_id%type; a number:=100; begin select last_name ,department_id into name ,dnum from employees where employee_id=a; DBMS_OUTPUT.PUT_LINE('Emp Name is '||name); DBMS_OUTPUT.PUT_LINE('Emp department is '||dnum); end; declare name employees.last_name%type; dnum employees.department_id%type; sal employees.salary%type; a number:=100; begin select last_name ,department_id ,salary into name,dnum ,sal from employees where employee_id=a; DBMS_OUTPUT.PUT_LINE('Emp Name is '|| name); DBMS_OUTPUT.PUT_LINE('Emp department is '|| dnum); DBMS_OUTPUT.PUT_LINE('Emp sal is '|| sal); end; -----------------------------------------****************************************** -----------------------------------------rec tableNAme%rowtype; declare rec employees%rowtype; a number:=&p; begin select * into rec from employees where employee_id=a; DBMS_OUTPUT.PUT_LINE('Emp Name is '|| rec.last_name); DBMS_OUTPUT.PUT_LINE('Emp department is '||

rec.department_id); DBMS_OUTPUT.PUT_LINE('Emp sal is '|| rec.salary); DBMS_OUTPUT.PUT_LINE('Emp job is '|| rec.job_id); end; -----------------------------------------****************************************** -----------------------------------------cursor--1)Implicit cursor 2)Explicit cursor 1)Implicit cursor---DML & select statement which returns single row attributes 1)SQL%found ---boolean 2)SQL%notfound ---boolean 3)SQL%isopen ---boolean (false) 4)SQL%rowcount--integer begin update employees set salary=salary+1000 where employee_id=0; if(SQL%rowcount=0) then DBMS_OUTPUT.PUT_LINE(SQL%rowcount ||' rows updated') else DBMS_OUTPUT.PUT_LINE(SQL%rowcount ||' rows updated') end if; end; -----------------------------------------begin update employees set salary=salary+1000; --where employee_id=100; if(SQL%rowcount=0) then DBMS_OUTPUT.PUT_LINE(SQL%rowcount ||' rows updated'); else DBMS_OUTPUT.PUT_LINE(SQL%rowcount ||' rows updated'); end if; end; -----------------------------------------****************************************** -----------------------------------------2)Explicit cursor--1)declare cursor 2)open cursor 3)fetch cursor 4)cursor data processing 5)colse cursor

attributes 1)cursorNAme%found ---boolean 2)cursorNAme%notfound ---boolean 3)cursorNAme%isopen ---boolean 4)cursorNAme%rowcount--integer cursor cursorNAme is subquery; declare cursor cemp is select * from employees where department_id=90; recemp employees%rowtype; begin open cemp; loop fetch cemp into recemp; exit when (cemp%notfound); DBMS_OUTPUT.PUT_LINE('Emp NAme'|| recemp.last_name); DBMS_OUTPUT.PUT_LINE('Emp salary'|| recemp.salary); end loop; close cemp; end; -----------------------------------------****************************************** -----------------------------------------cursor for loop declare cursor cemp is select * from employees where department_id=90; begin for recemp in cemp loop DBMS_OUTPUT.PUT_LINE('Emp NAme'|| recemp.last_name); DBMS_OUTPUT.PUT_LINE('Emp salary'|| recemp.salary); end loop; end;

declare cursor cemp is select * from employees where department_id=90; recemp employees%rowtype; begin open cemp; while(cemp%found or cemp%found is null ) loop fetch cemp into recemp; DBMS_OUTPUT.PUT_LINE('Emp Name: '||recemp.last_name); end loop; close cemp; end;

-----------------------------------------Cursor FOR Loop Using Subqueries BEGIN FOR emp_record IN (SELECT * FROM employees) LOOP DBMS_OUTPUT.PUT_LINE (emp_record.last_name || emp_record.department_id); END LOOP; end; -----------------------------------------****************************************** -----------------------------------------cursor with parameter CURSOR cursor_name [(para1 datatype, para2 datatype,...)] IS select statement; --using for loop DECLARE CURSOR emp_cursor(a number) IS SELECT * FROM employees where department_id=a; BEGIN for recemp in emp_cursor(100) LOOP DBMS_OUTPUT.PUT(recemp.employee_id|| ' ' ); DBMS_OUTPUT.PUT(recemp.last_name || ' '); DBMS_OUTPUT.PUT(recemp.salary); DBMS_OUTPUT.new_LINE (); END LOOP; end; -----------------------------------------DECLARE CURSOR emp_cursor(a number) IS SELECT * FROM employees where department_id=a; BEGIN for recemp in emp_cursor(100)

LOOP DBMS_OUTPUT.PUT(recemp.employee_id|| ' ' ); DBMS_OUTPUT.PUT(recemp.last_name || ' '); DBMS_OUTPUT.PUT(recemp.salary); DBMS_OUTPUT.new_LINE (); END LOOP; DBMS_OUTPUT.put_LINE('--------------'); for recemp in emp_cursor(90) LOOP DBMS_OUTPUT.PUT(recemp.employee_id|| ' ' ); DBMS_OUTPUT.PUT(recemp.last_name || ' '); DBMS_OUTPUT.PUT(recemp.salary); DBMS_OUTPUT.new_LINE (); END LOOP; end; -----------------------------------------****************************************** -----------------------------------------DECLARE CURSOR emp_cursor(a number) IS SELECT * FROM employees where department_id=a; BEGIN for recemp in emp_cursor(100) LOOP DBMS_OUTPUT.PUT_LINE (recemp.employee_id ); END LOOP; for recemp in emp_cursor(80) LOOP DBMS_OUTPUT.PUT_LINE (recemp.employee_id ); END LOOP; END; -----------------------------------------****************************************** -----------------------------------------using basic loop DECLARE

CURSOR emp_cursor(a number) IS SELECT * FROM employees where department_id=a; recemp emp_cursor%rowtype; BEGIN OPEN emp_cursor(100); LOOP FETCH emp_cursor INTO recemp; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (recemp.last_name); END LOOP; CLOSE emp_cursor; END ;

-----------------------------------------****************************************** -----------------------------------------for update & where current of clause --for update is Used to for explicit locks cursor data --Lock the rows before the update or delete. DECLARE CURSOR sal_cur IS SELECT last_name, salary FROM employees e, departments d WHERE d.department_id = e.department_id and d.department_id = 100 FOR UPDATE OF salary NOWAIT; BEGIN FOR emp_record IN sal_cur LOOP IF emp_record.salary < 5000 THEN UPDATE employees SET salary = emp_record.salary * 1.10 WHERE CURRENT OF sal_cur; END IF; END LOOP; END; ----------------------------------------record type ----------------------------------------type typeNAme is record ( variableName datatype, variableName datatype,.. variableN datatype); typeVariable typeNAme;

declare type recemp is record (name employees.last_name%type, sal number); rec recemp;

begin select last_name, salary into rec from emploYees where employee_id=100; dbms_output.put_line('emp name'||rec.naME); dbms_output.put_line('emp SAL'||rec.SAL); end; -----------------------------------------ref cursor -------------------------------------------- REF CURSOR is a data type. -- variable created based on such a data type is called a cursor variable. -- A cursor variable can be associated with different queries at run-time. ----to declare ref cursor type typeName is ref cursor refcursorvariable typeName; declare type refcur1 is ref cursor; refcurvar refcur1; c1 employees%rowtype; c2 departments%rowtype; begin open refcurvar for select * from employees; loop fetch refcurvar into c1; exit when refcurvar%notfound; dbms_output.put_line('book name :='||c1.last_name); end loop; close refcurvar; end; -----------------------------------------declare type refcur1 is ref cursor; refcurvar refcur1; c1 employees%rowtype; c2 departments%rowtype; begin open refcurvar for select * from employees; loop fetch refcurvar into c1; exit when refcurvar%notfound; dbms_output.put_line('book name declare type refcur1 is ref cursor; refcurvar refcur1; c1 employees%rowtype; c2 departments%rowtype; begin open refcurvar for select * from employees; loop fetch refcurvar into c1; exit when refcurvar%notfound; dbms_output.put_line('book name :='||c1.last_name); end loop; close refcurvar; open refcurvar for select * from departments; loop fetch refcurvar into c2; exit when refcurvar%notfound; dbms_output.put_line(' name :='||c2.department_name);

end loop; close refcurvar; end;

---------------------------------------declare type refcur1 is ref cursor; refcurvar refcur1; c1 employees%rowtype; c2 departments%rowtype; c3 departments.department_name%type; begin open refcurvar for select * from employees; loop fetch refcurvar into c1; exit when refcurvar%notfound; dbms_output.put_line('book name :='||c1.last_name); end loop; close refcurvar; open refcurvar for select * from departments; loop fetch refcurvar into c2; exit when refcurvar%notfound; dbms_output.put_line(' name :='||c2.department_name); end loop; close refcurvar; open refcurvar for select department_name from departments; loop fetch refcurvar into c3; exit when refcurvar%notfound; dbms_output.put_line(' name :='||c3); end loop; close refcurvar; end; -----------------------------------------****************************************** -----------------------------------------Exception 1)predefined exceptions 2)non perdefined exceptions 3)user defined exceptions --predefined & non perdefined exceptions are implicitly raised --we handle them usingexception handler --exceptiond are always handled with exception name in PLSQL. --user defined exceptions 1)declare exception 2)explicitly raise the exception 3)handle the exception

-----------------------------------------1)Predefined exception are not declared 2)implicitly raised 3)handle the Exception using exception handler

eg->NO_DATA_FOUND,TOO_MANY_ROWS, INVALID_CURSOR, ZERO_DIVIDE etc declare a number:=10; begin a:=a/0; DBMS_OUTPUT.PUT_LINE('value of a'||a); end;

declare a number:=10; begin a:=a/0; DBMS_OUTPUT.PUT_LINE('value of a'||a); exception when NO_DATA_FOUND then DBMS_OUTPUT.PUT_LINE('data not avaiable'); when ZERO_DIVIDE then DBMS_OUTPUT.PUT_LINE('cannot divide by zero'); when TOO_MANY_ROWS then DBMS_OUTPUT.PUT_LINE('too many rows fetched '); end; -----------------------------------------declare a number:=10; begin a:=a/0; DBMS_OUTPUT.PUT_LINE('value of a'||a); EXCEPTION WHEN ZERO_DIVIDE then DBMS_OUTPUT.PUT_LINE('cannot divide by zero'); end; -------------------------------------------sqlcode --sqlerrm declare a number:=10; rec employees%rowtype; begin --a:=a/0; select * into rec from employees ; --where employee_id=10; DBMS_OUTPUT.PUT_LINE('value of a'||a); exception

when NO_DATA_FOUND then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); when ZERO_DIVIDE then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); when others then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); end; ---------------------------------------declare a number:=10; rec employees%rowtype; begin --a:=a/0; select * into rec from employees where employee_id=100; DBMS_OUTPUT.PUT_LINE('name'|| rec.last_name); DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); exception when NO_DATA_FOUND then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); when ZERO_DIVIDE then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); when others then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); end; ----------------------------------------declare a number:=20; begin a:=a/0; DBMS_OUTPUT.PUT_LINE('value of a'||a); EXCEPTION WHEN ZERO_DIVIDE then DBMS_OUTPUT.PUT_LINE(sqlerrm); DBMS_OUTPUT.PUT_LINE(sqlcode); end; -----------------------------------------create table error_log(errorcode number, errormsg varchar2(200) ); declare a number; b varchar2(200); rec employees%rowtype; begin select * into rec from employees where employee_id=10; DBMS_OUTPUT.PUT_LINE('name'|| rec.last_name); DBMS_OUTPUT.PUT_LINE(sqlcode);

DBMS_OUTPUT.PUT_LINE(sqlerrm); exception when others then a:=sqlcode; b:=sqlerrm; insert into error_log values (a,b); end; ----------------------------------------declare a number:=101; code number; msg varchar2(200); name varchar2(30); sal number; begin select last_name,salary into sal,name from employees where employee_id=a; dbms_output.put_line('emp Name is :'||name); dbms_output.put_line('emp Salary is :'||sal); EXCEPTION WHEN others then msg:=sqlerrm; code:=sqlcode; insert into error_log values(code,msg); end; select * from error_log -- exception information is maintained in a table --- others handler is the last in when clause ------------------------------------------DECLARE CURSOR emp_cursor(a number) IS SELECT * FROM employees where department_id=a; recemp emp_cursor%rowtype; BEGIN OPEN emp_cursor(100); OPEN emp_cursor(100); LOOP FETCH emp_cursor INTO recemp; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (recemp.last_name); END LOOP; CLOSE emp_cursor; exception when others then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); END ;

DECLARE a number; b varchar2(200); CURSOR emp_cursor(a number) IS SELECT * FROM employees where department_id=a; recemp emp_cursor%rowtype; BEGIN -- OPEN emp_cursor(100); --OPEN emp_cursor(100); LOOP FETCH emp_cursor INTO recemp; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (recemp.last_name); END LOOP; CLOSE emp_cursor; exception when others then DBMS_OUTPUT.PUT_LINE(sqlcode); DBMS_OUTPUT.PUT_LINE(sqlerrm); a:=sqlcode; b:=sqlerrm; insert into error_log values(a,b); END ; -----------------------------------------2)Nonpredefined Oracle Server 1)declare exception & Associate error code with Exception name 2)implicitly raised 3)handle Exception using exception handler DECLARE emps_Exp EXCEPTION; PRAGMA EXCEPTION_INIT (emps_Exp, -2292); BEGIN DELETE FROM departments WHERE department_id = 100; EXCEPTION WHEN emps_Exp THEN DBMS_OUTPUT.PUT_LINE ('cannot delete parent value as child value exixts'); END; ------------------------------------------3)User-defined ---explicitly raised 1)declare exception 2)explicitly raised Exception 3)Handle the Exception using exception handler declare

a number:=100; emps_Exp EXCEPTION; begin update employees set salary=salary+1000 where department_id=a; if(SQL%rowcount=0) then raise emps_Exp; else dbms_output.put_line( sql%rowcount ||' rows updated' ); end if; exception when emps_Exp then dbms_output.put_line(sqlcode ||' '||sqlerrm); end; -----------------------------------------exception not raised sqlcode:0 Sqlerrm:ORA-0000:normal,successful ----------------------------------------userdefine exception sqlcode :1 sqlerrm:User-Defined Exception -----------------------------------------procedure, functions,package ,trigger--->pcode create or replace procedure procedureName(paraNAme mode datatype, para2 mode dat atype.....) is ---(declaration ) --begin ----Exception ----end; modes of parameters in--by default out in out create or replace procedure add12(a number, b number) is c number; begin c:=a+b; dbms_output.put_line('addition is '|| c); end; to check erros in procedure ,function,package etc

completion

DD--->select * from user_errors command ----> show error

to get source code of procedure ,function,package,triggers--- user_source select TEXT from user_source where NAME='ADD12'

begin add12(5,15); end; execute procedure from sql command prompt exec add12(12,3); execute add12(2,4); exec add12(&a,&b); -----value from user

------------------------------------------------------------------------------------------------------------find out error in following procedure? create or replace procedure add12(a number, b number) is c number; begin a:=a+b; dbms_output.put_line('addition is '|| c); end; error:expression 'A' cannot be used as an assignment target -------------------------------------------------------------------------------------------------------create or replace procedure add123(a number, b number , c out number) is begin c:=a+b; dbms_output.put_line('addition is '|| c); end;

declare s number;

begin dbms_output.put_line('value of s is:'||s); add123(3,4,s); dbms_output.put_line('value of s is:'||s); end; execute procedure from sql command prompt variable d number; exec add123(5,6,:d); print d exec add123(&a,&b,:d);--- value from user print d ---------------------------------------------------------------------------------------------------create or replace procedure sqr1(a in out number) is begin dbms_output.put('sqr is of '|| a ||' is:'); a:=a*a; dbms_output.put(a); dbms_output.new_Line(); end; declare d number:=5; begin sqr1(d); end;

execute procedure from sql command prompt variable d number; declare c number; begin c:=&d; sqr1(c); end; -----------------------------------------------------create or replace procedure pp1(s number) is CURSOR emp_cursor(a number) IS SELECT * FROM employees where department_id=a; recemp emp_cursor%rowtype; BEGIN OPEN emp_cursor(s);

LOOP FETCH emp_cursor INTO recemp; EXIT WHEN emp_cursor%NOTFOUND; DBMS_OUTPUT.PUT_LINE (recemp.last_name); END LOOP; CLOSE emp_cursor; exception when others then DBMS_OUTPUT.PUT_LINE('cursor already open'); END pp1; begin pp1(100); end; sql command prompt exec pp1(100); exec pp1(&a); -------------------------------------------------create procedure pSelect(e number, name out varchar2, sal out number) is begin select last_name,salary into name,sal from employees where employee_id=e; end; declare n varchar2(20); s number; begin pSelect(100,n,s); dbms_output.put_line( n || ' has salary '||s); end; variable n varchar2(30) variable n number exec pSelect(100,:n,:s); print n print s

-----------------------------------------------------Ways for Passing Parameters to procedure 1)Positional --- order in which actual & formal parameters is passed is same. 2)Named: order of actual parameters is in arbitrary order by associating each wi

th its corresponding formal parameter name 3)Combination: List some of the actual parameters as positional and some as name d. ------------------------------------------------------create or replace procedure add111(a number default 10, b number default 20, c n umber default 30) is begin dbms_output.put_line('a ='||a); dbms_output.put_line('b ='||b); dbms_output.put_line('c ='||c); dbms_output.put_line(a+b+c); end; begin add111; add111(30); add111(3,1,2); add111(c=>4); add111(b=>2); add111(c=>4,b=>2); add111(c=>4,a=>30); add111(b=>4,a=>30); end; --------------------------------------------------------create or replace procedure add1(a number default 30, b number default 20, c num ber ) is begin dbms_output.put_line('a ='||a); dbms_output.put_line('b ='||b); dbms_output.put_line('c ='||c); dbms_output.put_line(a+b+c); end; begin --add1; --add1(30); add1(3,1,2); add1(c=>4); --add1(b=>2); add1(c=>4,b=>2); add1(c=>4,a=>30); --add1(b=>4,a=>30); --add1(a=>2); add1(10,c=>2,b=>50); add1(10,23,c=>2); add1(30,c=>60); end;

-----------------------------------------------------CREATE OR REPLACE PROCEDURE add_dept (pid in number,p_name IN departments.department_name%TYPE DEFAULT 'unknown', p_loc IN departments.location_id%TYPE DEFAULT 1700) IS BEGIN INSERT INTO departments(department_id, department_name, location_id) VALUES (pid, p_name, p_loc); END add_dept;

begin add_dept(1); add_dept(2,p_loc => 2400, p_name =>'EDUCATION'); add_dept(3,p_loc => 2400); add_dept(4,p_name =>'E&T'); end; ----------------------------------------------------create table log_table(user_id varchar2(20), log_date date); CREATE OR REPLACE PROCEDURE leave_emp2 (p_id IN SAMPLE.a%TYPE) IS PROCEDURE log_exec IS BEGIN INSERT INTO log_table (user_id, log_date) VALUES (USER, SYSDATE); END log_exec; BEGIN DELETE FROM SAMPLE WHERE a= p_id; log_exec; END leave_emp2; -------------------------------------------------------drop procedure procedureName; drop procedure leave_emp2; -------------------------------------------------------function create or replace function funcationNAme(paraNAme mode datatype, para2 mode data type.....) return dataType is ---(declaration ) ---

begin ----Exception ----end; -------------------------------------------------------CREATE OR REPLACE FUNCTION tax(p_value IN NUMBER) RETURN NUMBER IS BEGIN RETURN (p_value * 0.08); END tax;

SELECT employee_id, last_name, salary, tax(salary) FROM employees WHERE department_id = 100; select tax(1000) from dual declare a number; begin a:=tax(1000); dbms_output.put_line(a); end; begin dbms_output.put_line(tax(1000)); end;

VARIABLE p_val NUMBER EXECUTE :p_val := tax(1000); PRINT p_val EXEC :p_val := tax(1000); -----------------------------------------------------CREATE OR REPLACE FUNCTION dml_call_sql (p_sal NUMBER) RETURN NUMBER IS BEGIN INSERT INTO employees(employee_id, last_name, email, hire_date, job_id, salary) VALUES(1, 'employee 1', 'emp1@company.com', SYSDATE, 'SA_MAN', 1000); RETURN (p_sal + 100); END;

------------------------------------------------drop function function funcationName; drop function tax; --------------------------------------------------------------------------------------------------------------package --------------------------------------------------------------------------------------------------------------packages is a collection of producedure, functions & cursors, other data member ---cant pass parameters to pacakege --- package cannot be nested --- first time you invoke any package member the whole package is loaded into me mory and all other users share the same copy ---we can overload package functions & procedures ------------------------------------------------package create & stored seperately in two parts 1)specification 2)body 1)specification---declaration (public members) create or replace package packageNAme is /as ----end; 2)body create or replace package body packageNAme is /as ----end; ------------------------------------------------------create or replace package p1 is procedure Cal( a number, b number); end p1; -----------------------------------------------create or replace package body p1 is procedure sub1(a number, b number) is c number; begin c:=a-b; dbms_output.put_line('sub is :'||c); end sub1;

procedure add(a number, b number); procedure Cal(a number, b number) is begin add(a,b); sub1(a,b); end Cal; procedure add(a number, b number) is c number; begin c:=a+b; dbms_output.put_line('Addition is :'||c); end add; end p1;

begin p1.Cal(4,5); end; command prompt exec p1.Cal(4,5); exec p1.Cal(&a,&c); --->i/p from user ---------------------------------------------------function t( a number) return boolean; function t(a number) return varchar2; error for above two functions its not function overloading -------------------------------------------create or replace package test is procedure add(a number, b number); procedure add(a varchar, b varchar2); end; create or replace package body test is procedure add(a number, b number) is c number; begin c:=a+b; dbms_output.put_line('Addition is :'||c); end add; procedure add(a varchar, b varchar2) is c varchar2(50); begin c:=a||b;

dbms_output.put_line(c); end add; end; begin test.add('hhh','aaa'); test.add(6,6); end;

exec test.add(55,44); exec test.add('ddd','ggg'); drop package packageNAme; ---sepecification & body both is dropped

drop package test; drop package body packageNAme; --only body is dropped but specification exixts drop package body test; create or replace package pack12 is CURSOR emp_cursor IS SELECT * FROM employees; procedure p1; procedure p2; end; create or replace package body pack12 is procedure p1 is recemp emp_cursor%rowtype; BEGIN OPEN emp_cursor; LOOP FETCH emp_cursor INTO recemp; EXIT WHEN emp_cursor%rowcount>10; DBMS_OUTPUT.PUT_LINE ('EmpNAme'||recemp.last_name); END LOOP; DBMS_OUTPUT.PUT_LINE ('----------------'); END p1; procedure p2 is recemp emp_cursor%rowtype;

BEGIN LOOP FETCH emp_cursor INTO recemp; EXIT WHEN emp_cursor%notfound; DBMS_OUTPUT.PUT_LINE ('EmpNAme'||recemp.last_name); END LOOP; DBMS_OUTPUT.PUT_LINE ('----------------'); close emp_cursor; END p2; end; begin pack12.p1; end; --------------------------------------------------------------------------------------------------------------nexting of blocks <<outer>> declare a varchar2(30):='Hello'; b varchar2(30):='hi'; begin declare a varchar2(30):='world'; c varchar2(30); begin a:=b||a; DBMS_OUTPUT.PUT_LINE('inner a :'||a); outer.a:=outer.a||a; DBMS_OUTPUT.PUT_LINE('outer a: '||outer.a); c:=b||a; DBMS_OUTPUT.PUT_LINE('value of c :'|| c); end; DBMS_OUTPUT.PUT_LINE('value of a :'|| a); end; -----------------------------------------------------find out put <<outer>> declare b varchar2(30):='hi'; begin declare b varchar2(30):='world'; c varchar2(30):='hello'; begin c:=c||b; DBMS_OUTPUT.PUT_LINE('inner c :'||c); outer.b:=outer.b||c; DBMS_OUTPUT.PUT_LINE('outer b: '||outer.b); b:=c||outer.b; DBMS_OUTPUT.PUT_LINE('inner b :'|| b);

end; DBMS_OUTPUT.PUT_LINE('value of b :'|| b); end;

<<outer>> declare b varchar2(30):='hi'; c number:=10; begin declare b varchar2(30):='world'; c number:=20; begin outer.b:=outer.b||b; DBMS_OUTPUT.PUT_LINE('outer b: '||outer.b); b:=outer.b ||b; DBMS_OUTPUT.PUT_LINE('Inner b: '||b); c:=outer.c+c; DBMS_OUTPUT.PUT_LINE('inner c :'|| c); end; DBMS_OUTPUT.PUT_LINE('value of b :'|| b); DBMS_OUTPUT.PUT_LINE('value of c :'|| c); end; --------------------------------------------------------------------------------------------------------------triggers --------------------------------------------------------------------------------------------------------------two types of triggers --Statement level --row level (for each row) --- triggers can be created only two database objects table & view create or replace trigger triggerNAme timining[before /after] event[update or delete or insert] on [tableNAme /view] begin ---end; --Statement level create or replace trigger t1 after update on employees begin RAISE_APPLICATION_ERROR(-20001,'cannot update emplyees table'); end;

update employees set salary=salary+1000; update employees set salary=salary-1000; ORA-20001: cannot update emplyees table ORA-06512: at "HR.T1", line 2 ORA-04088: error during execution of trigger 'HR.T1' 1. update employees set salary=salary-1000;

---------------------------------------------------------Statement level

create or replace trigger t12 before update or insert or delete on employees begin if(updating ) then RAISE_APPLICATION_ERROR(-20001,'cannot update emplyees table'); elsif (inserting)then RAISE_APPLICATION_ERROR(-20001,'cannot insert emplyees table'); else RAISE_APPLICATION_ERROR(-20001,'cannot delete emplyees table'); end if; end; --------------------------------------------------------create or replace trigger t12 before update or insert or delete on employees begin if( to_char(sysdate,'DY'))='SUN' or( to_char(sysdate,'DY'))='SAT' then if(updating ) then RAISE_APPLICATION_ERROR(-20001,'cannot update emplyees table'); elsif (inserting)then RAISE_APPLICATION_ERROR(-20001,'cannot insert emplyees table'); else RAISE_APPLICATION_ERROR(-20001,'cannot delete emplyees table'); end if; end if; end; delete from employees; -20001,'cannot delete emplyees table'

--------------------------------------------------------------------------------------------------------------for each row trigger --------------------------------------------------------------------------------------------------------------old new insert null Ater i update B U A U delete B D null

update employees set salary=salary-1000; create or replace trigger tty1 before update on employees for each row begin if(:old.salary>:new.salary) then RAISE_APPLICATION_ERROR(-20001,'cannot decrement emplyees salary'); end if; end;

1)update employees set salary=salary+1000 where employee_id=100; row updated

2 update employees set salary=salary-1000 where employee_id=100; ORA-20001: cannot decrement emplyees salary ORA-06512: at "HR.TTY1", line 3 ORA-04088: error during execution of trigger 'HR.TTY1' update employees set salary=salary-1000 where employee_id=100; --for testcase 1 & 2 trigger is invoked -------------------------------------------------------drop trigger triggerNAme; drop trigger tty1 -------------------------------------------------------******************************************************** -------------------------------------------------------Example on Instead of Update on View --Instead of triggers can be used only with views. --Effective for joins which are based on equi join -- To have an cascading effect of update on both the tables if columns are --mat ching --Also to update uncommon columns through equi join views

--Step 1 Creating tables s and r; create table s (rollno number, name varchar2(20)); create table r (rollno number, marks number); --Step 2 Inserting records in s and r. insert into s values(1,'a'); insert into s values(2,'b'); insert into r values(1,90); insert into r values(2,87); --Step 3 Creating an Equijoin View on s and r Create or replace view SR as select s.rollno,s.name,r.marks from s,r where s.rollno =r.rollno; --Step 4 Now creating the Instead of Trigger for update on the view SR Create or replace trigger tig12 Instead Of UPDATE on SR For Each Row Begin / * Updating roll numbers from both the tables s and r */ Update s set rollno = :new.rollno where rollno = :old.rollno; Update r set rollno = :new.rollno where rollno = :old.rollno; /* Updating name column of s table through view.*/ Update s set name = :new.name where name = :old.name; /*Updating marks column of r table through view.*/ Update r set marks = :new.marks where marks = :old.marks; End; ------------------------------------------------------

before---i,u,d after---i,u,d foreach before -i,u,d after-i,u,d triggers can be written on ---database event, on user/schema dby dba DDL events (create, alter, drop) ------------------------------------------------------create trigger thr1 before create on hr.schema begin raise_application_error(-20001,'cannot create object'); end;

----------------------------------------------------create table logs(msg varchar2(20)); create trigger tlogin before logon on hr.schema begin insert into logs values('log in event'); end; / invalid timing before logon ------------------------------------------------create trigger tlogin after logon on hr.schema begin insert into logs values('log in event'); end; / -------------------------------------------------------create trigger tlogoff after logoff on hr.schema begin insert into logs values('logoff event'); end; invalid timing after logoff --------------------------------------------------------create trigger tlogoff before logoff on hr.schema begin insert into logs values('logoff event'); end; --------------------------------------------------------------------------------

-------------------------------trigger ----------------------------------------------------------------------------------------------------------------It is a stored PL/SQL program unit associated with a specific database table --Oracle executes (fires) the trigger automatically whenever a given SQL operati on affects the table --They are invoked implicitly --They are useful for customizing a database --They should be used only when necessary --Can prevent invalid transactions --Can enforce complex security authorizations --Can enforce referential integrity across nodes in a distributed database --Can enforce complex business rules --Can provide sophisticated auditing --Can gather statistics on table access --Can restrict DML operations to regular business hours --------------------------------------------------------------------------------------------------------------begin create table tt( a number); end;

PLSQL only DML ,select -----------------------------------------------Dynamic SQL CREATE OR REPLACE PROCEDURE DynSQL(str varchar2 ) IS cursor_name INTEGER; a number; BEGIN cursor_name := DBMS_SQL.OPEN_CURSOR; DBMS_SQL.PARSE(cursor_name, str, DBMS_SQL.NATIVE ); a := DBMS_SQL.EXECUTE(cursor_name); DBMS_SQL.CLOSE_CURSOR(cursor_name); end; begin DynSQL('create table Test15(a number)' ) ; end; begin DynSQL('insert into test15 values(2)' ) ; end; begin DynSQL('alter table test15 add b number' ) ; end; begin DynSQL('alter table test15 add b number' ) ;

end;

-------------------------------------------------CREATE OR REPLACE PROCEDURE DynSQL1(str varchar2 ) IS BEGIN EXECUTE IMMEDIATE str; end;

Você também pode gostar