Вы находитесь на странице: 1из 66

check p71(59) procedural encapsulation.

check exceptions on 39
check page 57,out ex.

---------------------DATABASE TECHONOLOGIES---------------------

CONTENTS-----
1. SQL
2. SQL*PLUS - 19
3. PL/SQL -21

COMPUTER IS French word computaire (to compute/calculate)


Oracle 9i i stands for computer compatibility.

raw facts  prcessing  meaningful data


data  computer  information

(input) (output)

DATABASE  is a collection of large amount of data.

DBMS  Data Base Management System . Acc. to ANSI Difnition redymade


software that allows you to insert/update/delet/prcess.
eg. MS EXCEL, dBase, Foxpro, Clipper

RDBMS  (Relational Data Base Management System)


OODBMS  (Object Oriented Data Base Management System)
ORDBMS  (Object Relational Data Base Management System)
Oracle 9i  it is RDBMS,OODBMS as well as ORDBMS.

Dept no. DName Location.


10 Training Bombay
20 Exports Delhi

1
ARUN P SINGH
ex. of table
rowis record.
column field.

Diffrence between DBMS AND RDBMS.

DBMS RDBMS
1.1field 1. column Attriutes
1.2 Record 1.2 Row tupples,Entity,Opportunity

1.3 file 1.3Tables, relation Entity class,Matrix,Applet


2 In a DBMS the relationship 2. programming is not required.
is maintained via programs.
3 Processing at the client end 3 Processing at the server end.
4 High N/w traffic 4 Low N/w traffic
5 Slow and expensive 5 Faster and Cheaper
6 file level locking 6 row level locking
7 Not suited for multiusers 7 suited for multi-users.
8 Distributed database is not 8 most rdbms support distributed.
supported a.
9 Client server architecture 9 most of them support.
not supported. b.
10 In DBMS there is no security 10 provides multilevel of security.
c. logging level security.
d. Command level security.
e. Object level security.(limited the
access )

various RDBMS available

• iformix(fastest in terms of processing speed0


2
ARUN P SINGH
• Oracle (most popular)
• Sybase
• My SQL Server
• ingress
• progress, unify  character based only on Dos
• DB2 Mainframe specific
• CICS Mainframe specific
• TELONMainframe specific
• IDMSMainframe specific
• Ms Access  Pc Based
• Vactom SQL  Pc Based
• My SQL

Oracle 9i---------------(available on 113 Operating System)


• product of Oracle Corporation (1977)
• 2nd largest s/w company in the world(overall)
• No. one Database software.
• approx 63% of world RDBMS market (client server env)
• approx 86% of internet RDBMS market

Software development tools from oracle--------


-----------------------------------------------------------------------------------------------------
S/w development tools from oracle Corporation.
• SQL Structrued Query Language/standard query language pronounced
sequel use operations, insert,update,delete,grant,revoke,select, is common
for all database, conoforms to the ISO standards,now controlled by ANSI,
Source code 90% c/c++ 10%-assembly
• SQL*Plus extensions to SQL , additional 54 commands to remove
limitations of SQL,client software used to connect to database , reporting
tool(character based)(text reports only), setting oracle env.
• PL/SQL  Procedural Language SQL , Programming language from
Oracle, 4Generation Langauge(oops is supported),used for processing
• Oracles forms 6i  for Creating data entry screans.
• Oracle reports 6i gui based report writer.
• Oracle graphics 6i Pie-charts,bar graphs,etc
• Oracle Menus 6i  creating menu

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========================

there are 4- sub divison of sql.

DDL  Data Definition Langauge (create,drop,alter)


DML  Data Manipulation Language (insert,update,delete)
DCCL  Data Control Language (grant,revoke)
DQL  Data Query Language (select)

5th component of SQL ( not an ansi standard extra in oracle)


DTL/TCL  Data transaction Language/Transaction control
language(rollback,commit,savepoint)
DDL(truncate) ,DML(merge).

---------------------rules for table creation------------------------


• max 30 characters,
• a-z,A-Z,0-9,_
4
ARUN P SINGH
• sql is not case sensitive.
• hast to begin with an alphabet
• $, #,_ allowed //not allowed in other RDBMS.
• some reserved words not allowed
------------------------------------------column name-------------------------
• same rule apply as table

=======================DATA TYPES=================

CHAR
NUMBER
-----ARE the two data type mention by ANSI----------------
extra in oracle-----
DATE
Long
varchar2
Raw
Long Raw

Char  allows any character (max 2000 character)


1char -1byte
Date  (1/1/4712 BC to 31/12/9999 AD)
• total 78 formats for date
we can perform arithematic operation bcz initially every date is assign a
integer no. associated with
5th oct 1582 AD to 14th oct AD does not exists because Julian—Georgian 10
days are lost.
15th oct 1582 -5th oct 1582 = 1 days

01-currentmonth-least required data 00:00:00 –by default midnight

varchar2  (allows any character max 4000 character)


• varchar has variable length, ov7 onwards varchar was introduced
Long ( allows upto 2GB of varchar2 data)

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====================

• no upper limit on number of row per table


• max 1000 columns per table
• only 1 long column per table.
• keep the long column, form separate table.

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

26) update emp set sal=1000,city=’Pune’


