0% found this document useful (0 votes)
137 views

J.M.J College For Women (Autonomous) : Tenali: Certificate

The document describes experiments conducted on Oracle database tables. It includes creating a table called Employee with columns for employee number, name, job, manager, and salary. Additional experiments involve adding a commission column to the Employee table, inserting sample records, updating a job title, renaming the manager column, and deleting a record by employee number.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
137 views

J.M.J College For Women (Autonomous) : Tenali: Certificate

The document describes experiments conducted on Oracle database tables. It includes creating a table called Employee with columns for employee number, name, job, manager, and salary. Additional experiments involve adding a commission column to the Employee table, inserting sample records, updating a job title, renaming the manager column, and deleting a record by employee number.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 37

J.M.

J COLLEGE FOR WOMEN (AUTONOMOUS): TENALI


DEPARTMENT OF COMPUTER SCIENCE

CERTIFICATE

This is certified that bonafide record of practical work done by


__________________________________________________________ with
Regd. No: ___________________of Course_____________________ during the year
______________________

Total number of experiments done: _______________________

Lecturer in-charge Head of the Department

External Examiner
INDEX

S.No List of Experiments Page No

1 INTRODUCTION TO ORACLE 3

2 CREATION OF TABLES 7

3 QUERIES USING DDL AND DML 12

4 QUERIES USING AGGREGATE FUNCTIONS 21

5 PROGRAMS ON PL/SQL 24

6 PROCEDURES AND FUNCTIONS 30

7 TRIGGERS 32

8 CURSORS 36
INTRODUCTION TO ORACLE

1. DDL: Data Definition Language (DDL) statements are used to define the database
structure or schema.

DDL Commands: Create, Alter, Drop, Rename,

Truncate CREATE - to create objects in the database

ALTER - alters the structure of the

database DROP - delete objects from

the database

TRUNCATE - remove all records from a table, including all spaces allocated for the records are

removed RENAME - rename an object

2. DML:DataManipulationLanguage(DML)statementsareusedformanagingdatawithinsche
ma objects and to manipulate data of a databaseobjects.

DML Commands: Insert, Update, Delete,

Select INSERT - insert data into a table

UPDATE - updates existing data within a table

DELETE - deletes all records from a table, the space for the records

remain SELECT - retrieve data from the a database

3. DCL:DataControlLanguage(DCL)statementsareusedtocreateroles,permissions,andreferentia
l integrityaswellitisusedtocontrolaccesstodatabasebysecuringit.Tocontrolthedataof adatabase.

DCL Commands: Grant, Revoke

GRANT - gives user's access privileges to database

REVOKE -withdraw access privileges given with the GRANT command

4. TCL:TransactionControl(TCL)statements areusedto
managethechangesmadebyDML statements. It allows statements to be grouped together
into logicaltransactions.

TCL Commands: Commit, Rollback, Save point

COMMIT - save work done

3
SAVEPOINT - identify a point in a transaction to which you can later roll back

ROLLBACK - restore database to original since the last COMMIT

Syntax with examples

1. DDL (Data Definition Language) Commands: CREATE, ALTER and

DROP. CREATE: This command useful for creating creating table.

Syntax:

create table [table name] (column1 datatype[size], column 2 datatype[size],… column n datatype[size]
);

Ex:

SQL >create table student (s_rollnonumber(10) primary key,s_name varchar2(10), gender


varchar2(5),dob date,addr1 varchar2(10),addr2 varchar2(10),city varchar2(10), percentage
number(4));

SQL> DESC STUDENT;

Name Null? Type

S_ROLLNO NOT NULL NUMBER(10)

S_NAME VARCHAR2(10)

GENDER VARCHAR2(5)

DOB DATE

ADDR1 VARCHAR2(10)

ADDR2 VARCHAR2(10)

CITY VARCHAR2(10)

PERCENTAGE NUMBER(4)

SQL > select s_rollno,s_name from

student; no rows selected.

Create table by using Constraints:

4
Constraints are two types:

1. Table Level Constraints.


2. Column Level Constraints.

1. NOT NULL:

a) Not null constraint at column level.

Syntax:

<col><datatype>(size)not null

SQL > create table emp(e_id varchar(5) NOT NULL,e_name varchar(10), e_design varchar(10),dept
varchar(10),mgr varchar(10),salary number(10));

2. UNIQUE:

Unique constraint at column

level. Syntax:

<col><datatype>(size)unique Ex:-

SQL > create table depositor(customer_name varchar(10),acc_no number(15) UNIQUE, brach_name


varchar(10));

Unique constraint at table level:

Syntax:

Create table tablename(col=format,col=format,unique(<col1>,<col2>));

Ex:-

