Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
100% found this document useful (4 votes)
3K views

Oracle PLSQL Notes

1. A database is a collection of organized data stored in tables with rows and columns. Data is stored in database objects like tables. Tables have fields defined by data types and records are inserted into the fields as rows. 2. Oracle is a popular database software that provides relational and object-oriented features. It allows relationships between tables and bundles data into objects with properties like inheritance and encapsulation. 3. Data arrangement and integrity is ensured through normalization which uses constraints to restrict data and establish relationships between objects. Common database objects in Oracle include tables, views, indexes, and sequences.

Uploaded by

datastage_dwh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
100% found this document useful (4 votes)
3K views

Oracle PLSQL Notes

1. A database is a collection of organized data stored in tables with rows and columns. Data is stored in database objects like tables. Tables have fields defined by data types and records are inserted into the fields as rows. 2. Oracle is a popular database software that provides relational and object-oriented features. It allows relationships between tables and bundles data into objects with properties like inheritance and encapsulation. 3. Data arrangement and integrity is ensured through normalization which uses constraints to restrict data and establish relationships between objects. Common database objects in Oracle include tables, views, indexes, and sequences.

Uploaded by

datastage_dwh
Copyright
© Attribution Non-Commercial (BY-NC)
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 59

Database:-

It’s a collection of organized data where the data will be stored in


the form of rows and columns. Where each row is a called a record
and each column is a field. In the database the data is stored in the
objects, which are called the database objects. So first the objects
should be created and in order to create an object the data is to be
defined and that data should be defined in the form of columns and
those are called fields. After defining the fields the rows or records
can be inserted dynamically.
Oracle:-
Oracle is a package, which is developed by Sir E F Codd in 1969 and
implemented by Oracle Corporation in 1971. But this has got the
recognition of ANSI and ISO in 1979 and used as the most popular
database application by the programmers. This is a ORDBMS (Object
Relational DataBase Management System) where DBMS is a software
by using which the data can be
1.Defined
2.Inserted
3.Stored
4.Accesed
5.Deleted etc.
Oracle provides two additional features, which are
1.Relational:-This feature allows the user to establish a relationship
between more than one database objects .The relation can be any of
the following types.
1.One to One.
2.One to Many.
3.Many to One.

2.Object:- By using the objects a set of related data can be bundled


and their features can be available to any database objects later
on. This object concept supports three main features. Those are:-
1.Inheritance (Attaining property of one object to another)
2.Encapsulation:-(Wrapping up of different types of data into a single
bundle.)
3.Polymorphisim (Using a data for more than one purpose)

Normalization:-
In an application development cycle arrangement of data takes an
important role. This arrangement should be done by keeping all the
data and their activities in mind. This process is called normalization.
This normalization can be done by using the constraints which are
used to restrict the data to a particular extent and also by
establishing the relationship between two different data. There are
two types of constraints: -
1.Integrity constraints (To establish the data integrity in an object)
2.Referencial constraint (To establish relationship between the data
of more than one objects).
Maintenance of data in oracle database:-
Data can be maintained in the database by using some objects, which
are called database objects. There are 6 different objects in the
database: -
1.Table
2.View
3.Sequence
4.Index
5.Cluster
6.Synonym
But among all these the table is the main object and the rest of all
need the help of the table to function themselves.
Oracle is a software based on client-server technology where
database the server and though it can accessed by any number of
users each called the clients. So in order to login oracle we must
have to be connected with the database through any of the users.
There are 6 users, which will be created by default while installing
oracle. Those are
1.scott , 2.system, 3.Demo ,4.sys ,5.po8 6.dbsnmp
To store the data in the database first we have to create any of the
database objects.
There are 4 major components in oracle application which are
1.Sql 2.Pl/SQL 3.SQL*PLUS 4.Dev-2000

1.SQL: -
This is a non-procedural structure oriented language because it
follows some particular syntax. This is developed by E F Codd and
earlier known as SEQUEL.There 3 types of languages in SQL,which
are

1.Data definition lang:-Used to define the and remove the definition


of data.There are 4 commands in this language having different
purposes.
1.create 2.drop 3.Alter 4.Truncate

2.Data manipulation lang:-Used to make any manipulation or


changes over the existing data having 3 commands in it
1.insert 2.update 3.Delete

3.Data/Transaction control language:-The commands in this


language can further devided into two more parts.
1.Non data base comands:-Not related to the database directly and
those are
1.select 2.commit 3.Rollback 4.savepoint
2.Database commands:-Related directly to the database and those
are
1.grant 2.revoke
In addition to all these one more SQL command is there which does
not undergo any of the commands.That is “rename”.

While creating a table at first we have to define the fields each


according to their datatypes.There are different types of data we use
in our day to day life and oracle also provide some datatypes to deal
with those data.
A.Character data:-
1.char(w):-This is a fixed length character data type where any
character data upto 255 characters can be stored. The default width
for a character data is 1.
2.varchar2(w) :-This is a variable length character data type which
can accept maximum 2000 characters into it.
Ch varchar2
3.long:-This is also variable length character data type which can
accept maximum 2gb data into it. This is generally used for storing
large data like resumes, receipts etc. But only one long field is
allowed per a table.
B.Numeric data:-
1.number(w):-This data type accept any numeric data upto 39
digits.If any decimal data is to be stored in a field of number data
type that can be stored in the form of number(n,m). Where n is the
total width for the field ,m for the decimal number and n-m for the
whole part.
2.smallint:-To store only whole numbers.
3.float:-To store the floating point i.e. very large or very small
values.
C.Date data:-
1.date:-Used to store any data data between 1st jan 4712 bc to 31st
dec 4712 ad in the format ‘dd-mon-yy’ .
D.Pictures and graphical data:-
1.Raw:-Used to store the pricture data upto 256 character length.
2.Long raw:-Used to store picture and graphical data of large size
and stores upto 2gb .Only one long raw is allowed per a table.

E. Large objects:-
1.BLOB:-Binary large object
2.CLOB:-Character large object
3.NCLOB:-National character large object

Creating a table:-
A table can be created by using “create table” command as the
following syntax:-
syntax:-
create table <<tablename>>(field1 datatype(w),field2
datatype(w),...............,fieldn datatype(w) );
Ex:-
A. create table your_table(name varchar2(15),last_name
varchar2(12),
do_birth date,age number(3),address1 varchar2(20),address2
varchar2(20));

2. create table stud_01(rollno number(3),name varchar2(10),


doj date,marks1 number(3),marks2 number(3),marks4 number(3));

Whenever oracle is installed it creates 4 tables by default. Those are


1.emp 2.dept 3.salgrade 4.bonus
Note:-
1.A table name can be any name without a space and it should be
unique the current user. It does not allow any special symbols in
it except the underscore ( _ ).
2.Every SQL commands should end with a semicolon.
B.Alter:-Used to change the structure of a table created. It can be
done in three ways.
1.Adding new fields:-
syntax:-alter table <<tab name>> add (f1 dtype(w),f2
dtype(w),.......);
ex:-alter table stud add (tot number(3),avr number(5,2));
2.Changing the width of existing fields:-Width of an existing field can
be increased and also can be decreased if the table is empty.
syntax:-alter table <<tab name>> modify (f1 dtype(new width),f2
dtype(new width));
ex:-alter table stud modify(tot number(4),avr number(6,2));
3.To drop a column:-
syntax:-alter table <<tab name>> drop(col name);

C.Drop:-Used to remove the existence of a table in the database.


syntax:-drop table <<tab name>>;
ex:-drop table stud;

D.Truncate:-Used to delete all the records from a table permanently.


syntax:-Truncate table <<tab name>>;
ex:-truncate table stud;

B.Data manipulation commands:-

1.Insert:-Used to insert the records to an existing database table.


This can be done in 4 different ways:-
1.To insert all the values and for a single record:-
syntax:-insert into <<tab name>> values(f1val,f2val,....,fn val);
ex:-insert into stud values(101,’aaa’,45,66,78);
2.To insert for a few columns but for one record:-
syntax:-insert into <<tab name>> (f1,f2,f3,...) values(f1 val,f2 val,f3
val,...);
ex:-
a. insert into stud(rno,name,sub1,sub2,sub3)
Values(102,’aaa’,56,78,98);
b. insert into
stud(name,sub1,sub2,sub3,rno)values(‘cccc’,89,55,65,103);
3.For all the fields and more than one recs:-
syntax:-insert into <<tab name>> values(&f1,&f2,&f3,....);
ex:-insert into stud1 values(&rno,’&name’,&sub1,&sub2,&sub3);
4.For few fields and more than one recs:-
syntax:-insert into <<tab name>> (f1,f2,f3,...)
values(&f1,&f2,&f3,...);
ex:-insert into stud (rno,name) values(&rno,’&name’);
• To insert data from another table:-
Data to a table can be inserted from another existing table if the
structure of both are same.
syntax:-insert into <<tab name>> select */field names from
<<existing tab name>>;
ex:-
a.insert into stud(rno,name,sub1,sub2,sub3) select * from stud1;
b.insert into stud(rno,name) select rno,name from stud1;

2.Update:-
Used to update a field or column with any value or based on the data
of another field from the same or different table.
syntax:-
update <<table name>> set <<field name>> = <<value/expr
>>,<<field2>>= <<value/expr,..........., where condition;
The where condition sholud be given while updating a particular row
otherwise that is not necessary.
Ex:-update student set sname=’eeee’ where rollno=105
2. update student set
tot=sub1+sub2+sub3,avr=sub1+sub2+sub3/3;
By using logical operators:-
The logical operators ‘and’ and ‘or’ can be used with the condition to
combine more than one conditions.
ex:-
3.Delete:-Used to delete a record or more than one records
temporarily from the table.
syntax:-delete from <<table name>> where <<condition>>;
ex:-
1.delete from student where rollno=104;
2. delete from student;
Data control language commands:-
A.select :-
used for retriving the datas from a database object e.g. tables.
syntax:-
1.select * from <<table name>>;
----selects all the datas from a table.
2.select field1,field2,field3,..... from <tablename>>;
----selects the datas from a table only with the mentioned fields.
ex:-
1.select * from emp;
2.select rno,sname,tot,avr from stud;
B.commit:-
used to save the changes permanently to an object.
syntax:-
commit;
C.rollback:-
used to get the changes cancel out since the last commit . It acts just
like undo.
syntax:-rollback;