where empno=10;

*******************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.

31). exit;  it automatically commits the command.

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**********************************

********SQL CHARACTER FUNCTIONS*******


||concatenation

33) select fname || lname from a;


select fname || ‘ ‘ ||lname from a; //space will be concatenated
concat(str1,str2)
select concat( fname,lname) from a;
select concat(concat( fname,’ ‘),lname) from a; // we can use function within fuction
• function within function can be achieved to 255 levels in Oracle.

34)
select upper(fname) from a;

35) select lower(fname) from a;


36) select * from a where upper(fname)=’ARUN’; // this a case insensitive query.

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’);

**************************SQL NUMBER FUNCTIONS*****************************


52)
select round(num) from b;
53)
select round(num,1 ) from b; //to one decimal place
select round(num,-2) from b; // to two place left to decimal place ex. 1345.3451300
54)
select trun(num) from b; // simply removes the decimas.
55)
select trunc(num,2) from b;
56)
select ceil(num) from b; -- increment if any value to the right of decimal is there.
57)
select floor(num) from b; --works for negative numbers,

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

***************SQL DATE FUNCTIONS******************************************

67) select sysdate from dual; -- gives the server date.


select sysdate-1 from dual; --arithmetic operation can be performed on DATE
select sysdate-hiredate from emp; -- will give the value in no days and after decimal is
for hours and minutes. output 234.34
68)
select months_between(sysdate,hiredate) from emp; -- will give no. of the months
69)
select add_months(hiredate,2) from emp; -- will add 2 months to the hiredate
70)
select add_months(hiredate,-2) from emp;
71)
select next_day(sysdate,’monday’) from dual; -- will give the date of next Saturday.
72)
select next_day(sysdate-7,’monday’) from dual;
73)
select last_day(hiredate) from emp; -- will give the last day of that month.
74)
select to_char(sysdate,’dd/mm/yy’) from dual; -- prints the in given format

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;

Mon mon MON Month month MONTH


76)
select to_char(sysdate,’DAY’) from dual;
select to_char(sysdate,’DAY,dd/mon/yyyy’) from dual; TUESDAY 09/sep/2009
select to_char(sysdate,’YEAR’) from dual; --- TWO THOUSAND NINE
select to_char(to_date(2000,’yyyy’),’year’) from dual; --output – two thousands
select to_char(sysdate,’ddth’) from dual; --- 11th
DDTH -- all possible combination with lower clase upper case.
select to_char(sysdate,’DDsp’) from dual;
select to_char(sysdate,’d’) from dual; ---- D for day of the week
DD day of themonth
ddd day of the year
w weak of the month
ww weak of the year
77)
select to_char(sysdate,’dd/mm/yy hh:mi:ss’) from dual;
other format
HH:MI:SS
HH24:MI:SS 24 hour format
HH:MI:SS AM  will be used for 12 hour format.
select to_char(sysdate-5.5/24,’hh:mi:ss am’) “London Time” from dual; -- 5.5/24 is to convert
to day
78)
alter session set nls_date_format =’dd/mm/yyy’ ;
• to change the date format for the session(nls—national language support)
79)
glogin.sql global login c:\oracle\ora 90\sqlplus\admin>
this is the file loaded during login we can add our query there .

---------------------------------------------SQL LIST FUNCTIONS--------------------------------------------------

* Are independent of data type

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;

---------------------------------------------SQL ENVIRONMENT FUNCTIONS-------------------------------------

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;

------------------------------------------SINGLE ROW GROUP FUNCTIONS--------------------------------------


87)
select sum(sal) from emp; -- return one value for the whole column.
min(sal) max(sal)
15
ARUN P SINGH
avg(sal)
select count(sal) from emp; -- will give the no count for who has no null values null
values will not be counted.
select count(*) from emp; -- will count the exactly the real no of rows even null is
present.
88)
select count(*) from emp where sal>7000; // it will discard the null. – where clause can
be used with single row function.
89)
select count(*), min(sal),max(sal),sum(sal),avg(sal) from emp; -- SUMMARY REPORT
90)
select * from emp where sal>avg(sal); --ERROR cannot have the group function in
where clause.
select * from emp where sal>(select avg(sal) from emp);