SQL > create table depositor1(customer_namevarchar(10),acc_no number(15),


brach_name varchar(10),UNIQUE(acc_no));

3. PRIMARYKEY:

Primary key constraint at column level

Syntax:

<col><datatype>(size)primary key;

Ex:-

SQL> create table customer(customer_id number (5) PRIMARY KEY, customer_name


varchar(10),customer_street varchar(10),brach_name varchar(10));

5
Primary key constraint at table level.

Syntax:

Create table tablename(col=format,col=format primary key(col1>,<col2>);

Ex:-

SQL > create table customer1(customer_id number (5),customer_name varchar(10),customer_street


varchar(10),brach_name varchar(10),PRIMARY KEY(customer_id));

4. CHECK:

Check constraint constraint at column level.

Syntax: <col><datatype>(size) check(<logical expression>)

Ex:-create table loan(loan_no varchar(10),customer_name varchar(10), balance number (10)


CHECK(balance>1000));

Check constraint constraint at table level.

Syntax: check(<logical expression>)

Ex:-create table loan1(loan_no varchar(10),customer_name varchar(10), balance number (10),


CHECK(balance>1000));

5. FOREIGNKEY:

Foreign key constraint at column level.

Syntax:

Column_name Datatype(size) REFERENCES parent_table_name (parent_column_name)

Ex:- CREATE TABLE books (book_id NUMBER(3), book_title

VARCHAR2(30),book_price NUMBER(3), book_author_id NUMBER(3)

REFERENCES author(author_id ));

Foreign key constraint at table level

Syntax:

CONSTRAINT constraint_name FOREIGN KEY(child_table_column) REFERENCES


Parent_table_name(parent_table_column)

Ex:-CREATE TABLEbooks (book_id NUMBER(3) CONSTRAINT bok_bi_pk


PRIMARY KEY, book_title VARCHAR2(30), book_price
NUMBER(3), book_author_id NUMBER(3),CONSTRAINT bok_ai_fk
6
FOREIGNKEY (book_author_id) REFERENCES author(author_id));

WEEK-1
CREATION OF TABLES

1) Create a table called Employee with the followingstructure.

Name Type
Empno Number
Ename Varchar2(10)
Job Varchar2(10)
Mgr Number
Sal Number

a. Add a column commission with domain to the Employeetable.


b. Insert any five records into thetable.
c. Update the column details ofjob
d. Rename the column mgr in Employee table using altercommand.
e. Delete the employee whose Empno is105.

SOLUTION:
SQL> create table employee(empnonumber,ename varchar2(10),job
varchar2(10),mgrnumber,sal number);
Table created.
SQL> desc employee;
Name Null? Type

EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER

a. Add a column commission with domain to the Employeetable.

SQL> alter table employee add(commission number);


Table altered.
SQL> desc employee;
Name Null? Type

EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MGR NUMBER
SAL NUMBER
COMMISSION NUMBER

b. Insert any five records into thetable.

SQL>insert into employee values(101,'abhi','manager',1234,10000,'70')


7
1 row created.

SQL> insert into employee values(102,'rohith','analyst',2345,9000,'65')


1 row created.

SQL>
insert into employee values(103,'david','analyst',3456,9000,'65')
1 row created.

SQL> insert into employee values(104,'rahul','clerk',4567,7000,'55')


1 row created.

SQL> insert into employee values(105,'pramod','salesman',5678,5000,'50')


1 row created.

SQL> select * from employee;

EMPNOENAME JOB MGR SALCOMMISSION

101 abhi manager 1234 10000 70


102 rohith analyst 2345 9000 65
103 david analyst 3456 9000 65
104 rahul clerk 4567 7000 55
105 pramod salesman 5678 5000 50

c. Update the column details ofjob

SQL> update employee set job='trainee' where empno=103;


1 row updated.

SQL> select * from employee;


EMPNOENAME JOB MGR SALCOMMISSION

101 abhi manager 1234 10000 70


102 rohith analyst 2345 9000 65
103 david trainee 3456 9000 65
104 rahul clerk 4567 7000 55
105 pramod salesman 5678 5000 50

d. Rename the column of Employ table using altercommand.

SQL> alter table employee rename column mgr to manager_no;

Table altered.

SQL> desc employee;


Name Null? Type

8
EMPNO NUMBER
ENAME VARCHAR2(10)
JOB VARCHAR2(10)
MANAGER_NO NUMBER
SAL NUMBER
COMMISSION NUMBER

e. Delete the employee whose Empno is105.

SQL> delete employee where empno=105;


1 row deleted.

SQL> select * from employee;


EMPNOENAME JOB MANAGER_NO SALCOMMISSION

101 abhi manager 1234 10000 70


102 rohith analyst 2345 9000 65
103 david trainee 3456 9000 65
104 rahul clerk 4567 7000 55

