Professional Documents
Culture Documents
DBT Notes
DBT Notes
check exceptions on 39
check page 57,out ex.
---------------------DATABASE TECHONOLOGIES---------------------
CONTENTS-----
1. SQL
2. SQL*PLUS - 19
3. PL/SQL -21
(input) (output)
1
ARUN P SINGH
ex. of table
rowis record.
column field.
DBMS RDBMS
1.1field 1. column Attriutes
1.2 Record 1.2 Row tupples,Entity,Opportunity
3
ARUN P SINGH
• IDS (Forms+Reports+Menus+Graphics), front end software.
• EXP Exports. used for taking backups of table data.
• IMP Import, used for restoring from backups
• Oraterm Oracle Terminal, used for setting the keyboard mapping at
application level, personalization
• SQL*Loader Used to load data from other software/rdbms into Oracle
• OEM Oracle Enterprise Manager. , used for data base administration
(DBA)
• Oracle Case CASE tools (Computer Aided Software Engineering),RAD
Rapid Applicaion Development Tool
• Oracle Manfacturing 11i ERP(Enterprisewide Resourse Planning),
redymade s/w for manufacturing industry.
• Oracle Financing 11i ERP s/w , redymade for financial application
• Oracle HRMS 11i ERP s/w , redymade for HRD
• Oracle CRM 11i for Customer Relation Management(CRM)
• Oracle Applications 11i (OF+OM+OHRMS+OCRM)11i
• Personal Oracle single user version, available in dos/win
• Oracle lite Oracle on mobile Phones(needs Symbian OS)
===========================SQL========================
=======================DATA TYPES=================
CHAR
NUMBER
-----ARE the two data type mention by ANSI----------------
extra in oracle-----
DATE
Long
varchar2
Raw
Long Raw
5
ARUN P SINGH
eg. remarks, commits, resume ets.
Raw (binary data upto 2000 bytes)
barcode,smallp pix,signatures,fingerprints.
Long Raw(upto 2GB of binary data)
e.g photographs,sound,music,videos.
===========================ORACLE 9I –SQL====================
1)
select ename,sal,sal*12 "Annual"
form emp;
// sal*12 is psuedo column only for display purpose no
operation can be performed.
2)
select ename "Employ name" from emp;
// " Employ name" ia alias are used with " " or without
to give the name to the column no operation can be
perfromed using these names.
3)
select distinct job emp;
6
ARUN P SINGH
// distinct(with all) or unique(only with oracle) can be
used to not print duplicate, and print in sorted form
sorting is done at server end.
4)
select distinct job,ename from emp;
// will print all the columns of both if there is no job
and ename pair same, it takes job and ename both in consideration
5)
to type all username,password,host string we use
username/password@host string
6)
select * from tab;
//all tables created,tab is system table there are 352
system tables in Oracle, these all together called oracle
data dicionary or meta data or database catolog
7)
describe emp;
// describes the structure of the table
***************editing commands********************
8) List
// also L can be used shows the last command fired L1,L2
Ln,can be used to see nth line
9)
l2
c/*/newname c-stands for change, a-append,i-insert
between can also be used at place of c.
10)
save filename
// generally afidet.buf is used to save the last command
which is a buffer file,to save to diffrent file this command
is used,by default address bin
11)
@ filename
// open file
@ E:\arun\C-DAC\sql plus query\filename
address can also be typed in
7
ARUN P SINGH
12)
save abcd replace
//will replace existint abcd
13)
define_editor=notepad
// wil make system editor for that session sql*plus
14)
ed
will open buffer file afidet.buf in notepad
ed abcd
will open abcd in notepad
15)
host dir /p
to run operating system command at SQL prompt /p is page
wise
16)
select * from orders
order by amt;
// the table will be printed in ascending order by amt,can be
used will any data type
select * from orders
order by amt desc;
//desc-print in descending order
17)
select onum,amt,odate,amt*5 "amount"
from orders
order by "amount";
//alias("amount") is allowed with order by
18)
select * from orders
order by 2;
// we can give the no of the column in order by
19)
select * from emp
where ename>'A' and ename<'B';
//will print name Adams ,but not Blake bcz here white padding
8
ARUN P SINGH
comparison is done in 'A' the rest bit is padded with phi and then
compared so ADAMS>A0000 ,here d>0 and Blake<B0000 , blake Is greater than B
this is additional feature added with varchar2 , where we can use blank padded comparison
semantics.
20)
Select * from emp
where ename not like 'A%';
// starting with A ,'%A'-ending with A, '%A%'-showing all
containig A , '_ _ A%'-showing only containing A at third
postion
select * from emp
where ename like '____';
//showing all ename with excatly 4 letters.
21
select * from emp
where ename not like 'A%';
//not starting with A
22)
select * from emp
where sal>=2000 and sal<=3000;
equl to (Or)
select * from emp
where sal between 2000 and 3000;
//between can be used with any data type.
23)
select * from emp
where sal not between 2000 and 3000;
24)
select * from emp
where deptno=10 or deptno=20 or deptno=30;
********equal to
select * from emp
where deptno=any(10,20,30);
********equal to
select * from emp
where deptno in(10,20,30);
// In>any>relational operator -showing processing speed
,"not in " can be used, !=any >=any <=any can be used
9
ARUN P SINGH
***********************UPDATE**********************
25)
update emp set sal=1000
where empno=1;
//used to update the table
*******************Delete******************************
27) delete emp; //delete all rows but structure remains.
delete emp where empno=10;
28) **********COMMIT****************
commit; is used to save the changes in the end of transaction this makes the
transaction permanent. As DML(Data Manipulation command ) (insert,update,delete) does not
produce direct changes in the server hard disk so we need to call commit
29) ****************rollback***********
rollback; undo the changes produced till last commited. Only for DML commands.
30) create table is a DDL command it is not only saved but also commit all the command
before it.
32) insert
savepoint abc;
delete
update
savepoint dce;
insert
rollback to pqr;
we can use savepoint as a bookmark upto which we can explicitly define to rollback but it is
done sequentially.
• there savepoint cannot be used with commit;
32) ***************************Locking************************
• as in oracle support multiuser are supported there can be possibility that they have
access to same table they can view both at the time.
• But in case one doing DML query(insert,update,delete) on the table
• there is no changes made in the database until commit is performed
10
ARUN P SINGH
• the other user will view the old table and if want to perform DML command then it will
set in indefinite wait.
• to overcome the problem of wait he has to lock the resource before using the row
select * from emp for update; //entire row is locked
select * from emp
where deptno=19 for update nowait;
select * from emp for update wait 60;// waits for 60 seconds.
Note:- to lock manually only for update clause can be used.
**********************************FUNCTIONS**********************************
34)
select upper(fname) from a;
37) select initcap(fname) from a; // changes the first letter of every word to upper case
38) select lpad(fname,19) from a; // left of the filed (19-length) will be padded
39 select lpad(fname,11,’*’) from a;
select lpad(fname,11,’**’) from a;
select rpad(fname,19) from a; // will make varchar2 to char
select rpad(fname,11,’*’) from a; //
40)
select rpad(lpad(fname,19,’*’),28,’*’) from a; //this will do padding on both side
41)
select ltrim(fname) from a; // will remove all the spaces from left
select rtrim(fname) from a; // will remove all the spaces from right will change char to
varchar2.
select ltrim(fname,’*@’) from a; // will remove all the *’s and @ from the left.
42
select substr(fname,3) from a; // will start the substring form 3rd position onwards from
start
11
ARUN P SINGH
select substr(fname,3,2) from a; //will start from 3 and take total 2
43)
select substr(fname,-3) from a; // will start from end 3rd postion
select substr(fname,-3,2) form a;
44)
select replace(fname,’un’,’xyz’) from a; // replace ‘un’ with ‘xyz’ at every occurance
45)
select replace(fname,’un’) from a; // will replace ‘un’ with null
46)
select translate(fname,’an’,’xy’) from a; // this does character by character ax,ny
wherever the occurrence is there.
select translate(fname,’an’,’x’) from a; //nnull
select translate(fname,’an’,’xyz’) from a; // z will be discarded
47)
select instr(fname,’un’) from a; // returns the starting postion of the first occurance.
select instr(fname,’un’,4) from a; // start checking the process from 4th position
select instr(fname,’un’,-4,4) from a; // start checking from end onwards the final postion
count is from the right only.
48
select length(fname) from a;
49)
select ascii(fname) from a; //gives ascii value of the first character
select ascii(substr(fname,2)) from a; // for 2nd character ascii value
50)
select ascii(‘z’) from dual; // to simply print ascii for z , dual is a single row,column
system table.
select chr(87) from dual; // chr prints the character equivalent for the numeric value
51)
select * from a where soundex(fname)=soundex(‘aron aron’);
12
ARUN P SINGH
58)
select sign(-15) from dual; -- returns for –ve -1 and for +ve +1 and 00
* can be used for finding greatest of two number and for other calculation.
59)
select ascii(‘z’) from dual; output122
60)
select chr(‘122) from dual; outputz
61)
select ‘welcome to c-dac’ from dual;
62)
select sqrt(81) from dual;
63)
select power(10,3) from dual; -- is 10^3=1000
64)
select mod(9,5) from dual;
select mod(8.22,2.2) from dual;
65)
select abs(-10) from dual; -- gives absolute value
66)
sin(x) sinh(x)
cos(x) cosn(x)
tan(x) tanh(x)
log(x) lon(n,m)log (m) base n
13
ARUN P SINGH
------------------------------ Date formats-------------------------------------
DD
MM
YY
YYYY
YYY
Y
75)
select to_char(sysdate,’Dd-MONTH-yy’) from dual;
select to_char(sysdate,’DD-Mon-YY’) from dual;
14
ARUN P SINGH
* any comparison done with null returns null
80)
select * from emp where comm==null; will not work
select * from where comm is null; -- is a special operator used only for null
select * from emp where comm is not null;
81)
select sal +comm from emp; -- will not work with null any thing added to null will give
null
select sal +nvl(comm ,0) from emp; -- nvl(comm,0) returns 0 when null is encountered
nvl(comm,’pune’) being list function takes any data type
82)
select greatest(sal,4000) from emp; --compare two of sal and 4000 the greatest is taken
select greatest(col1,col2,col3,…………col255,4000) 255 no of parameter can be taken
x:= greater(p1,p2,p3,p4)
83)
select least( sal,least) from emp; --opposite to greatest
84)
select decode(deptno,10,’Training’,20,’Exports’,’others’) from emp;
in deptno column for the value of 10Training ,20Exports and for other values others
will be shown.
• if others is not used null will shown in its place
• can be used with expressions
select decode(deptno,10,sal*.4,20,sal*.5,sal*.2) from emp;
ques.
if sal<3000 show low income
=3000 show average income
>3000 show Low income
select decode(sign(sal-3000),-1,’Low income’,1,’High Income’,0,’Average income’) from emp;
85)
select user from dual;
select user, uid from dual;
86)
select userenv(‘terminal’) from dual;
select userenv(‘sessionid’) from dual;
select userenv(‘language’) from dual;
RULES----------
1. the column in the select statement need to have in group by clause.
2. vice versa need not to be true.
92)
select deptno, sum(sal) from emp where job like ’C%’ group by deptno;
DEPENDING THE no. of queries in the GROUP BY clause it can be said multidimensional
query
* if we use any function in select then we have to use same in GROUP BY
93)
select deptno, sum(sal) from emp where job like ’C%’ group by deptno having
sum(sal)>1700;
HAVING is used perform operation on group function after group by clause.
select deptno, sum(sal) from emp where job like ’C%’ group by deptno having
sum(sal)>1000 and sum(sal)<1700;
16
ARUN P SINGH
select from -
where group by having order by ;
94)
• Nesting of group function is allowed only in ORACLE.
select max(sum(sal)) from emp group by deptno; -- nesting of group function can be used
without group by clause.
95)
MATRIX REPORT
select deptno,count(*),min(sal),max(sal),avg(sal),sum(sal) from emp group by deptno;
----------------------------------JOINS-----------------------------------------------
96)
select dname,ename from emp,dept where dept.deptno=emp.deptno;
17
ARUN P SINGH
select a.ename,b.ename from emp b, emp a where a.mgr=b.empno; --making
two copy of emp a,b;
102)
select dname,ename,dhead from emp,dept,depthead where
depthead.deptno=dept.deptno and dept.deptno=emp.deptno;
join for three tables.
103)
===============================TYPES OF RELATIONSHIP========================
1:1 (dept:depthead)
1:Many (dept:Emp)
Many:1 (Emp:Dept)
Many:Many (Emp:projects)
(Many:Many) can be written as (1:Many:1)
104)
select ename from emp whre sal=(select min(sal) from emp);
-- the inner query is child and outer is parent query, nesting can be done to 255 level
can be used in any way where we use a single value as parameter.(multi –row query we
use operators that fetch single value ex Any , IN)
105)
------------------------------MULTI – ROWS QUERY-----------------------------------------
select ename from emp where sal=any(select sal from emp where job like ’M%’);
106)
select ename from emp where sal=ALL(select sal from emp where job like ’M%’)
IN performs logical operation OR
any or
all And
these are used with multi – rows query
107)
---------------------------------------------CARTESIAN SUB QUERY -----------------------------------------
EXISTS OPERATOR------------ when we use a join anongwith distinct it makes processing very
slow to make it fast we can use EXISTS.
select ename from emp where exists(select emp.deptno from emp,dept where
dept.deptno=emp.deptno);
for every main query the subquery retruns ‘true’for every succesfull search and the
ename is printed and vice versa will return ‘false’
===========================SET OPERATIONS=========================
18
ARUN P SINGH
108)
select ename,deptno from emp
union
select dname,deptno from dept;
• duplicate are suppressed , the column name is taken from first query,order by is used
for single at the last for whole.
109)
select ename,deptno from emp
union all
select dname,deptno from dept;
• this does not suppress duplicates.
110)
select ename,deptno from emp
intersect
select dname,deptno from dept;
• the matching rows are printed,duplicates are suppresed
111)
select ename,deptno from emp
minus
select dname,deptno from dept;
112)
---------------------------------RECURSION----------------------------------------
select ename,deptno from emp where sal>1000
intersect
select ename,deptno from emp where sal<1700;
• using data from the same table.
=============FAKE COLUMNS=================
1. computed fields( annual=sal*12)
2. expression
3. function based columns
113)
select rownum , ename, sal from emp ;
• is a pseudo column used for numbering, can be used in where clause,is not reliable,
select rownum , ename, sal from emp where rownum<4; will work
select rownum , ename, sal from emp where rownum=4; will not work
select rownum , ename, sal from emp where rownum>4; will not work
114)
ROWID – ROW IDENTIFIER--------------------------
select rowid , ename, sal from emp ;
• it is a 18 character string which is encrypted address to the row it is more reliable than
rownum.
19
ARUN P SINGH
==========================ALTER TABLE (DLL COMMAND)=========================
pg 53
direct command
• c
-----------SQL--------------------------------- --------------------SQL*PLUS-------------------------
1. common for all dbms. 1. Oracle only.
2. 9+5 commmands 2. +54 additional commands
3. goes into buffer 3. does not store into buffer
115)
prompt text -- a single text can be printed.
• help online is available use HELP , HELP INDEX gives all the 54 commands help
116)
set feedback off
set feedback on will set the message displayed at the end of every execution.
117)
select * from emp where deptno =&x;
enter value for x:
• used for interactive input , its done before compilation.
118)
set verify off
20
ARUN P SINGH
set verify on -- will suppress the old and new message at the start.
119)
select * from emp where job=&designation;
enter value for designation: ‘CLERK ‘
select * from emp where job=’&designation’;
enter value for designation: CLERK -- no ‘ ‘ double courts allowed here bcz it is
already given with address specifier.
120) SQL*PLUS
continue---------------from P-30.
break on report
compute min max sum of sal on report
set time on
set timing on
set autocommmit on
any DML command will be saved immediately
show autocommit -- gives the status of commit
show all -- will all the status .
set head off -- column name and table will be gone
column sal heading ‘salary’ format $99999.99
column ename heading ‘employee’ format a40 --40 character width reserved for
column name
column sal off -- will set off showing alias
clear columns -- will clear the seting from the memory
ttitle center ‘cdac’ skip 2 -- top title will be cdac skip will skip 2 lines
ttitle center ‘cdac’ skip 3
21
ARUN P SINGH
oo40 stands for oracle objects for ole(object linking embedding)
• it is used for data processing server side data processing, it is 4GL language.
ex.
begin
-----------
---------
end;
/ after end int terminator ( the first character of last line
denotes end of program
begin
-----------
begin
-----------
---------
end;
---------
end;
/ -- block inside block it is block level language.
ex. two.sql
declare
x number(11);
begin
x:=34323;
insert into tempp values('cdac',x);
end;
/
three.sql
declare
x number(5);
declare
x number(11);
22
ARUN P SINGH
begin
x:=&sal_of_employee;
insert into tempp values(x,'oraddd');
end;
/
• here input from the screen works bcz of & which is executed at the client end before
compilation
declare
x char(9);
begin
x:=&name;
insert into tempp values(900,x);
end;
/
declare
x char(9);
begin
x:=’&name’;
insert into tempp values(900,x);
end;
/
in this is we enter a number 66666 it is also accepted bcz NUMber char implicit
conversion occurs.
declare
x constant number(11):=4567;
begin
declare
x char(10);
y number(5);
z number(7,3);
hra constant number(4,2):=0.23;
begin
x:='&name_employee';
y:=&salary;
z:=y*hra;
23
ARUN P SINGH
insert into tempp values(y,x);
insert into tempp values(z,'hra');
end;
/
declare
x char(10);
y number(5);
z number(7,3);
hra constant number(4,2):=0.23;
begin
x:='&name_employee';
y:=&salary;
z:=y*hra;
dbms_output.put_line('employe name is=Mr.'||x);
dbms_output.put_line('salary sal is.'||y);
dbms_output.put_line('hra is .'||x);
end;
/
• use of select to get value and assign into variable, select column name into variable
from table where condition;
declare
x number(9);
begin
select sal into x from emp where ename='KING';
insert into tempp values(x,'KING');
end;
/
declare
x emp.sal%type;
y emp.job%type;
24
ARUN P SINGH
begin
select sal,job into x,y from emp where ename='KING';
insert into tempp values(x,y);
end;
• to avoid mismatch we can use direct column datat type with its specification
table.column%type.
• table%type is possible
declare
x emp%rowtype;
begin
select * into x from emp where ename='KING';
insert into tempp values(x.sal,x.job);
end;
/
declare
type pqr is record
(
a emp.sal%type,
b emp.job%type
);
x pqr;
begin
select sal,job into -
x from emp where ename=’KING’;
insert into tempp values(x.a,x.b);
end;
/
declare
type abc is record
(
a emp.sal%type,
25
ARUN P SINGH
b emp.job%type
);
declare
x number(9);
y char(15);
begin
select sal,decode(sign(sal-5000),-1,’low income’,1,’high income’,
’average income’) into x,y from emp where ename=’KING’;
insert into tempp values(x,y);
end;
/
declare
x number(9);
y char(15);
begin
select sal,decode(sign(sal-5000),-1,’low income’,1,’high income’,
’average income’) into x,y from emp where ename=’KING’;
if x>4000 then -- use of if statment
insert into tempp values(x,y);
end if;
end;
/
declare
x number(9);
y char(15);
begin
select sal,decode(sign(sal-5000),-1,’low income’,1,’high income’,
26
ARUN P SINGH
’average income’) into x,y from emp where ename=’KING’;
if x>5000 then
insert into tempp values(x,y);
else
insert into tempp values(00,’low income’); -- use of ELSE statment
end if;
end;
/
declare
x number(9);
y char(15);
begin
select sal,decode(sign(sal-5000),-1,’low income’,1,’high income’,
’average income’) into x,y from emp where ename=’KING’;
if x>5000 then
insert into tempp values(x,y);
else
if x<5000 then
----------
else -- NESTED IF ELSE STATMENSTS-----------
----------
end if;
insert into tempp values(00,’low income’);
end if;
end;
/
else
insert into tempp values(0010,’low INCOME’); -- default case.
end if;
27
ARUN P SINGH
end;
/
-----------------------------------BOOLEAN IN PL/SQL--------------
• it has three values TRUE ,FALSE ,NULL it does not support 0,1;
x:=true
if x then -- condition satisfied
x:=false
if not x then -- condition satisfied.
========================PL/SQL LOOPS=========================
declare
x number(9):=1;
begin
while x<10 -- while loop statment
loop
insert into tempp values(x,’inside loop’);
x:=x+1; -- we cannot use x++ increment/decrement opera not allowed
end loop;
end;
/
declare
x number(9):=1;
begin
while x<10
loop
insert into tempp values(x,’inside loop’);
x:=x+1;
if x>5 then
exit; -- to break out of the loop use exit.
end if;
end loop;
end;
/
declare
x number(9):=1;
begin
28
ARUN P SINGH
loop
insert into tempp values(x,’inside loop’);
x:=x+1;
exit when x>5; -- used as do while loop
end loop;
end;
/
-------------------------------------------FOR LOOP-------------------------------------------
• Auto increment of variable always increment by 1,
• the for loop variable is a read only variable cannot be initialized into the loop, need not
to be declared.,nesting of for loop is possible.
declare
x number(9):=1;
begin
for x in 1..10 --at 1,10 we can use variables,functions,expressions
--all are possible
loop
insert into tempp values(x,’inside loop’); -- local for loop variable is used
end loop;
insert into tempp values(x,’outside loop’);--here x=1 this is global variable
end;
/
-----------------------------------------------GOTO STATEMENT--------------------------------------------
Declare
29
ARUN P SINGH
x number(4):=1;
Begin
<<abc>> --abc is a label
insert into tempp values(1,’Onem’);
x:=x+1;
if x<5 then
goto abc; -- control is send to abc
end if;
End;
/
use of goto
DON’T’S OF GOTO----------------------
• cannot enter the if then end if; construct, <<label>>
end if; , label not allowed before end
statements, ex. end if; , end;
soln. <<label>>
null;
end; can use null, an executable do nothing
• Cannot enter a sub block but can come out.
SUB BLOCKS-----------------------------------------------------------------------
-----------------------------------------------------CURSORS------------------------------------------------------------
==============================================================================
• is a variable
• similar to 2D array, based on select statement, used for storing multiple statement
30
ARUN P SINGH
• used for processing multiple rows.
• used for storing data temporarily.
• cursor is read only variable, data in cursor cannot be manipulated.
ex 1.
Declare
cursor c1 is select * from emp;
x emp%rowtype; -- to store cursor in x , have same datat type.
Begin
open c1; -- this brings the copy of table in server ram
for y in 1..5
loop
fetch c1 into x;
insert into tempp values(x.empno,x.ename);
end loop;
close c1; -- the memory will be freed
end;
/
• initially cursor pointer points to the first row fetch c1 into x;
• you have to fetch 1 row at a time into some intermediate variable,
• only Sequential fetch(forward fetch)
• as the cursor has fetched the record the record will be freed from ram row by row.
• INFORMIX AND DB2 allows the cursor to fetch back.
ex2.
Declare
cursor c1 is select * from emp order by sal; -- will now point to ordered emp
x emp%rowtype; -- to store cursor in x , have same datat type.
Begin
open c1; -- this brings the copy of table in server ram
for y in 1..5
loop
fetch c1 into x;
insert into tempp values(x.empno,x.ename);
end loop;
close c1; -- the memory will be freed
end;
/
Ex. 3
Declare
cursor c1 is select * from emp order by sal;
31
ARUN P SINGH
x emp%rowtype;
Begin
open c1;
for y in 1..3 -- this is selected fetch of top 3 row that is ranking report
loop
fetch c1 into x;
insert into tempp values(x.empno,x.ename);
end loop;
close c1; --
end;
/
Ex 4.
Declare
cursor c1 is select * from emp order by sal;
x emp%rowtype;
Begin
open c1;
for y in 1..20 /* in this if 14 is the table last row then the row after 14 loop
that are fetch are the same 14 th row because cursor pointer remains on the
last one. */
loop
fetch c1 into x;
insert into tempp values(x.empno,x.ename);
end loop;
close c1; --
end;
/
ex5.
Declare
cursor c1 is select * from emp;
x emp%rowtype;
Begin
open c1;
/* */
32
ARUN P SINGH
loop
fetch c1 into x;
if c1%notfound then --if the cursor is unsuccessful then returns TRUE
exit; -- allternatinve to this is (exit when c1%notfound;)
end if;
insert into tempp values(x.empno,x.ename);
end loop;
close c1; --
end;
/
1. declaration x c1%rowtype
2. open c1;
3. fetching is done , fetch c1 into x;
4. a suitable exit condition c1%notfound;
5. closing close c1;
ABOVE ALL FIVE STEPS CAN BE DONE IN FEW LINE FOR LOOP INTEGRATED WITH CURSORS.
ex.
declare
cursor c1 is select * from emp;
begin
for x in c1
loop
insert into tempp values(x.sal,x.ename); -- x is automatically declared of c1 type
end loop;
End;
/
• the select statement of the cursor can be any complex query returning values acc to our
necessity.
33
ARUN P SINGH
• cursor c1 is select * from emp where deptno=&deptnumber; -- we can use ‘&’ but it is
still static
--------------------------------------------PRAMETERIZED CURSOR-------------------------------------------------
Declare
cursor c1(dd number) is select * from emp where deptno=dd;
begin
for x in c1(10)
loop
insert into tempp values(x.deptno,x.ename);
end loop;
for x in c1(20)
loop
insert into tempp values(x.deptno,x.ename);
end loop;
end;
/
declare
cursor c1 (dd number,ss number) is select * from emp where deptno=dd and sal>ss;
begin
for x in c1(10,5000)
loop
insert into tempp values(x.deptno,x.ename);
end loop;
for x in c1(20,2000)
loop
insert into tempp values(x.deptno,x.ename);
end loop;
end;
/
----------------------------------------------------------DEFAULT PARAMETER-----------------------------
declare
cursor c1 (dd number,ss number default 3000) is select * from emp where deptno=dd
and sal>ss;
begin
34
ARUN P SINGH
for x in c1(10)
loop
insert into tempp values(x.deptno,x.ename);
end loop;
for x in c1(20)
loop
insert into tempp values(x.deptno,x.ename);
end loop;
end;
/
declare
cursor c1 (dd number,ss number default 3000) is select sal*2 ”HRA”,ename from emp
where deptno=dd and sal>ss;
begin
for x in c1(10)
loop
insert into tempp values(x.HRA,x.ename);
end loop;
for x in c1(20)
loop
insert into tempp values(x.HRA,x.ename);
end loop;
end;
/
ex.
declare
y number(4):=1;
cursor c1 is select sal+y hra,ename from emp;
begin
35
ARUN P SINGH
for x in c1 -- 1st loop
loop
insert into tempp values(x.HRA,x.ename);
y:=y+1; /* Y will not be affected because the copy of c1 is already loaded in
server ram for the value of y:=1*/
end loop;
because in computed field sal+y this column is already loaded in server ram the changes will
come in effect only when c1 is closed and re open.
declare
cursor c2 is select * from dept;
cursor c1 is select * from emp;
begin
for x in c2
loop
for y in c1
loop
if x.deptno=y.deptno then
insert into tempp values(y.deptno,y.ename);
end if;
end loop;
end loop;
end;
/
• this how natural join works in sql
---------------OR----------------
declare
cursor c2 is select * from dept;
cursor c1(dd number) is select * from emp where deptno=dd;
begin
for x in c2
loop
36
ARUN P SINGH
for y in c1(x.deptno)
loop
insert into tempp values(y.deptno,y.ename);
end loop;
end loop;
end;
/
• this how natural join works in sql
---------------OR----------------
declare
cursor c1 is select dept.deptno,ename from emp,dept where dept.deptno=emp.deptno;
begin
for x in c1
loop
insert into tempp values(x.deptno,x.ename);
end loop;
end;
/
• this how natural join works in sql
---------------OR----------------
declare
cursor c1 is select * from emp for update; -- for update locks the table .
begin
for x in c1
loop
if x.sal>7000 then
37
ARUN P SINGH
update emp set sal=sal+1 where current of c1; /* updation to the current
row is done not to the whole column */
end if;
insert into tempp values(x.deptno,x.ename);
end loop;
COMMIT; -- to release the lock otherwise the table will be kept lock.
end;
/
1. EXPLICIT CURSORS
2. IMPLICIT CURSORS
Declare
cursor c1 select * from emp for update;
Begin
open c1;
close c1;
end;
/
this concept is know as pessimistic locking.
Declare
x number(4);
38
ARUN P SINGH
begin
delete s where city=’Athens’;
if SQL%found then
x:=sql%rowcount;
insert into tempp values(x,’no of rows deleted’);
end if;
end;
/
Exceptions:-
1. pre-defined
2. user-defined
1. Pre-defined –
• Are already available with the system are part of the software.
• Automatically raised as and when specific errors expected and unexpected occurs
ex.
invalied_number,zero_devide,cursor_already_open,invalid _cursors,dup_val_on _index
etc
2. no_data_found
3. value_error -- value error when in number precision exceeds.for data
type mismatch
39
ARUN P SINGH
4. invalid_number -- is when inserting values to columns in table.
5. zero_divide
Note:- division by null is null, not a error by oracle compiller.
declare
----
begin
-----
end;
/
• We use
EXCeption when others then
X:=SQLCODE; -- code of the error
Y:=SQLERRM; --error message
declare
x number(3):=1000000;
begin
sdfsfs;
40
ARUN P SINGH
end;
/
declare
ssc…………..
• ITS ALWAYS BENIFICIAL TO HAVE A DUMMY MAIN BLOCK OUTSIDE, THAT EVERY ERROR
CAN BE HANDLED.
NOTE:- to check in which line the error occurred we can have flag associated with
every line and can print the flag when exception occurs.(flags simple assigning value to a
variable after every statement).
pg 50.
41
ARUN P SINGH
=====================USER –DEFINED EXCEPTIONS===============================
declare
x number(4);
• In case of sub-blocks if we define the exception in sub-block there is no way that MAIN-
block is going to handle it ,If you want it to happen then don’t declare in sub-block.
ex.
declare
x number(4);
abcd exception; --declaring the exception.
pragma exception_init(abcd,-01843); --using pragma exception to give name to an
--exception code no 01843
begin
select sal into x from emp where hiredate='10-mmm-94';
42
ARUN P SINGH
------------------------------------------PL/SQL ARRAYS-------------------------------------------------
declare
type t is table of number(4) index by binary_integer; --creation of array data type
y t;
i binary_integer; --subscript to be declared binary
begin
i:=1;
y(1):=100;
y(2):=200;
y(3):=300;
while i<4
loop
insert into tempp values(y(i),’array is on’);
i:=i+1;
end loop;
end;
/ --running
43
ARUN P SINGH
=========================PL/SQL PROCEDURE==============================
Declare
x number(4):=0;
procedure prod_one
is
begin
insert into tempp values(1,’procedure’);
end;
Begin
insert into tempp values(1,’procedure 2’);
prod_one;
insert into tempp values(1,’procedure3’);
End;
/
• this is local procedure
• procedure aht to be declared at the last in the declaration.
Declare
x number(4):=0;
procedure prod_one
is
y number(4):=10; -- you can have variable declaration before begin in procedure
type pqr is record
(
l number(4),
m char(9)
); -- can have records
44
ARUN P SINGH
begin
for x in 1..y -- variable to control looping
loop
insert into tempp values(1,’procedure’);
end loop;
end;
Begin
insert into tempp values(1,’procedure 2’);
prod_one;
insert into tempp values(1,’procedure3’);
End;
/
45
ARUN P SINGH
Declare
x number(4):=0;
procedure prod_one
is
y number(4):=1; -- you can have variable declaration before begin in procedure
begin
insert into tempp values(1,’procedure’);
if x<6 then
prod_one;
end if;
end;
Begin
insert into tempp values(1,’procedure 2’);
prod_one;
insert into tempp values(1,’procedure3’);
End;
/
Declare
x number(9);
name char(91);
procedure prod_one(x number)
is
begin
46
ARUN P SINGH
prod_two(‘ramanujam’);
prod_three(6000,’nagarugun’);
End;
/
----------------------------------PROCEDURE OVERLOADING----------------------------------------
Declare
x number(9);
name char(91);
procedure prod_one(x number)
is
begin
47
ARUN P SINGH
is
begin
end;
Declare
x number(4):=0;
function funct_one return number
is
begin
return 10;
end;
Begin
x:=funct_one;
insert into tempp values(x,’function3’);
End;
/
--run
Declare
48
ARUN P SINGH
x number(4):=0;
function funct_one(x number) return number -- function with parameter
is
begin
return x;
end;
Begin
x:=funct_one(999);
insert into tempp values(x,’function3’);
End;
/
Declare
x number(4):=0;
function funct_one(x number) return number -- function with parameter
is
begin
return x;
end;
Begin
x:= funct_one(999);
if funct_one(999)>1 then
insert into tempp values(x,’function3’);
end if;
end;
/
• is present in all RDBMS, this is to speed up the search option for faster access.
• to speed the select option with where clause.
• the indexes are automatically invoked when and where required.
• when we insert/update/delete the table the indexes are automatically updated.
• If there is large no of indexes the DML operation will become slower because every
index have to be updated.
• we cannot index ROW and LONG ROW
• duplicates are allowed, null values are not allowed in indexes.
• avoid using null values (use replacements)
• by default indexes in all RDBMS are in ascending order(except in progress)
49
ARUN P SINGH
• if we drop the table, the indexes are dropped automatically.
COMPOSITE INDEX----------------------------------
• is a index on set of columns, composite index can combine maximum of 16 columns.
• if select retrieve less than 25% data of table then make Indexes.
• Primary/unique column should always be made indexes
• common field in join oopration should be always indexes.
50
ARUN P SINGH
======================CONSTRAINTS PRIMARY KEY====================
51
ARUN P SINGH
alter table salespeople drop constraint sys_c002761;
-- to drop the constraint
emp table
EMPNO ENAME SAL DEPTNO MGR
------ ---------- ---------- ---------- ------------
DEPT
53
ARUN P SINGH
• FK constraint is specified on the child column.
• Parent column has to be PRIMARY KEY.(mandatory)
• FK allows duplicate,null unless there is no other constraints.
• in same table FK is also possible, self refrencing
• you can only update the parent, if child does not exists. You can only update child if
parent exists.
(you have to first assign child NULL then update PARENT then update childVALUE.)
• you can have multiple columns of same or different table refrencing to same or difrent
tables multiple columns.
-------------------------------------CONSTRAINT CHECK------------------------------------------------------
54
ARUN P SINGH
constraint cons_table check(status in(‘t’,’c’,’r’,’m’));
constraint cons_table check(sal between 5000 and 9000);
constraint cons_table check(ename=upper(ename));
ALTER TABLE ORDERS DROP CONSTRAINT PRIM_SNUM_ORDER;
Note:-------------------------------------SYSTEM TABLE----------------------------------
STORED OBJECTS
TABLES,COLUMNS,INDEXES,CONSTRAINTS
55
ARUN P SINGH
as
select * from emp where deptno=1 WITH CHECK OTION;
• GROUP BY CLAUSED USED only select operation is allowed, no DML operations,use alias
• use for automatic code generation, only numeric sequences are possible.
56
ARUN P SINGH
• even when exit it will not reset it will start from the last value.
• rollback and commit have no effect on sequence.
(because it keeps in account the multiuser environment where no. of user operating on the
same sequence)
• by default cache is 20 but in large transcations where lakhs of user are there fetching
sequence from hard disk in no of 20 and updating back to the hard disk will make the
transactions very slow to avoid we can increase the cache.
all the three users have there own emp table to access the table on network we need to resolve
the scope.
Ans. orad1.emp orad2.emp orad3.emp username.tablename
is the way how we can access the table.
57
ARUN P SINGH
(databases) SCOTT DAC WIMS
(user) ORAD1 ORAD2 ORAD3
(tables) EMP EMP EMP
In the above case is we want to have same code on the user login then we have to copy and
modify the code again(same code cannot run on both of the machine even if they are using the
same table and code)
to resolve this we use SYNONYMS
we can assign a common SYNONYM to all of them and use the same code everywhere.
PUBLIC SYNONYM-----------------------------------------------------
create public synonym semp for scott.emp; -- now every one need not to mention there own
synonym(require dba privilages to create public synonym)
• if the procedures require OUT or IN OUT parameter it can be called through PL/SQL only
59
ARUN P SINGH
========================PROCEDURAL ENCAPSUATION===================
1. developer track
60
ARUN P SINGH
a SQL
b. PL/SQL
OCA( ORACLE CERTIFIED ASSOCIATE)
c. forms
d. reports
OCP (ORACLE CERTIFIED PROFESSIONAL)
2. DBA TRACK
a SQL
b. ARCHITECTURE
OCA( ORACLE CERTIFIED ASSOCIATE)
c. backup and recovery
d. performance tunning
OCP (ORACLE CERTIFIED PROFESSIONAL)
• this is routine (set of commands) that executed AUTOMATICALLY when some event take
place.
• trigger are written on tables.
-------USES------------------------
61
ARUN P SINGH
• maintain summary logs of insertion/deletion/updation (audit trails)
• all the triggers are at server level you can perform DML operation using any front-end
s/w ,trigger always get executed when the event occurs.
• all PL/SQL statements allowed
• whether you ROLLBACK or COMMIT you data will be consistent.
• COMMIT and ROLLBACK are not allowed in triggers (to avoid from data inconsistency)
• if the triggers fails the the DML operations will automatically rollback, and when DML
operations fails trigger will rollback.
• we can handle exceptions in triggers.
62
ARUN P SINGH
before insert
on salespeople FOR EACH ROW
begin
insert into tempp values(:new.sal,:new.ename); -- we can use :new.columnname(is of
--the value from insert statement which is been fired)
end;
/
• with this we can make copies of every changes made to the table, called data
mirroring,automatic data duplication, concept of parallel server
• the temp table created is also called shadow table.
example – where we require name in uppercase and user gives it in lower case or mixed, then
using trigger before entering the data into the table we will change it into uppercase
• we can make changes in related table if there is change made in one table with the
help of triggers.
for ex.(if a deptno is deleted/inserted/updated from dept table we can make
related changes to employee in the emp table)
----------------CASCADING TRIGGERS---------------
ex.
create or replace trigger trigg_1
before DELETE
on salespeople FOR EACH ROW
begin
insert into tempp values(100,’employee deleted’);
end;
/
• this will trigger another trigger of before insert on tempp cascading will occur
64
ARUN P SINGH
create or replace trigger trigg_1
before UPDATE of sal,deptno -- we can explicitly mention column for which trigger fires
on EMP FOR EACH ROW
begin
if updating(‘DEPTNO’) then
update deptot set saltot=saltot - :old.sal where deptno=:old.deptno;
update deptot set saltot=saltot + :old.sal where deptno=:new.deptno;
else
• in case updation made, the new value is same as old one 11 then
use --when (old.snum<>new.snum or old.sname<>new.sname)
end;
/
• generalize trigger for DML operation.
66
ARUN P SINGH