--------------------------------------------------SQL GROUP BY CLAUSE----------------------------------


91)
select deptno,sum(sal) from emp group by deptno; --this gives sum of the groups of
deptno.
WORKS IN 4-STEP
1.Rows are retrived from server hd to server RAM
2. sorting is done department wise
3. grouping is done department wise
4. summation/calculation.
5. having
6. order by

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;

OVERALL HIERARCHY OF CLAUSES

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;

empis driven table , dept is driving table


step wise processing pass through driven column and select the corresponding
mantching data
driving table should be preferably with lesser no of rows.
97)
select dname,ename from emp,dept where dept.deptno=emp.deptno and dname=’trn’;
98)
select dname,ename from emp,dept where dept.deptno=emp.deptno(+);--RIGHT
OUTER JOIN.
 outer join it will print the row with null even in the first table has no value for the
search
select dname,ename from dept,emp where dept.deptno(+)=emp.deptno; --LEFT OUTER
JOIN
-----------OUTER JOIN-----------
1 HALV OUTER JOIN
1.1 RIGHT
1.2 LEFT
2 FULL OUTER JOIN.
99)
select dname,ename from dept,emp where dept.deptno=emp.deptno(+)
union
select dname,ename from dept,emp where dept.deptno(+)=emp.deptno;
OR
select dname,ename from emp full outer join dept on(dept.deptno=emp.deptno);
100)
-------------------------CARTESIAN JOIN-------------------------------
select dname,ename from emp,dept;
emp-3 rows,dept-5 rows then Cartesian join will have 15 rows all possible combination
101)
---------------------SELF JOIN--------------------------

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)

========================SUB QUERIES (NESTED QUERIES)==========================

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* PLUS==================================

• it has 54 extra commands.


• reporting tool
• interface with database, client software, for running SQL and SQL*PLUS commands
• using for setting oracle environment
• earlier know as UFI ( user friendly interface) , OV4 onwards it was known as SQL*PLUS

-----------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

-------------ENDING A SQL COMMAND-------


sql> select * from emp;
2.sql> select * from emp
sql> /
3.sql> select * from emp
-- enter twice it stores in buffer.
sql>/

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

break on report on deptno on job


compute sum of sal on deptno

a separate compute for every of them

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

date 18-09-09------------------------------dbt-32 to dbt-35…


=============================PL*SQL==============================

• to load sample tables we use demobld7.sql


c:\oracle\ora90\oo4o\demobld7.sql

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.

•Screen input and output is not allowed………….


•you cannot have select statement in pl/sql
•insert,update,delete,rollback,commit,savepoint,select—as a subquery or for inserting
data
• DDL, command are not allowed ,DCL command are not allowed here,SQL/plus command
not allowed here, to get create a output table put the data in it
No .exe file is generated, each time it runs it compile and execute,

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

insert into tempp values(x,'press');


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;

23
ARUN P SINGH
insert into tempp values(y,x);
insert into tempp values(z,'hra');
end;
/

• to print output on the screen we use package dbms_output.put_line.


set serveroutput on
//dbms_output.put_line(text);

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;
/

• declaring another structure is possible


y emp%rowtype
y:=x --possible

• we can create our own data type.


• record is a structure.

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
);

type pqr is record


(
l number(4),
m abc
);
m number(9);
x pqr;
begin
select sal,job into x.m from emp where ename=’KING’;
insert into tempp values(x.m.a,x.m.b);
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’;
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;
/

• similar to SWITCH CONSTRUCT ELSIF CONSTRUCT.


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); --case 1
elsif x<5000 then
insert into tempp values(x,y); --case 2

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;
/

for x in 1..&y --is allowed


for x in &x...&y --is allowed one extra dot -x and y cannot be used even
cannot be printed in the loop and need not be declared.
for x in &x ..&y --is allowed, space after &x
for x in 1.4..9.6 --is allowed, the number will be round off automatically

-----------------------------------------------GOTO STATEMENT--------------------------------------------

• used to transfer the control

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

• if you have large number of goto statement spashetic code


• use goto to come out of large nesting, from if then end if; construct, from nested blocks.

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-----------------------------------------------------------------------

• Main blocks cannot access sub block variable , reverse is possible

-----------------------------------------------------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;
/

SOLUTION TO ABOVE PROBLEM --------------------CURSOR ATTRIBUTES-------------------------------

• cursor%notfound -- returns TRUE when the cursor reach to last row.


• cursor %found --returns TRUE when then cursor is not reach the last row.
• cursor %rowcount --return the count of how many row are fetch from cursor.
• cursor %isopen -- returns TRUE is the cursor is open

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;
/