2) Create department table with the followingstructure.

Name Type
Deptno Number
Deptname Varchar2(10)
location Varchar2(10)

a. Add column designation to the departmenttable.


b. Insert values into thetable.
c. List the records of dept table grouped bydeptno.
d. Update the record where deptnois9.
e. Delete any column data from thetable.

SOLUTION:
SQL> create table department(deptnonumber,deptname varchar2(10),locationvarchar2(10));
Tablecreated.

SQL> desc department;


Name Null? Type

DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)

a. Add column designation to the departmenttable.

SQL> alter table department add(designation varchar2(10));


Table altered.

9
SQL> desc department;
Name Null? Type

DEPTNO NUMBER
DEPTNAME VARCHAR2(10)
LOCATION VARCHAR2(10)
DESIGNATION VARCHAR2(10)

b. Insert values into the table.

SQL> insert into department values(9,'accounting','hyderabad','manager')

1 row created.
SQL>insert into department values(10,'research','chennai','professor')

1 row created.

SQL>
insert into department values(11,'sales','banglore','salesman')
1 row created.

SQL>
insert into department values(12,'operations','mumbai','operator')
1 row created.

SQL> insert into department values(9,'accounting','chennai','manager')


1 row created.

SQL> select * from department ;

DEPTNO DEPTNAME LOCATIONDESIGNATION

9 accounting hyderabad manager


10 research chennai professor
11 sales banglore salesman
12 operations mumbai operator
9 accounting chennai manager

c. List the records of dept table grouped bydeptno.

SQL> select deptno,deptname from department group by deptno,deptname;

DEPTNO DEPTNAME

9accounting
12operations
10 research
11 sales

d. Update the record where deptno is9.

10
SQL> update department set designation='accountant' where deptno=9;

2 rows updated.
SQL> select * from department;
DEPTNO DEPTNAME LOCATION DESIGNATION

9 accounting hyderabad accountant


10 research chennai professor
11 sales banglore salesman
12 operations mumbai operator
9 accounting chennai accountant

e. Delete any column data from thetable.

SQL> alter table department drop(designation);


Table altered.
SQL> select * from department;
DEPTNO DEPTNAMELOCATION

9 accounting hyderabad
10 research chennai
11 sales banglore
12 operations mumbai
9 accounting Chennai

11
WEEK -2
QUERIES USING DDL ANDDML

1. a. Create a user and grant all permissions to theuser.


b. Insert the any three records in the employee table and use rollback. Check theresult.
c. Add primary key constraint and not null constraint to the employeetable.
d. Insert null values to the employee table and verifytheresult.

SOLUTION:

a) create a user and grant all permissions to theuser.

CONNECT <USER-NAME>/<PASSWORD>@<DATABASE NAME>;

--Create user query

CREATE USER <USER NAME> IDENTIFIED BY <PASSWORD>;

--Provide roles

GRANT CONNECT,RESOURCE,DBA TO <USER NAME>;

--Assigning privileges

GRANT CREATE SESSION GRANT ANY PRIVILEGE TO <USER NAME>;


GRANT UNLIMITED TABLESPACE TO <USER NAME>;

--Provide access to tables.

GRANT SELECT, UPDATE, INSERT, DELETE ON <TABLE NAME> TO <USER NAME>;

b) Insert the any three records in the employee table and use rollback. Check theresult.

SQL> SELECT * FROM EMPLOYEE;


EMPNO ENAME JOB MANAGER_NO SAL COMMISSION

101 abhi manager 1234 1100 70


102 rohith analyst 2345 9000 65
103 david trainee 3456 9000 65
104 rahul clerk 4567 7000 55

SQL> insert into employee values(105,'aravind','salesman',5678,5000,50)


1 row created.

SQL> rollback;
Rollback complete.

SQL> SELECT * FROM EMPLOYEE;

12
EMPNO ENAME JOB MANAGER_NO SAL COMMISSION

101 abhi manager 1234 1100 70


102 rohith analyst 2345 9000 65
103 david trainee 3456 9000 65
104 rahul clerk 4567 7000 55

c) Add primary key constraint and not null constraint to the employeetable.
SQL> alter table employee modify(empno number primary key, ename varchar2(10) not null);
Table altered.

SQL> desc employee;


Name Null? Type

EMPNO NOT NULL NUMBER


ENAME NOT NULL VARCHAR2(10)
JOB VARCHAR2(10)
MANAGER_NO NUMBER
SAL NUMBER
COMMISSION NUMBER

d) Insert null values to the employee table and verify theresult.


SQL> desc employee;
Name Null? Type

EMPNO NOT NULL NUMBER


