R 5

Download as pdf or txt
Download as pdf or txt
You are on page 1of 70

R508 DATABASE LAB

SNGCE / CS / R508 / M03.1

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING

LABORATORY MANUAL

R 508 DATABASE LAB

0:0:4
Name Signature
Prepared by Bindu K

Checked by Lisha Kurian

Approved by Saini Jacob Soman (Asst.Prof.)

Sree Narayana Gurukulam College of Engineering


Kadayiruppu, Kolenchery-682 311

2008

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
1
R508 DATABASE LAB

SYLLABUS

DATABASE LAB
R508 0+0+4

Experiments for performing the following:

1. Creation, insertion, updation, deletion of tables, indexes, views


2. Simple queries, nested queries, use of arithmetic and string functions.
3. Simple PL/SQL programs, use of exceptions, savepoints, cursor, procedure, function,
trigger, sequence generator.
4. Importing and Exporting data.
5. Database Administration
6. ODBC/JDBC Interface.
7. Implementation of File Structures

Any experiment according to the syllabus of RT503 can be substituted.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
2
R508 DATABASE LAB

TABLE OF CONTENTS

Sl No. DESCRIPTION OF THE EXPERIMENT PAGE NO.


1 STUDENT DATABASE 6
2 LITERACY DATABASE 12
3 VIEW CREATION 15
4 EMPLOYEE DATABASE 17
5 PL /SQL PROGRAM TO PRINT SQUARE AND 28
NONSQUARE NUMBERS
6 PRINT ELECTRICITY BILL 31

7 CHECK WHETHER A NUMBER IS 34


ARMSTRONG OR NOT.
8 SWAP TWO NUMBERS 36
9 CHECK WHETHER A STRING IS 38
PALINDROME OR NOT

10 PLACEMENT DATABASE 47
11 BANK DATABASE 51
12 FIND HIGHEST PAID SALARY 54
13 SALARY INCREMENT 56
14 UPDATE SALARY USING PROCEDURE 57
15 EXCEPTION HANDLING 59
16 CALCULATE TOTAL SALARY USING 60
FUNCTION
17 FIND COURSE USING FUNCTION 61
18 TABLE MANIPULATION USING CURSOR 63
19 BANK DATABASE USING TRIGGER 67

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
3
R508 DATABASE LAB

CYCLE – I

APPLICATION OF DDL AND DML QUERIES AND SET


OPERATIONS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
4
R508 DATABASE LAB

Theoretical Background :

Basic SQL statements: DDL and DML

SQL statements are divided into two major categories: data definition language (DDL) and data
manipulation language (DML).
DDL statements are used to build and modify the structure of your tables and other objects in the
database. When you execute a DDL statement, it takes effect immediately.
DML statements are used to work with the data in tables.

The Data Definition Language (DDL) includes,


CREATE TABLE - creates new database table
ALTER TABLE - alters or changes the database table
DROP TABLE - deletes the database table
CREATE INDEX - creates an index or used as a search key
DROP INDEX - deletes an index
The Data Manipulation Language (DML) includes,

SELECT - extracts data from the database


UPDATE - updates data in the database
DELETE - deletes data from the database
INSERT INTO - inserts new data into the database

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
5
R508 DATABASE LAB

EXP . 1 STUDENT DATABASE

Aim : Create the tables with the following fields


Faculty (FacultyCode, FacultyName)
Subject (SubjectCode,SubjectName,MaxMark,FacultyCode)
Student(StudentCode,StudentName,DOB,StudentsBranch(CS/EC/EE/ME),AdmissionDate)
M_Mark (StudentCode, SubjectCode, Mark)
a) Display the name of faculties.
b) Display the number of faculties.
c) Display the total mark for each student.
d) Display the subject,average mark for each subject.
e) Display the name of subjects for which atleast one student got below 40%.
f) Display the name,subject and percentage of mark who got below 40 %.
g) Display the faculties and alloted subjects for each faculty.
h) Display the name of faculties who take more than one subject.
i) Display the name of admitted students whose age is below 22 years.
j) Display name,subject,mark, % of mark in ascending order of mark.

Table creation :
SQL> Create Table Faculty (F_code Number Primary Key, F_name Varchar(15));
Table Created

SQL> Create Table Subject (Sub_code Number Primary Key, Sub_name Varchar(15),
Max_mark Number, F_code Number, Foreign Key(F_code) References Faculty(F_code));
Table created.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
6
R508 DATABASE LAB

SQL> Create Table Student (St_code Number Primary Key, St_name Varchar(15), Dob Date,
St_Branch Char(2), Ad_Date Date, Check(St_Branch IN('CS','EC','ME','EE')));
Table created.

SQL> Create Table M_Mark (St_code Number, Sub_code Number, Mark Number(4,2),
Primary Key(St_code,Sub_code), Foreign Key(St_code) References Student(St_code), Foreign
Key(Sub_code) References Subject(Sub_code)) ;
Table created.

SQL> insert into faculty values(&f_code,'&f_name');


Enter value for f_code : 100
Enter value for f_name : vidya
1 row created.

SQL> insert into subject values(&sub_code,'&sub_name',&Max_mark,&f_code);


Enter value for sub_code: 501
Enter value for sub_name: dc
Enter value for max_mark: 100
Enter value for f_code: 101
1 row created.

SQL> insert into subject values(&st_code,'&st_name','&dob',&st-branch','&ad_date');


Enter value for st_code: 01
Enter value for st_name: anil
Enter value for dob: 05-jun-1980
Enter value for st-branch: CS
Enter value for ad_date: 01-jun-2000
1 row created.

Input tables :
SQL> select * from faculty;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
7
R508 DATABASE LAB

F_CODE F_NAME
100 vidya
101 smita
102 bindu

SQL> select * from student;


ST_CODE ST_NAME DOB ST
1 anil 05-JUN-80 CS
2 beena 07-AUG-76 EC
3 remya 02-FEB-81 ME

SQL> select * from subject;


SUB_CODE SUB_NAME MAX_MARK
501 dc 100
502 fsa 100
503 oops 100
504 dbms 100

SQL> select * from m_mark;


ST_CODE SUB_CODE MARK
1 501 39
2 502 56
3 503 36
1 504 72
2 501 92
3 502 68
1 503 94
2 504 83
3 501 46

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
8
R508 DATABASE LAB

Output :
a) Display the name of faculties.
SQL> select f_name from faculty;

F_NAME
vidya
smita
bindu

b) Display the number of faculties.


SQL> select count(*) from faculty;
COUNT(*)
3

c Display the total mark for each student.


SQL> select st_name,sum(mark) from M_mark,student where student.st_code =
m_mark.st_code group by st_name;
ST_NAME SUM(MARK)
anil 205
beena 231
remya 150

d Display the subject,average mark for each subject.


SQL> select sub_name,avg(mark) FROM SUBJECT,M_MARK WHERE subject.sub_code =
m_mark.sub_code group by sub_name;
SUB_NAME AVG(MARK)
dc 59
fsa 62
oops 65
dbms 77.5

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
9
R508 DATABASE LAB

e) Display the name of subjects for which atleast one student got below 40%.
SQL> select sub_name from subject,m_mark where mark<(40*max_mark)/100 and
subject.sub_code=m_mark.sub_code group by sub_name having count(distinct(st_code))>=1;
SUB_NAME
dc
oops

f) Display the name,subject and percentage of mark who got below 40 %.


