You are on page 1of 273

c 

c  
 c 
 




 

       

 



    ! 

 


 

     
"!    
 !c 

 

#
 $
 
 %
&



 

   '
(   

    
 
 



   
 



    


  



 (


     


 $


 

   




 (
 



 

     


 
) 


  
 

 


 (
  
 

 !* $   * 
!
 
 
    

   


 


!  
 
 
 ! 
! 
! 


 +
  !,! 
 $! 

   




  
     ! 
  c! 
(


 

   
 !      *  !   
-.     
 

 + 
 c! /
-

 *   

 ! 
   


*
!  

 
0 1!

 ( c! /
-*   

! 
 
  
   
 $ !
 


  
 *
!   

(  
 
 #2!3
! /



  !! 2!
*
!     !  

 
 
 +!   ) 


2455*
! ! 
    

 
6 


    c! /
     


  7 
  


 !
   
 

 


 ! 

   ! 


  
 
 *  +!!

 
 


  

  

Ö   * 

!5
!
 c! /
 


  !
* 

!
 

!    
s

  
s 3   
s


!
 
s +   

s (! )
 
s 

 

  #
 
3 4
c! /
( * 

 

!

 !
  !

  
 

8 + 
4
 c! /
 


 
!
 !
* 


!
 

9  $!
 $   :  

    


 
  
;


+    c! /
(
  
! 

!
  
 
 

 
 
  
  
  
5 


+    c! /
  
 <
 


 
 


  7  ! 
  
 


!
  
+  +    c! /



  !
* 


 


    
 


 

  

  

   ! c! /
  ! 
  
 

!
  


 ! 
  

0 2 , !*  c! /

 2 ,!*   ! 
  
  *   
!
 
 !* 

    ! 
 

 !  $
c 
! 
   * 
!
   !
 

   
  
   * 
‘  ‘ 
 ‘‘   
 ‘  
      
       !
 "  #
 $   
•   %
"&%   %
   ''  ($
 
 
(
) *
+    
 ,  
- % ! "&   - % ! "&   

 .! #
  % -'%

% 
 
+‘  
/%% %

% (
 0  *
  
% ' % 
      !
 #
$%
'  % 
% % 
 -'% %(1
 

 % 
(
) 
+    2  #
%
 % '%%%  
 ' %%  %

  
' 
(3
 
-' %
 %
  
%
'%(
$%
' % 
4
• %   %‘  %

• $  %
'%  %

'%(
 ''% %
 
 (
• %  %‘   
  %
'% 
% %
(
) 
+    
 &! #
‘   
  
$ .'  
 % 
 

+   


 
‘   *
   - % 
% 
‘   #
) 
+‘ )#
%

% -%   
 % - (
3 % %
%
 


  -(

‘  0 
  
  *
 
%  %  
+    
 ,  
- % ! "&   - % ! "&   

 .!   2  #
  *
% 
%-'%'  (
+5#
% -  %- 
 %

% 
5 ' %  '%% %- 
 

(3
%- 
  %
'%%%  (
+ #
% -  % '

% (%
 % -    
%
 (
+)$ )6 
#
)$ )6 %    -
%
 (
$  *
$ %'%
 ( '% 
$  - 
   - 
 #
) 
+$
- 
 & 7'778  7 !&&&7&!*
*9.77&!*
-*:.7 #
$%
'  %%

%

%(
) % *
+$
- 
 7 77 77 777727 #
3 %%
  
'%
%- 
( %
%
 %  ( 

  
%
- 
% 
-'%;
(
K
   - %- 
'%;
 
  (
3
  %
%
% 
-6<- 

% 
 6<- 
(

$%
' ''
 
%
%  % 

+$    "= - 


 
  - 
 #

) $>KK' 

+$     
- 
  7!7" #
$% - %
 
(
<   *
 
    (
+
   ? '%#

) <  >  

+
   ?@0  7
'%? & #

$%
  %
  %'%

% %% '
 (
0% 
  
   (
) 
  % 
  

+
   ?@0  7
‘2?@ =**9.7
'%? & #

‘  *

    

+‘  #

$%
'  %% 

+‘  '%#


) *

+‘'%? &=#

‘0   %


   %
' %  
 ‘   %%
% %
  (

    
     *

   *


  ‘0  
% 
-% (

+ #
> 4  

-%  %   


  
> 4 (

+> 4#

 - 

$%
'  4
 
  %  - 
 4 
4 4(

+ - #

   -


  4
 -(

   *


   -%

% 
- %'  (%' 
- 
  % (

) 
  % 

+
  #

% - -%'% 


%

(%' %4 %
 % (
      
%
      %
'%   

  @7
   
 (%  -'
     

A  A A #
) 
+   A  5
#
+5A #
% -   % 
% A '%% 
% (
$%
' %

%
 %
+   A 
AA   
  A 
'% ?!#
  $>
   '%%%
 
$ A  
A6   

A  A A  #
) 
+
A  AA   
 '%   =&&& #
 +
%'  % 

+
• % 
•   
•    
% 
 %  

 0
 ‘-  
+ (
K) 
+   B =&&  
'%  .&&&#
  
   

 '% %(%
   
?C???3'$6$
63'4646
66
(
)    
+ '%
 4@>D7#
% -  %%
%  '%> 
' 
%  (
+ '%
 4@>AA7#
    *
   
%

'
  
%  
  
•  
•> 
• 6 
$%
' -'% %
'%  @8  7 %E%
  %
  %  &&&&(%
+5
'%  ?@8  7
   &&&&#
$%
' -'% %
'%  %@8  77
 7   &&&&#
+5
'%   @8  77
 7    &&&&#
6 
$%
' -'% 
'%   &&&&%%' 
;
 

+5
'%  C? &&&&#
% -;
 
' 
% 
+5
'%   &&&&#
+5
'%   &&&&#

 8*
%  % %
  
6   
   
    '
6
%  

  %(
3 
*
 

%(

 %  
 3
 %

 %
' %

 %
+5 #
> 
*
 
 % - 
   +(
F
 
*
F
 
 %
 
 
;
  $F


%
  %(
  

'%%
% -  
(
$%
' -'%7 '%
 '%   %
+5
'%      

  % - 
     #
K

 >'K

F
K


 >'K
*
 >'K

- 

-';
% ( '

       

 @'%7
(% '

    
• ‘ K

• 6
K

• %  K

• -K

• 0 
K

‘ K
*
%  - 

 


'%%     
%A' 
'%%
 

(
A0%
% A%

   
   '%%

%(%  A%  (/%
%  %
%
) A%
+  A%  ! 

#
 A‘ 
%  A   '%%
%
  %  %%(
)  A K
*
+  A    
#
% -;
 %  %

%(
0%A3'*
%

%
%
'% - % 
%A'    !
) 
+%A'  7&G*‘*:G7 

#
6A‘ *
% %

A    
) 
+A   7K 7 
#
% -;
'% K (
6'A*
%'A
 %  
  
  %H
% 
'A  7%77%7 #
@%7  " - 
%
H'%@%7 
 % - %H
'%%% ' (
+'A @ "*K*::77777 

#
$
 !*K*::'%%% %
H@7
6
K
*
• 3 - 
 **************3
I 

• $) - 
 ************    
% ;
- 

•  - 
 ************ I 

• J - 
 *********J - 

• )K8 - 
 ************I 
> %
)K8

• K> - 
 ********    
% ;
- 

• 6 - 
 *********6 
  %I 

• F - 
 *******3  &F %- 

• 0‘ - 
- *********0‘


• 8/)> - 
 ******- 
 

8/)>
• ><6‘ - 
 *****>
 %
- 

• $F6 - 
 ********* - 
 -* 
- 
 - & 
- 
H(
• $6 - 
 *************$6- 

• $6J - 
 ************J$6- 

• +> - 
 **********+
> - 

• 6 - 
 ************6 - 

• 6J - 
 ***********J6 
- 

• ><6  - 
 *****I 

><6 

%  K
*
)6FJ
)6FJ%
%'   
%' %  % 
 
 (
) *
+ % @$7 
#
$ *
$ -%%' -
  (
) *
+$  @7 
#
/)>*
-%'' (
) *
+' @$7 
#
<88)>*
-%'
 (
) *
+
 @7 
#
>$0*
>$0 % 
+ @H  77H7 
#
>>$0*
>>$0 % 
+ @H  77 7 
#
  *
   % 
) *
    %  
+   @2 4772777 
#


% -  4(
>)8 )*
+  @2 4 2
772777 

#


% - 
3 4 3
(
<3>*
K <3>

 % 
)K08)*
+
 @'L
 79 
#
8‘*
8‘  4" 
(
• % 
%%   '%%
%  '%%  (
• %%
'%% % 
 %%
- 
(
•%%% '%'%%%  
% '%;
(
) *
+  @$7 &757 
#
%

 -% 5%'@$7(
8‘ @$7 
*******************
555555$
%  & %   
(
>8‘
%K
>8‘% %
8‘
(%
 
 4
%  % 
(
) *
+  @$7 &757 
#
%

 -% 5%'@$7(
>8‘ @$7 
*******************
$555555
‘) ‘)*
<4%  
'%% 
%  %   %‘) ‘)

 - 
- 
 (
 ‘) ‘)*
+ - 
 % !%!*** 
  #
) *
+     
  70  770 7 
'%   !&&&#
6 *
 K

% 
%   (
) *
+   A  A  6 
#
   *
%% % 
 %
   
+A MM A #
+ @%  @MM MM@7MM
  MM@ 7MM MM7 '7MM  MM@
%7 '% ?@0  7#
J>*
% -

%%  - 

% -
(
) *
+% G9 
#
% - 
@ 7% %

(
-K
*
-
- - 

   %(%-
 
  %' (
• A% 
• A 
• A

A%  *
K %
A%  NO 
'%% % '%%
%  (A%  -

-  - 
- % !
      ( $
 %- - % !
%
  ( %' 
 (
+A%   7%PQ%
7 
#
% -  %   
% % (% 
'  
!.%K
!&&&% 
@!.*K*&&7#
$% -     4

 - 4  %   
H  
(
A 
% A  % NO (%-
% - % !     (
K %%  (
%'  '%%
 
% @1 
!"!&&&7(
+A  @1 
!"!&&&77%*
*7 
#
@!"*2 *&&7'%

(
A
 *
%A

 '%-
   
%

  '%% %  
(%  
   
 -
 
  (
+A
 @ &&7 
#
0 
K
*
%'  % 



 (
• <
• <
• 6-
• IH
<*
%

% - 

 %

 (
) *
+<
#
%

 
(
<*
%

% 7
 
'%%- % !  (
) *
+

#
%
'% %

(
6
- 
 6- *
%6
- 


 
'%'' 6
- 
 H
%- 
'%%%
( % 
 - -  ! (
• $ 
-'
!(
• $ 
-'

• $  !   %
 -!%    
% (
) *
+    -   !=&& 
#
IH*
+IH @$7 
#
%

% -;
@,7(
 '% -

  
 '
(%-%

 -
'(
F
K
*
 


 
  

'(% 2


 %  
(% 



  
 H'(
• - K

• 0K

• 0 K

• 
K

• 
K

- K

%- 

% - 
- 
%
% 

%

) *
+ -    '%? &#
0K
*
%
' -%  - 
%

% 
(
) *
+    '%? &#
0 K
*
%
' -%% % - 

%
% 
(
) *
+     '%? &#

K
*
% -
 
 %

   - 
 (
) *
+
    '%? &#

K
*
$
%
'



($  4" 
(

 5 *
$
 '
-
  
6
(
+
 5 #
% -;

%

% 
-
- 
(

 A  *
$
%
- 
%


 6
- 
(
+
  #

 A  *
$ 
 A  
 

 - 
'%
 (
+ 
  #
% -;

%


  %
 (
 1
    *
( < !( < 
"( $ ,( 0

   '    
s The queries, which are related by a set operator
should have the same number of columns and the
corresponding columns must be of same data type(
s uch a Query should not contain any column of type
long.
sThe label under which the rows are displayed are those
from the first select statement.
<*
The union operator returns all distinct rows
selected by both queries. The following example
combines the result of two queries with the union
operator , which eliminates duplicate rows.
QL> elect dno from emp <6$6 elect dno from
dept ;
The union operator returns all distinct column values
from the emp and dept table respectively.
<*
The µUnion All¶ operator returns all rows select
by either query including duplicates.
QL> elect dno from emp <6$6 select dno
from dept;
$*
hntersect returns only the rows that are common
to both the queries.
QL> elect dno from emp $6)>)  elect dno
from dept;
0
*
Minus operator returns all distinct rows selected
only by the first query and not by the second.
QL> elect dno from dept 0$6< elect dno from
emp;
1
The purpose of a join is to combine the data
spread across tables. A join is actually performed by the
µwhere¶ clause which combines the specified rows of
tables.
There are Three types of Joins: -
• imple Join
• elf Join
• Outer Join
imple Join : -
ht is the most common type of join. ht retrieves
rows from two tables having a common column and is
further classified into 4   and 4  .
Equi - Join : -
A join, which is based on equalities, which is
called an equi - join. The equi join combines rows that
have equivalent values for the specified columns.
QL > select * from emp,dept
where emp.dno=dept.dno;
The above query fetches the rows from the table emp
and dept where the dno of emp table matches the dno of
the table dept.
6);
*1*
A Non Equi - Join specifies the relationship
between columns belonging to different tables by
making use of the relational operators(>.<,<=,>=,<>)
other than =. The following example is illustrative of
this
Example : -
QL> elect itemdesc,max_level,qty_ord,qty_deld
from itemfile,order_detail where
(itemfile.max_level<order_detail.qty_ord) and
(htemfile.itemcode=orderdetail.itemcode);
  *
To prevent ambiguity in a query we include table
names in the select statements. Table aliases are used to
make multiple table queries shorter and more readable.
QL > elect e.eno,e.ename,e.dno,d.dno,d.dname from
emp e,dept d where e.dno = d.dno;
1*
Joining the tables to itself is known as self join,
i.e., it joins one row in a table to another. The join is
performed by mirroring the table using the µwhere¶
clause it can compare each row of the table to itself and
also with other rows of the same table.
QL> elect e1.ename || µworks for¶ || e2.ename
³Employees and their Managers´ from emp e1,emp e2
where e1.mgr=e2.eno;

1*
The outer join extends the result of a simple join.
An outer join returns all the rows returned by simple
join as well as those rows from one table that do not
match any row from the other table. This cannot be
done with simple join alone. The symbol, (+)
represents outer join
QL> elect e.eno,e.ename,e.salary,d.dno,d.dname
from emp e,dept d
where d.dno=e.dno(+);
The above example will also retrieve rows from dept
table which do not have any matching records in the
emp table. uch a retrieval is due to the presence of an
outer join(+). The rows are retrieved in addition to
those records which have a simple join.

;

Nesting of queries one within the other, is termed as a
subquery. A statement containing a subquery is called a
parent statement. ubqueries are used to retrieve data
from tables that depend on the values in the table itself.
) *

The user want to view the details of the


employees who¶s salary is equivalent to
µAswin Kumar¶ salary. Without the help of subquery
the user has to perform 2 queries one is to identify the
salary of µAswin Kumar¶ and the second one is to list
the details
Of the employee who¶s salary is equivalent to µAswin
Kumar¶ salary. hf the user uses the subquery then
complication of the query is reduced.
QL> select * from emp
where salary in(select salary from emp
where ename = µAswin Kumar¶);
‘ifferent types of subqueries are :
• Nested ubquery
• Correlated ubquery
• Multiple ubquery
Let us consider the following tables for examples :-
TABLE NAME
(a) ‘EVELOPER
(b) CAREER
(c) PRO‘UCT
‘eveloper Table tructure

NAME Varchar2(30) Not Null


‘OB ‘ate
‘OJ ‘ate
EX Char(1)
KhLL1 Varchar2(20)
KhLL2 Varchar2(20)
ALARY Number(8,2)
Careers Table tructure

NAME Varchar2(30) Not Null


PLACE Varchar2(30)
COUR E Varchar2(30)
FEE Number(8,2)
Product Table tructure

NAME Varchar2(30) Not Null


ThTLE Varchar2(30)
ENVhRON Varchar2(30)
CO T Number(8,2)
‘CO T Number(8,2)
OL‘ Number(3)
Nested ubquery : -
hf a ubquery is nested with another query that is
Nested ubquery.
Example :-
hf the user want to view the details of the
programmer who¶s skill is VC++ and developed
projects in VC++ and has experience of 5 yrs atleast
then the following the query
QL> elect * from developer
where skill1 =µVC++¶ or skill2=µVC++¶ and
name in(select name from product where
environ=µVC++¶ and name in(select name
from developer where to_char(sysdate,¶yy¶)-
to_char(doj,¶yy¶)>=5));
Multiple ubquery : -
Example used for Nested query itself can be
applied to Multiple subquery.
QL> elect * from developer
where skill1 =µVC++¶ or skill2=µVC++¶
and name in(select name from product
where environ=µVC++¶) and name in
(select name from developer where
to_char(sysdate,¶yy¶)-to_char(doj,¶yy¶)>=5);
Correlated ubquery : -
A subquery is evaluated once for the entire
statement whereas a correlated subquery is evaluated
once for every row processed by the parent statement.
QL> elect deptno,ename,sal from emp x
where sal> (select avg(sal) from emp where
x.deptno=deptno)
Operators Used in ubquery : -
ubqueries can also return more than one value.
hn such cases we should include operators like any,all,in
or not in between the comparison operator and the
subquery.
QL> elect * from emp where salary < any
( elect salary from emp
where ename in(µRam Kumar¶,¶Balaji¶ ));
hn the above example the subquery returns the salary of
µRam kumar¶ and µBalaji¶ and the main query will
display the details of the employee¶s who are all drawing
less than these two employees.
All Operator :-
QL> elect * from emp where salary > all
( elect salary from emp
where ename in(µRam Kumar¶,¶Balaji¶ ));
hn the above example the subquery returns the salary of
µRam kumar¶ and µBalaji¶ and the main query will
display the details of the employee¶s who are all drawing
salary greater than these two employees.
Constraints
To maintain security and integrity of a database is the
most important factor in judging the success of a system.
An integrity constraint is a mechanism used by oracle to
prevent invalid data entry into the table.
The following are the various types of integrity
constraints : -
• ‘omain hntegrity Constraints
• Entity hntegrity Constraints
• Referential hntegrity Constraints
‘omain hntegrity Constraints : -
These constraints set a range, and any violations
that take place will prevent the user from performing the
manipulation that caused the breach. There are basically
two types of domain integrity constraints.
• Not Null Constraint
• Check Constraint
By default the tables can contain null values. The
enforcement of Not Null constraints in a table ensures
that the table contains values. Oracle will not validate
the record until this is satisfied.
The other type of constraint available under this
classification is the µcheck¶ constraint. This can be
defined to allow only a particular range of values. When
the demarcation specified in this range is violated Oracle
rejects the record.
Entity hntegrity Constraint : -
Entity hntegrity Constraints are two types.
• Unique Constraints
• Primary Key Constraints
The Unique Constraint designates a column or a group
of columns as a unique key. This constraint allows only
unique values to be stored in the column oracle rejects
duplication of records when the unique key constraint is
used.
The primary key constraint is similar to the unique key
constraint. The primary key constraint just like the
former avoids duplication of values. hts need is best felt
when a relation has to be set between tables, because in
addition to preventing duplication it also does not allow
null values.
Referential hntegrity Constraint :-
The Referential hntegrity constraint enforces
relationship between tables. ht designates a column or
combination of columns as a foreign key.
The foreign key establishes a relationship with a
specified primary or unique key in another table, called
the referenced key. hn this relationship, the table
containing the foreign key is called the child table and
the table containing the referenced key is called the
parent table.

hmplementation of Constraints :-
‘omain hntegrity - µNot Null¶ Constraint
Note:
• µNot Null¶ integrity constraint can be define using
alter table command even when the table has rows.
• Zero and Null are not equivalent.
• One null is not equivalent to another null.
Example : -
QL> create table emp (eno number(3),ename
varchar2(25) constraint nn not null ,salary number(8,2));
Check Constraint : -
This constraint is used to check the values in the
column satisfies the condition, i.e the user can restrict
the records to be inserted into the table with the help of
check constraint.
Example : -
QL> create table test(no number(3),name varchar2(25)
constraint nn Not Null,salary number(8,2)constraint
chk_sal check(salary>=2500),phone number(8));
hn the above table the user can insert records which
satisfies the condition.
Unique Constraints : -
This constraint checks for the uniqueness of the
record. hf the user don¶t want to have any duplication of
records at the time of insertion then the user can assign
unique constraint for that column.
How to add a constraint with the alter table statement
QL>alter table test add constraint uni unique phone
number(8,2);
The user can assign composite unique constraint also. hf
the user want to assign unique constraint for more than
one column then the user can prefer composite unique
constraint.
Example : -
QL>Create table test (no number(3),
name varchar2(25),salary number(8,2),
phone number(8),E-Mail varchar2(25)
unique(phone,e-mail));
Composite unique constraint can be assigned for more
than one column.
Primary Key Constraint : -
Primary Key Constraint is a combination of Not
Null and Unique Constraint, i.e., primary key column
won¶t accept duplicated records and null value. A table
can have only one primary key constraint and this
constraint is mainly introduced to set relationship
between tables.
hf the user want to assign primary key constraint for
more than one column than they can use composite
primary key, the composite primary key can be assigned
for 16 columns maximum.
Primary key constraint is assigned to a column with the
keyword primary key.
Table Level Constraints & Column Level Constraints:-
s The table level constraint is part of the table
definition .
s An integrity constraint defined at table level can
impose rules on any columns in the table.
s Column level constraint being a part of the column
definition can be imposed only on the column level.
Example for a Table Level Constraint : -
QL> Create table itemfile
(itemcode varchar2(5),
itemdesc varchar2(20),p_category varchar2(20),
qty_hand number(5),re_level number(5),
max_level number(5),itemrate number(9,2),
constraint max check(max_level<500),
constraint un_item unique(itemdesc));
Referential hntegrity Constraints : -
To establish a µparent - child¶ or a µmaster - detail¶
relationship between two tables having a common
column, we make use of referential integrity constraints.
To implement this we should define the column in the
parent table as a R 
  and the same column in the
child table as a     referring to the corresponding
parent entry.
Example : -
QL> Create table dept(deptno number(3)
constraint pk1 primary key,
deptname varchar2(30) constraint nn1 not null);
QL>Create table emp (eno number(4) primary key,
ename varchar2(35),
designation varchar2(25),deptno number(3)
constraint fk1 references dept(deptno),salary
number(8,2));
Note: The referential integrity constraint does not use
foreign key keyword to identify the columns that make
up the foreign key. This is because the constraint is
defined at ›   . The foreign key is
automatically enforced on the columns.
s Like other constraints it is also possible to define the
referential integrity constraint at table level.
s To alter an existing table for adding a referential
integrity constraint
QL> alter table emp add constraint fk1 foreign
key(deptno)references dept(deptno);
On ‘elete Cascade Clause: -
The µOn ‘elete Cascade¶ clause specifies that
oracle maintains referential integrity by automatically
removing foreign key values if a referenced primary key
value is removed. The syntax for creating a table to
include this clause is
Example : -
QL> Alter table order_master add constraint fk_code
foreign key (vencode) references vendor_master(vencode)
on delete cascade;
QL>delete from vendor_master where vencode=µv006¶;
‘eferrable Constraints
When a constraint is made deferrable, oracle 8
leaves the checking until the transaction is committed.
Each constraint has two additional attributes to support
deferred checking of constraints.
s ht may be deferrable or not deferrable
s The initial state may be set to initially deferred or
initially immediate.
The three conditions, which can be set, are
s ‘eferrable initially immediate - this checks for
constraint violation at the time of insert.
s ‘eferrable initially deferred - this checks for
constraint violation at the time of commit.
s Non deferrable initially immediate - this is the
default Condition which need not be specified.
The syntax for setting the condition is
alter table <tablename> add constraint <constraintname>
foreign key<columnname> references <tablename>
deferrable initially deferred.
The above syntax when used will add a constraint which
will by default only be checked at commit time.
The following statement enables all constraints
set constraints all immediate;
the next command is used to disable all constraints.
et constraint all deferred;
To ‘rop a Constraint yntax is
alter table <table_name> drop constraint
<constraint_name>;
LOCK & TABLE PARThThON

When a table is being accessed by different clients


concurrently transactions being performed simultaneously
can prove to be harmful at times. Oracle provides the
locking facility, which can be performed explicitly.
Another facility available to protect data is to R

the tables. ‘oing so will    ›
› › R  



The need for locking can be clearly understood with this
example. Consider the users from two different
departments in ABC ENTERPRh E - sales and
accounts, wish to access the same table i.e..,
order_master. hn such a case, the following situation may
arise.

ales Accounts
updates row1 of order_master; deletes row1 of
commit; order_master;
commit;
ince both the users are accessing the same row on the
same table at the same time it may end up in a situation
where user in accounts will delete the row that user in
sales has updated. To overcome this situation oracle
incorporates a locking facility which permits or denies
access to other users on a table or a certain rows in a
table, when a user is still is in the process of operating on
them.
Types of Locks
Locks are the mechanisms used to prevent
destructive interaction between users accessing the same
resource simultaneously . A resource can be an entire
table or a specific row in a table. Thus locks provide a
high degree of the data concurrency. Locks can be
acquired at two different levels.
• Row level lock (for specific rows)
• Table level lock (for entire table)
Row level locks
hn the row level lock, a row is locked exclusively
so that other users cannot modify the row until the
transaction holding the lock is committed or rolled back.
Row locks are acquired automatically by oracle as a
result of insert, update, delete and select.. for update
clause statement.
elect.. for update clause
The select command when used with for update of
clause places an exclusive lock on one or more rows of a
table. This command can be used to lock the rows that
would be updated later. The following example locks
rows in which the employees salary between 5000 to
15000.
Example : -
QL> select * from emp where salary between 5000 and
15000 for update of name,designation;
Table level lock
A table level lock will protect table data there by
guaranteeing data integrity when data is being accessed
concurrently by multiple users. A table lock can be held
in several modes they are
• hare Lock
• hare Update Lock
• Exclusive Lock
The general syntax for locking a table is given below:
Lock table <table_name> in <share or share update or
exclusive mode>;
hare Lock :
A share lock locks the table allowing other users to
only query but not insert, update or delete rows in a table.
Multiple users can place share locks on the same table at
the same time, i.e., it allows resources to be shared and
hence the name share lock.
Example : -
QL> lock table emp in share mode;
hare update lock
ht locks rows that are to be updated in a table. ht
permits other users to concurrently query, insert, update
or even lock other rows in the same table. ht prevents the
other users from updating the row that has been locked.
We can enforce a share update lock by using the µfor
update¶ clause in the select statement.
Example:-
QL>lock table emp in share update mode;
Note :-
• Although a share update lock falls under the table
level category, it is effective only for rows.
• ht allows numerous users to concurrently lock
different rows of a table.
Exclusive Lock : -
Exclusive lock is the most restrictive of the table
locks. When issued by one user, it allows the other user
to only query but not insert, delete or update rows in a
table. ht is almost similar to a share lock but only one
user can place an exclusive lock on a table at a time,
whereas many user can place a share lock on the same
table at the same time.
Example :-
QL>lock table emp in exclusive mode;
Note :-
• Locks can be released by issuing either 
› or
› .
Nowait:-
Consider a user has locked a table without a µnowait¶
clause in the lock table format. hf another user tries to
violate the above restrictions by trying to lock the table,
then, he will be made to wait indefinitely until the user
hnitially locked the table issues a commit or rollback
statement. This delay could be avoided by appending a
µnowait¶ clause in the lock table command.
Example:-
QL>lock table emp in exclusive mode nowait;
‘eadlock:-
A deadlock occurs when two users have a lock, each
on separate object, and, they want to acquire a lock on the
each other¶s object.
Oracle automatically detects the deadlock and solves the
problem by one of the two transactions.
Partitions
The additional feature in Oracle 8 is that the tables are
R
 And stored in different locations as per
requirement. A single logical table can be split can be
split into a number of physically separate pieces based
on ranges of key values. Each of the parts of the table
is called a partition. Although the partitions are held
and managed independently, they can be queried and
updated by reference to the name of the logical table.
There is difference between a table, which has a single
partition, and a table that has no partitions. A non-
partitioned table cannot be partitioned later. Each
partition is stored in a different segment and has
different physical attributes.
Table partitions can be stored in different tablespaces.
Oracle 8 provides partition independence. We can
access and manipulate data in one partition even if
some or all of the other partitions are unavailable. This
is the major benefit.
toring the partitions in different table spaces has its
advantages.
• ht reduces the possibility of data corruption in
multiple partitions.
• Back up and recovery of each partition can be done
independently.
Note:-
• Partitioned tables cannot contain any columns with
long or long raw datatypes, LOB datatypes
(BLOB,CLOB or BFhLE), or object types.
Example to create a partitioned table :
QL> Create table emp(empno number(3) primary key,
empname varchar2(25),designation
varchar2(30),salary number(8,2))partition by
range(salary)(partition p1 values less than(5000),
partition p2 values less than(10000));
hn the above example table emp is created with
partition, and the table is partitioned on the column
salary. The data¶s are stored in two partitions. Based on
the records the data¶s are splitted and stored. hn the
above example from 0 to 4999 the records are stored in
partition p1 and from 5000 to 9999 it is stored in p2
partition.
hnserting records into a partitioned table:-
The records are stored in the partitions of a table
based on the partition key specified. The partition key
specified in the insert statement is compared with
partition bound defined when creating the partitioned
table.
Example :-
QL>insert into emp
values(µ101¶,¶Maya¶,¶Programmer¶,5000);
QL>insert into emp values(µ101¶,¶Meera¶,¶ ystems
Analyst¶,9500);
QL>insert into emp
values(µ101¶,¶Megha¶,¶Programmer¶,8000);
QL>insert into emp values(µ101¶,¶snegha¶,¶ enior
Manager¶,8000);
QL>insert into emp
values(µ101¶,¶sathya¶,¶Accountant¶,5000);
QL>insert into emp
values(µ101¶,¶VijayKumar¶,¶Clerk¶,4500);
To view the records in partition table
QL> elect * from emp partition(p1);
QL> elect * from emp partition(p2);
Maintaining Partitions :-
This section describes the various partition maintenance
operations, including:
š Moving Partitions
š Adding Partitions
š ‘ropping Partitions
š plitting Partitions
šExchanging Table Partitions
Moving Partitions:-
The MOVE PARThThON clause of the ALTER
TABLE statement is used to move a partition from a
most active tablespace to a different tablespace in order
to balance h O operations.
Assuming that a tablespace called  

exists
let¶s try to move a partition from the  tablespace
into the student_data tablespace.
Example :-
QL> alter table emp move partition p1 tablespace
student_data;
Adding Partitions :-
The ALTER TABLE A‘‘ PARThThON
statement is used to add a new partition after the
existing last partition.
Example :-
QL> alter table emp add partition p3 values less
than(µ15000¶);
Note:-
š The add partition option shown above is only for
tables where the last existing partition has been defined
with a specific key value.
š hf we wish to add a partition at the beginning or in
the middle of a table, or if the partition bound on the
highest partition is MAXVALUE, we should use the
PLhT PARThThON statement.
plitting Partitions :-
The PLhT PARThThON clause can be used to split a
partition into two.
This is useful when a partition becomes too large and
causes backup, recovery or maintenance operations to
consume a lot of long time.
Example :-
QL> alter table emp split partition p3 at(µ12000¶) into
(partition p4, partition p5);
The partition p3 in the table emp is split into partitions
p4 and p5. Now p4 will contain records with salary
!  !! and p5 will contain the records from
! !.
‘ropping Partitions :-
To drop a partition the ‘ROP PARThThON clause
can be made use of the ALTER TABLE statement.
Example:-
QL> alter table emp drop partition p5;
Exchanging Table Partitions:-
Exchanging table partitions is used to convert a
partitioned table to non- partitioned table and non -
partitioned table to partitioned table.
Criteria in Exchanging the Table Partitions:-
s The structure of the tables should be same.
s The records in the table which the user want to
exchange the partition should satisfy the partition
condition.
Example :-
QL> alter table emp exchange partition p2 with table
emp1;
Views
A view is a tailored presentation of the data contained in
one or more tables. A view takes the output of a query
and treats it as a table; therefore, a view can be thought
as Ú   or a Ú 

  We can use
views in most places where a table can be used. The
tables upon which a view is based are called base tables.
yntax for creating views
Create [or replace][[no] [force]] view <view name>
[column alias name«] as <query>[with [check option]
[read only] [constraint]];
Example
QL> Create view emp_view as select * from emp;
Creating view with conditions
QL> Create or replace view emp_view as elect *
from emp where name like µM%¶;
Updating the records in a view
QL> Update emp_view set name =µGeetha¶
where name=µMaya¶;
Creating view with check option
QL> Create or replace view emp_view as
select * from emp where name like µR%¶
with check option constraint empv;
The above command creates a view called emp_view
which consists of records where employee name starts
with character µR¶. Now the user tries to update a record
in the view by changing the name of employee Ram to
am.
QL> Update view emp_view set ename=µ am¶
where ename=µRam¶;
For the above command oracle displays an error stating
view WhTH CHECK OPThON where -clause violation.
Creating view with Read Only Option :-
QL> Create or replace view emp_view as select *
from emp with read only ;
The above command creates a view called emp_view
and it won¶t allow the user to update that view. The
user can just select the records they cannot perform any
manipulations.
Creating view with functions
QL> Create or replace view
emp_view(name,designation,salary) as select
name,designation,salary from emp where dno=10;
Creating view by Force
Oracle by default creates a view for the existing table
and valid column names. hf the user want to create a
view for a table which does not exists or invalid column
name then with the help of force option the user can
create the view.
QL>‘rop table emp;
QL>Create force view emp_view as select * from emp;
for the above command the user displays
 ›
 › R
  
After creating the emp table the user can compile the
view and use the view.
QL> alter view emp_view compile;
Creating view with Joins (view having more than one
base table)
QL> create view emp_dept_view(emp_no,emp_name,
salary,dept_no,department_name) as select
(e.eno,e.ename,e.salary,d.no,d.dname) from emp
e,dept d where e.dno=d.dno;
The above view has two base tables emp and dept if the
user tries to update the view user will get an error
message.

A synonym is a database object, which is used as
an alias for a table,view or sequence they are used to
| implify QL tatements
|Hide the name and owner of an object
|Provide location transparency for remote objects of a
distributed database
|Provide public access to an object
ynonym can be either private or public.
Public ynonyms are created by a ‘atabase
Administrator to hide the identity of the base table and
reduce the complexity of QL statements. One such
example of a public synonym is TAB, which we use for
selecting the tables owned by the user. These public
synonyms are owned by user group PUBLhC.
yntax for Creating a ynonym
Create [public] synonym < ynonym name> for
<tablename>
Example for ynonym
QL>Create ynonym e1 for emp;
Granting Privileges to ynonym
QL>Grant all on e1 to cott;
The cott user can do all ‘ML manipulations such as
insert,delete,update o the synonym in the same way that
of the table but he cannot perform any ‘‘L operations
on ynonym except dropping the synonym. The
synonym is just an alias of a table and all the
manipulations on it actually affect the table.
;

A sequence is a database object, which ca generate
unique, sequential integer values. ht can be used
automatically generate primary key or unique key
values. A sequence can be either in an ascending or in
descending order
yntax for creating a sequence
Create sequence<sequence_name> [increment by n]
[start with n] [maxvalue n] [minvalue n] [cycle nocycle]
[cache nocache]
$ µn¶ is an integer which specifies the
interval between sequence numbers. The default is 1. hf
n is positive,then the sequence ascends and if it is
negative the sequence descends
 '% pecifies the first sequence numbers to be
generated
0- 
 pecifies the minimum value of the
sequence. By default, it is 1 for an ascending sequence
and 10e26-1 for a descending sequence.
0 - 
ht specifies the maximum value that the
sequence can generate. By default, it is -1 and 10e27-1
for descending and ascending sequences respectively
 pecifies that the sequence continues to generate
values from the beginning after reaching either its max
or min value.
6  pecifies that the sequence cannot generate
values from the beginning after reaching either its max
or min value. The default value is µno cycle¶.
%The CACHE option pre-allocates a set of
sequence numbers and retains them in memory so that
sequence numbers can be accessed faster. When the last
of the sequence numbers in the cache has been used
6 %The default value µnocache¶, does not
preallocate sequence numbers for faster access.
Example for creating sequence:
QL>Create sequence seq1 increment by 1
start with 1
maxvalue 10
minvalue 1
cycle
cache 4;
QL> hnsert into emp (no,name)
values(seq1.nextval,¶Gettha¶);
To view the values
QL> elect seql.currval from dual;
Alter equence
The sequence can be altered when we want to perform
the following:

š et or eliminate minvalue or maxvalue


š Change the increment value
š Change the number of cached sequence
numbers.
The following example will change the max value of
the sequence from 10 to 15.

QL> alter sequence seq1 maxvalue 15.


hndexes
hndexes are optional structures associated with
tables. We can create indexes explicitly to speed up
QL statement execution on a table. imilar to indexes
in books that helps us to locate information faster, an
oracle index provides a faster access path to table data.
User can create index on a column or combination of
column using CREATE hN‘EX command as follows.
QL> create index empind on emp(eno);
hndex is created on eno column which exists is table
emp.
Unique hndexes
hndexes can be unique or non - unique. Unique
indexes guarantee that no two rows of a table have
duplicate values in the columns that define the index.
Non-unique indexes do not impose this restriction on
the column values. Oracle enforces unique integrity
constraints by automatically defining a unique index
on the unique key. A unique index is created by using
create unique index command as follows.
QL> create unique index ind1 on test(no);
Note :-
š A unique index is automatically created when we
create unique or primary key constraint. We cannot
create index for a column which is already indexed.
Composite hndexes :-
A composite index(also called a concatenated
index) is a index created on multiple columns on a table.
columns in a composite index can be in any order and
need not be adjacent columns of the table.
Example : -
QL> Create index compind1 on
order_detail(orderno,itemcode);
Bitmap hndexes:-
Bitmap indexes are appropriate when nonselective
columns are used as limiting conditions in a query.
To create bitmap index, use BhTMAP clause of the create
index command. Consider the following example.
Example :-
QL> create bitmap index lodging on worker (lodging);
hndex Organized Tables:-
QL> create table indorg (vencode number(4) primary
key, venname varchar2(20)) organization index;
Note : -
Primary key is a must for creating index
organized table.
Regular Table : -
1. ROWh‘ uniquely identifies a row; primary key
can be optionally specified.
2. hmplicit ROWh‘ column; allows building
physical secondary indexes.
3. ROWh‘ based access
4. equential scan returns all rows
5. Unique constraint and triggers allowed.
Organized Table : -
1. Primary Key uniquely identifies the rows.
Primary key must be specified.
2. No hmplicit ROWh‘ column, cannot have
physical secondary indexes.
3. Primary key based access.
4. Full- index scan returns all rows in primary
key order
5. Unique constraint are not allowed. But
triggers are allowed.
QLPLU REPORT COMMAN‘
QLPLU is usually thought of as a kind of interactive
report writer. ht uses QL to get information from the
ORACLE database, and lets you create polished, well-
formatted reports by giving you easy control over
 › 
 



 
   
 
 ›
 
QLPLU also has a tiny, built-in editor of its own,
sometimes called the command line editor, which
allows you to quickly modify a QL query without
leaving QLPLU .
COMMAN‘ ‘EFhNhThON
remark Tells QLPLU that the words
are to be treated as comments,
not instructions.
set headsep The heading separator
identifies the single character
tells QLPLU to split a title
onto two or more lines.
ttitle sets the top title for a each page
of a report.
btitle sets the bottom title for each
page of a report.
Column Gives QLPLU a variety of
instructions on the heading,
format,and treatment of a
column.
Break on Tells QLPLU where to put
spaces between sections of a
report, or where to break for
subtotals and totals.
Compute sum Makes QLPLU calculate
subtotals.
et linesize ets the maximum number of
line per page.
et pagesize ets the maximum number of
lines per page.
et newpage ets the number of blank lines
between pages.
pool Moves a report you would
normally see displayed on the
screen into a files, so you
can print it.
** Marks the beginning and end
of a comment within a QL
query. imilar to remark.
-- Marks the beginning of an
inline comment within a QL
query. Treats everything
from the mark to the end of
the line a s a comment.
imilar to remark.
et pause Makes screen display stop
between pages of display.
ave ave the QL query you¶re
creating into the file of your
choice.
Host ends any command to the
host operating system.
Edit Pops you out of QLPLU
and into an editor of your
choice.
Abstract ‘atatype
Example :-
QL> Create or replace type address_ty as object
(street_no number(3), street_name varchar2(20), city
varchar2(20), state varchar2(20));
The above syntax creates a type named as address_ty
hmplementing object type as a column object.
QL> Create table emp (eno number(3), ename
varchar2(25),address address_ty, salary number(8,2));
hnserting records into Abstract ‘ata types
QL> insert into emp
values(101,¶ athya¶,address_ty(110,¶first t,
¶chennai¶,¶tn¶),15000);
electing from Abstract ‘ata types
QL> elect ename,e.address.street_no,
e.address.street_name from emp e;
Updating records in Abstract ‘ata types
QL> update emp e set e.address.street_no = 20 where
e.address.street_no=10;
‘eleting records in Abstract ‘ata types
QL> delete from emp e
where e.address.street_no=10;
‘ropping object Types
QL > drop type address_ty;
*
ERROR at line 1:
ORA - 02303: cannot drop or replace a type with type or
table dependents.
ince the type is used by the table and table is not
dropped the user cannot drop the type. But oracle as a
FORCE clause to drop the type even dependencies are
there.
QL> drop type address_ty force;
hndexing Abstract data type attributes
QL> create index streetnum on emp
(address.street_no);
Varying Arrays :-
These help in storing repeating attributes of a
record in a single row. Varray cannot be extended
beyond the limit that was defined when the varray was
created.
Creating Varrays
QL > create type itemcode as varray(5) of varchar2(5);
QL > create type qty_ord as varray(5) of number(5);
QL > create type qty_deld as varray(5) of number(5);
hmplementing Varray in table
QL> Create table order_detail(order_no varchar2(5),
item_va itemcode, qty_va qty_ord, qtyd qty_deld);
hnserting records into Varrays :-
QL > insert into order_detail values
(µo100¶,itemcode(µi100¶,¶i101,¶i102¶,¶i103¶,¶i104¶),
qty_ord(100,980,900,800,1000),
qty_deld(100,900,800,700, 600));
electing the data from varray:-
QL> select item_va from order_detail;
Nested Tables :-
Varying arrays are used to create collectors
within the tables and data types. Varying arrays have a
limited number of entries, whereas   have
no limit on the number of entries per row. A nested
table is table within a table. A   is represented as a

 within another table.
Let us assume that the table contains a structure as
shown below:
Column Type
Book_hd Varchar2(15)
Book_Name Varchar2(30)
Author_Name Varchar2(30)
Publications Varchar2(30)
Price Number(8,2)
For each book an unique id is maintained and that is
Book_hd . For example ORA001 is hd assigned for
oracle books. hf the user uses the Varray there is a
limitation to specify the maximum limit.
The user don¶t know how many books will be
purchased so he cannot give the maximum limit. This
drawback can be removed with the help of nested
tables. Let us see how to create a nested table.
QL> create type book_ty as object(book_name
varchar2(30),author_name varchar2(30),publications
varchar2(30),price number(8,2));
type is created.
The book_ty contains a record for each book. To use
this datatype as the basis for a nested table a new
abstract data type has to be created and is as shown
below.
QL> Create type book as table of book_ty;
Type created is the output for the above command.
The Ú

 clause tells oracle that this type will
be used as the basis of a nested table. This type i.e.,
book_ty can be used to create a table i.e., book_details
Example :-
QL> Create table book_details(book_id varchar2(15),
book_particulars book)nested table book_particulars
store as nested_book_details;
The output of the above command is table created.
Book_id is an ordinary column which is of varchar2
data type in the table book_details
Book_particulars is the nested table column in the
table book_details.
The user has to specify that the column is a nested
table column by specifying nested table keyword
hnserting records into a nested table :-
QL > insert into book_details values
(µ&book_id¶,book(book_ty(µ&book_name¶,¶&author
_name¶,¶&publications¶,&price)));
Uses of  keyword :-
Previous example is how to insert record into the table
which consist of nested table column first time. hf the
user want to insert record only to the nested table not
to the main table then user has to for  keyword.
Assume that 3 books has purchased for oracle and the
user has to insert the details of those books then
Example :-
QL > insert into the (select book_particulars from
book_details where book_id=µORA001¶)
values(book_ty(µHow-To Oracle8¶
,¶John¶,¶BPB¶,500));
electing records from the nested table:-
QL > select a.book_name,a.author_name from
the(select book_particulars from book_details) a;
Updating the records in the nested table :-
QL> update the (select book_particulars from
book_details where book_code =µORA001¶) set price=
595 where book_name=µHow-To Oracle8¶;
Uses of á  and 4 keyword
hf the user want to insert the same set of records in
nested table then the user can go for á  and
4 keyword.
For example in a library there will be more than one
book of the same series the user has to maintain the
details of all the books then.
Example :-
QL > insert into the (select book_particulars from
book_details where book_id=µVB001¶)
values(book_ty(µVisual Basic 6 Programming Black
Book¶ ,¶ teven Holzner¶,¶dream tech Press¶,475));
Later on the same book has purchased that details has
to be maintained.
Example :-
QL > insert into book_details values (µVB002¶ ,cast
(multiset (select * from the (select book_particulars
from book_details where book_id=µVB001¶)) as
book));
hntroduction to PL QL
PL QL tands for Procedural Language QL.
PL QL extends QL by adding control structures
found in other procedural language.
Advantages of PL QL
s upports the declaration and manipulation of objects
s Allows the calling of external functions and
procedures
s Contains new libraries of built - in packages
Architecture of PL QL
The PL QL engine executes PL QL blocks.
The PL QL engine executes only the procedural
statements and sends the QL statements to the QL
statement executor in the Oracle server. The PL QL
engine can either reside in the Oracle server or on
Oracle tools such as Oracle Forms 5, Reports 3.
hntroduction to PL QL block
A PL QL block can be divided into three parts,
namely, a declarative part, an executable part and an
exception handling part. The order is as shown below:
‘ECLARE
declarations
BEGhN
executable statements
EXCEPThON
handlers
EN‘;
Before proceeding to learn about the above three parts,
we need to have a brief idea on the character set and
lexical units used in the PL QL block
The PL QL character set includes the following:
• Upper and lower case letters. They are not case
sensitive except within strings and character literals.
• Numerals from 0 to 9.
• All special symbols and characters.
• Tab, space and carriage return.
PL QL text can contain groups of characters known
as lexical units. The following are the lexical units:
• hdentifiers
• Literals
• Comments
• ‘elimiters (simple and compound symbols)
Example:
Total :=salary * 0.90; -- to compute total
hn the above example,
total and salary ---------- identifiers
* and ; ---------- simple symbols
:= ---------- compound symbols
0.90 ---------- numeric literals
-- ----------- represents comment
ome of the simple symbols are
+,-,*, ,=,<,>,% (attribute indicator)
;(statement terminator) and : (host variable indicator).
The compound symbols consist of two characters like
< >,!=,:=(assignment), || (concatenation),
-- (single line comment), ** ( exponentiation),
* * (multi line comment),<<>>(label delimiter)
‘atatypes Used in PL QL
s Boolean
s Binary_integer ( used to store signed integer)
s Number (‘ec decimal, hnt integer Real)
s Varchar2 (4000 bytes), char(2000 bytes) Long
(32,760 bytes)
s Raw (types are used to store binary data)
s Rowid
s Composite Types (Collections and objects can be
used in PL QL)
s LOB Types (BLOB, CLOB, BFhLE)
Attributes
Attributes allow us to refer datatypes and objects
from the database. PL QL Variables and constants can
have attributes. The following are the types of attributes
by PL QL
s%type
s %rowtype
%Type:
%type attribute is used when declaring that refer
to the database columns. Consider the following
example where a called vcode is declared to be of type
vencode in the item table using %type attribute.
Example:
declare
enum emp.eno%type;
where enum is the variable name, emp is the name of the
table and eno is the name of the column.
The advantages of using %Type is,
s We need not know the exact type of the column
s hf the database definition is changed, then the data type
of the variable changes accordingly at run time.
%Rowtype
%Rowtype attribute provides a record type that
represents a row in a table. The record can store an entire
row of data selected from the table or fetched by a
cursor.
hn the following example, a record named µvend_inf¶
will have the same names and datatypes as the columns
in the customer table.
Example
‘eclare
vend_inf vendor_master%rowtype;
hn the above example, vend_inf stores a row selected
from the vendor_master table.
Logical Comparisons
PL QL supports the comparison of variables and
constants in QL and PL QL statements.
These comparisons, µBoolean expressions¶, are often
connected by logical operators AN‘,OR and NOT.
Control tructures
hn addition to QL commands,PL QL can also
process data using flow of control statements. The flow
of control statements can be classified under the
following categories :
s Conditional Control
s hterative Control
s equential Control
Conditional control
equence of statements can be executed based on a
certain condition using the statements, namely 
%%and %(The simplest form
of an  statement is the % statement . The syntax
is
%
;
 #
#
Example
‘eclare
orderstatus order_master.ostatus%type;
Begin
select ostatus into orderstatus from
order_master where orderno=µo001¶;
if orderstatus =µp¶ then
update order_master set odate=
µ01-jan-99¶where orderno=µo001¶;
Else
update order_master set odate=
µ26-jan-99¶ where orderno=µo001¶;
end if;
End;
the output of the above command is,
PL QL procedure successfully completed.
hterative control
A sequence of statements can be executed any
number of times using loop constructs. Loops can be
classified into
s imple Loop
s For Loop
s While Loop
imple Loop
The keyword should be placed before the
first statement in the sequence and the keyword 
 after the last statement in the sequence.
yntax for a simple loop is:
loop
--sequence of statements;
end loop;
Example
‘eclare
a number:=100;
Begin
Loop
a:=a+25;
exit when a=250;
End Loop;
dbms_output.put_line(a);
End;
While Loop
The /%statement includes a condition
associated with a sequence of statement. hf the
condition evaluates to true, then the sequence of
statements will be executed, and again control
resumes at the beginning of the loop. hf the condition
evaluates to false, then the loop is bypassed and the
control passes to the next statement.
yntax for a while loop
while <condition>
loop
sequence_of_statements;
end loop;
Example
QL> declare
i number:=0;
j number:=0;
Begin
while i<=100 loop
j:=j+i;
h:=h+2;
end loop;
dbms_output.put_line(µThe value of j is ¶ || j)¶
end;
The output of the above PL QL procedure is
given below.
The value of j is 2550
PL QL procedure successfully completed.
FOR Loop
The number of iterations for a '% loop is
unknown until the loop terminates, whereas the number
of iterations in a loop is known before the loop gets
executed.
The syntax is given below.
For counter in ,[REVER E] lower bound ..Upper bound
loop
sequence_of_statements
end loop;
Example
Begin
For h in Reverse 100..1
Loop
‘BM _OUTPUT.PUT_LhNE(h);
End Loop;
End;
Example

Begin
for i in 1..2
loop
update order_master set ostatus =µp¶
where odate<sysdate;
end loop;
end;
equential Control:
The  statement allows to branch label unconditionally.
The label which is enclosed with angle brackets must
precede an executable QL, statement a PL QL block.
When executed the statement transfers control to the
labeled statement or block.
Example:
‘eclare
qtyhand itemfile.qty_hand%type;
relevel itemfile.re_level%type;
Begin
select qty_hand,re_level into qtyhand,relevel
from itemfile where itemcode=µi201¶;
hf qtyhand < relevel then
goto updation;
End hf;
<< updation>>
update itemfile set qty_hand=qty_hand +relevel
where itemcode = µi201µ;
End;
Concept of Error Handling:
Error condition in PL QL is termed as an
exception, There are 2 types of exceptions They are:
Predefined Exception
User-defined Exception
Predefined Exception
An exception is raised implicitly when a PL QL
program violates Oracle rule. The following are the
predefined exceptions supported by PL QL
No_data_found Zero_‘ivide
Cursor_already_open hnvalid_Cursor
‘up_val_on_index Program_error
Login_denied torage_Error
hnvalid _number Too_many_rows
Example:
declare
qtyhand itemfile.qty_hand%type;
relevel itemfile.re_level%type;
begin
select qty_hand,re_level into qtyhand,relevel
from itemfile where itemcode=µi100¶;
Exception
when no_data_found then
dbms_output.put_line(µsuch an item number
not avaliable¶);
End;
User defined Exception
declare
lo_value exception;
qty_hand itemfile.qty_hand%type;
begin
select qty_hand into qtyhand from
itemfile where itemcode=µi201¶;
hf qty_hand < 200 then
raise lo_value;
End hf;
Exception
when lo_value then
dbms_output.put_line(µquantity not enough¶);
End;
Cursor Management
Oracle allocates an area of memory known as 
 for the processing of QL statements. The
context area contains information necessary to
complete the processing, including the number of rows
processed by the statement.
A cursor is a handle or pointer to the context area.The
three types of cursors are
s Explicit Cursor
shmplicit Cursor
An Explicit Cursor is one in which the cursor name is
explicitly assigned to the select statement.
An implicit cursor is used for all other QL statements.
Processing an explicit cursor involves 4 steps.
Processing of an implicit cursor is taken care by
PL QL. The declaration of the cursor is done in the
declarative part of the block.
A cursor variable is a reference type. A reference type
is similar to a pointer. ht can name different storage
locations as the program runs.
Explicit Cursor
The set of rows returned by a query can
contain zero or multiple rows depending upon the
query defined. These rows are called the -(
After declaring a cursor, we can use the following
commands to control the cursor.
s Open
s Fetch
s Close
The µOpen¶ statement executes the query, identifies the
active set and positions the cursor before the first row.
The syntax is
open <Cursor name>;
The µfetch¶ statement retrieves the current row and
advances the cursor to the next row to fetch the
remaining rows. yntax for µfetch¶ is
fetch <Cursor name> into <column name>;
After processing the last row in the active set, the
cursor is disabled with the help of the µclose¶
command. The syntax is as follows.
close <Cursor name>;
Example for an Explicit Cursor:
declare
icode order_detail.itemcode%type;
cursor a is select itemcode from
order_detail where itemcode =µi201¶;
begin
open a;
Loop
fetch a into icode;
update itemfile set itemrate=22.05
where itemcode=icode;
exit when a%NOTFOUN‘;
End Loop;
dbms_output.put_line(µtable updated¶);
Close a;
End;
Attributes in Explicit & hmplicit Cursor
s %notfound
s%found
s%rowcount
s%isopen
%Notfound
The attribute %notfound indicates fetch
statement returns from the active set. hf the last fetch
fails to return a row,then %notfound evaluates to
true,else it evaluates to false.
Example for a %notfound Attribute
‘eclare
order_no order_detail.orderno%type;
cursor a is select orderno from order_detail
where orderno=µo001¶;
Begin
Open a;
Loop
Fetch a into order_no;
Update order_master set del_date=
sysdate where orderno=order_no;
Exit When a%NOTFOUN‘;
End Loop;
Close a;
End;
%Found
The %found attribute is the logical opposite of
%notfound. ht evaluates to true if the last Fetch
statement returns at least one record.
%Rowcont
The %rowcount attribute is used to return the
number of rows fetched. Before the first fetch
%rowcount is 0.
When the fetch statement returns a row, then the
number is incremented.
Example to illustrate %Rowcount
declare
cursor a is select * from order_detail where
orderno=µo001¶;
myorder order_detail%rowtype;
begin
open a;
loop
fetch a into myorder;
exit when %Notfound;
dbms_output.put_line(µfetched¶ || a%rowcount || µ from
table¶);
Example to illustrate %hsopen
declare
cursor mycur is select * from order_master;
begin
if not mycur%isopen then
dbms_output.put_line(µthe cursor is yet o be
opened¶);
end if;
open mycur;
if mycur%isopen then
dbms_output.put_line(µthe cursor is now
opened¶);
end if;
close mycur;
end;
hmplicit Cursor
PL QL implicitly declares cursors for all
QL data manipulation statements, including
queries that return one row. For queries that return
more than one row, we should use explicit cursors
to access the rows individually.
hmplicit cursor attributes can be
 
  
%

+ ( The most recently executed QL
statement is referred as µ QLCUR OR¶.
Example for %Notfound attribute (hmplicit Cursor)
begin
delete from order_detail where orderno =µo201¶;
if sql%NOTFOUN‘ then
dbms_output.put_line(µvalue not found¶);
else
dbms_output.put_line(µvalue found and
deleted¶);
end if;
end;
Example for %Rowcount attribute (hmplicit Cursor)
declare
order_no order_master.orderno%type;
begin
select orderno into order_no from order_master
where orderno=µo001¶;
if sql%ROWCOUNT > 0 then
dbms_output.put_line(µrows selected from
table¶);
else
dbms_output.put_line(µ no rows selected from
table¶);
end if;
end;
Cursor For Loop
A µcursor for¶ loop can be used instead of explicit
cursors to simplify coding. A µcursor for¶ loop
implicitly opens a cursor, repeatedly fetches rows from
the active set, and then, closes the cursor when all rows
have been processed.
The syntax for the µcursor for¶ loop is as follows.

For <record_name> in <cursor name> loop


sequence of statements;
end loop;
XYZ enterprise would like to delete those rows from
the database whose orders have been fulfilled to the
extent they have ordered. Also the deletion would
depend on the vendor also. This they achieved as
shown below.
Example
declare
cursor for_cur is select orderno from order_master
where vencode = µv002¶;
cust_rec for_cur%rowtype;
begin
for cust_rec in for_cur loop
delete from order_detail
where orderno=cust_rec.orderno;
end loop;
dbms_output.put_line(µdetails has been deleted¶);
end;
ubprograms & Packages
ubprograms
ubprograms are named PL QL blocks that can
accept parameters and can be invoked whenever
required. imilar to a PL QL block, a subprogram can
also have a declarative part, an executable part and an
exception handling part. ome of the important features
offered by subprograms are given below.
s Modularity - ubprograms allow us to break a program
into manageable, well-defined logical modules.
s Reusability - ubprograms once executed can be used
in any number of applications
Maintainability - ubprograms can simplify
maintenance, because if a subprogram is affected,
only its definition changes.
PL QL supports two types of subprograms. They
are:
s Procedures
s Functions
Procedures are usually used to perform any specific
task and functions are used to compute a value.
Procedures
A procedure is a subprogram that performs a
specific action. The syntax for creating a procedure is
given below.
  
A 
N  O
   #
 
N
  O
NO % 
#
A procedure has two parts, namely,  and
(The procedure specification begins with the
procedure name or parameter list. The procedure body
begins with the keyword and ends with keyword
. ht can also include   -
  and
   within the keyword (
yntax to execute a procedure is given below.
QL> exec <proce_name>(parameters);
While declaring variables in the declarative part of the
procedure body, we should not specify the width of the
datatype, For example,
Procedure width (name char(40)) is
begin
(set of statements);
end;
hn the above example, char(40) should be replaced by
char. The example shown below explains the usage of
procedure. ht accepts a single parameter and updated
the table based on a condition . ht also arises an
exception if no data is retrieved.
Example
create or replace procedure items (orders varchar2))
is
qtyhand number;
relevel number;
maxlevel number;
begin
select qty_hand,re_level, max_level into
qtyhand,relevel,maxlevel from itemfile where
itemcode=orders;
hf qtyhand<relevel then
update itemfile set qty_hand=relevel + qtyhand
where itemcode=orders;
else
dbms_output.put_line(µitem level ok¶);
end if;
Exception
when no_data_found then
dbms_output.put_line(µno data returned¶);
end;
Execution of the procedure
QL> exec items(µi201¶)
when the above command is given the procedure is
executed and the output is given as shown below.
PL QL procedure completed successfully.
Modes in Parameters
The parameter list(defined in the create procedure
command) can hold any of the following modes
s in ( by default)
s out
sinout
hn parameter
The in parameter mode is used to pass values to
the subprogram when invoked. ht acts like a constant and
therefore it cannot be assigned a value.
Example for in parameter mode
create or replace procedure orders(a in varchar2) is
v_code varchar2(5);
o_stat char(1);
begin
select vencode,ostatus into v_code,o_stat
from order_master where orderno=a;
if o_stat=µp¶ then
dbms_output.put_line(µpending order ¶ || a);
else
dbms_output.put_line(µcompleted order µ || a);
end if;
end;
On compilation the user will get the message
8
 
QL> exec orders(µo001¶);
Out Parameter
The 
 parameter mode is used to return values to the
caller of a subprogram. ince the initial value for an 

parameter is undefined, its value can be assigned to
another variable.
Example
create or replace procedure test(a in varchar2,
b out number) is
identity number;
begin
select qty_ord into identity from order_detail
where orderno=a;
if identity <450 then
b:=100;
end if;
end;
After compilation of the above program procedure is
created.
Execution of the above Procedure
declare
a varchar2(5);
b number;
begin
test(µo202¶,b);
dbms_output.put_line(µthe value of b is µ ||
to_char(b));
end;
The value of b is 100 is the output of the above program
hn out Parameter
The 
 parameter is used to pass initial values
to the subprogram when invoked and it also returns
updated values to the caller. An 
 parameter acts
like an initialized variable and, therefore, can be
assigned to other variables or to itself.
Example
create or replace procedure or_detail(orno in
varchar2,b in out varchar2) is
qtyord number;
qtydeld number;
code varchar2(5);
Begin
select qty_ord,qty_deld,itemcode into
qtyord,qtydeld,code from order_detail
where orderno=no;
if qtydeld <qtyord then
b:=code;
end if;
end;
The output of the above program is 

 (To execute the above procedure a block as
shown below is written and executed.
‘eclare
a varchar2(5);
b varchar2(5);
begin
or_detail(µo202¶,b);
dbms_output.put_line(µthe item code is µ || b);
end;
The output of the above program is
the item code is i201
PL QL procedure successfully completed.
Functions
A function is a subprogram that computes a value.
The syntax for creating a function is given below.
Create or replace function <function_name>[argument]
return datatype is
(local declaration)
begin
(executable statements)
[Exception]
(exception handlers)
end;
Example
create or replace function items(it varchar2)
return number is
args number;
qtyhand number;
relevel number;
maxlevel number;
begin
select qty_hand,re_level,max_level into
qtyhand,relevel,maxlevel from itemfile
where itemcode=it;
hf (qtyhand-relevel ) > maxlevel then
args:=maxlevel;
return args;
else
args:=(qtyhand+relevel);
return args;
end if;
end;
The output of the above block of code is,
K
 (
To execute the function items the following block of
code is executed,
declare
a varchar2(5);
b number;
begin
a:=&a;
b:=items(a);
dbms_output.put_line(µthe value returned is µ || b);
end;
The output of the above program is
Enter the value for b: i201
old 5: b:=&b;
new 5: b:=µi201¶;
the value returned is 140
PL QL procedure successfully completed.
Packages
A package is a database object, which is an
encapsulation of related PL QL types, subprograms,
cursors, exceptions,variables and constants. ht consists
of two parts, a R ››
 and a ( hn the R
›

R ››
 ›
 ›
R 

 ›

› R›  
R 
 A package body
implements ›  R 
 defined in the
R
›
R ››

Note
š Packages cannot be called, hence, we cannot pass
parameters as we do in subprograms. Nesting of
packages is also not possible
Packages can be created using the following commands.
s Create Package command
s Create Package body command.
The R
›
R ››
 is  ›
 using a ›
 
R
›
 command.

 ›
 R
›
›

create package <package_name> is <declarations>
begin
(executable statements);
end [package name];
The procedures and cursors declared in the µcreate
package¶ command is fully defined and implemented by
the package body.

›
 
R
›

create package body <package_name> is declarations
begin
(executable statements)
end [body_name]
Example for Package pecification
Create or replace package pack_me is
procedure order_proc(orno varchar2);
function order_fun(ornos varchar2) return
varchar2;
end pack_me;

The output of the above package on successful


compilation is,
R
›

 
The package body is coded as given below
Example for Package body
create or replace package body pack_me as
procedure order_proc(orno varchar2) is
stat char(1);
begin
select ostatus into stat from order_master
where orderno=orno;
if stat=µp¶ then
dbms_output.put_line(µpending order¶);
else
dbms_output.put_line(µcompleted order¶);
end if;
Function order_fun(ornos varchar2) return varchar2 is
icode varchar2(5);
ocode varchar2(5);
qtyord number;
qtydeld number;
begin
select qty_ord,qty_deld,itemcode,orderno
into qtyord,qtydeld,icode,ocode from order_detail
where orderno=ornos;
if qtyord<qtydeld then
return ocode;
else
return icode;
end if;
end order_fun;
end pack_me;
The output of the above block of code when compiled is
R
›
›
 
Calling packaged subprograms
To reference the types, objects and subprograms
declared in a package specification the following
notation is used.

›

R 


›

 ›


›

R 


To execute the above package
QL> exec pack_me.order_no(µo001¶);
The output of the above QL command is
completed order
PL QL procedure successfully completed.
To execute the function that is given in the package a
block of code is written as shown below,
‘eclare
a varchar2(5);
b varchar2(5);
begin
b:=pack_me.order_fun(µ0202¶);
dbms_output.put_line(µthe value is µ || b);
end;

The output of the above program is,


the value is i201
PL QL procedure successfully completed.
‘atabase Triggers
A database trigger is a stored procedure that is fired
when an insert,update or delete statement is issued
against the associated table. ‘atabase triggers can be
used for the following purposes.
s To generate data automatically.
s To enforce complex integrity constraints.(e.g.
checking with sysdate, checking with data in another
table).
sTo customize complex security authorizations.
sTo maintain replicate tables.
sTo audit data modifications
yntax for creating triggers
The syntax for creating a trigger is given below.
Create or replace trigger <trigger_name>
[before after] [insert update delete] on
<table_name> [for each statement for each
row][when condition];
A database trigger can also have declarative and
exception handling parts.
Parts of a triggers
A database trigger has three parts, namely, a   

 
  

    ›
Trigger tatement
A trigger statement specifies the ‘ML statements
like update,delete and insert and it fires the trigger body.
ht also specifies the table to which the trigger is
associated.
Trigger Body
Trigger body is a PL QL block that is executed
when a triggering statement is issued
Trigger Restriction
Restriction on a trigger can be achieved using the
WHEN clause as shown in the syntax for creating
triggers. They can be included in the definition of a row
trigger, wherein the condition in the WHEN clause is
evaluated for each row that is affected by the trigger.
Note
• A subquery cannot be included
Types of Triggers
Before
After
for each row
for each statement
Before After Options
The Before After options can be used to specify
when the trigger body should be fired with respect to the
triggering statement. hf the user includes a before option,
then, Oracle fires the trigger before executing the trigger
statement. On the other hand, if AFTER is used, then,
Oracle fires the trigger after executing the triggering
statement.
For Each Row tatement
When the for each row statement option when
included in the µcreate trigger¶ syntax specifies that the
trigger fires once per row. By default, a database trigger
fires for each statement.
Using the combination of the above options we can
assign 12 types of triggers to a database table.
s Before Update row statement
s Before ‘elete row statement
s Before hnsert row statement
s After Update row statement
s After insert row statement
s After ‘elete row statement
Apart from above types of the Triggers one more type
is there that is 
this, trigger can be applied
only to views and not for tables and it can be defined
only in Row-Level and not in tatement Level.
Example
create or replace trigger orders before insert on
order_detail for each row
declare
orno order_detail.orderno%type;
begin
select orderno into orno from order_detail
where qty_ord<qty_deld;
if orno =µo001¶ then
raise_application_error(-20001,¶enter some
other number¶);
end if;
end;
There are two variables namely, :and 'which
retain the old and new values of the column updated in
the database. The values in these variables can be used
in database triggers for manipulation.
Example using  and  variable
create or replace trigger new_old_trig before
update on itemfile for each row
begin
if :new.qty_hand<:old.qty_hand then
raise_application_error(- 20001,
¶QUNAThTY ON HAN‘ h LE ¶);
end if;
end;
hnstead of Triggers
hn Oracle8 there is something new in the world of
triggers. hN TEA‘ OF triggers. These are the triggers
that are defined on a view rather than on a table. uch
triggers can be used to overcome the restrictions placed
by Oracle on any view, which is deemed to be non-
updateable. Prior to version 7.3 it was impossible to
issue ‘ML statements -hN ERT,UP‘ATE,‘ELETE -
against any view which contained a join.
There are few restrictions on hN TEA‘ OF triggers
s They are available only at the row level and not at the
statement level
s They can be applied only to view and not to tables.
Creating view with Joins
create view ord_view as select
order_master.order_no,order_master.ostatus,
order_detail.qty_‘eld,order_detail.qty_ord from
order_master,order_detail where
order_master.order_no=order_detail.order_no
the above view is created with joins
Create or replace trigger order_mast_insert
hN TEA‘ OF insert on ord_view referencing new as n
for each row
declare
cursor ecur is select * from order_master
where order_master.order_no = :n.orderno;
cursor dcur is select * from order_detail
where order_detail.order_no=:n.orderno;
a ecur%rowtype;
b dcur%rowtype;
begin
open ecur;
open dcur;
fetch ecur into a;
fetch dcur into b;
if dcur%notfound then
insert into order_master(orderno,o_status)
values(:n.orderno,:n.o_status);
else
update order_master set
order_master.o_status=:n.o_status where
order_master.orderno=:n.orderno;
end if;
if ecur%notfound then
insert into order_detail
(qty_ord,qty_deld,ordern)
values(:n.qty_ord:n.qty_deld,:n.ordern);
else
update order_detail set
order_detail.qty_deld=:n.qty_deld where
order_detail.ordernoo=:n.orderno;
end if;
end;
Enabling and ‘isabling Triggers
alter table order_master disable order_mast_insert;
To disable all the triggers syntax is
alter table <table-name> disable all triggers;
To enable all the triggers syntax is
alter table <table-name> enable all triggers;
‘ropping Triggers
drop trigger <trigger_name>;