ENAME NOT NULL VARCHAR2(10)
JOB NOT NULL VARCHAR2(10)
MANAGER_NO NUMBER
SAL NOT NULL NUMBER
COMMISSION NUMBER

SQL> insert into employee values(105,'mohith','salesman',5678,null,50)


insert into employee values(105,'mohith','salesman',5678,null,50)
*

2. a. create a user and grant all permissions to theuser.


b. Insert values in the department table and usecommit.
c. Add constraints like unique and not null to the departmenttable.
d. Insert repeated values and null values into thetable.

SOLUTION:

a) create a user and grant all permissions to theuser.

CONNECT <USER-NAME>/<PASSWORD>@<DATABASE NAME>;

--Create user query


13
CREATE USER <USER NAME> IDENTIFIED BY <PASSWORD>;

--Provide roles

GRANT CONNECT,RESOURCE,DBA TO <USER NAME>;

--Assigning privileges

GRANT CREATE SESSION GRANT ANY PRIVILEGE TO <USER NAME>;


GRANT UNLIMITED TABLESPACE TO <USER NAME>;

--Provide access to tables.

GRANT SELECT, UPDATE, INSERT, DELETE ON <TABLE NAME> TO <USER NAME>;

b) Insert values in the department table and usecommit.

SQL> insert into department values(13,'sales','delhi')


1 row created.

SQL> commit;
Commit complete.

SQL> select * from department;


DEPTNO DEPTNAMELOCATION

9 accounting hyderabad
10 research chennai
11 sales banglore
12 operations mumbai
9 accounting chennai
13 sales delhi

6 rows selected.
c) Add constraints like unique and not null to the departmenttable.

SQL> alter table department modify(deptno numberunique);

Tablealtered.

SQL> alter table department modify(location varchar2(10) notnull);

Tablealtered.

SQL> DESC DEPARTMENT;


Name Null? Type

DEPTNO NUMBER
DEPTNAME VARCHAR2(10)

14
LOCATION NOT NULLVARCHAR2(10)

d) Insert repeated values and null values into the table.

SQL> insert into department values(10,'research','')


insert into department values(10,'research','')
SQL> insert into department values(10,'research','hyderabad')
insert into department values(10,'research','hyderabad')

AIM:Creation,altering and dropping of tables and inserting rows in to a table(use constraints while
creating a table).
Examples using select command:
Student(sid,name,age,college,remarks);
Enroll(sid,cid ,grade);

CREATION OF TABLE USING CONSTRAINTS:

STUDENT Table:

SQL> create table students4(sidchar(20),name char(20),age integer,college char(20),remarks


char(20),primary key(sid));

Table created.

DESCRIPTION OF TABLE:

SQL> desc students4


Name Null? Type
----------------------------------------- -------- ----------------------------
SID NOT NULL CHAR(20)
NAME CHAR(20)
AGE NUMBER(38)
COLLEGE CHAR(20)
REMARKS CHAR(20)

INSERT VALUES INTO TABLE:

SQL> insert into students4 values('J18A31156','divya',19,'JMJ','Excellent')

1 row created.

SQLinsert into students4 values('J18A31161','harshitha',19,'JMJ','Excelle

1 row created.

SQL> insert into students4 values('J18A31173','rukmini',19,'JMJ','Good')

1 row created.

SQL> insert into students4 values('J18A31174','manju',18,'JMJ','Good')

15
1 row created.

SQL> insert into students4 values('09JM1A0505','krishnaveni',12,'Mrr','Average')

1 row created.

SQL> insert into students4 values('09JM1A0506','anitha',15,'GIST','Good')

1 row created.

SQL> insert into students4 values(' 09JM1A0507','anusha',14,'Amrita sai','Average')


1 row created.

SQLinsert into students4 values('09JM1A0508','manasa',17,'MVR','Good')

1 row created.

SQL> insert into students4 values('09JM1A0509','vasavi',18,'vasavi engg','Average')

1 row created.

SQL insert into students4 values('09JM1A0510','Prasanthi',20,'Nimra','Good')

1 row created.

SQL> set linesize100;

DISPLAYING TABLE:

SQL> select * from students4;

SID NAME AGE COLLEGE REMARKS


-------------------- -------------------- ---------- -------------------- --------------------
J18A31156 divya 19 JMJ Excellent
J18A31161 harshitha 19 JMJ Excellent
J18A31173 rukmini 19 JMJ Good
J18A31174 manju 18 JMJ Good
09JM1A0505 krishnaveni 12 Mrr Average
09JM1A0506 anitha 15 GIST Good
09JM1A0507 anusha 14 Amrita sai Average
09JM1A0508 manasa 17 MVR Good
09JM1A0509 vasavi 18 vasaviengg Average
09JM1A0510 Prasanthi 20 Nimra Good

10 rows selected.

ENROLL Table:

SQL> create table enroll12(sidchar(10),cid char(10),grade char(5),primary key(sid,cid),foreign key(sid)


references students4);

16
Table created.

SQL> desc enroll12;


Name Null? Type
----------------------------------------------------- -------- ------------------------------------
SID NOT NULL CHAR(20)
CID NOT NULL CHAR(10)
GRADE CHAR(5)

SQL> insert into enroll12 values('J18A31156','jm','A')

1 row created.

SQL> insert into enroll12 values('J18A31161','jm','A')

1 row created.

SQL> insert into enroll12 values('J18A31173','mf','B')

1 row created.

SQL>insert into enroll12 values('J18A31174','sd','B')

1 row created.

SQL>insert into enroll12 values('09JM1A0505','se','C')

1 row created.

SQL> insert into enroll12 values('09JM1A0506','ab','D')

1 row created.

SQL> select * from enroll12;

SID CID GRADE


-------------------- ---------- -----
J18A31156 jm A
J18A31161 jm A
J18A31173 mf B
J18A31174 sd B
09JM1A0505 se C
09JM1A0506 ab D
6 rows selected.

SQL QUERIES

1)Find all the names from students4 table?


