Download as doc, pdf, or txt
Download as doc, pdf, or txt
You are on page 1of 60

DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Objectives:

The major objective of this lab is to provide a strong formal foundation in database concepts,
technology and practice to the participants to groom them into well-informed database
application developers.
The sub-objectives are:
        to give a good formal foundation on the relational model of data
        to present SQL and procedural interfaces to SQL comprehensively
        to give an introduction to systematic database design approaches covering
conceptual design, logical design and an overview of physical design
        to present the concepts and techniques relating to query processing by SQL engines
        to introduce the concepts of transactions and transaction processing
Learning Outcomes:
After this lab, the student should be able to:
 Understand, appreciate and effectively explain the underlying concepts of database
technologies 
 Design and implement a database schema for a given problem-domain
 Create small scale database
 Populate and query a database using SQL DML/DDL commands.
 Declare and enforce integrity constraints on a database using a state-of-the-art RDBMS
 Programming PL/SQL including stored procedures, stored functions, cursors, packages.
 Create triggers

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

LIST OF EXPERIMENTS (As per syllabus)

S. No. Name of the Experiment

Overview of DDL, DML and DCL,TCL Commands

1 Creation, altering and droping of tables and inserting rows into a table (use
constraints while creating tables) examples using SELECT command.

2 Queries (along with sub Queries) using ANY, ALL, IN, EXISTS,
NOTEXISTS, UNION,

INTERSET, Constraints

3 Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN),
GROUP BY, HAVING

and Creation and dropping of Views.

4 Queries using Conversion functions (to_char, to_number and to_date), string


functions

(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length, substr and
instr), date

functions (Sysdate, next_day, add_months, last_day, months_between, least,


greatest, trunc,

round, to_char, to_date)

5 i)Creation of simple PL/SQL program which includes declaration section,


executable section and

exception –Handling section (Ex. Student no can be selected from the table and
printed and an exception can be raised if no records were found)

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

ii)Insert data into student table and use COMMIT, ROLLBACK and
SAVEPOINT in PL/SQL

block.

6 1)PL/SQL program to find biggest of 3 numbers

2)PL/SQL program to find area of circle.

7 Program development using WHILE LOOPS, numeric FOR LOOPS, nested


loops (to check whether the number is prime or not)

8 Programs using SAVEPOINT,ROLLBACK and COMMIT

9
Program using declaration, execution, exceptions. (when no_data_found)

10

Program using FUNCTIONS to check sid values of sailors and to find factorial
value.

11 Develop programs using features parameters in a CURSOR, FOR UPDATE


CURSOR, WHERE

CURRENT of clause and CURSOR variables.

Develop Programs using BEFORE and AFTER Triggers, Row and Statement
Triggers and

INSTEAD OF Triggers

12 Develop programs using REPORTS to display the sailor id, name, rating and
boat color, name in sailor and boat tables

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Programs using PACKAGES to execute both function and procedure

INTRODUCTION

DATA:
Collection of facts or raw material is known as Data
DATABASE:

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Collection of data that describes activities of one or more related organization from the
data is called ‘DATABASE’.
DATABASE MANAGEMENT SYSTEM(DBMS):
Collection of data and set of programs which are used to access the data in an efficient
manner is known as ‘DBMS’.

INTRODUCTION TO SQL:
SQL stands for Structured Query Language and is commonly pronounced as ‘SEQUEL’. It is
the interface between user and the oracle database. The American National Standard Institute has
accepted SQL as the standard access language for relational database management system and
all of ORACLE access tools are based on this standard.

SQL is the set of statements with which all the programs and users access data in an oracle
database. The purpose of SQL is to provide an interface to a relational database such as oracle
and all SQL statements. It has been a common language for communication with oracle server
from any tool or application.

SQL has 9 commands which are common to all RDBMS


* CREATE, DROP, ALTER for Tables
* INSERT, UPDATE, DELETE for Records
* GRANT, REVOKE for Permission
* SELECT for Query

COMPONENTS OF SQL

1. DATA DEFINITION LANGUAGE: These commands are used to define the database
structure or schema
 Create: It is used to create oracle database objects.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Syntax: create table <table name>(<col name> <datatype> <size>,…………);


 Alter: It is used to modify the columns in the table.
Syntax: alter table <table name>keywords(<col name> <datatype> <size>);
Keywords: 1. add: To add new column to table.
2.drop: To delete column from table.
3.modify: To enhance a width of a column
 Drop: It is used to drop the table.
Syntax: drop table <table name>