D.savepoint:-
allows to create a private area by the user which is saved
temporarily by means of which the user can rollback the changes up
to that particular point.
syntax:-savepoint <<savepoint name>>
ex:-savepoint s1;
while rolback:-
rolback to <<savepoint name>>
ex:-rollback to s1;

Logical operators:-
While giving the conditions by using where clause if more than one
condition are required for a query then logical operators can be used.
Those are
1.and 2.or
Truth table:-
and:-
cond1 cond2 res
T T T
T F F
F T F
F F F

OR:-
T T T
T F T
F T T
F F F

FOR RES AND DIV:-


UPDATE STUD SET RES=’PASS’ WHERE SUB1>=35 AND SUB2>=35
AND SUB3>=35;
UPDATE STUD SET RES=’FAIL’ WHERE SUB1<35 OR SUB2<35 OR
SUB3<35;
UPDATE STUD SET DIV=’FIRST’ WHERE RES=’PASS’ AND AVR>=60;
UPDATE STUD SET DIV=’SECOND’ WHERE RES=’PASS’ AND AVR>=50
AND AVR<60;
UPDATE STUD SET DIV=’THIRD’ WHERE RES=’PASS’ AND AVR>=35
AND AVR<50;

UPDATE STUD SET DIV=’NILL’ WHERE RES=’FAIL’;


Q.
CREATE A TABLE FOR EMPLOYEES WITH THE COLUMNS
ENO,ENAME,BASIC, HRA,DA,TA,PF,NSAL THE CALCULATE HRA OF
12%,DA OF 28%,TA OF 600 AND PF OF 10% THEN CALCULATE THE
NET SALARY.
symbols and operators:-
symbols:-
1. * :-stands for all.
2. & :-Address operator used to refer the location of the variable or
the field.
3.%:-Used for resembling the field values with a character.
operators:-
1.unary(the operators deal with a single field)
2.binary operator.
3.comparisonal operators.
Unary:-
+,-(signs)
2.binary opeartors:-the operators which deal with more than one
fields or variables.
e.g.+(add),-(sub),*(mul),/(div)
3.used for comparing the field values with any others.
e.g.
= (equal)
> (greater than)
< (Less than)
>= (Greater than or equals)
<=(Less than or equals)
!= (or) <> :-Not equals

Relational operators:-
a).IN:-Retrieves the data where the condition matches.
ex:-
1.SELECT * FROM EMP WHERE JOB IN ‘MANAGER’;
2.SELECT * FROM EMP WHERE DEPTNO IN (20,30);
NOT IN:-retrieves the row for which the condition does not match.
ex:- SELECT * FROM EMP WHERE JOB NOT IN (‘CLERK’,’MANAGER’);
b).BETWEEN:-Retrieves the data which lies in the range given by the
between operator.
ex:
1.SELECT * FROM EMP WHERE SAL BETWEEN 3000 AND 4000;
select * from emp where sal between 2000 and 3000;
not between(opp. of between).
ex:- SELECT * FROM EMP WHERE SAL NOT BETWEEN 3000 AND
5000;

c).LIKE:-Retrieves the data by using the meta characters(start letter,


end letter etc.).
ex:-SELECT * FROM EMP WHERE JOB LIKE ‘A%’;
2. SELECT * FROM EMP WHERE ENAME LIKE ‘%J__ES’;
3.SELECT * FROM EMP WHERE ENAME LIKE ‘%S’;
NOT LIKE(Opp. to like)
select * from emp where ename not like ‘A%’;

ORDER BY CLAUSE:-
This is used to retrieve the data from a table in ascending or
descending order.
syntax:-Select * from <<table name>> order by <<fieldname>>
asc/desc;
ex:-select * from emp order by sal asc
ex:- select * from emp order by ename desc;
Where asc is used for ascending order and desc for descending order
. But the default order is ascending.
Distinct:-Used to retrieve only the distinct(not repeated) rows from a
table.
ex:-select distinct * from list;

Retrieving the data based on an expression:-select * from table


name where cname=&cname;
----selects the records from a table for which the rno entered
satisfies.
ex:-select * from emp where empno=&empno;

CONSTRAINTS:-
Constraints are the clauses by using which the following features can
be added to a field of a table:-
1.preventing the insertion of duplicate rows into a column.
2.restricting the values with in a range.
3.Taking reference from one table to another table.
4.Not leaving a field as blank.
Basically Constraints are of two different types:-
a. Integrity constraints
b. Referential constraints
A. Integrity constraints:-

1.null:-allows to insert null values for a column which is a


default property of a column.
syntax:-column name dtype(w) null
ex:-create table con1(no number(3) NULL,name varchar2(10));

2.not null:-Does not allow to insert null values to a column.


syntax:-column name dtype(w) not null
Ex:- create table con1(no number(3) not null,name
varchar2(10));

3.primary key:-works as a not null constraint and also does not


allow repeated values for a field .From the field to which primary key
is associated, reference can be taken to other columns of the same or
different table.
Notes:-
1.Only one primary key can be associated with a particular table.
syntax:-column name dtype(w) constraints constr_name primary key
ex:-rno number(3) constraints rno_c primary key.
ex:- create table con1(no number(3) constraints pk1 primary key
,name varchar2(10));

4.unique:-This constraint designates a column as unique by means of


which
1. null values can be inserted
2. does not allow repeated values
3. reference can be taken to other tables from the column to
which it is associated.
4. More than once can be used in a single table.
syntax:-column name dtype(w) constraint constr_name unique
5. More than one unique keys are allowed in a table.

5.check:-By using this constraint a column value can be restricted to


certain range by giving a condition.
syntax:-column name dtype(w) constraints constr_name
check(condition);
create table tab1 (no number(5) constraints con_ck check(no
between 100 and 1000),
name varchar2(10) constraints con_ck1 check(name=upper(name)
and name like ‘P%’));
In the above table no value can be entered into no column which are
less than 100 and greater than 1000 and also no lower case
character can be entered for name and the name should start with
the alphabet ‘P’.
• Create a table for transaction in the bank with the fields
accountno,ac holder’s name,bal,tr type,closing bal to calculate
the closing bal as per the tr type.

6.references:-Used to refer a column of one table into another table


or to another column in the same table.
syntax:-<<col name>> dtype references <<table name>> (con
name),
ex:-eno number(3) references emp(empno),
notes:-
1.For the referred column of the parent table there should be a
primary key or a unique key.
2.The values available with the parent column only can be inserted to
the column which is the reference.
3.The width of the reference column should be equal to the width of
the parent column.
create table stud(rno number(3) constraints stud_pk1 primary key
,name varchar2(10),doj date));
create table stud1 (rno number(3) references stud(rno),sub1
number(3),sub2 number(3),sub3 number(3));
create table stud2(rollno number(3) references stud(rno),res
varchar2(4),div varchar2(6));
7.foreign key:-Establishes a parent and children relationship between
the tables by assigning a constraint name for that.
syntax:-Constraints <<c name>> foreign key(ref col name)
references <t name>(parent col name);
Ex:-
create table stud3(rollno number(3) constraints stud3_pk primary
key,s1 number(3),s2 number(3),s3 number(3),constraints stud3_fk1
foreign key(rollno) references stud(rno) on delete cascade);

create table depT1(deptno number(2) constraints de_pk primary


key,dname varchar2(10) constraints de_uq unique,loc
varchar2(10));

create table emp1(empno number(4) constraints empk1 primary


key,ename varchar2(10) constraints emck1
check(ename=upper(ename)),job varchar2(10), mgr number(4)
constraints emfk1 foreign key(mgr) references
emp1(empno),hiredate date default sysdate,sal number(7,2)
constraints emck2 check(sal between 800 and 5000),comm
number(4) null,deptno number(2),
constraints emfk2 foreign key(deptno) references dept1(deptno));
create table employ(eno number(4),ename varchar2(10) constraint
em_ck1 check(ename=upper(ename)),
job varchar2(10),mgr number(4), constraints em_fk1 foreign
key(mgr) references employ(eno),
hiredate date default sysdate,sal number(7,2) constraints em_ck2
check(sal between 2000 and 10000),
comm number(7,2) null,dno number(2), constraints em_fk2 foreign
key(dno) references depart(dno),constraints em_pk1 primary
key(eno));

Droping a constraint:-
syntax:-Alter table <<table name>> drop constraint <<con name>>
cascade;
ex:- alter table employ drop constraint em_ck2 cascade;
ex2:-Alter table stud drop primary key;
Adding a constraint:-
syntax:-alter table <<tablename>> add constraint <<con name>>
con type(col name);
ex1:-Alter table stud add constraint st_pk1 primary key(rno);
ex2:- alter table employ add constraints em_ck2 check(sal between
800 and 5000);

Joining conditions:-
The procedure for combining more than one tables based upon a
common data which shares the primary and foreign key relationship
is called joining statements.
These are of 4 types:-
1.equijoin
2.outer join
3.selfjoin
4.Joining by using set operators.

Equijoin:-
Joining more than one table by basing upon a common field
having primary and foreign key relationship and by using a (=)
symbol is called equijoin.
ex:-
1.select empno,ename,job,sal,dname,loc from emp,dept where
emp.deptno=dept.deptno; (Only for selecting)
2. create table empjoin as select
empno,ename,job,sal,emp.deptno,dname,loc from emp,dept
where emp.deptno=dept.deptno; (To store the joined data in a table
called empjoin)

Outerjoin:-
In equijoin though we are selecting the data from dept table
but all the data are not being retrieved .So to avoid this we have to
use outer join. This is possible by using a (+) symbol with the
deficiency column in the joining condition.
ex:- select empno,ename,job,sal,emp.deptno, dept.deptno,
dname,loc from emp,dept where emp.deptno(+) =dept.deptno;

Selfjoin:-
If in a single table any column is referred from another column
then those two can be joined by using a joining condition which is
called the selfjoin.
ex:- select
m.empno,m.ename,m.job,m.mgr,e.empno,e.ename,e.job,e.mgr from
emp e,emp m where e.empno=m.mgr;

Alias for table:-


If the name of a table is required as a subscription to identify a
column then with out writing the full name a single letter can be
used for that which is called the alias.
ex:-select e.ename,e.sal,e.empno,e.job,e.deptno,d.dname, d.loc from
emp e,dept d where e.deptno=d.deptno;

Joining two tables by using set operators:-


Tables can be joined by using the set operators if they have the same
structure. The set operators are
1.union
2.union all
3.intersection
4.minus
A={1,2,3,4,5,6}
B={4,5,6,7,8}
a u b={1,2,3,4,5,6,7,8}
a ua b={1,2,3,4,5,6,4,5,6,7,8}
a n b={4,5,6}
a-b={1,2,3}
b-a={7,8}