SQL> select name from students4;
17
NAME
--------------------
divya
harshitha
rukmini
manju
krishnaveni
anitha
anusha
manasa
vasavi
Prasanthi

10 rows selected.

2)Find the sid's of all students in theJMJcollege?


SQL> select sid from students4 where college='JMJ';

SID
--------------------
J18A31156
J18A31161
J18A31173
J18A31174

3)Find the sid's of students whose grade is A?


SQL> select s.sid from students4 s,enroll12 e where s.sid=e.sid and grade='A';

SID
--------------------
J18A31156
J18A31161

4)Find the names of the students whose remark is good?


SQL> select name from students4 where remarks='Good';

NAME
--------------------
rukmini
manju
anitha
manasa
Prasanthi

5)Find the names of the students whose age is in between 16 and 20?
SQL> select name from students4 where age>16 and age<20;

NAME
--------------------
divya
18
harshitha
rukmini
manju
manasa
vasavi

6 rows selected.

6)Find the names of students whose grade is A?


SQL> select name from students4 s,enroll12 e where s.sid=e.sid and grade='A';

NAME
--------------------
divya
harshitha.

ALTERING A TABLE:

7)Add the new coloumn marks to the table students4 ?

SQL> alter table students4 add(marks char(20));

Table altered.

8).Change the size of the coloumn marks to 10?

SQL> alter table students4 modify(marks char(10));

Table altered.

SQL> desc students4;

Name Null? Type


----------------------------------------------------- -------- ------------------------------------
SID NOT NULL CHAR(20)
NAME CHAR(20)
AGE NUMBER(38)
COLLEGE CHAR(20)
REMARKS CHAR(20)
MARKS CHAR(10)

DROPPING A TABLE:

9).Drop the table bonus ?


SQL> drop table bonus;

Table dropped.

SQL> select * from bonus;


select * from bonus
*
19
ERROR at line 1:
ORA-00942: table or view does not exist

10).Drop the table client ?


SQL> drop table client;

Table dropped.

SQL> select * from client;


select * from client
*
ERROR at line 1:
ORA-00942: table or view does not exist

UPDATING A TABLE:

11).Change the remarks of student whose sid is 09JM1A0505 ?


Ans.
SQL> update students4 set remarks='Good' where sid='09JM1A0505';

1 row updated.
SQL> select * from students4;
SID NAME AGE COLLEGE REMARKS MARKS
-------------------- -------------------- ---------- -------------------- -------------------- -----
J18A31156 divya 19 JMJ Excellent
J18A31161 harshitha 19 JMJ Excellent
J18A31173 rukmini 19 JMJ Good
J18A31174 manju 18 JMJ Good
09JM1A0505 krishnaveni 12 Mrr Average
09JM1A0506 anitha 15 GIST Good
09JM1A0507 anusha 14 Amrita sai Average
09JM1A0508 manasa 17 MVR Good
09JM1A0509 vasavi 18 vasaviengg Average
09JM1A0510 Prasanthi 20 Nimra Good

20
WEEK -3
QUERIES USING AGGREGATE FUNCTIONS

AIM :- Queries using aggregate


functions(COUNT,AVG,MIN,MAX,SUM),Group by,Orderby,Having.

E_id E_name Age Salary


101 Anu 22 9000
102 Shane 29 8000
103 Rohan 34 6000
104 Scott 44 10000
105 Tiger 35 8000
106 Alex 27 7000
107 Abhi 29 8000

(i) Create Employee table containing allRecords.