2. DATA MANIPULATION LANGUAGE: These commands are used for managing data
within schema
objects.
 Insert: It is used to insert new data into the existing table.
Syntax: insert into <table name> values(<exp1>,<exp2>,----------------<expn>);
 Delete: It is used to delete records from the table.
Syntax: delete from <table name> [where <condition>];
 Update: It is used to modify values in the table.
Syntax: update <table name> set <col name> =<exp> where <condition>;
 Select: It is used to access records from the database.
Syntax: Select <selection list> from <table name> where <condition>;

3. DATA CONTROL LANGUAGE : DCL commands are used to configure and control
database objects.
 GRANT : SQL GRANT is a command used to provide access or privileges on
the database objects to the users.
Syntax : GRANT privilege_name
ON object_name
TO {user_name |PUBLIC |role_name}
[WITH GRANT OPTION];
 REVOKE  : The REVOKE command removes user access rights or privileges to
the database objects.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Syntax: REVOKE privilege_name


ON object_name
FROM {user_name |PUBLIC |role_name}
4. TRANSACTION CONTROL LANGUAGE: statements used to manage the changes made
by DML statements. It allows statements to be grouped together into logical transactions.  
 COMMIT - save work done
 SAVEPOINT - identify a point in a transaction to which we can later roll back
 ROLLBACK - restore database to original since the last COMMIT
 SET TRANSACTION - Change transaction options like isolation level and what
rollback segment to use 
DOMAIN TYPES IN SQL :
 char(n) (or character(n)): fixed-length character string, with user-specified
length.
 varchar(n) (or character varying): variable-length character string, with user-
specified maximum length.
 int or integer: an integer (length is machine-dependent).
 smallint: a small integer (length is machine-dependent).
 decimal(p, d): a fixed-point number with user-specified precision, consists of p
digits (plus a sign) and d of p digits are to the right of the decimal point.
 real or double precision: floating-point or double-precision floating-point
numbers, with machine-dependent precision.
 float(n): floating-point, with user-specified precision of at least n digits.
 date: a calendar date, containing four digit year, month, and day of the month.
 time: the time of the day in hours, minutes, and seconds.

E-R MODEL

E-R model is known as Entity-Relationship model


Entity-relationship model(E-R model) is used to describe the structure of the data base.
To describe the data base structure this model uses following notations.
 ENTITY is a real world thing i.e student, person ,item. ...etc. and it is represented by

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

 ATTRIBUTES is the properties of entity i.e sno, sname. .etc. and it is represented by

 RELATIONSHIP is the association among different entities. It is represented by

Consider the following example:

In the above E-R diagram

 Student is an entity with the attributes sid, name, age, branch


 Course is another entity with the attributes c_name, faculty,c_id
 Completed is the relation among the entities student and course

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-1

Creation, altering and dropping of tables and inserting rows into a table (use constraints
while creating tables) examples using SELECT command.

Key constraints in SQL

NOT NULL: this is to restrict null values in specified column. Null is not a zero or a space.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

UNIQUE:restricts the duplicate values (rows)in the coplumn and allows the blanks in the
column.

PRIMARY KEY: It uniquely identifies each row in the coloumn but it does not allows the
blanks in the column.it is the combination of NOT NULL and UNIQUE.

FOREIGN KEY:It links the two tables

CHECK: It specifies the specified range to the columns.

CREATION: create command is used to create any oracle database objects like
tables,views,users etc.

Syntax

CREATE TABLE TABLENAME(COLUMNNAME1 <DATATYPE>(<SIZE>)(KEY


CONSTRAINTS),

COLUMNNAME2 <DATATYPE>(<SIZE>)(KEY CONSTRAINTS),…..);

Creation of client_master table

create table client_master

clientno varchar2(25) primary key,

name varchar(20) unique,

city char(15),

pincode number(6),

state char(15),

bal_due number(5));

Table created

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

DESC:It is used to descibe the table

desc <tablename>

desc client_master;

Data Lengt Precisio Primary Nullabl Defaul Comme


Table Column Type h n Scale Key e t nt

CLIENT_M CLIENT
Varchar2 25 - - 1 - - -
ASTER NO

  NAME Varchar2 20 - - - - -

  CITY Char 15 - - - - -

PINCOD
  Number - 6 0 - - -
E

  STATE Char 15 - - - - -

  BAL_Du Number - 5 0 - - -

Insert:It is used to insert new data into the table.

insert into client_master values('c00001','IvanBayross','Bombay',400054,'Maharashtra',15000);

1 row inserted

SELECT: This is used to retrieve the data from database tables.