union:-Retrieves the unique records from the two tables by


combining those two.
ex:-
select * from emp
union
select * from employ1;

union all:-retrieves all the records from both the tables irrespective
of the repetition.
ex:-Select * from emp
union all
select * from employ1;
intersect:-
retrieves only the rows which are common to both the tables.
ex:-select * from emp
intersect
select * from employ1;

minus:-Retrieves only the rows from the first table except the rows
which are common to both.
ex:-
select * from emp
minus
select * from employ1;

sql queries:-
The statement which is associated with a select command is called a
query. Queries are of three types. Those are
1.simple query
2.Nested query
3.Single row sub query.

Simple query:-The statement used for selecting the rows from a table
with a single select statement only is called simple query.
ex:-
Select * from emp;
select * from dept; etc.

Nested query:-
If in a single query more than one select statements exist one inside
another then that is called a nested query. The maximum number of
select commands can be taken in a nested query is 255.
EX:- select * from emp where deptno=(select deptno from emp
where job=’PRESIDENT’)
ex-2:-select * from emp where sal>=(select avg(sal) from emp);
Select the details of the employees who are getting sal more than the
avg sal of the employees from the department where president is
working ?
ex:-select * from emp where sal>=(select avg(sal) from emp where
deptno=(select deptno from emp where job=’PRESIDENT’));
Select * from emp where sal>(select avg(sal) from emp where
deptno=(select deptno from emp where ename='SMITH'));

Single row subquery:-


The queries which retrieves only a single row are called s.r.s.q.
Generally these kind of query uses a function.
ex:-
select sum(sal) from emp;
select avg(sal) from emp;
group by clause:-
used to retrieve the records from a table group by a field.
ex:-select avg(sal),deptno from emp group by deptno;

having clause:-
This can be used with a group by clause to compare the value of a
group function with any other values.
ex:-select job,max(sal) from emp group by job having
max(sal)>=5000;
select job,sum(sal) from emp group by job having sum(sal)>6000

Any/some and all operators:-


Any/Some:-Retrieves the rows for which the condition satisfies as
the subquery returns.
ex:-select empno,ename,job,sal from emp where
sal<=any/some(select sal from emp where job=’MANAGER’);
Retrieves all the records from emp where the sal is less than or equal
to any of the sal(min sal) from emp where deptno=10.
ex:-
all:-Retrieves the rows which satisfies for the maximum value of the
subquery as per the condition.
ex:-select * from emp where sal>=all(select sal from emp where
job=”manager”);
Retrieves all the rows from emp who gets sal more than the max sal
of all the managers.

Views:-
views are the logical windows to a table where data from one or
more than one tables can be stored and retrieved. Views are of two
types-
1.simple view
2.complex view

1.simple view:-The view created from the datas of a single table is


called a simple view. In a simple view if any changes made to either
to the table or the view that affects both of those. From a single table
more than one views and from a view also another view can be
created.
syntax:-Create or replace view <<view name>> as select
field1,field2,..../ * from <<table name>>;
ex:-1.create or replace view empview as select * from emp;
2.create or replace view empview as select empno,ename,job,sal
from emp;
3.create or replace view empview(empname,empno, empdesig,
empsal) as select ename,empno,job,sal from emp;
4.create or replace view empview as select * from emp where
deptno=10;
views with constraints:-
If a view is created with a where condition, even then the rows
can be inserted to that view which violates the where clause. So to
prevent this type of insertion the view can be created with the
constraint which is with check option.
syntax:-Create or replace view <<view name>> as select <<column
names/ *>> from <<table name>> where <<condition>> with
check option;
ex:-create or replace view empv1 as select empno,ename,
job,sal,deptno from emp where deptno=20 with check option;

Complex view/Join view:-The view which is based upon the data of


more than one tables or views is called a complex view.
syntax:-Create or replace view <<view name>> as select
<<columns/ *>> from <<table1,table2,....>;
ex:-create or replace view empv as select empno,ename
,job,sal,loc,dname from emp,dept where emp.deptno= dept.deptno;
notes:-Into complex views data can not be inserted because it’s
based upon more than one tables.

Sequences:-
Sequence is also a database object which generates the serial
numbers with a step or the same numbers. After creating a sequence
it can be attached to one or more than one tables for generate the
numbers as per the increment given.
syntax to create:-
create sequence <<sequence name>>
increment by <<number>>
start with <<number>>
minvalue <number>>
maxvalue <<number>>
cycle/nocycle
cache <<no>> /nocache;
ex:-
create sequence s5
increment by 2
start with 1
maxvalue 20;

sequence parameters:-
To generate the numbers for a field the sequence should be attached
to a table’s column by using the following parameters.
1.nextval:-It generates the next value of the sequence as per the
increment given.
2.currval:-It generates the current value of the sequence irrespective
of the increment.
attaching a seq to a column:-
The seq. generates the numbers in the insert statements .while
inserting it does not ask for the value of that column and it takes the
value automatically from the seq.
syntax:-
insert into <<table name>>
values(<<seq.name>>.parameter,&field2,&field3,.....);
ex:-
1.insert into stud values(s1.nextval,’&name’,&sub1,&sub2,&sub3);
2.insert into st1 values(s3.currval,’&name’,&sub1,&sub2,&sub3);
altering a asequence:-
Alter sequence <<seq name>> maxvalue <<number>>;
dropping a sequence:-
Drop sequence <<seq name>>;

Indexes:-
Index can be created on a column or on more than one columns
which is used to give the faster access to the user while retrieving
the rows with a query using a certain condition based on that
particular column where index is created. Index are of three types
1.simple index
2.multicolumn index
3.unique index

1.Simple index:-Index based on a single field of a table.


syntax:-create index <<index name>> on <<table name(column
name)>>;
ex:-create index idx01 on stud(sno);
2.multicolumn Index:- based on more than one fields of a table.
syntax:-create index <<index name>> on <<table
name(field1,field2,…);
Ex:- create index idx1 on emp(empno,mgr);
3.unique index:-Unique index just behaves like an unique constraint
for a column. It does not allow any repetition in the field values. If
already any repeated value is existing for a column for that the
unique index can not be created.
syntax:-create unique index <<index name>> on
<<table(columnname)>>;
ex:-create unique index idx1 on stud(rno);
Clusters:-
This is a database object which stores some common data in a single
space in the database based on a particular column which is called
the cluster key. By using this unnecessary wastage of memory space
can be avoided.
S yntax:-Create cluster <<cluster name>> (clu_key
datatype(width));
ex:-create cluster personnel(deptno number(3));
To use the cluster key in table we have to craete the table as
follows:-
1)create table emp(empno number(3) ,ename varchar2(10),job
varchar2(10),deptno number(3))cluster personnel(deptno);
2)create table dept(dname varchar2(10),deptno number(3))cluster
personnel(deptno);
note:-In order to insert rows into the cluster tables we have to
create a cluster index like
syntax:-create index <<index name>> on cluster <<cluster
name>>;
ex:- create index cl_idx1 on cluster personnel;
Now data can be inserted to the cluster tables e.g. to emp and dept.
USERS:-
select * from all_users;
This displays all the user lists existing.
Select user from dual;
Displays the current user logged in.
An user is nothing but a privileged member who can access to
the database. These are just like the accounts. Each users will have
one ID and all the Ids are associated with a password to open the
user account.
A user can not be created in any other user except the system user
unless until it has the DBA privilege .So in order to create a user at
first we should go for the system user.
Creating new users:-
syntax:-Create user <<username>> identified by <<password>>;
ex:-Create user maya identified by mehndi;
After creating the user they should have given functionality, which
are called the privileges. The privileges can be granted or taken off
from the user in a user which is having the DBA privilege only.
Privileges are the rights, which are of two types.
1.Database privileges.
2.Object privileges.
1.Database privileges :-The rights or privileges given to the user are
called database privileges ,though they deal with the database.
Those are
1.connect
2.Resource
3.DBA
These privileges can be given by using the following data control
language command:-
1.Grant:-Used to grant any of the privileges to an user.
syntax:-
Grant <<privilege>> to <<username>>;
ex:-Grant connect/resource/DBA to maya;
1.connect:-Grants the power to be connected to the database for the
user.
2.Resource:-Grants the power to create any object in the newly
created user.
3.DBA:-Grants the data base administration privileges e.g the power
to create user ,grant and revoke the privileges etc.
All these are the commands that only can be given from the user
which has the administration power e.g. system user.
Notes:-Before creating the user or granting any privilege first we
have to go for the system user.
For that give the command:-
connect system/manager
After creating the user give the required privileges e.g. connect,
resource etc
like
grant connect,resource to maya;
Now the user maya will be able to create any database objects like
tables, view etc in it.
Revoke:-This command is used to take out or withdraw any
privileges from the user.
syntax:-Revoke <<privilege name>> from <<username>>;
ex:-Revoke connect, resource from maya;

Object privileges:-The privileges which can be granted to an object is


called an object privilege. Those are insert, update, select ,delete and
all.
syntax:-Grant insert/select/update/delete/all on <<object>> to
<<user name>>;
select * from user.object;
SQL> show user
user is “MICRO”
SQL> connect
Enter user-name: scott
Enter password: *****
SQL> grant dba to scott;
Grant succeeded.
SQL> grant select on emp to micro;
Grant succeeded.
SQL> connect micro/mca
Connected.
SQL> select * from scott.emp;
Synonyms:-
These are just a duplicate copy for the tables in the same or different
users.If one table exist in scott user then a duplicate of that can be
created in any other users by
granting the object privillege to those.
syntax:-create synonym <<synonym name>> for <<table name>>;
ex:-Create synonym s_emp for scott.emp;
NOTES:-
1).If any changes are made in the table that reflects in the synonym
and vice versa.
2).If any previllege is granted or revoked from the table then it
affects to the synonym.
3).In synonyms it’s not possible to take ony a few columns from the
table.
dropping synonym:
drop synonym <<syn name>>;
Creating public synonym:-
This is a synonym which can be created in the user where the
host table is present and from that synonym data can be accessed in
any user present in oracle.
Syntax:-
Create public synonym <<syn name>> for <<table name>>;