SQL> create table emp(eidnumber,ename varchar2(10),age number,salary
number); Table created.
SQL> desc emp;

Name Null? Type

EID NUMBER
ENAME VARCHAR2(10)
AGE NUMBER
SALARY NUMBER

(ii) Count number of employee names from employeetable.


SQL> select count(ename) from emp;
COUNT(ENAME)
-
7
(iii) Find the Maximum age from employeetable.
SQL> select max(age) from emp;
MAX(AGE)

44
(iv) Find the Minimum age from employeetable.
SQL> select min(age) from emp;

21
MIN(AGE)
22

22
(v) Display the Sum of age employeetable.
SQL> select sum(age) from emp;
SUM(AGE)

220
(vi) Display the Average of age from Employeetable.
SQL> select avg(age) from emp;
AVG(AGE)

31.4285714
(vii) Create a View for age in employeetable.
SQL> create or replace view A as select age from emp where
age<30; View created.
(viii) Displayviews
SQL> select * from A;
AGE

22
29
27
29
(ix) Find grouped salaries of employees.(group byclause)
SQL> select salary from emp group by
salary; SALARY

9000
10000
8000
6000
7000
(x).Find salaries of employee in Ascending Order.(order by clause)
SQL>select ename,salary from emp order by
salary; ENAME SALARY

rohan 6000
alex 7000
shane 8000
23
abhi 8000
tiger 8000
anu 9000
scott 10000

7 rows selected.

(xi) Find salaries of employee in DescendingOrder.

SQL> select ename,salary from emp order by salary desc;

ENAME SALARY
-
scott 10000
anu 9000
shane 8000
abhi 8000
tiger 8000
alex 7000
rohan 6000
7 rows selected.
(xii) HavingClause.
SQL> select ename,salary from emp where age<29 group by ename,salary
having salary<10000;
ENAME SALARY
-
alex 7000
anu 9000

24
WEEK – 4
PROGRAMS ON PL/SQL

1) Write PL/SQL Program to Find Greatest of Three Numbers

declare
a number:=10;
b number:=12;
c number:=5;
begin
dbms_output.put_line('a='||a||' b='||b||' c='||c);
if a>b AND a>c
then
dbms_output.put_line('a is greatest');
else
if b>a AND b>c
then
dbms_output.put_line('b is greatest');
else
dbms_output.put_line('c is greatest');
end if;
end if;
end;

OUTPUT

a=10 b=12 c=5


b is greatest

Statement processed.

25
2) Write PL/SQL program for swapping 2 numbers.

declare
     a number;
     b number;
     temp number;
  begin
    a:=:a;
     b:=:b;
       dbms_output.put_line('before swapping:');
     dbms_output.put_line('a='||a||' b='||b);
         temp:=a;
     a:=b;
    b:=temp;
        dbms_output.put_line('after swapping:');
    dbms_output.put_line('a='||a||' b='||b);
     end;

OUTPUT

:a 5
:b 10
before swapping:
a=5 b=10
after swapping:
a=10 b=5

Statement processed.

26
3) Write a PL/SQL program to accept a number and find the sum of the digits
declare
num int :=0;
i int;
s int :=0;
r int;
begin
num:=:num;
while num > 0 loop
r:= MOD(num, 10);
s := s + r;
num:=floor(num/10);
end loop;
dbms_output.put_line(' the sum of digits is '||s );
end;
Output

:NUM 123
the sum of digits is 6

Statement processed.

27
4) Write a PL/SQL Program to accept a number from user and print number in reverse order.

Declare
Num1 number(5);
Num2 number(5);
Rev number(5)
begin
Num1:=:Num1;
Rev:=0;
while Num1>0 loop
Num2:=Num1 mod 10;
Rev:=Num2+(Rev*10);
Num1:=floor(Num1/10);
end loop;
dbms_output.put_line('Reverse number is'||rev);
end;
/

Output
:NUM1 321

'Reverse number is:123

28
5) Write a PL/SQL program to find the factorial of a givennumber.
declare
i number(4):=1;
n umber(4):=:n; f
number(4):=1;
begin
for i in1..n
loop
f:=f*i;
end loop;
dbms_output.put_line('the factorial of '||n||' is:'||f);
end;

Output

:N 5
the factorial of 5 is: 120

29
6) Write a PL/Sql Program to calculate the area of a circle

declare
pi constant number(4,2) := 3.14;
radius number(5);
area number(14,2);
Begin
radius := 3;
area := pi* power(radius,2);
dbms_output.put_line(‘area=’||area);
end;
/

Output

Area=28.26

Statement processed.

30
WEEK -5
PROCEDURES AND FUNCTIONS