select * from client_master;

CLIENTNO NAME CITY PINCODE STATE BAL_DUE

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

c00001 Ivan Bayross Bombay 400054 Maharashtra 15000

c00002 Vandana Saitwal Madras 780001 Tamilnadu 0

c00003 Pramada Jauste Bombay 400057 Maharastra 5000

c00004 Basu Navidgi Bombay 400056 Maharastra 0

c00005 Ravi Sreedaran Delhi 100001 Delhi 2000

Distinct:It is used to select unique rows in the table.

Select distinct * from client_master;

SID NAME BRANCH

c00001 gana Cse

c00002 suresh Cse

c00003 kumar It

c00004 mahesh It

Altering of tables

ALTER: It is used to modify the the table structure.

1)add:to add a new column to a table

Syntax:

alter table table name

add(newcolumn datatype(size));

2)drop:to delete a column from the table

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Syntax

alter table table name

drop(column name);

3)modify:to modify the column

Syntax

alter table table name

modify(columnname datatype(size));

DROP: to delete a table

Syntax : drop table <tablename>

drop table emp;

Table dropped

UPDATE: It is used to modify the data(values) in the table

Update <tablename> set ‘<expression>’ where ‘<expression>’;

update student set branch='csit' where sid='c00003'

1 row updated

update student set branch='csit' where sid='c00004'

1 row updated

Queries over the client_master table

1)Retrieve the list of names and cities of all clients.

select name,city from client_master;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

NAME CITY

ivan bombay

vandana Tamilnadu

basu hyderabad

pramada bombay

ravi Delhi

rukhmini bombay

2)List all the clients who are located in Bombay.

select name from client_master where city=’bombay’;

NAME

ivan

pramada

rukhmini

3)Change the city of client number c00005 to Bombay

update client_master

set city=’bombay’ where number=’c00005’;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

select * from client_master;

NUMBER NAME CITY PIN STATE BAL

c00001 ivan bombay 400054 maharashtra 15000

C00002 Vandana Madras 700001 Tamilnadu 0

c00003 pramada 15ombay 400057 maharashtra 5000

c00004 basu 15ombay15ad 500001 andhrapradesh 0

c00005 ravi bombay 100001 - 2000

c00006 rukhmini 15ombay 400050 maharashtra 0

4)Change the balance due of client number c00001 to Rs1000/-

update client_master

set balance=1000 where clientno=’c00001’;

NUMBER NAME CITY PIN STATE BAL

c00001 ivan bombay 400054 maharashtra 1000

C00002 Vandana madras 700001 Tamilnadu 0

c00003 pramada bombay 400057 maharashtra 5000

c00004 basu hyderabad 500001 andhrapradesh 0

c00005 ravi bombay 100001 - 2000

c00006 rukhmini 15ombay 400050 maharashtra 0

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

5)Delete from client master where the column name state holds the value tamilnadu

delete from client_master where state=’tamilnadu’;

select * from client_master;

NUMBER NAME CITY PIN STATE BAL

c00001 ivan bombay 400054 maharashtra 1000

c00003 pramada bombay 400057 maharashtra 5000

c00004 basu hyderabad 500001 andhrapradesh 0

c00005 ravi bombay 100001 - 2000

c00006 rukhmini bombay 400050 maharashtra 0

6)Add a column called telephone of data type number and size=10 to the client master table

alter table client_master

add(phno number(10));

Select * from client_master;

NUMBE
R NAME CITY PIN STATE BAL phno

c00001 ivan bombay 400054 maharashtra 1000

c00003 pramada bombay 400057 maharashtra 5000

c00004 basu hyderabad 500001 andhrapradesh 0

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

c00005 ravi bombay 100001 - 2000

c00006 rukhmini bombay 400050 maharashtra 0

EXERCISE-2

Queries (along with sub Queries) using ANY, ALL, IN, EXISTS,NOT EXISTS,
UNION,INTERSECT keywords,constrints.

Example queries on sailors, boats and reserves tables.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Creation of sailors

create table sailors

sid number(10) primary key,

name varchar(10),

rating number(10),

age number(6,3));

table created

insert into sailors(sid,name,raing,age)values(22,'dustin',7,45.0);

select * from sailors;

SID SNAME RATING AGE

22 Dustin 7 45

29 Brutus 1 33

31 Lubber 8 55.5

32 Andy 8 25.5

58 Rusty 10 35

64 Horatio 7 35

95 Bob 3 63.5

85 Art 3 25.5

71 Zorba 10 16