SQL > select st_name,sub_name,((mark/max_mark)*100)"Percentage" from subject, student,
m_mark where mark<(40*max_mark/100) and subject.sub_code = m_mark.sub_code and
student.st_code=m_mark.st_code;
ST_NAME SUB_NAME Percentage
anil dc 39
remya oops 36

g) Display the faculties and alloted subjects for each faculty.


SQL> select (f_name),sub_name from faculty,subject where faculty.f_code = subject.f_code
order by f_name;
F_NAME SUB_NAME
bindu fsa
bindu oops
smita dc
vidya dbms

h) Display the name of faculties who take more than one subject.
SQL> select f_name from faculty,subject where faculty.f_codeb=bsubject.f_code group by
f_name having count(distinct(sub_code))>1;
F_NAME
bindu

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
10
R508 DATABASE LAB

i Display the name of admitted students whose age is below 22 years.


SQL> select st_name from student where ((months_between(sysdate,dob))/12)<22 ;

ST_NAME
remya

j) Display name,subject,mark, % of mark in ascending order of mark.


SQL> select st_name,sub_name,mark, (mark/max_mark)*100 "percentage" from
student,subject,m_mark where student.st_code=m_mark.st_code and subject.sub_code =
m_mark.sub_code order by mark;
ST_NAME SUB_NAME MARK PERCENTAGE
remya oops 36 36
anil dc 39 39
remya dc 46 46
beena fsa 56 56
remya fsa 68 68
anil dbms 72 72
beena dbms 83 83
beena dc 92 92
anil oops 94 94

****************************************************************

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
11
R508 DATABASE LAB

EXP . 2 LITERACY DATABASE

Aim:
Create tables Kerala and Tamilnadu and perform the DML operations
Kerala (DistName, LiteracyRate, Population, Area)
TamilNadu (DistName, LiteracyRate, Population, Area)
a) From the above table select common literacy from both the tables.
b) Display the name of all the districts from both the table.
c) Use minus operations on the literacy fields of both tables.

Table creation :
SQL> create table kerala ( distname varchar(15) primary key, L_rate number(5,2),
population number, area number(9,2)) ;
Table created.
SQL> create table tamilnadu( distname varchar(15) primary key, L_rate number(5,2), population
number, area number(9,2));
Table created.
Table insertion:
SQL> insert into kerala values('&distname',&l_rate,&population,&area);
Enter value for distname: ernakulam
Enter value for l_rate: 98

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
12
R508 DATABASE LAB

Enter value for population: 100000


Enter value for area: 123456
1 row created.
SQL> insert into tamilnadu values('&distname',&l_rate,&population,&area);
Enter value for distname: coimbatore
Enter value for l_rate: 98
Enter value for population: 123456
Enter value for area: 253641
1 row created.

Input tables :
SQL> select * from kerala;
DISTNAME L_RATE POPULATION AREA
ernakulam 98 100000 123456
kasargode 82 110000 234568
calicut 79 120000 235689
trivandrum 92 130000 124578

SQL> select * from tamilnadu;


DISTNAME L_RATE POPULATION AREA
coimbatore 98 123456 253641
pondichery 79 124578 748596
dindigul 84 215487 987845
ooty 87 126545 789865

Output :
1. SQL> select l_rate from kerala intersect select l_rate from tamilnadu;
L_RATE
79
98
2. SQL> select distname from kerala union select distname from tamilnadu;
DISTNAME
calicut
coimbatore
dindigul
ernakulam

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
13
R508 DATABASE LAB

kasargode
ooty
pondichery
trivandrum
3. SQL> select l_rate from kerala minus select l_rate from tamilnadu;
L_RATE
82
92

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
14
R508 DATABASE LAB

EXP 3 VIEW CREATION

Aim:
Create a table employee with the following fields and create a view which contains the name and
salary > 10000 and update the view by changing employees salary to 10.
Employee( Name, DA, HRA, TA, Salary)
Table creation :
SQL>create table employee(name varchar2(10),da number(10), hra number(10), ta
number(10),salary number(10));
SQL>insert into employee values('&name',&da,&hra,&ta,&salary) ;
Input table :
SQL> select * from employee;
EMP_NAME DA HRA TA SALARY
anil 1000 2000 1000 15000
arun 1000 3000 1500 20000
anu 500 2000 500 9000
beena 900 2500 1000 11000
remya 1500 1000 2000 10000

Output :
SQL> create view emp as select emp_name,salary from employee where salary>10000;
View created.
SQL> select * from emp;
EMP_NAME SALARY
anil 15000
arun 20000

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
15
R508 DATABASE LAB

beena 11000

SQL> update emp set salary=10;


3 rows updated.
SQL> select * from employee;
EMP_NAME DA HRA TA SALARY
anil 1000 2000 1000 10
arun 1000 3000 1500 10
anu 500 2000 500 9000
beena 900 2500 1000 10
remya 1500 1000 2000 10000

***********************************************************************

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
16
R508 DATABASE LAB

MODEL QUESTION
EXP.4 EMPLOYEE DATABASE

Aim : Create the following tables and perform the operations


Create Table Department with the following Data
DEPTNO DEPTNAME LOC MGR EXP_BUDG REV_BUDG
10 Accounting Dallas 200 100000 0
30 Research San Francisco 105 125000 0
40 Sales Boston 109 280000 800000
50 Manufacturing Houston 210 130000 0
60 Shipping Houston 215 90000 0

Create table employee with the following data


EMPNO NAME JOB SALARY COMM DEPTNO S
100 Wilson Clrk 1700 10 M
101 Smith Slsm 2500 1300 40 F
103 Reed Anlt 3500 30 M
105 Watson Mngr 4500 0 30 M
109 Allen Mngr 3800 8000 40 F
110 Turner Clrk 1800 50 M
200 Chen Mngr 2900 10 F
210 Ramirez Mngr 3650 50 M
213 McDonnel Clrk 1625 60 M

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
17
R508 DATABASE LAB

214 Simpson Drvr 825 60 M


215 Di Salvo Spvr 2700 60 M
220 Schwartz Slsm 4250 5300 40 F

3.Write a SQL query that will return information about all managers in the EMPLOYEE table,
ordered alphabetically by name.
4.Write a SQL query that will return information about all employees in Department 40, ordered by
employee number.
5.Write a SQL query that will return information about all employees that are female,
ordered alphabetically by name.
6.To find the minimum salary, maximum salary, and the average salary for each department.
7.Suppose you want to know the minimum commission paid, the maximum commission paid, the
sum of all commissions paid, and the number of employees paid commission. Write one SQL query
to find this information.
8. Suppose you want to find out how many employees are listed in each job category. Write a SQL
query to find this information.
9.Suppose you want to find out how much total salary was paid to each different job category.
That is, how much total were clerks paid, how much were managers paid, etc. Write a SQL query
to find this information.
10.Write a SQL query that will return all the unique department numbers that are represented in the
EMPLOYEE table, ordered by department number.
11.Write a SQL query to return the employee number, name and salary of all females who work in
Department 10.
12.Write a SQL query to return the employee number, name and salary of all male managers,
ordered alphabetically by name.
13.Write a SQL query to return the name and job of all salesmen and managers who are female.
14) Write a query to find the employee number and name for anyone in the EMPLOYEE table
who is a manager and all the clerks working in department 50:
15) write a query to find the employee number and name of anyone who is a manager or a clerk
working in department 50.
16)To return all employees who are not a salesman or a clerk

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
18
R508 DATABASE LAB