1) calculate the net salary and year salary if da is 30% of basic, hra is 10% of basic and pf is
7% if basic salary is less than 8000, pf is 10% if basic sal between 8000 to160000.
Declare
ename varchar2(15);
basic number;
da number;
hra number;
pf number;
netsalary number;
yearsalarynumber;
begin
ename:=':ename';
basic:=:basic;
da:=basic*(30/100);
hra:=basic * (10/100);
if (basic < 8000)
then
pf:=basic * (7/100);
elseif (basic >= 8000 and basic <= 16000) then
pf:=basic * (10/100);
end if;
netsalary:=basic + da + hra - pf;
yearsalary := netsalary*12;
dbms_output.put_line('Employee name : ' || ename);
dbms_output.put_line('Providend Fund : ' || pf);
dbms_output.put_line('Net salary : ' || netsalary);
dbms_output.put_line('Year salary : '|| yearsalary);
end;
/

31
2) Create a function to find the factorial of a given number and hence findNCR.

create or replace function fact(n number)


return number
is
a number:=n; f
number:=1; i
number; begin
for i in 1..n
loop
f:=f*a;
a:=a-1;
end loop;
return f;
end;
/
create or replace function ncr(n number ,r number) return number
is
n1 number:=fact(n); r1
number:=fact(r);
nr1number:=fact(n-r);
resul number;
begin
resul:=(n1)/(r1*nr1);
return resul;
end;

3) Create a procedure to reverse a string.

CREATE OR REPLACE PROCEDURE ReverseOf(input IN varchar2(50))

IS

DECLARE
reverse varchar2(50);
BEGIN
FOR i in reverse 1..length(input) LOOP
reverse := reverse||''||substr(input, i, 1);
END LOOP;
dbms_output.put_line(reverse);
END;

32
/

WEEK-6

TRIGGERS

1. Create a row level trigger for the customers table that would fire for INSERT orUPDATE
or DELETE operations performed on the CUSTOMERS table. This trigger will display the
salary difference between the old values and newvalues:

CUSTOMERS table:

ID NAME AGE ADDRESS SALARY


1 Alive 24 Khammam 2000
2 Bob 27 Kadappa 3000
3 Catri 25 Guntur 4000
4 Dena 28 Hyderabad 5000
5 Eeshwar 27 Kurnool 6000
6 Farooq 28 Nellur 7000

CREATE OR REPLACE TRIGGER


display_salary_changes BEFORE DELETE OR INSERT
OR UPDATE ON customers FOR EACH ROW
WHEN (NEW.ID > 0)
DECLARE
sal_diff
number; BEGIN
sal_diff := :NEW.salary - :OLD.salary;
dbms_output.put_line('Old salary: ' ||
:OLD.salary); dbms_output.put_line('New salary: '
|| :NEW.salary); dbms_output.put_line('Salary
difference: ' || sal_diff);
END;
/
Trigger created.

Here following two points are important and should be noted carefully:

OLD and NEW references are not available for table level triggers, rather you can use them
for record level triggers.

If you want to query the table in the same trigger, then you should use the AFTER keyword,
33
because triggers can query the table or change it again only after the initial changes are applied
and the table is back in a consistent state.

Above trigger has been written in such a way that it will fire before any DELETE or INSERT or
UPDATE operation on the table, but you can write your trigger on a single or multiple operations,
for example BEFORE DELETE, which will fire whenever a record will be deleted using
DELETE operation on the table.

Let us perform some DML operations on the CUSTOMERS table. Here is one INSERT statement,
which will create a new record in the table:
INSERT INTO CUSTOMERS (ID,NAME,AGE,ADDRESS,SALARY) VALUES (7, 'Kriti',
22, 'HP', 7500.00 );

When a record is created in CUSTOMERS table, above create trigger


display_salary_changeswill be fired and it will display the following result:

Old salary:
New salary:
7500 Salary
difference:

2) Convert employee name into uppercase whenever an employee record is inserted or


updated. Trigger to fire before the insert orupdate.

SQL> create table Employee(ID VARCHAR2(4 BYTE) NOTNULL,First_Name


VARCHAR2(10BYTE),Last_Name VARCHAR2(10BYTE),Start_Date DATE,End_Date
DATE,Salary NUMBER(8,2),City VARCHAR2(10BYTE),Description VARCHAR2(15 BYTE)
10);

Table created.

SQL> CREATE OR REPLACE TRIGGER employee_insert_update BEFORE INSERT OR


UPDATE ONemployee FOR EACH ROW
DECLARE
dup_flagINTEGER;
BEGIN
--Force all employee names touppercase.
:NEW.first_name :=UPPER(:NEW.first_name);
END;
Trigger created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary,


City, Description)2 values('01','Jason', 'Martin',to_date('19960725','YYYYMMDD'),
to_date('20060725','YYYYMMDD'), 1234.56, 'Toronto','Programmer')

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date,