74 Horatio 9 35

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Creation of boats table

create table boats

bid number(10) primary key,

bname varchar(10),

color varchar(10));

table created

insert ino boats(bid,bname,color)values(101,'interlake,'blue');

select * from boats;

BID BNAME COLOR

104 Marine Red

103 Clipper Green

102 Interlake Red

101 Interlake Blue

Creation of reserves table

Foreign key is used to relate the two or more than two tables.

create table reserves

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

sid number(10),

bid number(10),

day date,

foreign key(sid) references sailors(sid),

foreign key(bid) references boats(bid));

insert into reserves(sid,bid,day)values(22,101,'10/oct/98');

select * from reserves;

SID BID DAY

22 101 10/10/98

74 103 9/8/98

64 102 9/8/98

64 101 9/5/98

31 104 11/12/98

31 103 11/6/98

31 102 11/10/98

22 104 10/7/98

22 103 10/8/98

22 102 10/10/98

Queries

1)Find the names of sailors who have reserved the boat number 103

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

select s.name from sailors s,reserves r where s.sid=r.sid and r.bid=103;

NAME

Dustin

Lubber

2).Find the names of sailors who have reserved a red boat

select s.name from sailors s,reserves r,boatss b where s.sid=r.sid AND r.bid=b.bid AND
b.color='red';

NAME

Dustin

Lubber

Horatio

3)Find the colours of boats reserved by lubber

select b.color from sailors s,reserves r,boats b where s.sid=r.sid AND r.bid=B.bid AND
s.name='lubber';

COLOR

Green

Red

Red

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

4)find the names of sailors with age over 20 .

select s.sname from sailors s where s.age>20;

SID SNAME RATING AGE

22 Dustin 7 45
USING IN,NOT IN,EXISTS,ANY
29 Brutus 1 33
5) Find the names of sailors who have
31 Lubber 8 55.5
reserved boat number 103 using IN operator.
32 Andy 8 25.5
select s.sname from sailors s where s.sid
in(select r.sid from 58 Rusty 10 35 reserves r where
r.bid=103); 64 Horatio 7 35

95 Bob 3 63.5

85 Art 3
SNAME 25.5

Dustin

74 Horatio Lubber
9 35

Horatio

6) Find the names of sailors who have reserved boat number 103 using EXISTS operator.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

select s.sname from sailors s where exists(select * from reserves r where r.bid=103 and
s.sid=r.sid);

SNAME

Dustin

Lubber

Horatio

7) Find the names of sailors who have not reserved boat number 103 using NOT
EXISTSoperator.

select s.name from sailors s where not exists(select * from reserves r where r.bid=103 AND s.sid=r.sid);

NAME

Zorba

Art

Horatio

Rusty

Andy

Horatio

Brutes

Bob

8)Find the names of sailors who have not reserved a red boat using NOT IN operator

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

select s.name from sailors s where s.sid NOT IN(select r.sid from reserves r where r.bid
IN(select b.bid from boatss b where b.color='red'));

NAME

Rusty

Brutes

Andy

Zorba

Horatio

Art

Bob

9)Find the names of sailors who have reserved a red or green boat.

select s.name from sailors s,reserves r,boatss b where s.sid=r.sid AND r.bid=b.bid
AND(b.color='red' OR b.color='green');

NAME

Dustin

Lubber

Horatio

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

10)Find the names of sailors who have reserved a red or a green boat using union operator.

select s.name from sailors s,reserves r,boatss b where s.sid=r.sid AND r.bid=b.bid AND
b.color='red'

UNION

select s1.name from sailors s1,reserves r1,boats b1 where s1.sid=r1.sid AND r1.bid=b1.bid AND
b1.color='green';

NAME

Dustin

Lubber

Horatio

11)Find the sailors whose rating is better than some sailor called horatio using ANY operator.

select s.sid from sailors s where rating>any(select s.rating from sailors s where
s.name='horatio');

SID

58

71

74

31

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

32

12)Find the sailors with the highest rating using all operator.

select s.sid from sailors s where rating>=all(select s.rating from sailors s);

SID

58

71

13)Find the names of sailors who have reserved a both red and green boat using intersect
operator.

select s.name from sailors s,reserves r,boatss b where s.sid=r.sid AND r.bid=b.bid AND
b.color='red'

intersect

select s1.name from sailors s1,reserves r1,boats b1 where s1.sid=r1.sid AND r1.bid=b1.bid AND
b1.color='green';

SNAME

Lubber

Lubber

Dustin

Dustin

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-3