17)Suppose you want to list all employees who are not in a specific department, say department 10,
but who are clerks.
18)Query to find name of employee whose name contains letters 'u' and 'e'
19)To list all employees who have earned a commission to date:
20)Write a SQL query to find employee number, name and job of all females who are not
managers
21)Write a SQL query to find employee number, name and salary of all employees who make less
than $1000 or more than $4000, ordered by salary.
22)Write a SQL query to find the name and employee number of all salesmen whose name begins
with the letter S.
23)Use the IN operator to write a SQL query to find the name and employee number of all
employees who are analysts or managers, ordered alphabetically by name.
24)Write a SQL query to find the employee number, name, salary and commission of all
employees who have been paid commission and whose salary is greater than 4000.
25)Find the location of the employee named Chen
26)Write an SQL query to find the department number,department name,employee
number,employee name,job,sex and salary and order the rows by employee number within
department number.
27)Find the employee name, employee number and department number for all employees who
work in Houston, with the results in descending employee number order.
28)Retrieve the names and salaries for all employees who earn more than the average salary.
29)Retrieve the names and salaries for all employees who earn more than the average salary.
30)Suppose you need to know the name, job, department name, and location of all female
employees. Write a SQL query that will return this information. Order the list in alphabetical order
by employee name.
31)Suppose you need to know the name, department name, and employee number of all managers.
Write a SQL query that will retrieve this information. Order the list in alphabetical order by
department name.
32)Suppose you need to know the name and department name of the employee who earns the
highest salary. Write a SQL query to return this information.
33)Suppose you need to know the name, department name, and commission of all employees who

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
19
R508 DATABASE LAB

were paid commission. Write a SQL query to retrieve this information. Order the list in alphabetical
order by employee name.
34)Suppose you need to know the employee name and department name of all employees that
work in a department that has at least 3 employees. Write a SQL query to retrieve this information.
Order the list in alphabetical order first by department name, then by employee name.
Output:
1. Create Table Department with the following Data
DEPTNO DEPTNAME LOC MGR EXP_BUDG REV_BUDG
10 Accounting Dallas 200 100000 0
30 Research San Francisco 105 125000 0
40 Sales Boston 109 280000 800000
50 Manufacturing Houston 210 130000 0
60 Shipping Houston 215 90000 0

2.Create table employee with the following data


EMPNO NAME JOB SALARY COMM DEPTNO S
100 Wilson Clrk 1700 10 M
101 Smith Slsm 2500 1300 40 F
103 Reed Anlt 3500 30 M
105 Watson Mngr 4500 0 30 M
109 Allen Mngr 3800 8000 40 F
110 Turner Clrk 1800 50 M
200 Chen Mngr 2900 10 F
210 Ramirez Mngr 3650 50 M
213 McDonnel Clrk 1625 60 M
214 Simpson Drvr 825 60 M
215 Di Salvo Spvr 2700 60 M
220 Schwartz Slsm 4250 5300 40 F

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
20
R508 DATABASE LAB

3.Write a SQL query that will return information about all managers in the EMPLOYEE table,
ordered alphabetically by name.
SQL> select * from employee where job = 'mngr' order by name;
4.Write a SQL query that will return information about all employees in Department 40, ordered by
employee number.
SQL> select *from employee where deptno = 40 order by empno;
5.Write a SQL query that will return information about all employees that are female,
ordered alphabetically by name.
SQL>select * from employee where sex = 'f' order by name;
6.To find the minimum salary, maximum salary, and the average salary for each department.
SQL>select deptno, min(salary), max(salary), avg(salary) from employee group by deptno;
7.Suppose you want to know the minimum commission paid, the maximum commission paid, the
sum of all commissions paid, and the number of employees paid commission. Write one SQL query
to find this information.
SQL >select min(comm), max(comm), sum(comm), count(comm) from employee;
8. Suppose you want to find out how many employees are listed in each job category. Write a SQL
query to find this information.
SQL> select job, count(*) from employee group by job;
9.Suppose you want to find out how much total salary was paid to each different job category.
That is, how much total were clerks paid, how much were managers paid, etc. Write a SQL query
to find this information.
SQL>select job, sum(salary) from employee group by job;
10.Write a SQL query that will return all the unique department numbers that are represented in the
EMPLOYEE table, ordered by department number.
SQL>select distinct deptno from employee order by deptno;
11Write a SQL query to return the employee number, name and salary of all females who work in
Department 10.
SQL>select empno, name, salary from employee where sex = 'f' and deptno = 10;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
21
R508 DATABASE LAB

12.Write a SQL query to return the employee number, name and salary of all male managers,
ordered alphabetically by name.
SQL>select empno, name, salary from employee where sex = 'm' and job = 'mngr' order by name;
13.Write a SQL query to return the name and job of all salesmen and managers who are female.
SQL>select name, job from employee where sex = 'f' and (job = 'slsm' or job = 'mngr');
14) Write a query to findthe employee number and name for anyone in the EMPLOYEE table
who is a manager and all the clerks working in department 50:
SQL> select empno, name, job, deptno from employee
where job = 'mngr' or (job = 'clrk' and deptno = 50);
15) write a query to find the employee number and name of anyone who is a manager or a clerk
working in department 50.
SQL> select empno, name from employeewhere (job = 'mngr' or job = 'clrk') and deptno = 50;
16)To return all employees who are not a salesman or a clerk
SQL>select name, empno from employee where job not in ('slsm','clrk');
(or)
SQL>select name, empno from employee where job != 'slsm' and job <> 'clrk';
17.Suppose you want to list all employees who are not in a specific department, say department 10,
but who are clerks.
SQL> select name, job, deptn o from employee where job = 'clrk'
and deptno ^= 10;
18 Query to find name of employee whose name contains letters 'u' and 'e'
SQL>select empno, name from employee where name like '%u%e%';

19)To list all employees who have earned a commission to date:


SQL>select name from employee where comm is not null
and comm > 0;
20)Write a SQL query to find employee number, name and job of all females who are not
managers
SQL>select empno, name, job from employee where sex = 'f' and job != 'mngr';
21)Write a SQL query to find employee number, name and salary of all employees who make less
than $1000 or more than $4000, ordered by salary.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
22
R508 DATABASE LAB

SQL>select empno, name, salary from employee where salary not between 1000 and 4000 order
by salary;

22)Write a SQL query to find the name and employee number of all salesmen whose name begins
with the letter S.
SQL>select name, empno from employee where name like 's%' and job = 'slsm';
23)Use the IN operator to write a SQL query to find the name and employee number of all
employees who are analysts or managers, ordered alphabetically by name.
SQL>select name, empno from employee where job in ('anlt', 'mngr') order by name;
24) Write a SQL query to find the employee number, name, salary and commision of all
employees who have been paid commission and whose salary is greater than $4000.
SQL>select empno, name, salary, comm from employee where comm is not null and comm > 0
and salary > 4000;
25) to find the location of the employee named Chen
SQL>select name, loc from employee, deptwhere name = 'chen' and employee.deptno =
dept.deptno;
26) write an sql query to find the department number,department name,employee
number,employee name,job,sex and salary and order the rows by employee number within
department number.
SQL> select employee.deptno, deptname, empno, name, job, sex, salary from employee, dept
where employee.deptno = dept.deptno deptno order by employee.deptno, empno;
27)to find the employee name, employee number and department number for all employees who
work in Houston, with the results in descending employee number order.
SQL>select name, empno, deptno from employee where deptno in(select deptno from dept where
loc = 'houston') order by empno desc;
28)to retrieve the names and salaries for all employees who earn more than the average salary.
SQL>select name, salary from employee where salary >(select avg(salary) from employee);
29)to retrieve the names and salaries for all employees who earn more than the average salary.
SQL>select name, salary from employee where salary >(select avg(salary) from employee);
30)Suppose you need to know the name, job, department name, and location of all female

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
23
R508 DATABASE LAB