Salary, City, Description)2 values('02','Alison',
34
‘Mathews',to_date('19760321','YYYYMMDD'),
to_date('19860221','YYYYMMDD'), 6661.78,'Vancouver','Tester')

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date,


Salary, City, Description)2 values('03','James',
'Smith',to_date('19781212','YYYYMMDD'), to_date('19900315','YYYYMMDD'),
6544.78,'Vancouver','Tester')

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date,


Salary, City, Description)2 values('04','Celia', 'Rice',
to_date('19821024','YYYYMMDD'), to_date('19990421','YYYYMMDD'),
2344.78,'Vancouver','Manager')

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date,


Salary, City, Description)2 values('05','Robert',
'Black',to_date('19840115','YYYYMMDD'), to_date('19980808','YYYYMMDD'),
2334.78,'Vancouver','Tester')

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date,


Salary, City, Description)2 values('06','Linda',
'Green',to_date('19870730','YYYYMMDD'), to_date('19960104','YYYYMMDD'),
4322.78,'New York','Tester')
1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date,


Salary, City, Description)2 values('07','David',
'Larry',to_date('19901231','YYYYMMDD'), to_date('19980212','YYYYMMDD'),
7897.78,'New York','Manager')

1 row created.

SQL> insert into Employee(ID, First_Name, Last_Name, Start_Date, End_Date, Salary,


City, Description)2 values('08','James', 'Cat',
to_date('19960917','YYYYMMDD'), to_date('20020415','YYYYMMDD'),
1232.78,'Vancouver','Tester')

1 row created.

SQL> select * from employee;

ID FIRST_NAME LAST_NAMESTART_DATEND_DATE SALARYCITY DESCRIPTION


35
-
01 JASON Martin 25-JUL-96 25-JUL-06 1234.56 Toronto Programmer
02 ALISON Mathews 21-MAR-76 21-FEB-86 6661.78 Vancouver Tester
03 JAMES Smith 12-DEC-78 15-MAR-90 6544.78 Vancouver Tester
04 CELIA Rice 24-OCT-82 21-APR-99 2344.78 Vancouver Manager
05 ROBERT Black 15-JAN-84 08-AUG-98 2334.78 Vancouver Tester
06 LINDA Green 30-JUL-87 04-JAN-96 4322.78 New York Tester
07 DAVID Larry 31-DEC-90 12-FEB-98 7897.78 New York Manager
08 JAMES Cat 17-SEP-96 15-APR-02 1232.78 Vancouver Tester
8 rows selected.
SQL> drop table Employee 2 /

Table dropped.

3) Trigger before deleting a record from emp table. Trigger will insert the row tobe
deleted into another table and also record the user who has deleted therecord.

SQL> CREATE OR REPLACE TRIGGERemployee_before_delete


2 BEFOREDELETE
3 ON employee
4 FOR EACH ROW
5 DECLARE
6 v_username varchar2(10);
7 BEGIN
8 -- Find username of person performing the DELETE on thetable
9 SELECT user INTOv_username
10 FROMdual;
11 -- Insert record into audittable
12 INSERT INTO employee_audit (id, salary, delete_date,deleted_by)
13 VALUES (:old.id,:old.salary, sysdate, v_username);
14 END;
15 /

Trigger created.

SQL> delete from employee;

8 rows deleted.

SQL> select * from employee_audit;

ID SALARY DELETE_DADELETED_BY
01 1234.56 09-SEP-06JAVA2S
02 6661.78 09-SEP-06JAVA2S
03 6544.78 09-SEP-06JAVA2S
04 2344.78 09-SEP-06JAVA2S
05 2334.78 09-SEP-06JAVA2S
36
06 4322.78 09-SEP-06JAVA2S
07 7897.78 09-SEP-06JAVA2S
08 1232.78 09-SEP-06JAVA2S

8 rows selected.

SQL> drop table employee_audit;

Table dropped.

WEEK-8
CURSORS

DEFINITION OF A CURSOR

1. Cursor can be created to store the values from tabletemporally.


2. In execution these values fetch from cursor for access the database
 Create cursor fetch the values from thetable
 Declare thevariables
 Open thecursor
 Fetch the values from thecursor
 Close thecursor

CURSOR EXAMPLE:
declare
cursor xx is select empno,ename,sal from emp26;
a_empno emp26.empno%type;
a_ename emp26.ename%type;
a_sal emp26.sal%type;
begin
open xx;
loop
fetch xx into a_empno,a_ename,a_sal;
exit when xx% not found;
dbms_output.put_line(a_empno||' '||a_ename||' '||a_sal);
end loop;
close xx;
end;

SQL>/

37

You might also like