-----------------------DECLARING VARIABLE WITH SAME DATAT TYPE AS CURSOR-------------


s
• variable cursor%rowtype
• cursor c1 is select ename,sal from temp;
• x c1%rowtype
• x has the same structure as the cursor c1.

---------------------------------------IN CURSOR THE FIVE BASIC STEPS----------------------------------

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;
/

• allow MULTIPLE PARAMETERS…………..

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;
/

---------COMPUTED FIELDS,ARITHEMETIC OPERATIONS,(PSUEDO COLUMNS)-------------------------

• USE alias for calculation purpose


• can alias in “arun” or simply arun ( giving in “ “ it becomes case sensitive)

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;

for x in c1 -- 2nd loop


loop
insert into tempp values(x.HRA,x.ename); /*here the value of y will come in
picture a c1 is closed in first loop and then reallocated mem in second */
end loop;
end;
/

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----------------

INIT.ORA STARTUP FILE FOR ORACLE(ON SERVER)


• it is a parameter file
• we can make changes there
ex. OPEN_CURSORS =250
DB_BLOCK_SIZE=16M
SGA_SIZE=512
changes made need the system to restart.

--------------------------------------LOCKING IN PL/SQL (FOR UPDATE)------------------------------------------

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;
/

--------------------------------------CURSORS ARE OF TWO TYPES---------------------------------------------

1. EXPLICIT CURSORS
2. IMPLICIT CURSORS

1. EXPLICIT CURSORS  Are progrmers created, it has to be declared explicitly


• used to storing/processing/handling multiple rows.
• Locking rows Manually

Declare
cursor c1 select * from emp for update;
Begin
open c1;
close c1;
end;
/
this concept is know as pessimistic locking.

2. IMPLICIT CURSORS  Oracle created (system cursors), lakhs of them are


available
• one o them is available, used to check the status of the last ‘DML statement
• we can get a count to how many rows were affected by last DML statement.
• used to maintain the lock of DML operators.
• name of implicit cursors is SQL.

SQL%rowcount gives the no. of rows were affected by the last


DML command.
SQL%found  returns TRUE if change made to DML statement.
ex.

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 (ERROR HANDLING)-----------------------

Exceptions:-

• are used to handle runtime errors.

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

there are 18 named the rest 35000 + are unnamed.

FEW TYPES OF EXCEPTION OF ERRORS.-------------------------------

1. select sal inot x from emp where ename=’KING’


exception when too_many_rows then

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.

WHEN HANDLING TWO MANY EXCEPTIIONS.-------------------------------

declare
----
begin
-----

exception when too_many_rows then


----
when no_data_found
----
when zero_divide then
---

end;
/

TWO GET THE ERROR MESSAGE AND ERROR CODE.----------------------------------------------------

• We use
EXCeption when others then
X:=SQLCODE; -- code of the error
Y:=SQLERRM; --error message

----------------EXCEPTIONS IN SUB-BLOCKS -----------------------------------------


p-49

• we can have exceptions in sub-block


• when the exception is handled in the sub-block the process of the main block goes
normally if nothing happened.
• when not handled in sub-block the main block handles it.

declare
x number(3):=1000000;
begin
sdfsfs;

40
ARUN P SINGH
end;
/

• error in DECLARE CANNOT be handled.

TO HANDLE ERROR IN MAIN BLOCK AND EVEN IN EXCEPTION BLOCK.


use main block

declare
ssc…………..

begin -- MIAN block


axyz………….;
declare
x number(3):=1000000; -- the declare error will be handled in parent block
begin
sdfsfs;
exception when others then
sdfd………………..;-- even error in exception block will be handled in main block
end;
exception when others then
sdfd………………..;
end;

• 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);

abcd exception; -- declare the exception


begin
select sal into x from emp where ename=’KING’;
if x<2000 then
raise abcd; -- you have to raise the exception where ever you need
else
insert into tempp values(x,’KING’);
end if;

exception when abcd then -- give the exception block.


insert into tempp values(1,'helllo');
end;
/ --running

• 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.

----------------GIVING NAME TO UNAMMED EXCEPTIONS -----------------------------------

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';

exception when abcd then -- whenever error 08143 occurs it is executed.


insert into tempp values(1,'helllo');
end;
/

42
ARUN P SINGH
------------------------------------------PL/SQL ARRAYS-------------------------------------------------

• to store multiple elements of the sme datatype


• multidimensional arrays are allowd.
• can create array for scalar datatypes and composite datatypes.
• arrya size is dynamic
• subscript hast to be declared BINARY_INTEGER.
• base 2< base 10 implicit conversion
• range of binary integer is from -2billion to +2billion

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==============================