Queries using Aggregate functions (COUNT, SUM, AVG, MAX and MIN), GROUP BY,
HAVING

Creation of Views and Updating and Destroying of views.

USING AGGREGATE FUNCTIONS

1)find the average age of sailors

select avg(age) from sailors;

AVG(AGE)

36.9

2)find the sum of ages of sailors whose rating is 10.

select sum(age) from sailors s where rating=10;

SUM(AGE)

51

3)Find the age of oldest sailor.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

select max(age) from sailor;

MAX(AGE)

63.5

4)Find the age of youngest sailor

select min(age) from sailors;

MIN(AGE)

16

5)count the no of different sailors names.

select count(distinct s.sname) from sailors s;

COUNT(DISTINCTS.SNAME)

6)count the no of sailors.

Select count(*) from sailors;

COUNT(DISTINCTS.SNAME)

10

7)find the age of the youngest sailor for each rating level.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

select s.rating,min(s.age) from sailors s group by s.rating;

RATING MIN(S.AGE)

1 33

8 25.5

7 35

3 25.5

10 16

9 35

8) find the age of youngest sailor who is eligible to vote(18 years age)for each rating level with
atleast 2 sailors.

select s.rating,min(s.age) from sailors s group by s.rating having s.age>18;

RATING MIN(S.AGE)

3 25.5

7 35

8 25.5

CREATION , UPDATION AND DESTROYING OF VIEWS

View is a virtual table which is created from a base table. They allows user to see only the part of
data but not all data. These are dynamic in nature. They donot accupy any memoryAny
changes/modifications made to the views are reflected back to the original table and vice versa.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

CREATION

Syntax

create view <viewname>(column1,column2…)as select (column1,column2..) from


<basetablename>

ex:

let us create a view from clent_master table

select * from client_master;

CLIENTNO NAME CITY PINCODE STATE BAL_DUE

c00001 Ivan Bayross Bombay 400054 Maharashtra 15000

c00002 Vandana Saitwal Madras 780001 Tamilnadu 0

c00003 Pramada Jauste Bombay 400057 Maharastra 5000

c00004 Basu Navidgi Bombay 400056 Maharastra 0

c00005 Ravi Sreedaran Delhi 100001 Delhi 2000

Create view viewclient(name,city,pincode)as select name,city,pincode from client_master;

View created

Select * from viewclient

NAME CITY PINCODE

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Ivan Bayross Bombay 400054

Vandana Saitwal Madras 780001

Pramada Jauste Bombay 400057

Basu Navidgi Bombay 400056

Ravi Sreedaran Delhi 100001

update viewclient set city='Hyderabad' where pincode='100001';

view updated

select * from viewclient

NAME CITY PINCODE

Ivan Bayross Bombay 400054

Vandana Saitwal Madras 780001

Pramada Jauste Bombay 400057

Basu Navidgi Bombay 400056

Ravi Sreedaran Hyderabad 100001

Destroying of view:

syntax

drop view <viewname>

drop view viewclient

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

View dropped.
Select * from viewclient

ORA-00942: table or view does not exist

EXERCISE- 4

Queries using Conversion functions (to_char, to_number and to_date)

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

String functions(Concatenation, lpad, rpad, ltrim, rtrim, lower, upper, initcap, length,
substr and instr) Date functions (Sysdate, next_day, add_months,last_day,
months_between , to_char, to_date)

These are performed from a table called Dual easily. Because dual is a dummy table. We cannot
create it separately. We can also perform these functions from any user created table.

select 2*2 from dual;

DUMMY

Date functions:

Sysdate: to show the present date(system date)

select sysdate from dual;

SYSDATE

07-MAR-10

Add_months: it returns date after adding a specified date with specified number of months

Syntax: add_months(d,n).

D=date and n= no of months

select add_months(sysdate,3) from dual;

ADD_MONTHS(SYSDATE,3)

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

07-JUN-10

Last_day: it returns the date corresponding to last day of the month.

select last_day(sysdate) from dual;

LAST_DAY(SYSDATE)

31-MAR-10

Months_between: used to find no of months between two dates

Syntax: months_between(d1,d2)

D1=date1,d2=date2

select months_between('01-apr-10','01-jan-10') from dual;

MONTHS_BETWEEN('01-APR-10','01-JAN-10')

Next_day: used to find the immediate next day of the specified date

Syntax: next_day(d,day)

Where d=date,day=any weekday

select next_day(sysdate,'sunday') from dual;

NEXT_DAY(SYSDATE,'SUNDAY')

14-MAR-10

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

String Functions