employees. Write a SQL query that will return this information. Order the list in alphabetical order
by employee name.

SQL>select name, job, deptname, loc from employee, deptwhere sex = 'F'and employee.deptno =
dept.deptnoorder by name;

NAME JOB DEPTNAME LOC


Allen Mngr Sales Boston
Chen Mngr Accounting Dallas
Schwartz Slsm Sales Boston
Smith Slsm Sales Boston
31)Suppose you need to know the name, department name, and employee number of all
managers. Write a SQL query that will retrieve this information. Order the list in alphabetical order
by department name.
SQL>select empno, name, deptname from employee, dept where employee.deptno = dept.deptno
and job = 'Mngr' order by deptname;
EMPNO NAME DEPTNAME
200 Chen Accounting
210 Ramirez Manufacturing
105 Watson Research
109 Allen Sales

32)Suppose you need to know the name and department name of the employee who earns the
highest salary. Write a SQL query to return this information.
SQL> select name, deptname from employee, dept where employee.deptno = dept.deptno
and salary = (select max(salary) from employee);
NAME DEPTNAME
Watson Research
33)Suppose you need to know the name, department name, and commission of all employees who

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
24
R508 DATABASE LAB

were paid commission. Write a SQL query to retrieve this information. Order the list in alphabetical
order by employee name.
SQL>select name, comm, deptname from employee, is331.dept where employee.deptno =
dept.deptno and comm is not null and comm > 0 order by name;
NAME COMM DEPTNAME
Allen 8000 Sales
Schwartz 5300 Sales
Smith 1300 Sales

34)Suppose you need to know the employee name and department name of all employees that
work in a department that has at least 3 employees. Write a SQL query to retrieve this information.
Order the list in alphabetical order first by department name, then by employee name.
SQL>select name, deptname from employee, dept where employee.deptno = .deptno
and employee.deptno in (select deptno from employee group by deptno having count(*) >2)
order by deptname, name;
NAME DEPTNAME
Allen Sales

Schwartz Sales
Smith Sales
Di Salvo Shipping
McDonnel Shipping
Simpson Shipping

*****************************************************************

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
25
R508 DATABASE LAB

CYCLE-II
PL/ SQL PROGRAMS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
26
R508 DATABASE LAB

Theoretical Back ground :

With PL/SQL, you can use SQL statements to manipulate ORACLE data and
flow-of-control statements to process the data. Moreover, you can declare
constants and variables, define subprograms (procedures and functions),
and trap runtime errors. Thus, PL/SQL combines the data manipulating power
of SQL with the data processing power of procedural languages.

PL/SQL is a block-structured language. That is, the basic units (procedures,


functions, and anonymous blocks) that make up a PL/SQL program are logical
blocks, which can contain any number of nested sub-blocks. Typically, each
logical block corresponds to a problem or subproblem to be solved.

A block (or sub-block) lets you group logically related declarations and
statements. That way you can place declarations close to where they are used.

The declarations are local to the block and cease to exist when the block
completes.

[DECLARE
-- declarations]
BEGIN
-- statements
[EXCEPTION
-- handlers]
END;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
27
R508 DATABASE LAB

EXP.5 PRINT SQUARE AND NONSQUARE NUMBERS

Aim :Write a PL/SQL program to insert square numbers into table-Square and non square
numbers into NonSquare table upto a limit. Also write PL/SQL code to print
odd square numbers from the square table.
Algorithm :
1 Start
2 Create tables square and nonsquare
3 declare the cursor c
4 enter the limit
5 loop for I varies from 1 to n
6 set flag as zero
7 loop for j varies from 1 to I
8 if I = j*j then set flag as 1
9 end if
10 end loop
11 if flag =1 then insert the value into square table
12 else insert into nonsquare table.
13 End if
14 end loop
15 open cursor c
16 fetch c into variable and exit when c%not found
17 print the odd numbers
18 end loop
19 close cursor
20 end

Table creation :
SQL > create table square (num int);
Table created.
SQL > create table nonsquare (no int);
Table created.

Program:
declare
n number;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
28
R508 DATABASE LAB

temp number;
cursor odd is
select * from square where mod(i,2)!=0;
flag number:=0;
begin
n:=&limit;
for i in 1..n
loop
flag:=0;
for j in 1..n
loop
if(i=j*j) then
insert into square values(i);
flag:=1;
end if;
end loop;
if(flag<>1) then
insert into nonsquare values(i);
end if;
end loop;
open odd;
dbms_output.put_line('odd squares are');
loop
fetch odd into temp;
exit when(odd%notfound);
dbms_output.put_line(temp);
end loop;
close odd;
end;

Output
Enter value for limit : 17
odd squares are
1
9

SQL> select * from squares;


1
4

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
29
R508 DATABASE LAB

9
16
SQL> select * from nonsquares;
2
3
5
6
7
8
10
11
12
13
14
15
17

******************************************************************

EXP 6 PREPARE ELECTRICITY BILL

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
30
R508 DATABASE LAB

Aim : Write a PL/SQL program to accept the customer number and print the bill for the
same. The charges are calculated as follows:
Units consumed Charge
<20 Nil
20-100 50% per unit
101-300 75% per unit
301-500 150% per unit
>500 225% per unit

Print the electricity bill in the following format:


ELECTRICITY BILL
CustomerNo:
Present Reading:
Past Reading:
Units Taken:
Charge:
Algorithm :
1 start
2 create table customer and insert values into it
3 declare the variables
4 enter the value for customer number
5 find the units by subtracting present and past reading
6 if unit<20 then set change = nil
7 else if unit>=20 and unit<=100 then charge = unit * 50/100
8 else if unit<=300 and unit>=101 then charge= unit*75/100
9 else if unit<=500 and unit>=301 then charge= unit*150/100
10 else charge= unit*225/100
11 end if
12 print the electricity bill.
13 stop

Input table
SQL> select * from customer;
CUST ID PRE-READ PAST -READ

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
31
R508 DATABASE LAB

101 540 350


102 350 100
103 780 200
104 650 630
105 650 640

Program
declare
cid number;
p1 number;
p2 number;
u number;
chrge varchar(5);
begin
cid := &customerno;
select pre_read,past_read into p1,p2 from customer where custid=cid;
u:=p1-p2;
if u<20 then
chrge:='NIL';
elsif u> 20 and u<100 then
chrge:=u*50/100;
elsif u>101 and u<300 then
chrge:= u*75/100;
elsif u>301 and u<500 then
chrge:= u*150/100;
else
chrge:=u* 225/100;
endif;
dbms_output.put_line('ELECTRICITY BILL');
dbms_output.put_line('customer No:'||cid);
dbms_output.put_line('Present Reading:'||p1);
dbms_output.put_line('Past Reading:'||p2);
dbms_output.put_line('Units Consumed:'||u);
dbms_output.put_line('Charge:'||chrge);
end;
\