• routine set of commands that have to be called explicitly.


• can call a procedure in another procedure declaration, you have to declared called
procedure before calling procedure. not after it.
• but still if you want to have a call to procedure after it then have a forward declaration.
• can have recursion under condition ( mentioning condition inside the procedure
controlling the self iteration.
• we can use parameterized procedures.
• procedure overloading is also possible.(same as in other progaraming language)
• we can also have default values.

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.

--------------------------------CAN HAVE LOCAL VARIABLES---------------

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;
/

-----------------------------can have no of procedures-------------------------------


Declare
x number(4):=0;
procedure prod_one
is
begin
insert into tempp values(1,’procedure’);
end;
procedure prod_two
is
begin
insert into tempp values(1,’procedure’);
end;
procedure prod_three
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;
/

------------------------------------RECURSION UNDER CONDITION----------------------------

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;
/

-----------------------------Parameter passing is allowed-------------------------------

Declare
x number(9);
name char(91);
procedure prod_one(x number)
is
begin

insert into tempp values(x,’procedure’);


end;
procedure prod_two(name char)
is
begin
insert into tempp values(12,name);
end;
procedure prod_three(x number,name in char)
is
begin
insert into tempp values(x,name);
end;
Begin
prod_one(200);

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

insert into tempp values(x,’procedure’);


end;
procedure prod_one(name char)
is
begin
insert into tempp values(12,name);
end;
procedure prod_one(x number,name in char)
is
begin
insert into tempp values(x,name);
end;
Begin
prod_one(200);
prod_one(‘ramanujam’);
prod_one(6000,’nagarugun’);
End;
/

• there are three types of parameter in procedure (IN, OUT, IN OUT)


• BY default IN

========IN (BY DEFAULT)----------------


• read only cannot write data to it.
procedure abc( y in number)

47
ARUN P SINGH
is
begin
end;

======== OUT ----------------


• write only cannot read data to it.(means cannot use on the left side of operator)
procedure abc( y out number)
is
begin
end;

======== IN OUT ----------------


• CAN read and write data to it.
procedure abc( y in out number)
is
begin
end;

============================== SQL FUNCTIONS ==============================

• routines that return value (here it is mandatory)


• same as procedure(the rest feature)
• PARMAETER MAY BE in , out, in out

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;
/

============================== INDEXES ==================================

• 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.

CONDITION WHEN indexes SHOULD BE CREATED------------------------------------------------

• 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.

---------------------COMMAND TO CREATE INDEXES------------------------------------

create index indexname on table(columnname);

create index emp_index on emp(empno); // creating index


create index dep_ena_index on emp(deptno,ename); // creating composite index
create index i_emp_empno on emp(empno desc); // creating descensding index

create index i_emp_deptno_empno on emp(deptno desc,empno ); // creating index


descensding for deptno and ascending for empno(which is by default)

TO KNOW THE LIST OF INDEXES---------------------------------------------------------

select * from user_indexes;


select * from user_indexes where table_name=’EMP’;
select * from user_ind_columns where table_name=’EMP’;
drop index index_deptno_emp ;

create unique index_i_empno on emp(empno);


arter creating column index unique will not allow to insert duplicate value in the table
with the column name made unique.

sql> create unique index_i_empno on emp(empno);


• you will not be allowed to insert any duplicate value in the table.

50
ARUN P SINGH
======================CONSTRAINTS PRIMARY KEY====================

• columns or set of columsn that uniquely identifies a row


• duplicate values not allowed (has to be unique)
• null values not allowed
• recommended that every table should have a primary key
• long and long row are not allowed
• it creates index automatically when we define any column a primary key
• COMPOSITE PRIMARY KEY->two or more column serve the purpose of the primary
key(you can group 16 columns)
• only one PK is allowed per table.
• the other table that can serve as primary key are candidate key.
• All constraints are at server level.
(you can perform any DML operation using any front-end the constraint will always be valid.)
non-subversion rule codd’s rule.

using primary key constraints.

create table salespeople


(
SNUM number(4) constraint prim_salespeople primary key, -- optional can give name or not.
SNAME varchar2(10),
CITY varchar2(10),
COMM number(3,2)
);

select * from user_constraints where table_name='SALESPEOPLE';


select CONSTRAINT_NAME,CONSTRAINT_TYPE from user_constraints where
table_name='SALESPEOPLE';
• we can use to know the status of constraints on a table.

select * from user_cons_columns;


select * from user_cons_columns where table_name='SALESPEOPLE';
• it will give detail for every columns for which constraint is been puton.
--always give table name other row in upper case bcz oracle use upper case to store it in its
system table.

51
ARUN P SINGH
alter table salespeople drop constraint sys_c002761;
-- to drop the constraint

alter table salespeople add


constraint prim_snum_salespeople
primary key(snum);
after table creation.
--------------------------------------COMPOSITE PRIMARY KEY-------------------------------------------------

create table salespeople


(
SNUM number(4),
SNAME varchar2(10),
CITY varchar2(10),
COMM number(3,2),
constraint prim_salespeople primary key(SNAME,CITY)
);

CONSTRAINTS ARE OF TWO TYPES :-


1. COLUMN LEVEL CONSTRAINTS(SINGLE COLUMN)
2. TABLE LEVEL CONSTRAINT (MULTIPLE COLUMNS THAT IS COMPOSITE CONSTRAINT)

alter table salespeople add


constraint prim_snum_salespeople
primary key(snum,sname);
after table creation.

----------------------------NOT NULL CONSTRAINT --------------------------------------


• null values are not allowed created
• duplicates are allowed,always column level constraint.

create table salespeople


(
SNUM number(4),
SNAME varchar2(10) constraint not_salespeople not null,
CITY varchar2(10) constraint not_city_salespeople not null,
COMM number(3,2)
);

--------------------------------------UNIQUE CONSTRAINTS ------------------------------------

• will not allow duplicate values


52
ARUN P SINGH
• null values are allowed,a unique index is automatically ,can combine upto 16 columns
• can have any no of unique constraints per table.
• index are generated automatically.

create table salespeople


(
SNUM number(4),
SNAME varchar2(10) constraint uniq_salespeople unique,
CITY varchar2(10) constraint uniq_city1_salespeople unique,
COMM number(3,2),
constraint uniq_city_salespeople unique(city,comm)
);

alter table salespeople add


constraint prim_snum_salespeople
unique(snum,sname,city);
after table creation.

------------------------------------------- FOREIGN KEY -----------------------------------------------------

emp table
EMPNO ENAME SAL DEPTNO MGR
------ ---------- ---------- ---------- ------------

DEPT

DEPTNO DNAME LOC


----------- -------------- -------------

FOREIGN KEY(FK) DEPENDENCIES.

in above DEPTNO(EMP) ------>>DEPTNO(DEPT)


CHILD PARENT
IN the same table MGR(EMP) ------>>EMPNO(EMP) (self refrencing)
CHILD PARENT

• is column or a set of column that refrences a column or a set of columns of different or


same table.

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

create table emp (


EMPNO char(4) constraint pk_primary_key_emp primary key,
ENAME varchar2(9),
SAL number(9,2),
DEPTNO number(2) constraint fk_emp_deptno references dept(deptno),
MGR char(4) constraint mgr_emp references emp(empno)
);

alter table orders add


constraint prim_snum_orders
foreign key(snum) references salespeople(snum);
after table creation

• deleting the PARENT record provided no matching child record is there.


(to avoid above we have to delete first all matching record in child,then the parent record)
• inserting into child record provided (is allowed) the same is present in PARENT. alter
table orders add
constraint prim_snum_orders
foreign key(snum) references salespeople(snum) ON DELETE CASCADE;
 using on delete cascade will automatically delete matching record from child table.

• 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------------------------------------------------------

• used for validation ex. sal can’t be –ve


• can be used at the creation of table or after the creation of table using alter table.

alter table orders add


constraint prim_snum_order
check(amt>1);

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----------------------------------

oracle 9i---------has 352 system table


oracle 10g---------has 534 system table
oracle 11g---------has around 2000 system table

it is system data ,(metadata)


whatever we create are columns of system table(master table).

=========================== VIEWS ================================

STORED OBJECTS
TABLES,COLUMNS,INDEXES,CONSTRAINTS

• is a stored object ( are present in every rdbms)


• view is a handle to a table/view, its hard disk pointer locator
• used for indirect access to the table.
• (for security purpose) to restrict the access of users.
• view name and table name cannot be same.

create view view1


as
select empno,ename from emp;
• view can say view is a stored query, in system table corresponding query is stored with
the view.
• view speedup the application, system tables are views
• DML operations on view is possible
• to restrict row and column access

create view view1


as
select * from emp where deptno=1;
limited access.

but -- insert into view1 values(6,’f’,9000,2) ; --is possible, to restrict it use


WITH CHECK OPTION
create view view1

55
ARUN P SINGH
as
select * from emp where deptno=1 WITH CHECK OTION;

-------------FROCE VIEW(WITH COMPILATION ERRORS)------------------

create FORCE view view1


as
select * from emp where deptno=1;
with compilation errors.
describe view;

create view view1


as
select * from emp order by sal;
• ORDER BY CLAUSE USED then only select operation is allowed, no DML operations.

create view view1


as
select ename,sal*.12 HRA from emp order by sal; --alias required for
computed or arithmetic operation.
• only select operation is allowed, no DML operations.

• GROUP BY CLAUSED USED only select operation is allowed, no DML operations,use alias

• JOINS ARE ALLOWED only select operation is allowed, no DML operations,use

sql> alter view v1 compile -- recomple on regular basis.

========================== SEQUENCES ===================================

• use for automatic code generation, only numeric sequences are possible.

create sequence sequencename;


create sequence sequence_one;
insert into tempp values(sequence_one.nextval,’arunnnn’); -- will give 1 by default for first time
insert into tempp values(sequence_one.nextval,’arunnnn’); -- will give 2
insert into tempp values(sequence_one.nextval,’arunnnn’); -- will give 3

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)