Sql functions:-
Functions are the instructions which are allready created and
initiates a particular action when
called.These are of 4 types
1.Character functions
2.Numeric functions
3.Date functions
4.Conversion functions
Character functions:-
1.lower:-Used to convert a string into lower case.
syntax:-lower(‘string’)
ex:-select lower(‘MICRO COMPUTERS’) from dual;
output:-micro computers
ex:-select ename,lower(ename) from emp;
note:-dual is oracles own table from where the datas not present in
any table can be retrived.
2.upper:-used to convert a string into upper case letters.
syntax:-upper(‘string’)
ex:-
a)select upper(‘micro computers’) from dual;
output:-MICRO COMPUTERS
b)select ename,lower(ename),upper(lower(ename)) from emp;
3.initcap:-used to conver a string into it’s first character as upper
case letter.
syntax:-initcap(‘string’/fieldname)
ex:-
select initcap(‘micro computer associates’) from dual;
output:-Micro Computer Associates
select ename,initcap(ename) from emp;
4.length:-used to find out the number of characters in a string.
syntax:-length(‘string’/fieldname)
ex:-select length(‘computer’) from dual;
output:-8
select ename,length(ename) from emp;
5.instr:-Used to find out the position of a particular character in a
string.
syntax:-instr(‘string’/field name,’char’);
ex:-select instr(‘computer’,’t’) fromdual;
output:-6
select ename,instr(ename,’s’) from emp;
6.substr:-displays only the number of characters given starting from
a particular position.
syntax:-substr(‘string’,start no(POS),no of char);
ex:-select substr(‘computer’,3,4)from dual;
output:-mput
7.translate:-Used to replace a character in the string with any other
char.
syntax:-translate(‘string’,’char1’,’char2’);
ex:-select translate(‘computer’,’m’,’r’) from dual;
output:-corputer
select ename,translate(ename,'ABC','XYZ') FROM EMP;
8.replace:-Used to replace a data with another.
syntax:-replace (fieldname,’old’,’new’)
ex:-select job,replace(job,’CLERK’,’JR. ASST.’) FROM EMP;
9.lpad:-Used to remove fill the leading blanks in a data from left.
syntax:-lpad(fieldname,nos.,’char’)
ex:-select job,lpad(job,10,’*’) from emp;
10.rpad:-used to fill the leading blanks in a char data from right.
syntax:-rpad(fieldname,nos.,’char’)
ex:- select job,rpad(job,12,’*’) from emp;
Ascii(american standard code for information interchange.
a->97,b->98,....,z->122
A->65,......,Z->90
0-48 ,9->57
11.ascii:-Used to display the ascii code of a char.
syntax:-ascii(‘char’);
ex:-select ascii(‘a’) from dual;
output:-97
12.chr:-displays the char for an ascii number.
syntax:-chr(num)
ex:-select chr(65) from dual;
output:-A
13.concat:-Used to add one string into another string’s end.
syntax:-concat(‘string1’,’string2’);
ex:-select concat(‘michel’,’jackson’) from dual;
select ename,job,concat(ename,job) from emp;
14.Soundex():-Used to select the data from a table for a particular
field for which it sounds as the data given.
Syntax:-where soundex(field)=soundex(data);
Ex 1:-select * from emp where soundex(job)=soundex(‘CLERC’);
Ex 2:-select * from emp where soundex(ename)=soundex(‘myler’);
15:-Ltrim:-To remove the space from a string from the left side.
Syntax:-ltrim(‘ string’);
SELECT 'The employee '||ename||ltrim(‘ is getting Rs.
‘)||sal||’ per month’ from emp;

Numeric functions:-
The functions dealing with numbers is called numeric
functions.Those are
1.mod:-used to find the reminder of a division.
syntax:-mod(num,divisor)
ex:-select mod(45,7) from dual;

2.abs:-Returns the absolute value of a number.


syntax:-Abs(num)
ex:-select abs(-345) from dual;
==>345
3.power:-returns the power of a number raised to a number.
syntax:-power(num,index)
ex:-select power(3,4) from dual;
==>81
4.sqrt:-Returns the sq. root of any number.
syntax:-Sqrt(num)
ex:-select sqrt(144) from dual;
output:-12
5.round:-Returns the number after rounding off it upto certain digits.
syntax:-round(num, no of places to be rounded)
ex:-select round(238.5678,2) from dual;
==>238.57
6.trunc:-used to round off a number after cutting it to a certain
position.
syntax:-trunc(num,no. of digits)
ex:-select trunc(45.5678,2) from dual;
==>45.56
7.sign:-used to display the sign of a number value that whether it’s
positive or negative.
syntax:-sign(field/num)
ex:-select sign(sal-4000) from emp;
8.nvl:-Returns a value given for the null values while taking part in
an operation.
ex:-nvl(field,any value)
syntax:-select sal,comm,sal+nvl(comm,0) from emp;
9.uid:-Returns the user id number from the table.
Ex:-select uid from dual;
10.user:-Returns the current user name logged into the system.
11. greatest():-Returns the greatest of a set of numbers.
Syntax:-greatest(no1,no2,no3,….);
Ex;-select greatest(24,56,43) from dual;
12. Least() :-Returns the smallest of set of any numbers.
Syntax:-least(no1,no2,no3,….);
Ex:-select least(23,66,89,4) from dual;
Ex:-select sub1,sub2,sub3,greatest(sub1,sub2,sub3) great
,least(sub1,sub2,sub3) small from stud
13.Floor:-Returns the integral part of a decimel number.
syntax:-floor(no)
ex:-select floor(23.56) from dual;
output:-23
14.ceil:-Returns the next whole of a decimal number.
syntax:-ceil(no)
ex:-select ceil(23.346) from dual;
output:-24
group numeric functions:-
1.sum:-used to find out the sum of a field values.
ex:-sum(field name)
ex:-select sum(sal) from emp;
2.avg:-returns the average of the field values.
syntax:-avg(field name)
ex:-select avg(sal) fromemp;
3.max/min:-returns the min or max of the field values.
syntax:-max/min(sal)
ex:-select min(sal) from emp;
select max(sal) from emp; etc.
4.count():-Returns the number of data for each group.
Syntax:-count(column name)
Ex:-select count(empno) where job=manager;
Ex 2:-select job,sum(sal),avg(sal),min(sal),max(sal),count(sal) from
emp group by job;
Date functions:-
1.Sysdate:-Returns the current system date.
ex:-select sysdate from dual;
2.month_between:-Calculates the months between two dates.
syntax:-months_between(date1,date2)
ex:-select months_between(sysdate,hiredate) from emp;
select months_between(‘15-jun-99’,’21-dec-99’) from dual;
3.add_months:-Used to add any number of months in a date.
syntax:-add_months(date,no of months)
ex:-select sysdate,add_months(sysdate,10) from dual;
4.next_day:-Returns the date for next appearance of the given day.
syntax:-next_day(date,’day’)
ex:-select sysdate,next_day(sysdate,5) from dual;
select next_day(15-may-99’,’friday’) from dual;
15th may is saturday
output:-21-may-99
5.last_day:-Returns the last day of the month.
syntax:-last_day(date)
ex:-select hiredate,last_day(hiredate) from emp;
select last_day(sysdate) from dual;
conversion function:-
1.to_char: converts number or date to character format .
syntax:-to_char(date/number,’format’)
to_char(date,’date picture’)
codesuse

day monday
d 1-7
dd date of the month
dy Day of the weak in 3 chars.(e.g sun,mon,…)
ddth date with the abbr. 2nd,5th,3rd
mon 3 letter format(jan,feb)
month full month
mm 1-12

y last digit of the year


yy last two digits
yyy last three dig
yyyy full year
year In character format like (two thousand two)

hh time in 12 hours
hh24 time in 24 hours
mi minutes
ss seconds
am am/pm
a.m. am/pm with (.)

ex:-select to_char(sysdate,’ddth month yyyy hh24:mi:ss’) from dual;


select to_char(sysdate,’day ddth month yyyy’) from dual;
select to_char(sysdate,’dd mm yy’)from dual;
select to_char(sysdate,’mm - dd - yyyy’) from dual;
Number formats:-
Format Use
99,999 Separates the thousands place with a comma.
$9999 Displays the number with a leading dollar($)
Symbol
9999MI returns a (–) sign to the end if a negative number.
RM Returns the number with roman format.
ex:-select sal,to_char(sal,’$99,999’) from dual;

2.to_date:- converts the char value representing date into a date


value according to the format specified. if the format is omitted form
is dd-mon-yy.
syntax:-to_date(‘char’,’fmt’)
ex:-insert into emp(hiredate)
values(to_date(‘11/11/2001’,’dd/mm/yyyy’));
ex2:-insert into dd values(to_date(‘08-25-2002’,’mm-dd-yyyy’))
3.Decode:-used to change the values for a certain field based upon
another field of a table.
syntax:-decode(field,’value of the field’,changed value with expr)
ex:-select sal,job,decode(job,’MANAGER’,sal*1.5/100) from emp;
• >increases the sal by 1.5% for managers.

SQL*PLUS:-
This is the main software of oracle which checks and
keeps track on all the activities of oracle applications. It has some
commands which are:-
1.cl scr:-To clear the screen.
2.save:-To save a command in a file with the extension .sql
syntax:-
a)save filename
b)save filename replace:-To replace the content of a command file
with another command.
c)save file append :-To add another command to an already existing
command file.
3.@ /start:-To execute a command file.
Syntax:-@filename
4.edit:-Used to open a file in the notepad buffer.
Syntax:- edit filename
5.describe:-Used to describe the database structure of a table.
Syntax:-Desc tablename
6.quit/exit:-To close oracle sql*plus.
7.prompt:-To display any text on the screen.
Syntax:-prompt string
8.accept:-Used to accept a value for a variable .
syntax:-Accept varname prompt “Any text :” hide
ex:-
accept rollno number prompt “Enter the rollno :”
accept pawd char prompt “Enter password :” hide
9.define:-Used to display the value stored in a variable.
Syntax:-define variablename

10.column:-Used to get various effects with the columns of a table.


Syntax:-column <<c name>> heading/format <<new heading
/format>>
Ex:-
column empno heading eno
column sal heading salary etc.
column sal format ‘$9,999’
column ename format a4
column ename HEADING ‘EMPLOYEE|NAME’
Concatenation operator:-
Select ‘The employee ‘||ename ||’ is drawing Rs.’ ||sal||’ per
month’ from emp;
11.Clear column:-To cancel the column commands.

12.Show:-Used to show various options like