Concat: adding of only two strings

select concat('cse','it') from dual;

CONCAT('CSE','IT')

cseit

Lower : converts a string from uppercase to lowercase

select lower('CSE') from dual;

LOWER('CSE')

Cse

Upper:converts a string from lowercase to uppercase

select upper('cse') from dual;

UPPER('CSE')

CSE

Ltrim: it removes the string on leftside

Syntax: ltrim(‘string’,’substring’)

select ltrim('abcdefg','abc') from dual;

LTRIM('ABCDEFG','ABC')

Defg

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Rtrim: it removes the string on rightside

Syntax: rtrim(‘string’,’substring’)

select rtrim('abcdefg','efg') from dual;

RTRIM('ABCDEFG','EFG')

Abcd

Translate: translates a character with another character

Syntax: translate(char,from,to)

select translate('siva','s','v') from dual;

TRANSLATE('MANA','M','G')

Viva

Substr: to derive substring from main string

Syntax: substr(string,startingvalue,length)

select substr('gana','1','4') from dual;

SUBSTR('GANAS','1','4')

Gana

Numeric Functions:

they accept numeric input and return numeric values as the output.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Abs(n):

select abs(-17) from dual;

ABS(-17)

17

Ceil(n):

select ceil(44.78) from dual;

CEIL(44.78)

45

Exp(n):

select exp(0) from dual;

EXP(0)

Power(m,n):

select power(2,0) from dual;

POWER(2,0)

Mod(m,n):

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

select mod(10,2) from dual;

MOD(10,2)

Sqrt(n):

select sqrt(4) from dual;

SQRT(4)

Round(m,n):

select round(99.99,1) from dual;

ROUND(99.99,1)

100

Trunc(m,n):

select trunc(99.99,1) from dual;

TRUNC(99.99,1)

99.9

Conversion Functions:

To_char( ): used to convert data to a value of varchar from specified format

Syntax: to_char(d,[fmt]) where d=date and fmt=format mode of date

select to_char(sysdate,'ddth "of" month yyyy') from dual;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

TO_CHAR(SYSDATE,'DDTH"OF"MONTHYYYY')

08th of march 2010

To_date( ): used to convert char datatype to value of date datatype

Syntax: to_date(char,[fmt])

select to_date('01-january-2010','dd-mon-yy') from dual

TO_DATE('01-JANUARY-2010','DD-MON-YY')

01-JAN-10

What is PL/SQL?

PL/SQL stands for Procedural Language extension of SQL.


PL/SQL is a combination of SQL along with the procedural features of programming languages.
It was developed by Oracle Corporation in the early 90’s to enhance the capabilities of SQL.
A Simple PL/SQL Block:
A PL/SQL Block consists of three sections:

 The Declaration section .


 The Execution section (mandatory).

 The Exception (or Error) Handling section (optional).

DECLARE
     Variable declaration
BEGIN
     Program Execution
EXCEPTION
     Exception handling
END;

Advantages of PL/SQL.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

 Block Structures: PL SQL consists of blocks of code, which can be nested within each
other. Each block forms a unit of a task or a logical module. PL/SQL Blocks can be
stored in the database and reused.
   Procedural Language Capability: PL SQL consists of procedural language constructs
such as conditional statements (if else statements) and loops like (FOR loops).

   Better Performance: PL SQL engine processes multiple SQL statements simultaneously


as a single block, thereby reducing network traffic.

 Error Handling: PL/SQL handles errors or exceptions effectively during the execution
of a PL/SQL program.

EXERCISE-5

First we have to create employee table(emp)

EMPNO ENAME SALARY

1 Raju 2500

2 John 3200

3 Raghu 2500

4 Ganesh 4500

5 Siva 2500

a)program which includes declaration, execution and exception section (Ex:select salaery
from emp where name is raju and excepton can be raised if no_data_found)

set serveroutput on;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

declare

newsal number(10);

begin

select salary into newsal from emp where ename='raju';

dbms_output.put_line('salary' || newsal);

exception

when no_data_found then

dbms_output.put_line('Record is not found');

end

b)update data in emp table and use ROLLBACK, SAVE POINT, COMMIT in pl/sql block

declare

total_sal number(10);

begin

savepoint emp_sal;

update emp set salary=salary+7000 where ename='john';

update emp set salary=salary+5000 where ename='raju';

select sum(salary) into total_sal from emp;

if(total_sal>90000) then

rollback to savepoint emp_sal;

end if;

commit;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

end;

before this program create a table called emp with columns empno, ename and salary