create sequence seq_two minvalue 4; --the sequence will start from 4


create sequence seq_three minvalue 4 maxvalue 1000 -- the will go from 4 to 1000;
create sequence seq_2 minvalue 4;
alter sequence seq_three maxvalue 8000; --the max value is altered to 8000
drop sequence seq_2;
create sequence seq_5 minvalue 4 maxvalue 1000
cycle;
create sequence seq_7 minvalue 1 maxvalue 1000 -- 4…..1000 then 1……….1000 will be used
start with 4 cycle;

create sequence seq_7 minvalue 4 maxvalue 1000


increment by 2;
create sequence seq_7 minvalue 1 maxvalue 1000
increment by -1; -- 1000 , 999 ,998………1 in reverse order is printed

• negative values are allowed


create sequence seq_9 minvalue -1000 maxvalue 1000
increment by 2;

create sequence seq_8 minvalue 1 maxvalue 10000000000


cache 1000;
by default cache is 20;

• 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.

==================== SCHEMA =========================

ORAD1 ORAD2 ORAD3


EMP EMP EMP

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

For different database we have to use DBNAME.USERNAME.OBJECTNAME(TABLE,VIEW,…)

If we are accessing on the network then


DBLINKNAME. DBNAME.USERNAME.OBJECTNAME(TABLE,VIEW,…)
-------------------------------------------schema.object----------------------------------
SCHEMA IS  DBLINKNAME. DBNAME.USERNAME