user,pagesize,linesize,underline. etc
syntax:-show <<options>>
13.set:-used to set linesize,pagesize,numwidth etc.
syntax:-set <<option>>
set underline <<char>>
set underline off/on
set heading off/on
set timing on/off :-Displays the time taken for the execution of a
command.
Set time on/off :-Displays the current time as sql prompt.
Set feedback off/on:-Does not display any feedback after the
execution of the command.
Set sqlprompt “text” :-To change the sql prompt to any text.
14.Setting title for a table:-
Titles are of two types.
1.ttitle:-Stands for top title, a title which appears at the top of each
page.
2.btitle:-Stands for the bottom title, a title which appears at the
bottom of each page.
These titles can be given in 3 alignments those are
1.left 2.right 3.center
syntax:-
ttitle/btitle left/right/center “title”
Some sql defined columns also can be used like
Sql.pno :-For current page
Sql.lno :-for current line
Sql.user :-for the user name who is logged in currently.
Ex:-
1.TTITLE “EMPLOYEE REPORT”
2.TTITLE LEFT “EMPLOYEE REPORT” CENTER “MICRO COMPUTERS”
RIGHT “PAGE:” SQL.PNO
15.Report header and footer:-
Report header is a message which appear at the top of the report and
report footer which appears at the end of the report.
Syntax:-
Rephead/repfoot “any message”
Ex:- rephead center “ANNUAL REPORT-2001”
repfoot center “END OF THE ANNUAL REPORT”
ex:-
ttitle left ‘Sathyam Infoways’ center ‘Employee Reports’ right ‘Page :’
sql.pno-
skip 1 center ‘For Year –2001’
16.Skip :-Used to move the control to any no of lines or a page
forwards.
Syntax:-
Skip page
or skip <<no of lines>>

16.break:-used to break a particular column.


syntax: break on <<cname>>
17.clear:-used to clear the formats or column attributes applied to
the fields or tables.
syntax:-clear columns/break/compute etc.
18.compute:-Used to calculate the sum,avg,min,max of the field
values at each breaks.
Syntax:-compute <<opt>> of <<field>> on <<break column>>
ex:-
break on deptno skip page
compute sum avg min max of sal on deptno
select * from emp order by deptno;
19.input:-Used to accept more than one SQL*PLUS commands as a
single one and can be saved as a command file.
Syntax:-
Input
Command 1
Command 2
…………..
…………
save filename
input
rephead “Employee Info.”
ttitle “Data for 2002”
break on deptno skip 1
compute sum of sal on deptno
select * from emp order by deptno;

PL/SQL(procedural language ext. to SQL):-


Though It’s a procedural language it supports programming features.
Features of pl/sql are:-
1.Though it’s an extension to SQL it supports almost all SQL
commands.
2.It supports the programming feature by using which more than one
statements can be combined together to perform a particular task.
3.It allows the user to take decisions by using the if else statements.
4.Any statements can be repeated in the execution by using the
loops.
5.It ‘s most important feature is it allows the user to create stored
program units like procedures, functions, packages, triggers etc.
which can be called at any moment it required.
Every plsql prog. is called the combination of statements or
more than one blocks. Which can be written as the following
syntax:-
declaration section

Begin
execution part
<<input statements
arithmatical statements
output statements>>
exception handler section
end;
declaration sec:-In this section all the variables which is to be used
in a prog. should be declared as their types. And these variables are
called bind variables.
synt:-
var datatype(w);
ex:-rno number(3);
name varchar2(10); etc.
input statements:-
The statement required to enter the data to the variables is called in
put statement.
syntax:-
var:=&var name;
ex:-rno:=&rollno;
name:=’&name’; etc.

Arithmetical statements:-
Statements used for calculation
var:=var (o) var;
ex:-
sum:=no1+no2;
tot:=sub1+sub2+sub3;

Note:-While assigning values to variable the “ : “ should be used


before the assignment operator(=) e.g (:=).
output statements:-
The statement used for getting the output .
dbms_output.put_line(‘Any string’); -->to print the string
dbms_output.put_line(var name); --> to print the value in a variable
ex:-
dbms_output.put_line(‘welcome to pl/sql’);
dbms_output.put_line(‘roll no=’ || rno); etc.
Note:-“ ||(concatenation) “ is used for combining two strings or
values.
set serveroutput on:-Used to make the output console open.
--(used for comments)
• prg1:-
• WAP to print any statement.
set serveroutput on
begin
dbms_output.put_line(‘============================’);
dbms_output.put_line(‘Wel come to Pl/sql programming’);
dbms_output.put_line(‘============================’);
end;
• WAP to print any two numbers

set serveroutput on
declare
no1 number(3):=100;
• initialization of variables no2 number(3,1):=5.6; begin
dbms_output.put_line(‘First number=’||no1);
dbms_output.put_line(‘Second number=’||no2);
end;
• WAP to enter any two numbers and find out their sum, difference,
product, quotient and reminder.

set serveroutput on
declare
no1 number(5);
no2 number(5);
s number(5);
d number(5);
p number(8);
q number(7,2);
rem number(3);
begin
no1:=&number1;
no2:=&number2;
s:=no1+no2;
d:=no1-no2;
p:=no1*no2;
q:=no1/no2;
rem:=mod(no1,no2);
dbms_output.put_line(‘Sum=’||s);
dbms_output.put_line(‘Difference=’||d);
dbms_output.put_line(‘Product=’||p);
dbms_output.put_line(‘Quotient=’||q);
dbms_output.put_line(‘Reminder=’||rem);
end;
/

• WAP to find out the total and average of 3 sub marks for any
student.
set serveroutput on
declare
rno number(3);
sname varchar2(10);
sub1 number(2);
sub2 number(2);
sub3 number(2);
tot number(3);
avr number(5,2);
begin
rno:=&rollno;
sname:=’&stud_name’;
sub1:=&sub1;
sub2:=&sub2;
sub3:=&sub3;
tot:=sub1+sub2+sub3;
avr:=tot/3;
dbms_output.put_line(‘ ‘);
dbms_output.put_line(‘Roll no=’||rno);
dbms_output.put_line(‘Stud name=’||sname);
dbms_output.put_line(‘Sub1 marks=’||sub1);
dbms_output.put_line(‘Sub2 marks=’||sub2);
dbms_output.put_line(‘Sub3 marks=’||sub3);
dbms_output.put_line(‘Total marks=’||tot);
dbms_output.put_line(‘Average marks=’||avr);
end;
/
• WAP to accept the principal amount, rate and time period then
find the simple interest and also find the amount to be paid by the
bearer.
• wap to find out the area and circumference of a circle.

set serveroutput on
declare
pi number(5,3):=3.141;
rad number(5,2);
area number(7,2);
circum number(7,2);
begin
rad:=&radius;
area:=pi*rad*rad;
circum:=2*pi*rad;
dbms_output.put_line(‘Radius=’||rad||’Cms.’);
dbms_output.put_line(‘Area=’||area||’Sq. Cms.’);
dbms_output.put_line(‘Circumference=’||circum||’Cms.’);
end;
/
• WAP to enter any roll number and print the corresponding name
from emp table.

set serveroutput on
declare
x varchar2(10);
en varchar2(10);
s number(7,2);
begin
x:=’&job’;
select ename,sal,job into en,S,x from emp where job=x;
dbms_output.put_line(‘Job=’||x||’ ‘||’emp name=’||en||’
salary=’||s);
end;
/

IF ELSE STATEMENTS:-
Unlike other softwares in pl/sql also it’s possible to take decission by
using the keywords “if” and “else”.The keyword if is allways
associated with a condition and if the condition satisfies then the
statements following it executes.
syntax:-
if condition then
statements for true;
else
statements for false;
end if;

for more than one choice:-


if cond1 then
statements ;
elsif cond 2 then
statements;
.
.
else
statements for false;
end if;

• wap to find out the greatest of any two numbers


soln:-
set serveroutput on
declare
no1 number(5);
no2 number(5);
begin
no1:=&number1;
no2:=&number2;
if no1>=no2 then
dbms_output.put_line(no1||’ is greatest’);
else
dbms_output.put_line(no2||’ is greatest’);
end if;
end;

• WAp to enter any number and find out whether it’s positive or
negative or zero.

set serveroutput on
declare
num number(5);
begin
num:=&number;
if num>0 then
dbms_output.put_line(num||’ is positive’);
elsif num<0 then
dbms_output.put_line(num||’ is negative’);
else
dbms_output.put_line(num||’ is equal to zero’);
end if;
end;

• WAP to accept the monthly salary of any employee and the find
the bonus of 12% on annual salary if experience is more than 3
years and otherwise the bonus is Rs.1000.After all calculate the
total salary received by the employ on that month along with
the bonus amount.

Declare
Msal number(7,2):=&msal;
Annsal number(9,2);
Bonus number(7,2);
doj date:=’&date_of_join’;
Exp number(3);
Totsal number(9,2);
Begin
Exp:=months_between(sysdate,doj)/12;
Annsal:=msal*12;
If exp>3 then
Bonus:=annsal*12/100;
Else
Bonus:=1000;
End if;
Totsal:=msal+bonus;
Dbms_output.put_line(‘Annual salary=Rs.’||annsal);
Dbms_output.put_line(‘Experience=’||exp||’ years’);
Dbms_output.put_line(‘Bonus amount=Rs.’||bonus);
Dbms_output.put_line(‘Total salary drawn=Rs.’||totsal);
End;
/
Nested if-else:-
If one condition is written inside another condition then that is called
nested if-else.This is required when we need to combine more than
one conditions.
Syntax:-
if cond1 then
if cond 2 then
Statements
Else
statements
end if;
else
if cond3 then
statements
else
stements
end if;
end if;
• WAP to accept any number and check whether that is a multiple of
only 3 or only 5 or both 3 and 5 or none of them.

Declare
No number(4):=&no;
Begin
If mod(no,3)=0 then
If mod(no,5)=0 then
dbms_output.put_line(no||‘ is mutiple of both 3 and 5’);
else
dbms_output.put_line(no||‘ is mutiple of only 3’);
end if;
else
if mod(no,5)=0 then
dbms_output.put_line(no||‘ is mutiple of only 5’);
else
dbms_output.put_line(no||‘ is mutiple of none of 3 and 5’);
end if;
end if;
end;
/
declare
r number(3);
s1 number(2);
s2 number(2);
s3 number(2);
t number(3);
a number(5,2);
re varchar2(6);
d varchar2(8);
begin
r:=&rno;
select sub1,sub2,sub3 into s1,s2,s3 from stud where sno=r;
t:=s1+s2+s3;
a:=t/3;
if s1>=35 and s2>=35 and s3>=35 then
re:=’pass’;
else
re:=’fail’;
end if;
if re=’pass’ and a>=60 then
d:=’first’;
elsif re=’pass’ and a>=50 and a<60 then
d:=’second’;
elsif re=’pass’ and a>=35 and a<50 then
d:=’third’;
else
d:=’nill’;
end if;
update stud set tot=t,avr=a,res=re,div=d where sno=r;
end;
• wap to input any number and check wheather it’s even or odd.