EMPNO ENAME SALARY

1 Raju 2500

2 John 3200

3 Raghu 2500

4 Ganesh 4500

5 siva 2500

Then output table can be seen after executing the above code

select * from emp;

EMPNO ENAME SALARY

1 Raju 7500

2 John 10200

3 Raghu 2500

4 Ganesh 4500

5 Gana 2500

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-6

a)Write a program to find Bigest of 3 numbers

declare
a number(3):=&a;
b number(3):=&b;
c number(3):=&c;
begin
if (a>b and a>c)then
dbms_output.put_line('A is Big'||a);
elsif (b>c)then
dbms_output.put_line('B is Big'||b);
else
dbms_output.put_line('C is Big'||c);
end if;
end;

out put
-------

old 2: a number(3):=&a;
new 2: a number(3):=3;
old 3: b number(3):=&b;
new 3: b number(3):=4;
old 4: c number(3):=&c;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

new 4: c number(3):=5;
C is Big5
PL/SQL procedure successfully completed.

b)PL/SQL Block for calculating area of the Circle for given radius

declare
pi constant number(5,2):=3.14;
r number(5):=&r;
a number(7,2);
begin
a:=pi*r*r;
dbms_output.put_line('Area of Circle is'||a);
end;

old 3: r number(5):=&r;
new 3: r number(5):=4;
Area of Circle is50.24
PL/SQL procedure successfully completed.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-7
a)PL/SQL Program to check whether a given number is prime or not.

set serveroutput on;


declare
i number(3);
a number(3):=&a;
flag number(3):=0;
begin
for i in 2..a-1
loop
if(mod(a,i)=0)then
flag:=1;
end if;
end loop;
if(flag=0)then
dbms_output.put_line('given number is prime');
else
dbms_output.put_line('given number is not prime');
end if;
end;

Output
------

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

old 3: a number(3):=&a;
new 3: a number(3):=7;
given number is prime
PL/SQL procedure successfully completed.
/*PL/SQL Block to interpret Pre-defined Exception*/

set serveroutput on;


declare
num number(5);
e_name varchar2(20);
e_sal number(7);
begin
select empno,ename,salary into num,e_name,e_sal from emp where empno=&no;
dbms_output.put_line('Record Customer Details');
dbms_output.put_line('empnum'||'----'||'emp Name'||'----'||'empsal ');
dbms_output.put_line(num||'---------------------'||e_name||'-------------------'||e_sal);
exception
when No_data_found then
dbms_output.put_line('Record is Not found');
end;

output:
-------
old 6: select accno,cname,balance into num,c_name,c_bal from banks where accno=&no;
new 6: select accno,cname,balance into num,c_name,c_bal from banks where accno=501;

Record Customer Details

Customer No----Customer Name----Customer Balance


501--------------raju-------------------1000
PL/SQL procedure successfully completed.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

output:
-------
old 6: select accno,cname,balance into num,c_name,c_bal from banks where accno=&no;
new 6: select accno,cname,balance into num,c_name,c_bal from banks where accno=444;

Record is Not found

PL/SQL procedure successfully completed.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-8
A procedure is a module performing one or more actions. It does not need to return any values.

Parameters in Procedure:

In PL/SQL, we can pass parameters to procedures and functions in three ways.

1) IN type parameter: These types of parameters are used to send values to stored
procedures.
2) OUT type parameter: These types of parameters are used to get values from stored
procedures. This is similar to a return type in functions.
3) IN OUT parameter: These types of parameters are used to send values and get values
from stored procedures.

a)program for calculating increment and decrement values using procedures.

create or replace procedure incr_dec(i in out number,j in out number)is

begin

i:=i+1;

j:=j-1;

end;

calling program

declare

a number:=&a;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

b number:=&b;

begin

incr_dec(a,b);

dbms_output.put_line('Increment Value'||a||'Decrement Value'||b);

end;

b)Write PL/SQL Block using procedures to display the bonus given to employee based on
designation and salary

create or replace procedure bonus(id number) as


bons number(7);
des varchar2(10);
sal number(6);
begin
select salary,edesg into sal,des from emp2 where empno=id;
if(sal>15000 and des='manager') then
bons:=4000;
update emp2 set salary=salary+bons where empno=id;
elsif(sal>10000 or des='asst_manager') then
bons:=2000;
update emp2 set salary=salary+bons where empno=id;
else
bons:=1000;
update emp2 set salary=salary+bons where empno=id;
end if;
dbms_output.put_line('Employee Bonus:'||bons);
end;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