============================ SYNONYMS =================================

(user) ORAD1 ORAD2 ORAD3


(tables) EMP EMP EMP
select * from emp; select * from orad1.emp select * from orad1.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

(user) ORAD1 ORAD2 ORAD3


(tables) EMP EMP EMP
create synonym semp create synonym semp create synonym semp
for emp for orad1.emp for
select * from emp; select * from orad1.emp
orad1.emp; orad1.emp
select * from
orad1.emp

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)

• we can have synonym for sequenc,indexes, views,stored procedures,stored functions


58
ARUN P SINGH
============================= STORED PROCDURE ==================

• It is a global procedure,stored in the database


• can be callaed in sql*plus ,pl/sql, forms , reports, menus, graphics ,etc
• can be called through any front-end ,stored in database in the compiled format
• hiding the code from end user
• execution will bery fast.
• execution it takes palace in server ram, ideally
• ideally suited for server-side data processing
• only a single copy brought into the server RAM, programe code shared by all users.
• parameter may be IN ,OUT, IN OUT
• Overloading of stored procedure is not possible.

create or replace procedure prod_1


as
begin
insert into tempp values(1,’inside prod_1’);
end;

• if the procedures require OUT or IN OUT parameter it can be called through PL/SQL only

select * from user_objects where object_type=’PROCEDURE’;

• we can make parameterized procedure;

create or replace procedure prod_1(x number)


as
begin
insert into tempp values(x,’inside prod_1’);
end;
/

• we can use OUT, IN OUT only in PL/SQL .


execute procedure_one;
drop procedure procedurename;
alter procedure procedurename compile;

59
ARUN P SINGH
========================PROCEDURAL ENCAPSUATION===================

Select * from user_source;


spool abc
select TEXT from user_source;
spool off

to avoid source code from seen.


-------------------------------WRAP UTILITY---------------------------------------------

sql> @ D:\oracle\ora90\BIN\wrap.exe -- command prompt will open


(in command prompt type) wrap iname=p2.sql oname=p2.txt --running
or simply open command prompt and use below command.
D:\oracle\ora90\BIN wrap iname=p2.sql oname=p2.txt

============================STORED FUNCTIONS =============================

• global functions can be called in PL/SQL and in other front-end ONLY.


• cannot be called independently.
• can be used in SQL select command(as we use inbuilt function)