Output:
Enter the value for customerno: 103

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
32
R508 DATABASE LAB

ELECTRICITY BILL
Customer No:103
Present Reading:780
Past Reading:200
Units consumed:580
charge:1305

PL/SQL procedure successfully completed.


*********************************************************

EXP. 7 CHECK WHETHER A NUMBER IS ARMSTRONG OR NOT.

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
33
R508 DATABASE LAB

Aim : Write a PL/SQL program to print whether a number is armstrong or not.


Algorithm :
1 start
2 declare the variables, s=0
3 enter the number , n
4 assign n to a
5 while n>0 repeat the following steps
6 r = mod(n,10)
7 s = s + (r*r*r)
8 n = trunc (n/10)
9 if a=s then
10 print the given number is armstrong
11 else
12 print the given number is not armstrong
13 stop

Program :
declare
m number;
l number;
r number := 0;
d number
begin
m := & number;
l := m;
while m > 0
loop
d:=(mod(m,10);
r := r + (d*d*d);
m:=trunc(m/10);
dbms_output.put_line (m);
end loop;
if (l=r) then
dbms_output.put_line(l||' is an armstrong number');
else
dbms_output.put_line(l||' is not an armstrong number');
end if;
end;

output :
case 1 :

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
34
R508 DATABASE LAB

enter value for number : 153


153 is an armstrong number
case 2:
enter value for number : 121
121 is not an armstrong number

*****************************************************

EXP 8 SWAP TWO NUMBERS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
35
R508 DATABASE LAB

Aim : Write a PL/SQL program to input two numbers. If the first number is greater than
second then swap it, else if first number is less than second raise it to its power else double it.
Algorithm :
1 start
2 declare the variables
3 enter two numbers a and b
4 if a>b then t = a , a = b , b = t
5 else if a<b then , a= a**a
6 else a= 2*a
7 end if
8 Print a and b
9 stop

Program:
Declare
a number(5);
b number(5);
t number(5);
begin
a := &a;
b := &b;
dbms_output.put_line( 'initial value of a = '||a ||' b = '||b )
if a>b
then
t := a;
a:= b;
b:=t;
elsif A<B then
a:=a**a;
b:=b**b;
ELSE
a:=2*a;
b:=2*b;
end if;
dbms_output.put_line('final value of a = '||a ||' b = '||b);
end;

Output :

case 1 :

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
36
R508 DATABASE LAB

Enter value for a: 4


Enter value for b: 5
initial value of a = 4 b = 5
final value of a = 256 b = 3125
PL/SQL procedure successfully completed.
case 2 :
Enter value for a: 5
Enter value for b: 4
initial value of a = 5 b = 4
final value of a = 4 b = 5
PL/SQL procedure successfully completed.
case 3 :
Enter value for a: 5
Enter value for b: 5
initial value of a = 5 b = 5
final value of a = 10 b = 10
PL/SQL procedure successfully completed.
case 4:
Enter value for a: 5
Enter value for b: 5
initial value of a = 5 b = 5
final value of a = 10 b = 10
PL/SQL procedure successfully completed.

EXP. 9 CHECK WHETHER A STRING IS PALINDROME OR NOT

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
37
R508 DATABASE LAB

Aim :
Write a PL/SQL program to reverse a string and check whether it is a palindrome
or not.
Algorithm :
1 start
2 declare the variables
3 enter the string
4 find the length of the string
5 loop for I =1 to length, reverse the string
6 end loop
7 if the reversed string = string entered then
8 print the string is a palindrome
9 else
10 print the string is not a palindrome
11 stop
Program :
declare
g varchar2(20);
r varchar2(20);
begin
g:='&g';
dbms_output.put_line('the given text :'||g);
for i in reverse 1.. length(g) loop
r:= r || substr(g,i,1);
end loop;
dbms_output.put_line('the reversed text :'||r);
if r=g then
dbms_output.put_line('the given text is palindrome ');
else
dbms_output.put_line('the given text is not palindrome ');
end if;
end;

Output :

case 1 :
enter value for g: malayalam

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
38
R508 DATABASE LAB

the given text : malayalam


the reversed text : malayalam
the given text is palindrome
pl/sql procedure successfully completed.
case 2:
enter value for g: hello
the given text :hello
the reversed text :olleh
the given text is not palindrome
pl/sql procedure successfully completed.
********************************************

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
39
R508 DATABASE LAB

CYCLE – III

CURSORS, PROCEDURES AND FUNCTION

Theoretical Background:Cursors :
A cursor is a mechanism by which you can assign a name to a "select statement" and

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
40
R508 DATABASE LAB

manipulate the information within that SQL statement.


We've categorized cursors into the following topics:
Declare a Cursor
OPEN Statement
FETCH Statement
CLOSE Statement
Cursor Attributes (%FOUND, %NOTFOUND, etc)
A cursor is a SELECT statement that is defined within the declaration section of your
PLSQL code. We'll take a look at three different syntaxes for cursors.
Cursor without parameters (simplest)
The basic syntax for a cursor without parameters is:
CURSOR cursor_name
IS
SELECT_statement;
For example, you could define a cursor called c1 as below.
CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;
The result set of this cursor is all course_numbers whose course_name matches the
variable called name_in.
Once you've declared your cursor, the next step is to open the cursor.
The basic syntax to OPEN the cursor is:
OPEN cursor_name;
For example, you could open a cursor called c1 with the following command:
OPEN c1;
The basic syntax for a FETCH statement is:
FETCH cursor_name INTO <list of variables>;
For example, you could have a cursor defined as:
CURSOR c1 IS

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
41
R508 DATABASE LAB

SELECT course_number
from courses_tbl
where course_name = name_in;
The command that would be used to fetch the data from this cursor is:
FETCH c1 into cnumber;

This would fetch the first course_number into the variable called cnumber;
The final step of working with cursors is to close the cursor once you have finished using it.
The basic syntax to CLOSE the cursor is:
CLOSE cursor_name;
For example, you could close a cursor called c1 with the following command:
CLOSE c1;
Example:
A function that demonstrates how to use the cursor:
CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;
CURSOR c1
IS
SELECT course_number
from courses_tbl
where course_name = name_in;
Begin
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
END;

While dealing with cursors, you may need to determine the status of your cursor. The
following is a list of the cursor attributes that you can use.
%ISOPEN
-- Returns TRUE if the cursor is open, FALSE if the cursor is closed.

%FOUND

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
42
R508 DATABASE LAB

- Returns INVALID_CURSOR if cursor is declared, but not open; or if cursor has been closed.
− Returns NULL if cursor is open, but fetch has not been executed.
− Returns TRUE if a successful fetch has been executed.
− Returns FALSE if no row was returned

%NOTFOUND
- Returns INVALID_CURSOR if cursor is declared, but not
open; or if cursor has been closed.
- Return NULL if cursor is open, but fetch has not been executed.
- Returns FALSE if a successful fetch has been executed.
- Returns TRUE if no row was returned.

%ROWCOUNT
- Returns INVALID_CURSOR if cursor is declared, but not
open; or if cursor has been closed.
- Returns the number of rows fetched.
The ROWCOUNT attribute doesn't give the real row count until you have iterated through
the entire cursor. In other words, you shouldn't rely on this attribute to tell you how
many rows are in a cursor after it is opened.

Functions & Procedures :


PL/SQL Function
The syntax for a function is:
CREATE [OR REPLACE] FUNCTION function_name
[ (parameter [,parameter]) ]
RETURN return_datatype
IS | AS
[declaration_section]
BEGIN
executable_section
[EXCEPTION

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
43
R508 DATABASE LAB

exception_section]
END [function_name];
When you create a procedure or function, you may define parameters. There are three types
of parameters that can be declared:
1 IN - The parameter can be referenced by the procedure or function. The value of the
parameter can not be overwritten by the procedure or function.
2 OUT - The parameter can not be referenced by the procedure or function, but the value of
the parameter can be overwritten by the procedure or function.
3 IN OUT - The parameter can be referenced by the procedure or function and the value of
the parameter can be overwritten by the procedure or function.

A simple example of a function:


CREATE OR REPLACE Function FindCourse
( name_in IN varchar2 )
RETURN number
IS
cnumber number;
cursor c1 is
select course_number
from courses_tbl
where course_name = name_in;

BEGIN
open c1;
fetch c1 into cnumber;

if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;

EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
44
R508 DATABASE LAB

This function is called FindCourse. It has one parameter called name_in and it returns a
number. The function will return the course number if it finds a match based on course
name. Otherwise, it returns a 99999.

PL/SQL Procedure
The syntax for a procedure is:
CREATE [OR REPLACE] PROCEDURE procedure_name [ (parameter [,parameter]) ] IS
[declaration_section]
BEGIN
executable_section
[EXCEPTION
exception_section]
END [procedure_name];
When you create a procedure or function, you may define parameters. There are three types
of parameters that can be declared:
1 IN - The parameter can be referenced by the procedure or function. The value of the
parameter can not be overwritten by the procedure or function.
2 OUT - The parameter can not be referenced by the procedure or function, but the value of
the parameter can be overwritten by the procedure or function.
3 IN OUT - The parameter can be referenced by the procedure or function and the value of
the parameter can be overwritten by the procedure or function.
A simple example of a procedure:
CREATE OR REPLACE Procedure UpdateCourse
( name_in IN varchar2 )
IS
cnumber number;

cursor c1 is
select course_number
from courses_tbl
where course_name = name_in;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
45
R508 DATABASE LAB

BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
insert into student_courses
( course_name,
course_number)
values ( name_in,
cnumber );
commit;
close c1;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||' -ERROR-
'||SQLERRM);
END;

This procedure is called UpdateCourse. It has one parameter called name_in. The
procedure will lookup the course_number based on course name. If it does not find a
match, it defaults the course number to 99999. It then inserts a new record into the
student_courses table.

EXP. 10 PLACEMENT DATABASE

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
46
R508 DATABASE LAB

Aim :Create the following tables with the fields specified


Jobs(Jcode,JName,Qualification,SalaryOffered,JPlace, NoOfVacancies)
Applicants(AppCode,AppName,Qualification, ExpctSalary,PlaceChosen,PlacedOrNot)
PlacedList(PLCode,AppCode,JCode)
a) Write a PL/SQL script to select the best suitable job for the applicants and store it in
PlacedList.
Hint:(Selection Criteria:Vacancies available, Qualification should match,
SalaryOffered > = ExpctSalary, PlaceChosen and JPlace should match unless place chosen is
'NIL')
b) Update the NoOfVacancies and the status of Placed Or Not
c)Display the details of the person(s) who gets maximum salary.