calling program.
declare
id number(10);
begin
id:=&id;
bonus(id);
end;

output:
------
old 4: id:=&id;
new 4: id:=105;
Employee Bonus:2000
PL/SQL procedure successfully completed.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-9

FUNCTIONS

Functions are another type of stored code and are very similar to procedures. The

Significant difference between is that function is a pl/sql block which returns a single

Value. Functions accept one, many, or no parameters. But a function must have a return clause in
the executable section of the function.

a)Program to implement factorial of a given number using funcions

create or replace function factorial(a number) return number is

f number:=1;

i number:=1;

begin

while(i<=a)

loop

f:=f*i;

i:=i+1;

end loop;

return f;

end;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

OUTPUT:

Function created

select factorial (4)”FACTORIAL” from dual;

FACTORIAL

24

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

b)Program that implements a function by checking sid values of sailors table

create or replace function sailors_check(id number) return string is

x varchar2(10);

begin

select sname into x from sailors where sid=id;

return 'EXIST’;

exception

when no_data_found then

return 'NOTEXISTS';

end;

OUTPUT:

Function created.

select sailors_check(73)”STATUS” from sailors;

STATUS

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

EXIST

select sailor_check(122)”STATUS” from sailors;

STATUS

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

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

NOTEXISTS

EXERCISE-10

Package

Package contains both procedures and functions

Write a PL/SQL Block using packages to execute both function and procedure*
create or replace package pack as
function mul(a number,b number) return number ;
procedure incr_dec(i in out number,j in out number);
end pack;

create or replace package body pack as


function mul(a number,b number)return number as
c number;
begin
c:=a*b;
return c;
end mul;
procedure incr_dec(i in out number,j in out number)is
begin
i:=i+1;
j:=j-1;
end incr_dec;
end pack;

calling program

declare

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

a number:=&a;
b number:=&b;
c number;
begin
c:=pack.mul(a,b);
dbms_output.put_line('Value after Multiplication'||c);
pack.incr_dec(a,b);
dbms_output.put_line('Increment Value'||a||'Decrement Value'||b);
end;

output:
Value after Multiplication72
Increment Value10Decrement Value7
PL/SQL procedure successfully completed.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-11

CURSORS

A cursor is a temporary work area created in the system memory when a SQL statement is
executed. A cursor contains information on a select statement and the rows of data accessed by
it. This temporary work area is used to store the data retrieved from the database, and manipulate
this data. A cursor can hold more than one row, The set of rows the cursor holds is called the
active set.

Write a PL/SQL Block using Cursor to display the Employee Names and Employee
Salaries from Employee table

set serveroutput on;


declare
cursor c is select ename,salary from emp;
a emp.ename%type;
b emp.salary%type;
num number;
begin
num:=0;
open c;
loop
fetch c into a,b;
exit when c%notfound;
num:=num+1;
dbms_output.put_line('Employee Name:'||a);
dbms_output.put_line('Employee Salary:'||b);
end loop;

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

end;

output:

Employee Name:raju
Employee Salary:24000
Employee Name:john
Employee Salary:21000
Employee Name:kumar
Employee Salary:12000
Employee Name:krishna
Employee Salary:10000
Employee Name:joe
Employee Salary:8000
PL/SQL procedure successfully completed.

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

EXERCISE-12

TRIGGERS

A Trigger is a procedure that is automatically invoked by the DBMS in response to

Specified changes to the database, and is typically specified by the DBA. A Trigger

Description contains three parts:

 Event: A change to the database that activates the trigger


 Condition: A Query or test that is run when the trigger is activated.
 Action: A procedure that is executed when the trigger is activated and its
Condition is true

Deleting a trigger: DROP TRIGGER <triggername>;

a)PL/SQL block trigger for before insertion

create or replace trigger incr_count before insert on emp


declare
num number(3);
begin
select count(*) into num from emp where empno>=501;
dbms_output.put_line('Number of employees for before insertion is:'||num);
end;
OUTPUT:

Trigger created

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Insert into emp values(6,’ram’,24000);

b)PL/SQL block trigger for after insertion

create or replace trigger incr_count after insert on emp


declare
num number(3);
begin
select count(*) into num from emp where empno>=501;
dbms_output.put_line('Number of employees for after insertion is:'||num);
end;

OUTPUT:

Trigger created

Insert into emp values(6,’ram’,24000);

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1
DATABASE MANAGEMENT SYSTEMS LAB MANUAL

Prepared by T Siva Rama Krishna, T S R Lakshmi, CH Rama Satya


1

You might also like