set serveroutput on
declare
num number(4);
begin
num:=&number;
if mod(num,2)=0 then
dbms_output.put_line(num||’ is even’);
else
dbms_output.put_line(num||’ is odd’);
end if;
end;

• WAP to find out the greatest of any three numbers.


set serveroutput on
declare
no1 number(4);
no2 number(4);
no3 number(4);
begin
no1:=&number1;
no2:=&number2;
no3:=&number3;
if no1>no2 and no1>no3 then
dbms_output.put_line(no1||’ is the greatest’);
elsif no2>no3 and no2>no1 then
dbms_output.put_line(no2||’ is the greatest’);
else
dbms_output.put_line(no3|| ‘ is the greatest’);
end if;
end;
/

• WAP to enter any number and check wheather it’s a multiple of 3


or 7 or both 3 and 7 or not of 3 or 7.
set serveroutput on
declare
num number(5);
begin
num:=&number;
if mod(num,3)=0 and mod(num,7)=0 then
dbms_output.put_line(num||’ is multiple of both 3 and 7’);
elsif mod(num,3)=0 then
dbms_output.put_line(num||’ is multiple of only 3’);
elsif mod(num,7)=0 then
dbms_output.put_line(num||’ is multiple of only 7’);
else
dbms_output.put_line(num||’ is neither multiple of 3 nor of 7’);
end if;
end;
/

• WAP to enter any alphabet and check it wheather it’s a consonant


or a vowel.

declare
ch varchar2(1);
begin
ch:=’&char’;
if ch=’a’ or ch=’e’ or ch=’i’ or ch=’o’ or ch=’u’ OR ch=’A’ or ch=’E’ or
ch=’I’ or ch=’O’ or ch=’U’ then
dbms_output.put_line(ch ||’ is a vowel’);
else
dbms_output.put_line(ch|| ‘ is a consonant’);
end if;
end;
/

create table cust(cno number(3),itemname varchar2(10),price


number(7,2),qtytaken number(4),tot number(8,2),dis
number(6,2),billamt number(8,2));
insert into cust (cno,itemname,price,qtytaken)
values(&cno,’&itemname’,&price,&qtytaken);
• wap to findout tot ,dis and billamount in the above prg. where
dis=2.5% if tot>10000 otherwise dis=1.5%.

declare
cn number(3);
qty number(4);
pr number(7,2);
t number(8,2);
d number(6,2);
net number(8,2);
begin
cn:=&cust_number;
select cno,price,qtytaken into cn,pr,qty from cust where cno=cn;
t:=pr*qty;
if t>10000 then
d:=2.5*t/100;
else
d:=1.5*t/100;
end if;
net:=t-d;
update cust set tot=t,dis=d,billamt=net where cno=cn;
end;
/

Loops:-
Loops are used to repeate the execution of a statement for more than
once in a programme.
Those are generally of 4 types:-
1.simple loop
2.while loop
3.for loop
4.cursor for loop
Simple loop:-This loop starts the repetition according to initial value
given to the loop variable and continues till the exit statement
encounters it.
syntax:-
initialisation of loop variable x:=1; x:=10;
loop
statements;
increment/decrement; x:=x+1; x:=x-1;
(if <<condition x<=10/x>=1>> then
exit;)
end if;
((or))
exit when condition(x>10);
end loop;

• WAP to to print a string for 10 times.


set serveroutput on
declare
x number(2):=1;
begin
loop
dbms_output.put_line(‘Welcome to loops’);
x:=x+1;
exit when x>10;
end loop;
end;
/

• WAP to print the number 1 to 10 set serveroutput on declare


x number(2); --x number(2):=10;
begin
x:=1;
loop
dbms_output.put_line(x);
x:=x+1; --x:=x-1;
if x>10 then --if x<1 then
exit;
end if;
end loop;
end;
/

• WAP to print the table of any number


declare
x number(2):=1;
n number(4);
t number(5);
begin
n:=&number;
loop
t:=n*x;
dbms_output.put_line(n||’*’||x||’=’||t);
x:=x+1;
exit when x>10;
end loop;
end;
/
• WAP to print the numbers from 1 to 30 with alternate difference
of 3 and 4.
1 4 8 11 15 18 22 25 29
declare
x number:=1;
d number:=3;
begin
loop
dbms_output.put_line(x);
x:=x+d;
if d=3 then
d:=4;
elsif d=4 then
d:=3;
end if;
exit when x>30;
end loop;
end;
/
• WAP to print 40 to 1 with an alternate difference of 3.5 and 4.5 in
decreasing order.

declare
x number:=1;
d number:=3.5;
begin
loop
dbms_output.put_line (x);
x:=x+d;
if d=3.5 then
d:=4.5;
elsif d=4.5 then
d:=3.5;
end if;
exit when x>40;
end loop;
end;

--WAP to findout the factorial of any number.


declare
n number(3);
x number(2):=1;
f number(5):=1;
begin
n:=&number;
loop
f:=f*x;
x:=x+1;
exit when x>n;
end loop;
dbms_output.put_line(‘Factorial of ‘||n||’ is=’||f);
end;
/

/
--WAP to findout the reverse of a number and sum of the digits of a
number.
declare
n number(4);
r number(4);
s number(4):=0;
t number(4);
begin
n:=&number;
t:=n;
loop
r:=mod(n,10);
s:=s+r;
n:=floor(n/10);
exit when n=0;
end loop;
dbms_output.put_line(‘Sum of the digits of ‘||t||’ = ‘||s);
s:=0;
n:=t;
loop
r:=mod(t,10);
s:=s*10+r;
t:=floor(t/10);
exit when t=0;
end loop;
dbms_output.put_line(‘reverse of ‘||n||’ = ‘||s);
end;
/

For loop:-
syntax:-
for <<var>> in startno..endno
loop
statements;
end loop;

--WAP to print the numbers from 1 to 10 and print the numbers with
their type(i.e even or odd)
declare
n number(2);
t varchar2(5);
begin
dbms_output.put_line(‘Number’||’Type’);
for n in 1..10
loop
if mod(n,2)=0 then
t:=’even’;
else
t:=’odd’;
end if;
dbms_output.put_line(n||’ ‘||t);
end loop;
end;
/
--WAP to find out the sum of the squares upto any number starting
from 1.
sum=1*1+2*2+3*3+4*4+.....+n*n

declare
n number(5);
s number(5):=0;
i number(3);
begin
n:=&number;
for i in 1..n
loop
s:=s+(i*i);
end loop;
dbms_output.put_line(‘The sum of the series=’||s);
end;
/
Armstrong numbers:-
Sum of the cubes of the digits of the number=num
153=1*1*1+5*5*5+3*3*3=>1+125+27

set serveroutput on
declare
n number(5);
s number(6):=0;
r number(2);
n1 number(4);
begin
n:=&number;
n1:=n;
loop
exit when n1<1;
r:=mod(n1,10);
s:=s+power(r,3);
n1:=floor(n1/10);
end loop;
if s=n then
dbms_output.put_line(n||’is armstrong’);
else
dbms_output.put_line(n||’is not armstrong’);
end if;
end;

Cursors:-
It’s an area where data can be selected and accessed either by
oracle or the user. There two types of cursors:-
1.implicit cursor:-The cursor which is created by the oracle buffer
automatically where any dml statements encounters to a table.
2.Explicit cursor:-this is the users private area Where data can be
collected from a table and can be accessed.
A cursor supports 3 attributes to work with it. Those are:-
1.sql%found:-Returns a true value if the cursor retrieves any rows
from the table.
2.sql%notfound:-Returns a true value if the cursor does not find any
value in the query.
3.sql%rowcount:-Counts the number of rows retrieved by the query.

--wap to delete the data for employees after entering the job.

declare
no number(3);
begin
delete from employ where job=’&job’;
if sql%notfound then
dbms_output.put_line(‘There is no employee doing this job’);
elsif sql%found then
dbms_output.put_line(‘Some data has been retrieved by the cursor’);
end if;
no:=sql%rowcount;
dbms_output.put_line(‘No of records deleted=’||no);
end;
/

--WAP to increase the sal of employees by 1000 rs. for deptno=10;

set serveroutput on
declare
x number(4);
begin
update emp set sal=sal+1000 where deptno=&deptno;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
end;
/

set serveroutput on
declare
x number(4);
begin
delete from emp where job=’&job’;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
end;
/

set serveroutput on
declare
x number(4);
begin
update emp set sal=sal+1000 where deptno=&dno;
if sql%found then
dbms_output.put_line(‘Some rows are retrived by the query’);
elsif sql%notfound then
dbms_output.put_line(‘query is not able to retrive any row’);
end if;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
end;
/

--WAP to increase the salary for the employees of a particular


department and enter the no of records updated,date,time,dept no
and name of the person who increased the salary into another table
called cursor_ret.

create table cursor_ret(mess varchar2(30),update_date date,


time varchar2(10),deptno number(3),name varchar2(10));