Program:

declare
pcode number:=10;
cursor c is
select apcode,jcode from applicant,jobs
where jobs.qual=applicant.qual and vacancy>0 and off_sal>=exp_sal
and (jplace=place or place is null);
begin
for i in c
loop
insert into placedlist
values(pcode,i.apcode,i.jcode);
pcode:=pcode+1;
end loop;
end;
update applicant
set pon='y'
where apcode in(select apcode from placedlist);
declare
cursor c is
select count(jcode) c_jcode,jcode from placedlist
group by jcode;

begin

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
47
R508 DATABASE LAB

for i in c
loop
update jobs
set vacancy=vacancy-i.c_jcode
where jcode=i.jcode;
end loop;
end;

select applicant.apcode,apname,jobs.qual,jname,off_sal from jobs,applicant,placedlist


where jobs.jcode=placedlist.jcode and applicant.apcode=placedlist.apcode
and off_sal in(select max(off_sal) from jobs,placedlist where
jobs.jcode=placedlist.jcode)

Input:
SQL > Select * from jobs;

Jcode Jname Qual Salofrd Jplace Vacno


100 manager mba 23000 chennai 2
102 supervisor pg 14000 bangalore 4
104 accountant pg 14000 ekm 5
106 staff degree 12500 chennai 10
108 manager mba 23000 bangalore 2
110 staff degree 12000 ekm 8
112 Sfw.engr btech 25000 ekm 3
114 Sfw.engr btech 27000 bangalore 1

SQL > Select * from app;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
48
R508 DATABASE LAB

Appcode Appname Quali Salexp Placechosen placed_not


1002 chetana mba 22000 bangalore no
1003 darsheel pg 15000 ekm no
1004 gopal degree 10000 chennai no
1006 jenny mba 20000 chennai no
1008 kavitha btech 22000 ekm no

Output :
SQL > Select * from plcdlist;

Plcode Appcode Jcode


1 1002 108
2 1003 104
3 1004 106
4 1006 100
5 1008 112

SQL > Select * from app;

Appcode Appname Quali Salexp Placechosen placed_not


1002 chetana mba 22000 bangalore yes
1003 darsheel pg 15000 ekm yes
1004 gopal degree 10000 chennai yes
1006 jenny mba 20000 chennai yes
1008 kavitha btech 22000 ekm yes

Select * from jobs;

Jcode Jname Qual Salofrd Jplace vacno

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
49
R508 DATABASE LAB

100 manager mba 23000 chennai 1


102 supervisor pg 17000 bangalore 2
104 accountant pg 17000 ekm 4
106 staff degree 12500 chennai 9

SQL > Select app.appcode,appname,qual,jname,salofrd from jobs,app,plcdlist


