Dbms Lab
Dbms Lab
DEPARTMENT OF
COMPUTER SCIENCE & ENGINEERING
Lab In Charge
J PRIYA
Asst. Prof.
Programme : UG
CSE
Year:II
II
No.of pages :
11
Procedures
Creation, Execution and Modification of stored Procedure
12
Cursors
A cursor on the given data
Page
No.
ADDITIONAL PROGRAMS
S.No.
Page
no
PROGRAM OUTCOMES
1. An ability to apply knowledge of mathematics, science and engineering to develop and
analyze computing systems.
2. an ability to analyze a problem and identify and define the computing requirements
appropriate for its solution under given constraints.
3. An ability to perform experiments to analyze and interpret data for different applications.
4. An ability to design, implement and evaluate computer-based systems, processes,
components or programs to meet desired needs within realistic constraints of time and space.
5. An ability to use current techniques, skills and modern engineering tools necessary to
practice as a CSE professional.
6. An ability to recognize the importance of professional, ethical, legal, security and social
issues and addressing these issues as a professional.
7. An ability to analyze the local and global impact of systems /processes /applications
/technologies on individuals, organizations, society and environment.
11.A recognition of the need for and an ability to engage in life-long learning and continuing
professional development
DBMS
Lab Manual
EXPERIMENT 1
AIM
E-R Model
Analyze the problem with the entities which identify data persisted in the database which
contains entities and attributes.
Objectives:
Student will able to learn the Entity-Relationship(ER) modeling to develop a conceptual model of data.
Outcomes:
Student gains the ability
About business rules, notations and constructs.
To Construct E-R diagrams including: Entities (strong,
weak, associative) Attributes (simple, multi-valued,
derived) Relations (unary, binary, ternary)
Roadway Travels
System Requirements
Analysis Roadway
Travels:
Roadway travels is in business since 1997 with several buses connecting different places in india. Its
main office is located in Hyderabad. The company wants to computerize its operations in the following
areas.
The company wants to computerize its operations in the following areas:
1. Reservations and Ticketing
2. Cancellations
Reservations & Cancellation:
Reservations are directly handled by booking office. Reservations can be made 30 days in
advance and tickets issued to passenger. One passenger/ person can book many tickets (to his/her
family).Cancellations are also directly handed at the booking office.
In the process of Computerization of Roadway Travels you have to design and develop a
Database which consists the data of Buses, Passengers, Tickets and Reservation and cancellation
details. You should also develop querys using SQL to retrieve the data from the database.
BUS
Ticket
Passenger
Reservatio
n
Cancellation/modification
Ticket_booking
Ticket_datejourne
y
Ticket_to
Ticket_fro
m
Ticket_id
Ticket_no of tickets
Passenger:
Pid
Pname
Pgend
er
Page
precancel
VIVA QUESTIONS
1.
2.
3.
4.
5.
EXPERIMENT 2
Concept design with E-R Model and apply cardinalities for each
relationship. Identify strong entities and weak entities for
relationships like generalization, aggregation, specialization.
Objectives:
Student will able to learn data structures in terms of entity types, relationship types and attributes or
classes, associations and attributes.
Outcomes:
Student gains the ability to describe the data requirements for a new information system in a direct and
easy to understand graphical notation.
E_R diagram:
Bus No
Source
BUS
Destination
Departure Time
Reservation
Date of journey
Sex
Ticket no
Ticket Source
Departure time
Age
VIVA QUESTIONS
1.
2.
3.
4.
5.
EXPERIMENT 3
AIM
Relation Model represents attributes as columns in tables and
different types of attributes like composite, Multi-valued and
Derived.
Objectives:
Student will able to learn the structural components of the relational data model.
Student will able to learn to map ER models into relational models.
Outcomes:
Student gains the ability
To describe the Model Structure.
To define Properties of Relations.
To define Domains.
To implement Notation to Describe the Relational Schema
To Represent an ER Model as a Relational Model.
Example: The passenger tables look as below. This is an example. You can add more attributes based
on your E-R model. This is not a normalized table. Passenger
passenger
Bus
Passenger_tic
tickets
kets
bus_no
ppno
source
destination
ppno
name
tickets _no
ticket_no
age
no of tkts
jrny_date
sex
from_place
address
to_place
phone_no
bus_no
jrny_date
ID
Name
Age
Sex
Address
Passport
Note: The student is required to submit a document by Represent relationships in a tabular fashion to
the lab teacher.
2. Concept design with E-R model
Relate the entities appropriate for each relationship. Identify strong entities and week entities (if any).
Indicate the type of relationships (total/partial). In this we will design the different E-R diagram for
different entities and also the whole Roadway Travels.
E-R diagram: An entity-relationship(ER) diagram is a specified graphic that illustrates the
interrelationships between entities and database. W e can express the overall logical structure of
database graphically with an E-R diagram.
3. Relational Model and Normalization
Represent all the entities (Strong, Weak) in tabular fashion. Represent relationships in a tabular fashion.
There are different ways of representing relationships as tables based on the cardinality. Represent
attributes as columns in tables or as tables based on the requirement. In this we will represent the
different entities, attributes of different keys in a tabular fashion or manner.
Relational Model:
The relational model is a depiction of how each piece of stored
information relates to the other stored information. It shows how
tables are linked, what type of the links are between tables, what
keys are used, what information is referenced between tables. Its
an essential part of developing a normalized database structure to
prevent repeat and redundant data storage.
Different types of keys:
A super key is a set of one or more attributes which;
taken collectively, allow us to identify uniquely an entity in
the entity set.
A primary key is a candidate key(there may be more than
one) chosen by the DB designer to identify entities in an
entity set.
A super key may contain extraneous attributes, and we are
often interested in the smallest super key. A super key for which
no subset is a super key is called a candidate key. An entity
does not posses sufficient attributes to form a primary ket is
called a weak entity set. One that does have a primary key is
called a strong entity set.
A foreign key is a field in a relational table that matches
the primary key column of another table. The foreign key
can be used to cross-reference tables.
Normalization
Database normalization is a technique for designing relational
database tables to minimize duplication of information and, in so
doing, to safeguard the database against certain types of logical
or structural problems, namely data anomalies. In this we will
write the normalization tables that is entities of Roadway
Travels.
Normalization: In relational databases, normalization is a
process that eliminates redundancy, organizes data efficiently;
Normalization is the process of efficiently organizing data in a
database. There are two goals of the normalization process:
eliminating redundant data(for example, storing the same data in
more than one table) and ensuring data dependencies make
VIVA QUESTIONS
1.
2.
3.
4.
5.
E
X
P
E
R
I
M
E
N
T
A
I
M
N
o
r
m
a
l
i
z
a
t
i
o
n
o
f
t
a
b
l
e
s
b
j
e
c
t
i
v
e
s
:
Student will able to learn to avoid problems that are associated with updating
redundant data.
Outcomes:
Student gains the knowledge to build The database that does not have
redundant data.
A basic objective of the first normal form defined by Edgar
Frank "Ted" Codd in 1970 was to permit data to be queried and
manipulated using a "universal data sub-language" grounded in
first-order logic.(SQL is an example of such a data sub-language,
albeit one that Codd regarded as seriously flawed.)
The objectives of normalization beyond 1NF (First Normal Form) were stated
as follows by Codd:
1. To free the collection of relations from
undesirable insertion, update and deletion
dependencies;
2. To reduce the need for restructuring the collection
of relations, as new types of data are introduced, and
thus increase the life span of application programs;
3. To make the relational model more informative to users;
8
7
1
2
9
0
4
1
5
O
c
t
2
0
0
3
2
0
0
3
1
8
1
4
9
2
0
5
0
r. ID
2
Date
0
Amount
N
12898 14-Octo
2003 21
v
Tr. ID
2
Date
0
Amount
0
1
3
2
9
0
7
7
0
1
5
O
c
t
-
1
5
0
0
3
2
7
N
o
v
2
0
0
3
6
0
VIVA QUESTIONS
1. Explain the need of normalization?
2. What is functional dependency?
3. Explain difference between third normal form and boyce codd normal
form?
4. What is PJNF?
5. What is transitivity dependency?
E
X
P
E
R
I
M
E
N
T
A
I
M
INSTALLATION OF MYSQL and Practicing DDL commands
Objectives:
Student will able to learn DDL Statements to Create and Manage Tables.
Outcomes:
Student gains the ability to
Categorize the main database objects
Review the table structure
List the data types that are available for columns
Create a simple table
Describe how constraints are created at the time of table creation
Describe how schema objects work.
Requirements:
MYSQL, software for database that is MYSQL.exe required
space for installing MYSQL server. Description: In this we
will install the MYSQL server and also practice the DDL
commands. Installation of MySQL and Practicing DDL
commands:
Installation of MySQL:
Why MySQl:MySQL is undoubtedly the most popular and widely-used open
source database:
It is simple to setup and use.
It is recognised as one of the fastest databse engines.
Most linux( and many Windows-based)web hosts offer MySQL.
MySQL is closely integrated with PHP, which
makes it an ideal cndidate for many web applications.
Why Install MySQL Locally?
Installing MySQL on your development PC allows you to
safely create and test a web application without affecting the
data or systems on your live website.
colname><
datatype>[constraints],[table
level
constraints])
student table:
Syntax:
Sid
int
pK
Sname
Varchar(30)
Notnull
Course
Varchar(30)
default cpp
these operations, we have to use alter table that has the following
syntax,
1. Alter column: this option is used to change the datatype
of a column or add or remove not null constraint.
Syntax:
Alter
Tabl<tablEname>AlterColumn<colname><da
Q:
tatype>Null/NotNull
Sp_helpstudent
//Execute
EX: The following example changes the data types of sname
column of student table to char with maximum length 40
removes the not Null Column constraint available on it.
Q: Alter Table Student
Alter Column Sname
Char
(40)
Null
Q:
sp_helpstudent
//Execute
3. Drop Column: this option is
used to delete columns from the
table
Syntax:
Table<tablEName>Drop
Column<Column List>
Alter
VIVA QUESTIONS
1. Write the syntax for all DDL commands?
2. What is the difference between drop and truncate command?
3. What is DDL interpreter?
4. What is the command to delete columns from table?
E
X
P
E
R
I
M
E
N
T
A
I
M
P
r
a
c
t
i
c
i
n
g
D
M
L
c
o
m
m
a
n
d
O
b
j
e
c
t
i
v
e
s
:
Student will able to learn commands that make changes
in relational database and transaction management.
Outcomes:
Student gains the knowledge to perform transactions like updating,
deleting, inserting and selecting data from a data base.
SELECT INSERT,UPDATE,DELETE.
5. Data Manipulation Language commands
following
Values
Values
(1003,
C,S
QL)
Select
* from
studen
t
//Exec
ute
this
line
Ex:The
following
examples
insert
rows
Marks
Values
Insert
Marks
Select
from
marks
Syntax:
Update
<tablEname>
Set<column>=<value>,<colname>=<value>
[Where<condition>] Ex:The following examples updates name
and course of the student with id 1004 to S and DOTNET Q:
Update student set name-S, course=DOTNET where
sid=1004
Q: Select * from student
EX: The following example updates marks table by
calculating total and average for all rows. Q: update
marks set total=C+CPP+SQL,aveg=(C+CPP+SQL)/3.0
Q: Select * from marks
Ex:the following example updates marks table by
calculating the grade on average marks. Q: Update
marks set grade=
Case
When Aveg>=70 then distinction
When Aveg>=60 and Aveg<70 then first class
When
Aveg>=50 and
Aveg<60
thenSecond
class
When
Aveg>=35 And
Aveg<50
thenthird
class
E
l
s
e
F
a
i
l
E
n
d
The
following
the
marks.
Q:
Delete marks
Output
RATING
MINAGE
25.5
35
25.5
Output
Table
BUS
Column
Nullable
Data Type
Default
Length
Precision
Scale
Primary Key
Comment
BUSNO
-
Varchar2
-
10
-
SOURCE
Varchar2
-
50
-
DESTINATION
Varchar2
50
-
1-3
tirupathi
',banglore); insert
into bus
values(34,'hyderaba
d',chennai);
Display table
Syntax
Select <select list> from <table name>
Query
Select * from bus;
Output
BUSNO
SOURCE
DESTINATION
1234
hyderabad
tirupathi
2345
hyderabad
tirupathi
23
hyderabad
kolkata
45
tirupathi
banglore
34
hyderabad
chennai
Output
Table
PASSENGER
Column
Nullable
Data Type
Default
Length
Precision
Comment
Scale
Varchar2
-
15
-
NAME
Varchar2
-
15
-
AGE
Number
-
SEX
Char
-
10
-
PPNO
Primary Key
ADDRESS
Varchar2
50
-
1-5
Inserting
records
into
PASSENGER
table
Syntax
Insert into <table name> values (val 1,val2,val3)
Query
insert into PASSENGER
values(1,'TIRUMALAY',19,'MALE','AMBERP
ET'); insert into PASSENGER
values(2,'SUPRIYA',20,'FEMALE','B.B
NAGAR'); insert into PASSENGER
values(3,'AMULYA',20,'FEMALE','ECIL');
insert into PASSENGER
values(4,'NAGARAJU',20,'MALE','NAGARA
M'); insert into PASSENGER
values(5,'AVS.RAVI',20,'MALE','B.B
NAGAR');
Display table
Syntax
Select <select list> from <table name>
Query
Select * from PASSENGER;
Output
PPNO
NAME
AGE
SEX
ADDRESS
TIRUMALAY 19
MALE
AMBERPET
SUPRIYA
20
FEMALE
B.B NAGAR
AMULYA
20
FEMALE
ECIL
NAGARAJU
20
MALE
NAGARAM
AVS.RAVI
20
MALE
B.B NAGAR
VIVA QUESTIONS
1. What is the syntax for insert command?
2. Define Key constraint?
3. What is the difference between NULL Values and NOT NULL Values?
4. What is the command to display table?
E
X
P
E
R
I
M
E
N
T
A
I
M
QUERYING
QUERIES
ANY,
USING
ALL,
IN,
INTERSECT,
UNION
Objectives:
Student will able to learn to operate on multiple
result sets to return a single result set. Student will
able to learn to perform nested Queries.
Outcomes:
Student gains the knowledge to implement queries using ANY, ALL, IN,
INTERSECT, UNION.
Describing table
Query
Desc TICKET
Output
Table
Comment
TICKET
Column
TICKET_NO
JOURNEY_DATE
Data Type
Number
Date
Length
Precision
Scale
Primary Key
Nullable
Default
AGE
Number
SEX
Char
10
SOURCE
Varchar2
50
DEP_TIME
Varchar2
50
SEX
SOURCE
1203
10-FEB-11
10.30 AM
19
MALE
HYDERABAD
1213
HYDERABAD
10-FEB-11
10.30 AM
19
FEMALE
1201
HYDERABAD
13-FEB-11
11.30 AM
20
FEMALE
1202
14-FEB-11
11.00 AM
20
MALE
TIRUPATHI
1205
14-FEB-11
11.00 AM
20
MALE
HYDERABAD
Describing table
Query
Desc PASSENGER_TICKETS
Output
Table
PASSENGER_TICKE
TS
Column
PPNO
Data Type
Varchar2
TICKET_NO Number
Length
Precision
Scale
Primary Key
15
Nullable
into
PASSENGER_TICK
ETS
values(1,1203);
insert
into
PASSENGER_TICK
ETS
values(2,1213);
insert
into
PASSENGER_TICK
ETS
values(3,1201);
insert
into
PASSENGER_TICK
ETS
values(4,1202);
insert
into
PASSENGER_TICK
ETS values(5,1205);
Display table
Syntax
Select <select list> from <table name>
Query
select * from TICKET;
Output
PPNO
TICKET_NO
1203
1213
1201
1202
1205
RE
SE
RV
ATI
ON
Column
Default
PNR_NO
Data Type
Comment
15
-
Length
Precision
Scale
Primary Key
Varchar2
JOURNEY_DATE Date
7
-
NO_OF_SEATS
8
-
Number
ADDRESS
Varchar2
-
50
-
CONTACT_NO
Number
-
10
STATUS
Char
Query
insert into reservation values(1,'10/feb/11',5,'amberpet','7416944004','yes');
insert into reservation values(1,'11/feb/11',8,'amberpet','7416944004','yes');
insert into reservation values(2,'11/feb/11',8,'b.b nagar','7207204221','yes');
insert into reservation values(2,'14/feb/11',2,'b.b nagar','7207204221','yes');
insert into reservation values(3,'14/feb/11',3,'ecil','00000000','yes');
insert into reservation values(4,'14/feb/11',4,'nagaram','9700135300','yes');
insert into reservation values(5,'16/feb/11',1,'b.b nagar','8143528258','yes');
insert into reservation values(5,'15/feb/11',7,'b.b nagar','8143528258','yes');
Display table
Syntax
Select <select list> from <table name>
Query
select * from reservation;
Output
PNR_NO
JOURNEY_DATE
NO_OF_SEATS
ADDRESS
CONTACT_NO
STATUS
10-FEB-11
amberpet
7416944004
yes
11-FEB-11
amberpet
7416944004
yes
11-FEB-11
b.b nagar
7207204221
yes
14-FEB-11
b.b nagar
7207204221
yes
14-FEB-11
ecil
yes
14-FEB-11
nagaram
9700135300
yes
16-FEB-11
b.b nagar
8143528258
yes
15-FEB-11
b.b nagar
8143528258
yes
Creating table
Syntax
Create table <table name> (col1 datatype,col2 datatype,col3
datatype)
Query
create
table
cancellation
(pnr_no
varchar2(15),journey_date
date,no_of_seats
number(8),address
varchar2(50),contact_no
number(10),status
char(3),foreign
key(pnr_no)references
passenger_tickets(ppno));
Describing table
Query
Desc reservation
Output
Table
CANCELLAT
ION
Column
PNR_NO
Data Type
Varchar2
Length
Precision
Scale
Primary Key
Nullable
Def
15
JOURNEY_DATE Date
NO_OF_SEATS
Number
ADDRESS
Varchar2
50
CONTACT_NO
Number
10
STATUS
Char
Inserting records
into
CANCELLATION
table Syntax
Insert into <table name> values (val 1,val2,val3)
Query
insert into cancellation
values(1,'10/feb/11',5,'amberpet','7416944004
','yes'); insert into cancellation
values(1,'11/feb/11',8,'amberpet','7416944004
','yes'); insert into cancellation
values(2,'11/feb/11',8,'b.b
nagar','7207204221','yes'); insert into
cancellation values(2,'14/feb/11',2,'b.b
nagar','7207204221','yes'); insert into
cancellation
values(3,'14/feb/11',3,'ecil','00000000','yes');
insert into cancellation
values(4,'14/feb/11',4,'nagaram','9700135300'
,'yes'); insert into cancellation
values(5,'16/feb/11',1,'b.b
nagar','8143528258','yes'); insert into
cancellation values(5,'15/feb/11',7,'b.b
nagar','8143528258','yes');
Display table
Syntax
Select <select list> from <table name>
Query
select * from cancellation
Output
PNR_NO JOURNEY_DATE
CONTACT_NO STATUS
NO_OF_SEATS
ADDRESS
10-FEB-11
7416944004
5
yes
amberpet
11-FEB-11
7416944004
8
yes
amberpet
11-FEB-11
7207204221
8
yes
b.b nagar
14-FEB-11
7207204221
2
yes
b.b nagar
14-FEB-11
yes
ecil
14-FEB-11
9700135300
4
yes
nagaram
16-FEB-11
8143528258
1
yes
b.b nagar
15-FEB-11
8143528258
7
yes
b.b nagar
29. Display the ticket numbers and names of all the passengers.
Query
select p.name,t.ticket_no from passenger p,passenger_tickets
t where
t.ppno=p.ppno
NAME
TIRUMALAY
TICKET_NO
Output
1203
SUPRIYA
1213
AMULYA
1201
NAGARAJU
1202
AVS.RAVI
1205
30. Find the ticket numbers of the passengers whose name start with
t and ends with y.
Query
select
t.ticket_no
from
passenger
p,passenger_tickets t where p.name like 'T
%Y'and t.ppno=p.ppno;
Output
TICKET_NO
1203
31. Find the names of passengers whose age is between 15 and 20.
Query
select name from passenger where age between 15 and 20
Output
NAME
T
I
R
U
M
A
L
A
Y
S
U
P
R
I
Y
A
A
M
U
L
Y
A
N
A
G
A
R
A
J
U
A
V
S
.
R
A
V
I
Output
NAME
A
M
U
L
Y
A
A
V
S
.
R
A
V
I
A
M
U
L
Y
A
A
V
S
.
R
A
V
I
N
A
G
A
R
A
J
U
S
U
P
R
I
Y
A
TIRUMALAY
CANCELLATION
Operator).
tables.
(Use
UNION
from
passenger
Query
select
p,cancellation
where
p.ppno=c.pnr_no union
select * from passenger p1,cancellation c1 where
p1.ppno=c1.pnr_no
Output
PP
NO
NAME
A
GE
SEX
ADDR
ESS
PNR_
NO
JOURNEY_
DATE
NO_OF_S
EATS
ADDR
ESS
CONTAC
T_NO
STA
US
TIRUMA
LAY
19
MAL
E
AMBER
PET
10-FEB-11
amberpe
t
7416944004
yes
TIRUMA
LAY
19
MAL
E
AMBER
PET
11-FEB-11
amberpe
t
7416944004
yes
SUPRIY
A
20
FEMA
LE
B.B
NAGAR
11-FEB-11
b.b
nagar
7207204221
yes
SUPRIY
A
20
FEMA
LE
B.B
NAGAR
14-FEB-11
b.b
nagar
7207204221
yes
AMULY
A
20
FEMA
LE
ECIL
14-FEB-11
ecil
yes
NAGAR
AJU
20
MAL
E
NAGAR
AM
14-FEB-11
nagaram
9700135300
yes
AVS.RA
VI
20
MAL
E
B.B
NAGAR
15-FEB-11
b.b
nagar
8143528258
yes
AVS.RA
VI
20
MAL
E
B.B
NAGAR
16-FEB-11
b.b
nagar
8143528258
yes
SUM(NO_OF_SEATS)
13
10
Output
PNR_NO
1
3
5
2
4
SUM(NO_OF_SEATS)
13
10
VIVA QUESTIONS
1. What is the syntax for create command?
2. What is the difference between primary key and foreign
key?
3. What is the command to display data from a table?
4. What are the types of clause used in mysql ?
EXPERIMENT 8 & 9:
Querying Using Aggregate functions (COUNT,
SUM, AVERAGE using GROUPBY and HAVING)
Queries using Aggregate functions (COUNT,
SUM, AVG, MAX and MIN),
GROUP BY,
HAVING and Creation and dropping of Views.
Objectives:
Student will able to learn to perform mathematical operations that
return a single value, calculated from values in a column.
Outcomes:
Student gains the knowledge to perform aggregate operations on the database
appropriately.
Aggregate
operators:
In addition to simply
MAX
(Column name)
Example: SELECT MAX (Sal) FROM emp;
SQL>
select
by
deptno;
DEPTNO
MAX(SAL)
------ -------10
5000
20
3000
30
2850
--------
30
2850
MIN
(Column name)
Example: SELECT MIN (Sal) FROM emp;
SQL>select deptno,min(sal) from emp group by
deptno
having
MIN(SAL)
-----
--------
10
1300
min(sal)>1000;
DEPTNO
ENAME
JOB
----
------ -------
7369
SMITH
CLERK
7876
ADAMS
CLERK
7900
JAMES
CLERK
7934
MILLER
CLERK
2.Example:
CREATE
VIEW
[Current
Product List]
AS SELECT
ProductID,Pr
oductName
FROM
Products
WHERE Discontinued=No
DROP VIEW: This query is used to delete a view , which has
been already created.
Syntax:
Example
SQL>
:
DROP
VIEW
EMPLOYEE;
View dropped
lpad,
rpad,
ltrim,
rtrim,
date
add_months,
functions (Sysdate,
last_day,
and
next_day,
months_between,
VARCHAR2,
NCHAR,
or
RPAD
(ORACLE,15,*)FROM
DUAL;
ORACLE*********
Ltrim: Returns a character expression
after removing leading blanks.
SQL>SELECT
LTRIM(SSMITHSS,S)FROM
DUAL; MITHSS
Rtrim: Returns a character string
after truncating all trailing blanks
SQL>SELECT
RTRIM(SSMITHSS,S)FROM
DUAL; SSMITH
DUAL;
dbms
Upper: Returns a character expression with lowercase
character data converted to uppercase
SQL>SELECT
UPPER(dbms)
FROM DUAL;
DBMS
Length: Returns the number of characters, rather
than the number of bytes, of the given string expression,
excluding trailing blanks.
SQL>SELECT
LENGTH(DATABASE)F
ROM DUAL; 8
Substr: Returns part of a character,
binary, text, or image expression.
SQL>SELECT
SUBSTR(ABCDEFGHIJ3,4)FROM
DUAL; CDEF
Instr: The INSTR functions search string for substring.
The function returns an integer indicating the position
of the character in string that is the first character of
this occurrence.
SQL>SELECT
INSTR('CORPORATE
FLOOR','OR',3,2)FROM DUAL; 14
3. Date functions:
Sysdate:
SQL>SELECT
SYSDATE
FROM
DUAL; 29-DEC-08
next_day:
SQL>SELECT
NEXT_DAY(SYSDATE,WED)F
ROM DUAL; 05-JAN-09
add_months:
SQL>SELECT
ADD_MONTHS(SYSDATE,2)F
ROM DUAL; 28-FEB-09
last_day:
SQL>SELECT
LAST_DAY(SYSDATE)F
ROM DUAL; 31-DEC-08
months_between:
SQL>SELECT
MONTHS_BETWEEN(SYSDATE,HIREDATE)FROM EMP; 4
Least:
SQL>SELECT
LEAST('10-JAN-
07','12-OCT-07')FROM DUAL;
10-JAN-07
Greatest:
SQL>SELECT
GREATEST('10-JAN-
Round:
SQL>SELECT
ROUND(SYSDATE,'DAY')F
ROM DUAL; 28-DEC-08
to_char:
SQL>
select
to_char(sysdate,
"dd\mm\yy")
from
dual; 24-mar-05.
to_date:
SQL>
select
to_date(sysdate,
"dd\mm\yy")
from
dual; 24-mar-o5.
VIVA QUESTIONS
3. Define View?
4. What is the difference between group by and order by
clause?
EXPERIMENT 10
Triggers:
Creation
of
INSERT
TRIGGER,
SQL>insert
into
passenger
(81,srinu,
values
10,
22);
Value inserted
SQL>insert
into
passenger
(25,rksd,
values
5,
16);
ORA-20110: invalid
age.
ORA-06512: atgcet_550.passenger_age, line 4.
ORA-04088: error during execution of
triggergcet_550.passenger_age
VIVA QUESTIONS
1. What is Trigger?
2. What is Nested Trigger?
3. What are the types on Triggers?
4. What is the difference between For Trigger and After
trigger?
EXPERIMENT 11:
Procedures:
Creation
of
stored
procedures,
Execution of procedure and modification
of procedures.
Objectives:
Student will able to learn the features like
reusability, maintainability and modularity.
Student will able to learn to develop procedures
and function for various operation.
Outcomes:
Student gains the knowledge to implement procedures and function for
various operations.
COUNT
(Tickets)
FROM
Ticket
WHERE
age>=40; End;
Procedures created
SQL>CREATE PROCEDURE
myproc(in_customer_id INT)
BEGIN
DECLARE v_id INT;
DECLARE v_name VARCHAR(30);
DECLARE c1 CURSOR
FOR SELECT
stdId,stdFirstname FROM
students WHERE
stdId=in_customer_id;
OPEN c1;
F
E
T
C
H
c
1
i
n
t
o
v
_
i
d
,
v
_
n
a
m
e
;
C
l
o
s
e
c
1
;
End;
/
PL/SQL procedure successfully completed.
VIVA QUESTIONS
1. What is difference between Function and Stored Procedure?
2. What is Stored Procedure?
3. What is PL/SQL?
4. Show how functions and procedures are called in a PL/SQL
block?
EXPERIMENT 12
Cursors: A
cursor
the
on
given
database.
Objectives
:
Student will able to learn about cursors that enable
traversal over the records in a database.
Outcomes:
Student gains the ability to implement cursors on the database.
We use a cursor when we have a SELECT statement that
returns more than one row from the database. A cursor is
basically a set of rows that we can access one at a time.
We retrieve the rows into the cursor using our SELECT
statement and then fetch the rows from the cursor.
We may follow five steps when using a cursor.
Declare variables to store the column values from the SELECT
statements.
1. Declare the cursor specifying our SELECT statement.
2. Open the cursor.
3. Fetch the rows from the cursor.
4. Close the cursor.
declare
v_sno student.sno%TYPE;
v_s
nna
me
stu
den
t.sn
am
e
%T
YP
E;
v_b
ran
ch
stu
den
t.br
anc
h
%T
YP
E;
v_a
ge
stu
den
t.ag
e
%T
YP
E;
cursor MyCursor (c_sno number) is select
sno,sname,branch,age from student where sno=c_sno;-c_record MyCursor%rowtype;
begin
if
(NOT
MyCu
rsor
%ISO
PEN)t
hen
Open
MyCu
rsor
(1201
);
end if;
loop
c
l
o
s
e
M
y
C
u
r
s
o
r
;
endif;
if(N
OT
My
Cur
sor
%I
SO
PE
N)t
hen
opr
n
My
Cur
sor(
120
2);
endif;
loop
e
M
y
c
u
r
s
o
r
;
endif;
end;
VIVA QUESTIONS
1. Show code of a cursor for loop?
2. Explain uses of cursor?
3. What is Raise_application_error?
4. What is Cursor?
ADDITIONAL
PROGRAMS
syntax
SQL>Create table <table name> (col1
datatype,col2 datatype,col3 datatype)
Query
SQL> create table employee1(empsid
number,empname varchar(20),empjob
varchar(20)
,empsalary
number,em
pjoindate
varchar(20)
);
Describing table
SQL> desc employee1;
Name
Null?
Type
----------------------------------------- -------------------------EMPSID
NUMBER
EMPNAME
VARCHAR2(20)
EMPJOB
VARCHAR2(20)
EMPSALARY
NUMBER
EMPJOINDATE
VARCHAR2(20)
m
e
:
'
a
n
i
l'
E
n
t
e
r
v
a
l
u
e
f
o
r
e
m
p
j
o
b
:
'j
a
v
a
'
for
empjoinda
te: '4-jan2009' old
1:
insert
into
employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1 values(20,'anil','java',20000,'4-jan2009')
1 row created.
SQL> /
Enter value for empsid: 50
Enter value for empname: 'jyothi'
Enter value for empjob: 'faculty'
Enter value for empsalary: 30000
Enter value
for
empjoindat
e:
'5-mar-
2003' old 1:
insert into
employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1 values(50,'jyothi','faculty',30000,'5mar-2003')
1 row created.
SQL> /
Enter value for empsid: 60
Enter value for empname: 'avinash'
Enter value for empjob: 'software'
Enter value for empsalary: 30000
Enter
value
for
empjoinda
te: '5-apr2009'
1:
old
insert
into
employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1
values(60,'avinash','software',30000,'5-apr-2009')
1 row created.
SQL> /
Enter value for empsid: 70
for
empjoinda
te: '2-jun2008'
1:
old
insert
into
employee1
values(&empsid,&empname,&empjob,&empsalary,&empjoindate)
new 1: insert into employee1 values(70,'anitha','sql',40000,'2-jun2008')
1 row created.
Display table
SQL> select * from employee1;
EMPSID EMPNAME
EMPJOB
EMPSALARY
EMPJOINDATE
---------- -------------------- -------------------- ---------- -----------20
anil
4-jan-2009
java
20000
50
jyothi
5-mar-2003
faculty
30000
60
avinash
5-apr-2009
software
30000
70
anitha
2-jun-2008
sql
40000
Null? Type
----------------------------------------------------------------- ------------------------DPSID
DPNAME
VARCHAR2(20)
NUMBER
DPJOB
VARCHAR2(20)
DPJOINDATE
VARCHAR2(20)
DPLOCATION
VARCHAR2(20)
SQL>
department
insert
values(&dpsid,&dpname,&dpj
ob,&dpjoindate,&dplocation);
Enter value for dpsid: 1
E
n
t
e
r
v
a
l
u
e
f
into
o
r
d
p
n
a
m
e
:
'
c
s
e
'
E
n
t
e
r
v
a
l
u
e
f
o
r
d
p
j
o
b
:
'
d
b
m
s
'
Enter
value for
dpjoinda
te:
jan2002'
Enter
'4-
value for
dplocati
on: 'hyd'
old
1:
insert
into
department
values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocatio
n) new 1: insert into department values(1,'cse','dbms','4jan-2002','hyd')
1 row created.
SQL> /
Enter value for dpsid: 2
E
n
t
e
r
v
a
l
u
e
f
o
r
d
p
n
a
m
e
:
'
o
s
'
E
n
t
e
r
v
a
l
u
e
f
o
r
d
p
j
o
b
:
'
c
o
'
Enter
value for
dpjoinda
te:
'5-
apr2003'
Enter
value for
dplocatio
n: 'hyd'
old
1:
insert
into
department
values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocatio
n) new 1: insert into department values(2,'os','co','5-apr2003','hyd')
1 row created.
SQL> /
Enter value for dpsid: 3
E
n
t
e
r
v
a
l
u
e
f
o
r
d
p
n
a
m
e
:
'
e
c
e
'
E
n
t
e
r
v
a
l
u
e
f
o
r
d
p
j
o
b
:
'
s
t
l
d
'
Enter
value for
dpjoindat
e: '6-dec2004'
Enter
value for
dplocatio
n: 'hyd'
old
1:
insert
into
department
values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocatio
n) new 1: insert into department values(3,'ece','stld','6-dec2004','hyd')
1 row created.
SQL> /
Enter value for dpsid: 4
E
n
t
e
r
v
a
l
u
e
f
o
r
d
p
n
a
m
e
:
'
e
e
e
'
E
n
t
e
r
v
a
l
u
e
f
o
r
d
p
j
o
b
:
'
b
e
e
'
Enter
value for
dpjoinda
te:
'6-
jun2006'
Enter
value for
dplocatio
n: 'hyd'
old
1:
insert
into
department
values(&dpsid,&dpname,&dpjob,&dpjoindate,&dplocatio
DPNAME
DPJOB
DPJOINDATE
DPLOCATION
cse
dbms
4-jan-2002
os
co
5-apr-2003
ece
stld
6-dec-2004
eee
bee
6-jun-2006
hyd
hyd
hyd
hyd
DDL&DML COMMANDS
on
Sailors,
boats
DDL(Data
reserves
Definition
Language):SQL>
alter
employee1
emptime
&
table
add
number;
Table altered.
SQL> desc employee1;
Name
Null? Type
----------------------------------------------------------------- -------------------EMPSID
EMPNAME
EMPJOB
E
M
S
Q
>
ta
le
NUMBER
employee1;
VAR
Table
CHA
dropped.
R2(2
SQL>
0)
desc
VAR
emplo
CHA
yee1;
R2(2
ERRO
0)
R:
NUMBER
VAR
CHA
R2(2
0)
NU
MBE
R
Query
Create table sailors (sid number, sname varchar2(20), rating
number, age number(4,2));
Describing table
Query
Desc sailors
Output
into
sailors
values(22,'du
stin',7,45.0);
insert
into
sailors
values(29,'br
utus',1,33.0);
insert
into
sailors
values(31,'lu
bber',8,55.5);
insert
into
sailors
values(32,'an
dy',8,25.5);
insert
into
sailors
values(58,'ru
sty',10,35.0);
Table
SAILORS
Column
Nullable
Data Type
Length
Precision
Scale
Primary Key
Default Comment
SID
Number
-
SNAME
Varchar2
-
20
-
RATING
Number
-
AGE
Number
-
1-4
insert into
sailors
values(64,'hor
atio',7,35.0);
insert into
sailors
values(71,'zob
ra',9,35.0);
insert into
sailors
values(74,'hor
atio',9,35.0);
insert into
sailors
values(85,'art'
,3,25.5);
insert into
sailors
values(95,'bo
b',3,63.5);
Display table
Syntax
Select <select list> from <table name>
Query
select * from sailors;
Table
Column
Data Type
Nullable
Default
Comment
Length
Precision
Scale
Primary Key
Output
SID
SNAME
RATING
AGE
22
dustin
45
29
brutus
33
31
lubber
55.5
32
andy
25.5
58
rusty
10
35
64
horatio
35
71
zobra
10
16
74
horatio
35
85
art
25.5
95
bob
63.5
BOATS
BID
Number
-
BNAME
Varchar2
-
10
-
COLOR
Varchar2
-
10
-
1-3
I
n
s
e
r
t
i
n
g
r
e
c
o
r
d
s
i
n
t
o
t
a
b
l
e
S
y
n
t
a
x
Insert into <table name> values (val 1,val2,val3)
Query
insert
into
sailors
values(101,'inter
lake',blue);
insert
into
sailors
values(102,'inter
lake',red);
insert
into
sailors
values(103,'clipp
er,green);
insert
into
sailors
values(104,'mari
ne',red);
Display table
Syntax
Select <select list> from <table name>
Query
select * from boats;
Output
BID
BNAME
COLOR
101
interlake
blue
102
interlake
red
103
clipper
green
104
marine
red
t
a
b
l
e
S
y
n
t
a
x
Create table <table name> (col1 datatype,col2 datatype,col3
datatype)
Query
Create table Reserves (sid number, bid number, day date);
Describing table
Query
Desc reserves
Output
Data
Table
RE
SE
RV
ES
Column
Nullable
SID
-
Type
t
Number
Lengt
Precisio
Defaul
h
n
Comment
Scal
Primary
Key
BID
Number
-
DAY
Date
-
7
-
into
values(22,101
,10/10/98);
insert
into
sailors
values(22,102
,10/10/98);
insert
into
sailors
values(22,103
,10/8/98);
insert
into
sailors
values(22,104
,10/7/98);
insert
into
sailors
values(31,102
,11/10/98);
insert
into
sailors
values(31,103
,10/6/98);
insert
into
sailors
values(31,104
,10/12/98);
insert
into
sailors
values(64,101
,9/5/98);
Display table
Syntax
Select <select list> from <table name>
Query
select * from reserves;
Output
SID
BID
DAY
22
101
10/10/98
22
102
10/10/98
64
102
9/8/98
74
103
9/8/98
22
103
10/8/98
22
104
10/7/98
31
102
11/10/98
31
103
11/6/98
31
104
11/12/98
64
101
9/5/98
1) Find the names of sailors who have reserved boat number 103
(Using AND).
Query
Select s. sname from sailors s, reserves r where s.sid=r.sid and
r.bid=103;
SNAME
horatio
Output
dustin
lubber
2) Find the sids of sailors who have reserved a red boat (Using
AND).
Query
select r.sid from boats b,reserves r where b.bid=r.bid and
b.color='red'
Output
SID
22
6
4
2
2
3
1
3
1
3) Find the names of sailors who have reserved a red boat (Using
AND).
Query
e
r
Query
select b.color from sailors s,reserves r,boats b where
s.sid=r.sid and r.bid=b.bid and s.sname='lubber'
Output
COLOR
green
red
red
5) Find the names of sailors who have reserved at least one boat.
Query
Select s.sname from sailors s, reserves r where s.sid=r.sid;
Output
SNAME
lubber
d
u
s
t
i
n
h
o
r
a
t
i
o
Query
Select s.age from sailors s where s.sname like 'b_%b';
Output
AGE
63.5
7) Find the names of sailors who have reserved a red or a green
boat (Using AND,OR).
Query
select s.sname from sailors s,reserves r,boats b where
s.sid=r.sid and r.bid=b.bid and (b.color='re' or
b.color='green')
Output
SNAME
horatio
d
u
s
t
i
n
l
u
b
b
e
r
b.color='red'
intersect
select s2.sname from sailors s2,reserves r2,boats b2
where s2.sid =r2.sid and r2.bid=b2.bid and b2.color='green'
Output
SNAME
dustin
h
o
r
a
t
i
o
l
u
b
b
e
r
9)Find the sids of sailors who have reserved red boats but not
green boats.
Query
Select s1.sname from sailors s1, reserves r1,
boats b1 where s1.sid=r1.sid and r1.bid=b1.bid
and b1.color='red'
and s1.sid not in (select s2.sid from
sailors s2,boats b2,reserves r2 where
s2.sid=r2.sid and
b2.color='green');
r2.bid=b2.bid
and
Output
SNAME
horatio
10) Find all sids of sailors who have a rating of 10 or reserved boat
104.
Query
Select
s.sid
from sailors s
where
s.rating=10
Union
Select r.sid from reserves r where r.bid=104;
Output
SID
22
3
1
5
8
7
1
11) Find the names of sailors who have reserved boat 103 (Using
nested queries).
Query
Select s.sname from sailors s where s.sid in
(select r.sid from reserves r where r.bid=103)
Output
SNAME
dustin
l
u
b
b
e
r
h
o
r
a
t
i
o
12) Find the names of sailors who have reserved a red boat (Using
nested queries).
Query
select s.sname from sailors s where s.sid in (select
r.sid from reserves r where r.bid in(select b.bid
from boats b where b.color='red'));
Output
SNAME
dustin
l
u
b
b
e
r
h
o
r
a
t
i
o
13. Find the names of sailors who have not reserved a red boat
(Using nested queries).
Query
r
t
bob
Output
SNAME
dustin
l
u
b
b
e
r
h
o
r
a
t
i
o
3
2
5
8
7
1
7
4
17. Find the sailors with the highest rating (Using ALL Operator).
Query
Select s1.sid from sailors s1 where s1.rating >=
all (select s2.rating from sailors s2);
Output
SID
58
71
Output
AVG(S.AGE)
36.9
Output
AVG(S.AGE)
25.5
AGE
bob
63.5
25.Find the age of the youngest sailor for each rating level (Using
Group By).
Query
Select s.rating, min (s.age) from sailors s group by s.rating;
Output
RATING
MIN(S.AGE)
33
25.5
35
25.5
10
16
35