set serveroutput on
declare
x number(4);
m varchar2(30);
t char(6);
D NUMBER(3);
name varchar2(10) not null :=’ ‘;
begin
D:=&DNO;
name:=’&your_name’;
update employ set sal=sal+1000 where dno=D;
if sql%found then
dbms_output.put_line(‘Some rows are retrieved by the query’);
elsif sql%notfound then
dbms_output.put_line(‘query is not able to retrieve any row’);
end if;
x:=sql%rowcount;
dbms_output.put_line(x||’ no. of row updated’);
m:=concat(to_char(x),’ no of rows updated on ‘);
t:=to_char(sysdate,’hh24:mi’);
insert into cursor_ret values(m,to_date(sysdate),t,D,name);
end;
/
Explicit cursors:-This is the oracles private area which can be created
by the user. After the creation data from a database can be selected
into the cursor. There are 4 main parts in a cursor which are:-
(declaration of a cursor:-
cursor <<cur name>> is select <<field names>> from table name
<<cond>>;
ex:-cursor c1 is select empno,ename,sal from emp where deptno=10;
(opening a cursor:-
open <<cursor name>>;
ex:-open c1;
(fetching the data from the cursor to the bind variables:-
syntax:-fetch <<cursor name>> into <<variables>>;
ex:-fetch c1 into eno,name,salary;
(closing the cursor:-
close <<cur name>>;
ex:-close c1;

---WAP to insert the datas of the clerks from emp table to another
table .
clerk table:-
create table cl_table(empno number(4),ename varchar2(10),
sal number(8,2),job varchar2(10),deptno number(3));

declare
eno number(4);
name varchar2(10);
salary number(8,2);
dno number(3);
j varchar2(10);
cursor c1 is select empno,ename,sal,job,deptno from emp where
job=’principal’;
begin
open c1;
loop
fetch c1 into eno,name,salary,j,dno ;
exit when c1%notfound;
insert into cl_table values(eno,name,salary,j,dno);
end loop;
close c1;
end;
/

• WAP to calculate the total salary for each deptno of the emp table
and put those into another table.

create table temptot( chcol varchar2(40),totsal number(9,2));


set serveroutput on
declare
tot1 number(6):=0;
tot2 number(6):=0;
tot3 number(6):=0;
d number(4);
s number(6);
cursor c1 is select sal,deptno from emp;
begin
open c1;
loop
fetch c1 into s,d;
exit when c1% notfound;
if d=10 then
tot1:=tot1+s;
elsif d=20 then
tot2:=tot2+s;
elsif d=30 then
tot3:=tot3+s;
end if;
end loop;
dbms_output.put_line(‘Dept 10 total salary :’||tot1);
dbms_output.put_line(‘Dept 20 total salary :’||tot2);
dbms_output.put_line(‘Dept 30 total salary :’||tot3);
insert into temptot(chcol,totsal)values(‘Dept 10 total salary :’,tot1);
insert into temptot(chcol,totsal)values(‘Dept 20 total salary :’,tot2);
insert into temptot(chcol,totsal)values(‘Dept 30 total salary :’,tot3);
close c1;
end;
/

cursor for loops:-


This is a kind of loop which executes the number of times till the
cursor retrieves the last record of the table.
syntax:-
declaration of the cursor
begin
for var in <<cur_name>>
loop
statements
end loop;

• WAp to calculate the electricity bill for apseb with the


conditions:-
if charged unit<=100 rate=1.35,mrent 100
charged unit >100 rate=2.95,mrent 150
charged unit >400 rate=4.5,mrent 200
create table apseb(cno number(3),cname varchar2(5), pmr
number(4),cmr number(4),cu number(4),total number(7,2),mrent
number(3),netbill number(8,2));
• insert the records:-
insert into apseb(cno,cname,pmr,cmr) values(101,’aaa’,2360,3278);
insert into apseb(cno,cname,pmr,cmr) values(102,’bbb’,256,421);
insert into apseb(cno,cname,pmr,cmr) values(103,’ccc’,3160,3228);
insert into apseb(cno,cname,pmr,cmr) values(104,’ddd’,360,1278);
insert into apseb(cno,cname,pmr,cmr) values(105,’eee’,2010,2278);
declare cursor c is select cno,pmr,cmr from apseb;
cunit number(4);
tamt number(7,2);
mr number(3);
bill number(8,2);
begin
for i in c
loop
cunit:=i.cmr-i.pmr;
if cunit<=100 then
tamt:=1.35*cunit;
mr:=100;
elsif cunit>100 and cunit<=400 then
tamt:=1.35*100+(cunit-100)*2.95;
mr:=150;
elsif cunit>400 then
tamt:=100*1.35+300*2.95+(cunit-400)*4.5;
mr:=200;
end if;
bill:=tamt+mr;
update apseb set cu=cunit,total=tamt,mrent=mr,netbill=bill where
cno=i.cno;
end loop;
end;
/
• WAP to calculate tot and average of students for three subjects by
using cursor for loop.

declare
cursor c1 is select sub1,sub2,sub3,sno from stud;
t number(3);
a number(5,2);
i number(3);
begin
for i in c1
loop
t:=i.sub1+i.sub2+i.sub3;
a:=t/3;
update stud set tot=t,avr=a where sno=i.sno;
end loop;
end;
/

Exceptions:-
If in a pl/sql programme any error encounters then the exceptions
are used to control and handle those.
The exceptions are of different types those are:-
1.when_no_data_found
2.Too_many_rows
3.Dup_val_on_index etc.

1.too_many_rows:-This exception occurs if the select statement


retrieves more than one rows when the user need only one.
syntax:-
exception
when too_many_rows then
action;

• WAP to accept any employee no. and insert the existing data
into another table. Write the exceptions such that if any error
encounters then the empno and a message should be inserted
to another table called error_tab.

sql>create table error_tab(eno number(6),err_type varchar2(50));


sql>create table empl as select empno,ename,job,sal,deptno from
emp ;
sql>truncate table empl;

declare
e number(6);
n varchar2(10);
s number(8,2);
d number(2);
j varchar2(10);
begin
e:=&empno;
select ename,job,sal,deptno into n,j,s,d from emp1 where empno=e;
insert into empl values(e,n,j,s,d);
exception
when too_many_rows then
insert into error_tab values(e,’There are more than one rec with
same no.’);
when no_data_found then
insert into error_tab values(e,’There are no rec with this no.’);
when value_error then
insert into error_tab values(e,’Width of the field exceeds the limit’);
end;
/
Note:-Value_error occurs if the width of a field exceeds while
entering the value.

declare
e number(4);
n varchar2(10);
s number(8,2);
d number(2);
j varchar2(10);
begin
e:=&empno;
select ename,job,sal,deptno into n,j,s,d from emp1 where empno=e;
insert into temp1 values(e,n,j,s,d);
end;
/
create table err_tab(eno number(4),err_type varchar2(20));
dup_val_on_index:-This error occurs when a duplicate value is
entered into a column having unique index or primary key.
• Wap to enter the data to dept table by using exception such that it
should not display any error if duplicate deptno is inserted.

set serveroutput on
declare
dno number(2);
name varchar2(10);
l varchar2(10);
begin
dno:=&deptno;
name:=’&dname’;
l:=’&location’;
insert into dept values(dno,name,l);
exception
when dup_val_on_index then
insert into error_tab values(dno,’Record already exist’);
dbms_output.put_line(‘Record allready exist’);
end;
/

User defined exceptions:-


These can be defined by the user in the declaration section and can
be used in the plsql block.
syntax:-
declare
excep_name exception;
begin
.
.
if cond then
raise <<exception name>>;
end if;
when <<exception name >> then
action;
.
end;
/

declare
no number(3):=&rollno;
sname varchar2(10):=’&name’;
s1 number(3):=&sub1;
s2 number(3):=&sub2;
s3 number(3):=&sub3;
xyz exception;
begin
if s1>=100 or s2>=100 or s3>=100 then
raise xyz;
else
insert into stud values(no,sname,s1,s2,s3);
end if;
exception
when xyz then
dbms_output.put_line(‘Sorry ,U can not enter marks more than
100’);
insert into error_tab values(no,’Sorry mark can not be greater than
100’);
end;
/
ex:-
drop table bank;

create table bank(acno number(3),ahname varchar2(10),


pbal number(7,2),dep number(7,2),wit number(7,2),
cbal number(7,2));
declare
ano number(3);
name varchar2(10);
b number(7,2);
d number(7,2);
w number(7,2);
my_exp exception;
begin
ano:=&accno;
name:=’&ahname’;
b:=&bal;
d:=&dep_amt;
w :=&wit_amt;
insert into bank values(ano,name,b,d,w,0);
if (b+d)<w then
raise my_exp;
else
update bank set cbal=(b+d)-w where acno=ano;
end if;
exception
when my_exp then
insert into err_tab values(ano,’insufficient balance’);
end;
/

Attributes:-
By using the atributes the columns and rows can be declared by any
other columns or rows from an existing table.Attributes are of 2
types:-
1.column%type:-Declares a field as a column type from any oracle
table. This acts as the data type in the pl/sql blocks.
2.row%type:-designates the variable as a row type from any valid
oracle table.
• WAP to calculate hra,da,ta,pf,net for employees based on basic
sal.

drop table empl;


create table empl(eno number(3),ename varchar2(10),
sal number(7,2),hra number(5,2),da number(6,2),ta number(6,2),
pf number(5,2),net number(8,2));
insert into empl (eno,ename,sal) values (101,’aaa’,5000); insert into
empl (eno,ename,sal) values (102,’bbb’,3500); insert into empl
(eno,ename,sal) values (103,’ccc’,6500); insert into empl
(eno,ename,sal) values (104,’ddd’,8000);
declare cursor c1 is select eno,sal from empl;
no empl.eno%type;
s empl.sal%type;
h empl.hra%type;
d empl.da%type;
t empl.ta%type;
p empl.pf%type;
n empl.net%type;
begin
open c1;
loop
if c1%isopen then
fetch c1 into no,s;
exit when c1%notfound;
h:=s*13/100;
d:=s*25/100;
t:=800;
p:=s*10/100;
n:=(s+d+t+h)-p;
end if;
update empl set hra=h,da=d,ta=t,pf=p,net=n where eno=no;
end loop;
close c1;
end;
/
syntax for rowtype:-
rec_name(any var) table%rowtype;

WAP to select the datas of any employee from empl2 table and insert
it to another table called empl1.
drop table empl1;
create table empl1(eno number(4),ename varchar2(10), job
varchar2(10), sal number(8,2),dno number(2));
create table empl2 as select empno,ename,job,sal,deptno from emp;

declare
emp_rec empl2%rowtype;
x number(4);
begin
x:=&empno;
select * into emp_rec from empl2 where empno=x;
insert into empl1
values(emp_rec.empno,emp_rec.ename,emp_rec.job,emp_rec.sal,e
mp_rec.deptno);
end;
/

Procedures:-
Procedure is a pl/sql programme unit which will be stored
permanently if created once then they can be called by their names
several times when required.
syntax:-
create or replace procedure <<pro_name>>(argument lists) as/is
declaration of the variables.
begin
statements
end;

Executing a procedure individually:-


exec <<procedure name>>(arg1,arg2,...);
Create a procedure for adding any two numbers:-
create or replace procedure pro_add(no1 in number,no2 in number)
as
s number;
begin
s:=no1+no2;
dbms_output.put_line(‘Sum of the two numbers=’||s);
end;
/

Calling a procedure by using the programmes:-


set serveroutput on
declare
x number;
y number;
begin
x:=&num1;
y:=&num2;
pro_add(x,y);
end;
/

create or replace procedure input_rec(no number,name varchar2) as


begin
insert into empl (eno,ename) values(no,name);
end;
/
exec input_rec(101,’aaa’);
exec input_rec(102,’bbb’);
exec input_rec(103,’ccc’);
exec input_rec(104,’ddd’);
exec input_rec(105,’eee’);

create or replace procedure update_emp(no number,s number) is


h empl.hra%type;
d empl.da%type;
t empl.ta%type;
p empl.pf%type;
n empl.net%type;
begin
if s>=10000 then
h:=12*s/100;
d:=25*s/100;
t:=1000;
p:=10*s/100;
elsif s>=5000 and s<10000 then
h:=14*s/100;
d:=23*s/100;
t:=8*s/100;
p:=10*s/100;
else
h:=15*s/100;
d:=21*s/100;
t:=800;
p:=10*s/100;
end if;
n:=(s+h+d+t)-p;
update empl set sal=s,hra=h,da=d,ta=t,net=n,pf=p where eno=no;
end;
/

create or replace procedure delete_emp(no number) as


begin
delete from empl where eno=no;
end;
/

create or replace procedure addemp as


cursor c1 is select * from empl2 order by empno;
e number;
na varchar2(10);
j varchar2(10);
s number;
d number;
begin
open c1;
loop
fetch c1 into e,na,j,s,d ;
exit when c1%rowcount>5;
insert into empl1 values(e,na,j,s,d);
end loop;
close c1;
end;
/

Functions:-
These are also the stored programme units which can be created and
called any where in any other programs . Generally the function
returns a value. Unlike procedures they can not be called individually
by using the execute command.
syntax:-
create or replace function name(arg1 dtype,arg2 dtype,...) return
dtype is/as
declaration of variables.
begin
statements
return var;
end;

create a function for adding any three numbers.


create or replace function funadd(no1 in number,
no2 in number,no3 in number) return number is
s number;
begin
s:=no1+no2+no3;
return s;
end;
/

• prog to call addfun:-


set serveroutput on
declare
a number(3):=&no1;
b number(3):=&no2;
c number(3):=&no3;
x number(5);
begin
x:=funadd(a,b,c);
dbms_output.put_line(‘Sum of three numbers= ‘||x);
end;
/
declare
s number;
begin
s:=funadd(100,200,300);
dbms_output.put_line(‘Sum of three numbers= ‘||s);
end;
/

• crteate a function to find factorial of a number.

create or replace function funfact(no in number) return number is


x number:=1;
f number:=1;
begin
while x<=no
loop
f:=f*x;
x:=x+1;
end loop;
return f;
end;
/

declare
n number;
f number;
begin
n:=&numbe;
f:=funfact(n);
dbms_output.put_line(‘Factorial of ‘||n||’= ‘||f);
end;
/

• WAP to get the hiredate of an employee from the emp table and
print it.

create or replace function funhire(eno in number) return date is


hdate date;
begin
select hiredate into Hdate from emp where empno=eno;
return hdate;
end;
/

declare
e number(4);
hire date;
begin
e:=&empno;
hire:=funhire(e);
dbms_output.put_line(‘The employee is hired on ‘||to_char(hire,’day
ddth month yyyy’) );
end;
/
PACKAGES:-
This is also a stored program unit which is a combination of more
than one procedures or functions.While calling the procedures and
function they should be written along with the package name.There
are two parts in a packege.
1.Package definition
2.Package body definition

1.Package definition:-
syntax:-
create or replace package <<package name>> as/is
procdure and function inclusion
end <<packagename>>;
/
2.Package body definition:-
create or replace package body <<pack body name>> as/is
procedure <<pro name1>> (arg1 dtype,arg2 dtype) is
procedure definition
.....................
..............
end <<pro_name1>>;
procedure <<pro name2>> (arg1 dtype,arg2 dtype) is
procedure definition
.....................
..............
end <<pro_name2>>;
create or replace package my_pack is procedure addpro(no1 in
number,no2 in number); procedure subpro(no1 in number,no2 in
number);
function profun(no1 in number,no2 in number) return number ;
function divfun(no1 in number,no2 in number) return number;
end my_pack;
/

• Package body creation

create or replace package body my_pack is


procedure addpro(no1 in number,no2 in number) is
s number;
begin
s:=no1+no2;
dbms_output.put_line(‘Sum of the two numbers=’||s);
end addpro;
procedure subpro(no1 in number,no2 in number) is
d number;
begin
d:=no1-no2;
dbms_output.put_line(‘Difference of the two numbers=’||d);
end subpro;
function profun (no1 in number,no2 in number) return number is
p number;
begin
p:=no1*no2;
return p;
end profun;
function divfun (no1 in number,no2 in number) return number is
q number;
begin
q:=no1/no2;
return q;
end divfun;
end my_pack;
/

• To find product and quotient


declare
n1 number(4):=&no1;
n2 number(4):=&no2;
p number(5);
q number(5,2);
begin
p:=my_pack.profun(n1,n2);
q:=my_pack.divfun(n1,n2);
dbms_output.put_line(‘Product of the two numbers=’||p);
dbms_output.put_line(‘Quotient of the two numbers=’||q);
end;
/

exec my_pack.addpro(20,30)
exec my_pack.subpro(34,20) etc.

• Create a package with three procedures 1.For adding the


student data to a table 2.For calculating the total, average,
result and division 3.for deleting a record from the student
table. after that write a program to call all of those.

Create or replace package pack_me is


Procedure adddata (no number,sname varchar2) ;
Procedure caldata(no number,s1 number,s2 number,s3 number);
Procedure deldata(no number) ;
End pack_me;
/

create or replace package body pack_me is


procedure adddata(no number,sname varchar2) is
begin
insert into stud (rno,name)values(no,sname);
end adddata;
procedure caldata (no number,s1 number,s2 number,s3 number) is
t stud.tot%type;
a stud.avr%type;
re stud.res%type;
di stud.div%type;
begin
t:=s1+s2+s3;
a:=t/3;
if s1>=35 and s2>=35 and s3>=35 then
re:=’pass’;
else
re:=’fail’;
end if;
if re=’pass’ and a>=60 then
di:=’first’;
elsif re=’pass’ and a>=50 then
di:=’second’;
elsif re=’pass’ and a>=35 then
di:=’third’;
else
di:=’Nill’;
end if;
update stud set
sub1=s1,sub2=s2,sub3=s3,tot=t,avr=a,res=re,div=di where rno=no;
end caldata;
procedure deldata(no number) is
begin
delete from stud where rno=no;
end deldata;
end pack_me;
/

exec pack_me.adddata(102,’bbbb’)
exec pack_me.caldata(101,34,55,65)
exec pack_me.deldata(102)

Database triggers:-
Triggers are the stored program units which fires when a dml
statement encounters the table based on which it is created.The
triger always fires for each row in the table.Triggers are of two types
according to the time of firing.Those are
1.After insert or update or delete
2.Before insert or update or delete
Syntax:-
create or replace trigger <<trigg name>> after/before
insert or update or delete on <<table name>> for each row
declare
<<declaration section>>
begin
<<execution part>>
end;
drop table mess;
create table mess(mess varchar2(20),time varchar2(30));

create or replace trigger mytri before insert or update or delete on


stud for each row
declare
m varchar2(20);
time varchar2(30);
begin
if (inserting) then
m:=’you are inserting’;
end if;
if (updating) then
m:=’u are updating’;
end if;
if (deleting) then
m:=’u are deleting’;
end if;
time:=to_char(sysdate,’ddth month yyyy hh:mi am’);
insert into mess values(m,time);
end;
/

Create a trigger to update the stock table when purchased and sold.

drop table stock;

create table stock(itemno number(3) constraints st_pk primary


key,iname varchar2(10),qstock number(4));

drop table purchase;


create table purchase(itemno number(3) references
stock(itemno),iname varchar2(10),qpur number(4));

drop table sales;


create table sales(itemno number(3) references
stock(itemno),iname varchar2(10),qsold number(4));
insert into stock values(101,’tv’,100);
insert into stock values(102,’cooler’,100);
insert into stock values(103,’fridge’,100);
insert into stock values(104,’suitcase’,100);

create or replace trigger pur_tri after insert on purchase for each


row
declare
q number(4);
begin
select qstock into q from stock where itemno=:new.itemno;
update stock set qstock=q+:new.qpur where itemno=:new.itemno;
end;
/

create or replace trigger sale_trig after insert on sales for each row
declare
q number(4);
begin
select qstock into q from stock where itemno=:new.itemno;
if q<:new.qsold then
raise_application_error(‘-20001’,’Insufficient stock’);
else
update stock set qstock=q-:new.qsold where itemno=:new.itemno;
end if;
end;
/

• create a table for bank and write a trigger for transaction.



• create table bank_main(acno number(3) constraints b_pk primary
key,
• ahname varchar2(10),bal number(10,2));

• create table bank_trans(acno number(3) references
bank_main(acno),
• payeename varchar2(10),trtype varchar2(10),
• tramount number(10,2));

• insert into bank_main values(101,’rajesh’,20000);
• insert into bank_main values(102,’Suresh’,10000);
• insert into bank_main values(103,’Satish’,5000);
• insert into bank_main values(104,’Priya’,7500);
• insert into bank_main values(105,’Simran’,4500);

• create or replace trigger trans_tri after insert on bank_trans for
each row
• declare
• b number(10,2);
• begin
• select bal into b from bank_main where acno=:new.acno;
• if :new.trtype=’withdraw’ and b<:new.tramount then
• raise_application_error(-20002,’Insufficient balance,overdraft’);
• elsif :new.trtype=’withdraw’ then
• update bank_main set bal=b-:new.tramount where
acno=:new.acno;
• elsif :new.trtype=’deposit’ then
• update bank_main set bal=b+:new.tramount where
acno=:new.acno;
• end if;
• end;
• /

• create or replace trigger date_tri before insert or update or delete
on bank_trans for each row
• begin
• if to_char(sysdate,’d’)=1 then
• raise_application_error(-20003,’Today is Sunday’);
• elsif to_char(sysdate,’hh24’) not between 9 and 13 then
• raise_application_error(-20004,’This is not working hour’);
• elsif to_char(sysdate,’dd’)=23 and to_char(sysdate,’mon’)=’feb’
then
raise_application_error(-20005,’Today this is Holiday for Bakrid’);
end if;
end;
/
--Create a trigger to calculate the total and average marks for 3
subjects after inserting the marks to the student table.

You might also like