create or replace function funct_1(x number) return number


as
begin
insert into tempp values(x,’inside funct_1’);
return x;
end;
/

======================= ORACLE CERTIFICATION =====================

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)

=================== DATABASE TRIGGERS ===========================

• this is routine (set of commands) that executed AUTOMATICALLY when some event take
place.
• trigger are written on tables.

events that on which tiggers can be written.


1. before insert
2. after insert
3. before update
4. after update
5. before delete
6. after delete

create or replace trigger trigg_1


before insert
on salespeople
begin
insert into tempp values(1,’trigger run’);
end;
/

-------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.

create or replace trigger trigg_1


before insert --it is statement level will fire for every insert statment
on salespeople
begin
insert into tempp values(1,’trigger run’);
end;
/

create or replace trigger trigg_1


before insert
on salespeople FOR EACH ROW --is row level will fire for every DML operation on row
begin
insert into tempp values(1,’trigger run’);
end;
/

-----------------TRIGGERS ARE OF TWO TYPES------------------------

1. Statement level trigger


2. Row level trigger.
• when there is row level trigger then it is detailed logs(audit trails)
• there are all total 12 triggers possible on each table.

2types of trigger * 3 types of DML optn * 2 before/after = 12 triggers.

-------------WE CAN USE TABLE VARIABLE DIRECTLY---------------------


:new.columnname (for insert operation) -- can be used ONLy when we use FOR EACH
ROW
:old.columnname --is used in delete operation as table variable
:old.columnname , :new.columnname -- both can be used for update operation.

create or replace trigger trigg_1

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.

-----------------------DATA CLEANSING USING TRIGGER-----------------------

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

create or replace trigger trigg_1


before insert
on salespeople FOR EACH ROW
begin
:new.ename:=upper(:new.ename) -- changing the name to uppercase before inserting
end;
/

• 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)

-------------TRIGGER WITH DELETE STATEMENT-----------------

create or replace trigger trigg_1


before delete
on salespeople FOR EACH ROW
begin
insert into tempp values(100,’employee deleted’);
end;
/

:old.columnname is used in delete operation as table variable

• is used to maintain history tables in the case of delete.

• related changes can be made to related table.


63
ARUN P SINGH
ex.
create or replace trigger trigg_1
before delete
on emp FOR EACH ROW
begin
update deptot set saltot=saltot - :old.sal where deptno=:old.deptno;
end;
/

----------------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

create or replace trigger trigg_1


before INSERT
on TEMPP FOR EACH ROW
begin
insert into tempp values(100,’employee deleted’);
end;
/

• no upper limit for cascading.


• when in cascading of series of triggers the last trigger tries to update the first then
oracle fires an error. mutating tables ( will rollback all the changes)

-----------UPDATING RELATED TABLE USING UPDATE TRIGGER--------------

create or replace trigger trigg_1


before UPDATE
on EMP FOR EACH ROW
begin
update deptot set saltot=saltot - :old.sal + :new.sal where deptno=:old.deptno;
end;
/
--- updating the related table ………………….

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

update deptot set saltot=saltot - :old.sal + :new.sal where deptno=:old.deptno;


end if;
end;
/

• 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)

create or replace trigger trigg_1


before UPDATE
on salespeople FOR EACH ROW
when (old.snum<>new.snum or old.sname<>new.sname) -- use to check if change is made or
not, then after check it enter the trigger body
begin
insert into tempp values(100,’employee deleted’);

end;
/
• generalize trigger for DML operation.

create or replace trigger trigg_1


before insert or update or delete --all DML operation
on salespeople FOR EACH ROW
begin
if inserting then -- no parameter required row level operation
insert into tempp values(100,’employee enserted ‘);
elsif deleting then
insert into tempp values(100,’employee deleted’);
elsif updating(‘snum’) then -- parameter required column level operation
insert into tempp values(100,’employee updated’);
end if;
end;
65
ARUN P SINGH
/

---------------USER DEFINED ERROR THAT CAN BE RAISED-------------


(not exception)

raise_application_error(-20001 , ‘deletion not allowed’);

create or replace trigger trigg_1


before delete
on salespeople FOR EACH ROW
begin
raise_application_error(-20001 ,‘deletion not allowed’); -- will not to allow any
deletion in salespeople(every time error will occur)
end;
/

• the range for user defined error_code is between -20001 to -20999


• here we are creating an error at back-end and will work with every front-end
drop trigger abc;
alter trigger abc compile;
alter trigger abc disable;
alter trigger abc enable;
• you can write trigger on synonyms.
• wrap utility cannot be used on triggers.

66
ARUN P SINGH

Вам также может понравиться