where jobs.jcode=plcdlist.jcode and app.appcode=plcdlist.appcode and salofrd
in(select max(salofrd) from jobs,plcdlist where jobs.jcode=plcdlist.jcode

Appcode Appname Qual Jname Salofrd


1008 kavitha btech Sfw.engr 25000
1012 rohan btech Sfw.engr 25000
1014 sarath btech Sfw.engr 25000

Result: PL/SQL program and query has been executed.

EXP. 11 BANK DATABASE

Aim :
A bank has an acco_master table where it holds the current status of a clients bank

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
50
R508 DATABASE LAB

account. Another table acco_trans holds each transaction as it occurs at bank(ie,


deposit/withdrawal).The acco_trans table must hold a flag indicating whether thetransaction was
credit or debit. Write a PL/SQL program to update the acco_master table and set the balance
depending upon whether the account is debited or credited. The updation should be done only for
those records that are not processed.
acco_master(accno,name,balance)
acco_trans(accno,trans_date,deb_cre,amount,process)
Table creation:
SQL> create table acco_master (accno number(10) primary key,name
varchar2(10),balance number(10));
Table created
SQL>insert into acco_master values(&accno,'&name',&balance);
Enter value for accno:111
Enter value for name:anu
Enter value for balance:200000

SQL>create table acco_trans(accno number(10),trans_date date,deb_cre


varchar2(10),check(deb_cre IN('debit','credit')),amount number(10), process varchar2(10)
check(process IN('yes','no')) foreign key (accno)references acco_master);
Table Created
SQL> insert into acco_trans values(&accno,'sysdate,'&deb_cre',&amount,
'&process');
Enter value for accno:111
Enter value for deb_cre:debit
Enter value for amount:1000
Enter value for process:yes

Program:
SQL>set serveroutput on
SQL>declare

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
51
R508 DATABASE LAB

cursor c_bank is select * from acco_trans;


v_bank c_bank%rowtype;
balance number(5);
begin
open c_bank;
loop
fetch c_bank into v_bank;
exit when c_bank%notfound;
if v_bank.process='no' then
update acco_trans set process='yes' where
accno=v_bank.accno;
if v_bank .deb_cre='credit' then
update acco_master set balance=balance+v_bank.amount
where v_bank.accno=acco_master.accno;
elsif v_bank.deb_cre='debit' then
update acco_master set balance=balance-v_bank.amount
where v_bank.accno=acco_master.accno;
elsif balance<=0 then
dbms_output.put_line('Transaction not possible');
end if;
end if;
end loop;
close c_bank;
end;

Output:
SQL>select * from acco_trans;
AccNo Trans_Date Deb_Cre Amt Pro
1012 12-Jan-08 debit 5000 yes
1024 14-Feb-08 credit 100 yes
1987 04-Dec-07 credit 1000 yes
2345 17-Mar-08 credit 20000 yes

SQL>select * from acco_master;


AccNo Name Balance
1012 adam 10000

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
52
R508 DATABASE LAB

1024 jack 600


1987 helen 35500
2345 jenny 70000

Result: PL/SQL program has been executed.

EXP. 12 HIGHEST PAID SALARY

Aim : Write a PL/SQL program using cursors to select the five highest paid employees from the

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
53
R508 DATABASE LAB

emp table.
Input Table :
SQL> SELECT ename, empno, sal FROM emp ORDER BY sal DESC;
ENAME EMPNO SAL
KING 7839 5000
SCOTT 7788 3000
FORD 7902 3000
JONES 7566 2975
BLAKE 7698 2850
CLARK 7782 2450
ALLEN 7499 1600
TURNER 7844 1500
MILLER 7934 1300
WARD 7521 1250
MARTIN 7654 1250
ADAMS 7876 1100
JAMES 7900 950
SMITH 7369 800

Program :
DECLARE
CURSOR c1 is
SELECT ename, empno, sal FROM emp
ORDER BY sal DESC; -- start with highest paid employee
my_ename VARCHAR2(10);
my_empno NUMBER(4);
my_sal NUMBER(7,2);

BEGIN
OPEN c1;
FOR i IN 1..5 LOOP
FETCH c1 INTO my_ename, my_empno, my_sal;
EXIT WHEN c1%NOTFOUND; /* in case the number requested */
/* is more than the total */
/* number of employees */

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
54
R508 DATABASE LAB

INSERT INTO temp VALUES (my_sal, my_empno, my_ename);


COMMIT;
END LOOP;
CLOSE c1;
END;
Output Table :
SQL> SELECT * FROM temp ORDER BY col1 DESC;

NUM_COL1 NUM_COL2 CHAR_COL


5000 7839 KING
3000 7902 FORD
3000 7788 SCOTT
2975 7566 JONES
2850 7698 BLAKE

EXP. 13 SALARY INCREMENT

Aim :
Write a Procedure to increase the salary for all the employees in the EMP table :

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
55
R508 DATABASE LAB

Input table :
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 700 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1600 300 30

Program :
create or replace procedure inc(i number) is
begin
update emp set sal =sal+i;
end;
/
Procedure created.

To execute the procedures in the PL/SQL block:


SQL> declare
begin
inc(100);
end;
/
PL/SQL procedure successfully completed.
Output:
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO
7369 SMITH CLERK 7902 17-DEC-80 800 20
7499 ALLEN SALESMAN 7698 20-FEB-81 1700 300 30

EXP. 14 SALARY UPDATION

Aim :

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
56
R508 DATABASE LAB

write a procedure to increase the salary for the specified employee using empno in the emp
table based on the following criteria: increase the salary by 5% for clerks, 7% for salesman ,
10% for analyst, 20 % for manager and 25% for president. activate using pl/sql block.
Input table :
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM
DEPT
7369 smith clerk 7902 17-dec-80 800
20

Procedure :
create or replace procedure designation(eno number) is
begin
update emp set sal=sal+sal*5/100 where job ='clerk' and empno=eno;
update emp set sal=sal+sal*7/100 where job='salesman' and empno=eno;
update emp set sal=sal+sal*10/100 where job='analyst' and empno=eno;
update emp set sal=sal+sal*20/100 where job='manager' and empno=eno;
update emp set sal=sal+sal*25/100 where job='president' and empno=eno;
end;
/
Procedure created.
Program :
SQL> declare
begin
designation(7369);
end;
/
PL/SQL procedure successfully completed.

Output:
SQL> select * from emp;
EMPNO ENAME JOB MGR HIREDATE SAL COMM

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
57
R508 DATABASE LAB

DEPT
7369 SMITH CLERK 7902 17-DEC-80 840 20

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
58
R508 DATABASE LAB

EXP. 15 EXCEPTION HANDLING


Aim:
Create a procedure to accept an Empno and a salary increase amount, if Empno is not
found or current salary is NULL then raise exceptions otherwise update salary.

Procedure:
Create or replace procedure raise_salary(emp_id integer, increase real) is
current_salary real;
salary_missing exception;
BEGIN
select sal into current_salary from emp where empno=emp_id;
if current_salary is null then
raise salary_missing;
else
update emp set sal = sal+increase where empno = emp_id;
end if;
Exception
WHEN NO_DATA_FOUND THEN
insert into emp_audit values (emp_id, 'No such number');
WHEN salary_missing THEN
insert into emp_audit values (emp_id,'salary is null');
END raise_salary;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
59
R508 DATABASE LAB

EXP. 16 TOTAL SALARY USING FUNCTION

Aim : Create a function that queries the employee table and returns the total salary for a specified
department.
Program:
CREATE FUNCTION dept_salary (dnum NUMBER)
RETURN NUMBER IS
total_wages number(11,2) : =0;
SELECT sum(sal, nvl(comm,0)) into total_wages FROM emp
WHERE deptno = dnum;
dbms_output.put_line('Total Wages=' ||TO_CHAR (total_wages));
return total_wages;
end dept_salary;

Input table :
Assume the emp table contains the following records:

EMPNO SAL COMM DEPT


1002 1500 500 20
1203 1000 30
1289 1000 10
1347 1000 250 20

Output:
Total Wages = 3250

PL/SQL procedure successfully executed.

EXP. 17 FIND COURSE USING FUNCTION

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
60
R508 DATABASE LAB

Aim :
Create a function called FindCourse. It has one parameter called name_in and it returns a
number. The function will return the course number if it finds a match based on course name.
Otherwise, it returns a 99999.
Program:
CREATE OR REPLACE Function FindCourse ( name_in IN varchar2 )
RETURN number IS
cnumber number;
cursor c1 is
select course_number from courses_tbl where course_name = name_in;
BEGIN
open c1;
fetch c1 into cnumber;
if c1%notfound then
cnumber := 9999;
end if;
close c1;
RETURN cnumber;
EXCEPTION
WHEN OTHERS THEN
raise_application_error(-20001,'An error was encountered - '||SQLCODE||'
-ERROR- '||SQLERRM);
END;
Function Created.
You could then reference your new function in an SQL statement as follows:
SQL >select course_name, FindCourse(course_name) as course_id from courses
where subject = 'Mathematics';
Input:
SQL > Select * from course;
CourseNo CourseName
10 mba
20 btech
30 medicine
40 mca
50 Bsc

Output:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
61
R508 DATABASE LAB

Course_Name :B Tech
Course_No :20
PL/SQL procedure successfully completed
Result: PL/SQL program has been executed.

EXP. 18 TABLE MANIPULATION USING CURSOR

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
62
R508 DATABASE LAB

Aim :
A relation T1(e,f) whose tuples are pairs of integers. Using cursors the program
will delete every tuple whose first component is less than the second, and insert the reverse
tuple into T1.
Program:
DECLARE
/* Output variables to hold the result of the query: */
a T1.e%TYPE;
b T1.f%TYPE;
/* Cursor declaration: */
CURSOR T1Cursor IS
SELECT e, f
FROM T1
WHERE e < f
FOR UPDATE;
BEGIN
OPEN T1Cursor;
LOOP
/* Retrieve each row of the result of the above query into PL/SQL variables: */
FETCH T1 Cursor INTO a, b;
/* If there are no more rows to fetch, exit the loop: */
EXIT WHEN T1 Cursor %NOTFOUND;
/* Delete the current tuple: */
DELETE FROM T1 WHERE CURRENT OF T1Cursor;
/* Insert the reverse tuple: */
INSERT INTO T1 VALUES(b, a);
END LOOP;
/* Free cursor used by the query. */
CLOSE T1Cursor;
END;

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
63
R508 DATABASE LAB

CYCLE IV

DATABASE TRIGGER

Database Triggers

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
64
R508 DATABASE LAB

Theoretical Background:
A database triggers is stored PL/SQL program unit associated with a specific database table or view.
The code in the trigger defines the action the database needs to perform whenever some database
manipulation (INSERT, UPDATE, DELETE) takes place.

Unlike the stored procedure and functions, which have to be called explicitly, the database triggers
are fires (executed) or called implicitly whenever the table is affected by any of the above said DML
operations.
A database trigger has three parts :
1.A triggering event
2.A trigger constraint (Optional)
3.Trigger action

A triggering event can be an insert, update, or delete statement or a instance shutdown or startup
etc. The trigger fires automatically when any of these events occur A trigger constraint specifies a
Boolean expression that must be true for the trigger to fire. This condition is specified using the
WHEN clause. The trigger action is a procedure that contains the code to be executed when the
trigger fires.

Types of Triggers
The following are the different types of triggers.
Row triggers and statement triggers
A Row trigger fires once for each row affected. It uses FOR EACH ROW clause. They are useful if
trigger action depends on number of rows affected.
Statement Trigger fires once, irrespective of number of rows affected in the table. Statement
triggers are useful when triggers action does not depend on

Before and afterTriggers

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
65
R508 DATABASE LAB

While defining the trigger we can specify whether to perform the trigger action (i.e. execute trigger
body) before or after the triggering statement. BEFORE and AFTER triggers fired by DML
statements can only be defined on tables.
BEFORE triggers The trigger action here is run before the trigger statement.
AFTER triggers The trigger action here is run after the trigger statement.
INSTEAD of Triggers provide a way of modifying views that can not be modified directly using
DML statements.
LOGON triggers fires after successful logon by the user and LOGOFF trigger fires at the start of
user logoff.
Points to ponder
A trigger cannot include COMMIT, SAVEPOINT and ROLLBACK.
We can use only one trigger of a particular type .
A table can have any number of triggers.
We use correlation names :new and :old can be used to refer to data in command line and data in

Create or replace trigger <triggername>


Delete/update/insert on <tablename>
For each row
Begin
PL/SQL block
End;

table respectively.

EXP. 19 BANK DATABASE USING TRIGGER

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
66
R508 DATABASE LAB

Aim: Create a database containing tables acct_t, depostior, loan, borrower .


Depositor (account_no Primary key, c_name)
Loan (loan_no, br_name)
Borrower (loan_no,c_name)
Acct_t (account_no, balance,br_name)
Depsositor table contains account number and customer name. Acct_t table contains account
number, balance amount and branch name.
User can update account details on table acct_t. If the user decrement the balance amount in the
acct_t table then the trigger must insert the account number and borrower’s name to the table
borrower and the trigger must insert the account number, loan amount and branch name to table
loan also.

Theoretical Background:
An AFTER UPDATE Trigger means that Oracle will fire this trigger after the UPDATE operation
is executed.
The syntax for an AFTER UPDATE Trigger is:
CREATE or REPLACE TRIGGER trigger_name
AFTER UPDATE
ON table_name
[ FOR EACH ROW ]
DECLARE
-- variable declarations
BEGIN
-- trigger code
EXCEPTION
WHEN ...
-- exception handling
END;

trigger_name is the name of the trigger to create.

Restrictions:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
67
R508 DATABASE LAB

• You can not create an AFTER trigger on a view.


• You can not update the :NEW values.
• You can not update the :OLD values.

Table Creation :
SQL > create table depositor (accno primary key , cname char(10));
SQL > create table borrower (loanno number , cname char(10));
SQL > create table loan( loanno number , brname char(10),amt number);
SQL > create table acct-t( acctno number , bal number, brname char(10), foreign key (acctno)
references depositor (acctno);
Table insertion:
SQL > insert into depositor values (&accno , &cname );
Enter value for accno : 101
Enter the value for cname : Alan
SQL > insert into acct-t values( &acctno , &bal , '&brname ');
Enter value for accno : 101
Enter the value for bal : 20000
Enter the value for brname : tvm
Input table :
SQL > select * from depositor;
ACCNO CNAME
101 Alan
102 Ann
103 Ben
SQL > select * from acct-t;
ACCNO BAL BRNAME
101 20000 tvm
102 10500 ekm
103 5000 tcr

Trigger:

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
68
R508 DATABASE LAB

SQL > create or replace trigger account after update of bal on acct-t for each row
declare
c varchar2 (20)
begin
if (:new.bal < :old.bal) then
insert into loan values (:new.accno, :new.brname , :old.bal-:new.bal);
select cname into c from depositor where accno = new.accno;
insert into borrower values (:new.accno,c);
endif;
end;
/
Trigger created.
Query :
SQL > update acct-t set bal = bal-5000 where acctno=101;
1 row updated.
Output:
SQL >select * from borrower;
LOANNO CNAME
101 Alan

SQL >select * from loan;


LOANNO BR NAME AMT
101 tvm 15000

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
69
R508 DATABASE LAB

References

1. Database System Concepts - Henry F Korth, Abraham Silbershatz, Mc Graw Hill 2nd
edition.
2. An Introduction to Database Systems - C.J.Date (7th Edition) Pearson Education
Asia
3. Database Principles, Programming and Performance – Patrick O’Neil, Elizabeth O’Neil
4. An Introduction to Database Systems - Bibin C. Desai

DEPARTMENT OF COMPUTER SCIENCE AND ENGINEERING


SREE NARAYANA GURUKULAM COLLEGE OF ENGINEERING, KADAYIRUPPU
70

You might also like