DBMS Lab Manual R20
DBMS Lab Manual R20
6 Querying 37
ANY,ALL,IN,NOT,EXISTS,UNIOUN,INTERSECT
Querying(continued..) 39
7
Quaries using aggregate functions(COUNT,SUM,AVG, and
MAX and MIN),GROUP BY HAVING
41
8
Creating Tabels
9 Querying 42
Quaries related to students,class,enrolled,faculty.
10 procedures 45
Requirement Analysis of Roadway Travels
Roadway travels is n business since 1997 with several buses connecting different places in
India its main office is located in Hyderabad.
Reservation
Ticketing
Cancellations
AIM:
Analyze the problem carefully and come up with entities in it. Identify what data has to be
persisted in the database. This contains the entities, attributes etc.
PROCEDURE:
I analyzed the ROADWAY travels .in this I have taken the three entities
1) BUS
2) TICKET
3) PASSENGER
BUS
Source :varchar
Destination :varchar
Pname :varchar
:varchar
Address :varchar
Seatno :integer
TICKET
Ticketno :numeric
:numeric
Noseats :numeric
Status :varchar
Experiment- 1
E-R Model
Analyze the problem carefully and come up with entities in it. Identify what date has to be
persisted in the database. This contains the entities, attributes etc.
Identify the primary keys for all the entities. Identify the other keys like candidate keys, partial
keys, if any.
Definitions:
Entity: the object in the ER Model represents is an entity which is thing in the real world with an
Independent existence.
Eg:
ER-Model:
Describes data as entities, relationships and attributes .The ER-Model is important preliminary
for its role in database design. ER Model is usually shown pictorially using entity relationship
diagrams.
Attributes:
The properties that characterize an entity set are called its attributes. An attribute is referred to by
the terms data items, data element, data field item.
Ex: attributes for bus entity and ticket entity.
Candidate key:
It can be defined as minimal super key or irreducible super key. In other words an attribute or
combination of attributes that identifies the record uniquely but none of its proper subsets can
identify the record uniquely.
Busno,serviceno--------------->candidate key
Primary key:
A candidate key that is used by the database designer for unique identification of each row in a
table is known as primary key. A primary key consists of one or more attributes of the table.
Partial key:
A weak entity type normally has a partial key which is the set of attributes that can uniquely
identify weak entity that are related to the same owner entity.
Bus entity:
Attributes for the bus entity are
Bus schema:
Busno serviceno source destination deptime retime bustype noofseats
Ticket entity:
Attributes for the ticket entity are
Ticket schema:
Ticketno Joudate Joutime Source Destination Seatno Amount Catcard
Passenger entity:
Attributes for the Passenger entity are
Definitions:
The cardinality ratio: - for a binary relationship specifies the maximum number of relationships
that an entity can participate in.
Weak and strong entity: - an entity set may not have sufficient attributes to form a primary key.
Such an entity set is termed a weak entity set. An entity set that has primary key is termed a
strong entity set.
Total participation:-
Ex: - if a travel agency states that every passenger must make reservation then every passenger
Travels in bus. Than a passenger’s entity can exist only if it participates in at least one
travels relationship instances. Thus the participation of passenger in travel is called total
participation meaning that every entity in the “total set” passenger entities must be related to
bus via travels relationship.
Aggregation: allows us to indicate that a relationship set participates in another relationship set.
Specialization: in the process of identifying subsets of an entity set (the super set) that share
some distinguishing characteristics. This entity type is called the super class of the specialization.
Generalization:
Aggregation:
Specialization:
E-R
Experiment-3
Relational Model
Represent all entities (strong, week) in tabular fashion. Represent relationships in a tabular
Fashion. There are different ways of representing as tables based on the cardinality. Represent
attributes as columns in the tables or as tables based on the requirement. Different types of
attributes (composite, multivalued and derived).
Definitions:
Composite attributes: can be divided into smaller sub parts which represent more basic
Attributes with independent meaning.
Multivalued attributes: for ex the attribute in the Bus entity Bus type can have different types of
buses according that the Bus type attribute contains the values as Garuda, Luxury, Express, and
Ordinary. This type of attribute is called multivalued attribute and may have lower and upper
bounds to constrain the number of values allowed for each individual entity.
Derived attributes:
In some cases, two or more attribute values are related. With the help of one attribute we get the
value of another attribute. Age and DOB attributes. With the DOB we get the age of the person to
the current date.
Rserves(pnrno:numeric,joudate:date,noofseats:int(4),address:varchar(50),contact_no:numeric(10)
,status:char(3))
Cancels(pnrno:numeric,joudate:date,noofseats:int(4),address:varchar(50),contact_no:numeric(10
),status:char(3))
TABLES:
Reserves:
Cancels:
Ticket:
Ticketno Joudate Joutime Source Destination Seatno Amount Catcard
Passenger:
Normalization
1. First Normal Form: 1NF requires that the values in each column of a table are atomic.
By atomic we mean that there are no sets of values within a column.
2. Second Normal Form: where the 1NF deals with atomicity of data, the 2NF deals with
relationships between composite key columns and non-key columns. To achieve 2NF the
tables should be in 1NF. The 2NF any non-key columns must depend on the entire
primary key. In case of a composite primary key, this means that non-key column can’t
depend on only part of the composite key.
3. Third Normal Form: 3NF requires that all columns depend directly on the primary key.
Tables violate the third normal form when one column depends an another column, which
in turn depends on the primary key(transitive dependency). One way to identify transitive
dependency is to look at your tables and see if any columns would require updating if
another column in the table was updated. If such a column exists, it probably violates
3NF.
Bus:
In this relation the values in each column are atomic so it is already in 1NF.
In the Bus entity Busno+serviceno is the primary key.
There exists following partial dependencies.
Busno ----> Bustype,Noofseats
Serviceno---->Source,Dest
The above relation is 2NF. And all columns directly depend on primary key. So there is no
transitive dependency and the relation is 3NF.
Normalization of Ticket entity:
In this relation the values in each column are atomic so it is already in 1NF.
In the above relation there are no partial functional dependencies so the relation is in 2NF.
The ticket entity might face the following transitive dependency
Ticketno-------> catcard
Catcard--------->amount
So the relation is in 3NF.
Put the catcard and amount attributes in a separate table. Then the relation should be in 3NF.
Catcard Amount
No 96
Yes 88
Yes 88
No 96
Yes 172
Finally all the tables are normalized and free from data redundancy, partial functional
dependencies and transitive dependencies.
Experimen-5
This article provides step-by-step installation guide for MySQL 5.1 (or higher) on Windows as a
development machine. Other releases of MySQL should have similar installation process.
You can download version 5.1 from this page Download MySQL 5.1
Double click the MSI installer to start installing MySQL. You will go through a setup wizard so it's
fairly simple. Just follow the installation instructions step by step.
(1) Welcome to the Setup Wizard for MySQL Server 5.1. Click Next to continue.
After review the settings, click Install. If you want to change any settings, click [Back] button.
(4) Installation in progress.
This step is just an informational step for MySQL Enterprise Subscription. Click the [More...]
button if you want to know more. Otherwise, click [Next] to go to next step.
Make sure you have selected 'Configure the MySQL Server now' checkbox if you want to
configure it after clicking Finish button.
What's next
MySQL 5.1 provides an easy-to-use wizard to configure MySQL server instance. Next, we are
going to go through detailed steps about MySQL server configuration. See How to configure
MySQL server 5.1 on Windows.
After installing MySQL 5.1 on Windows, we will need to configure it. This article provides step-
by-step MySQL server 5.1 configuration guide on Windows as a development box.
If you want to install multiple versions of MySQL on the same box, read this article How to install
two different versions of MySQL on the same computer for more info.
If you have selected the checkbox 'Configure the MySQL Server now' in the last step
when installing MySQL 5.1, the configuration wizard should start automatically when you click
the Finish button.
Alternatively, you can launch the wizard from Start menu. Start -> Programs -> MySQL ->
MySQL Server 5.1 -> MySQL Server Instance Config Wizard.
2. Select configuration type.
Select Detailed Configuration here. If this is the only MySQL server installed on your computer,
you can select Standard Configuration.
As this MySQL server is running on a development box, select Developer Machine as the server
type.
4. Select the database usage.
Depends on the purpose of your development box, you can select either Multifunctional Database
or Transactional Database Only.
InnoDB table type is the storage engine for a transactional database. Use the default settings here.
6. Set the database engine's concurrent connections option.
Here we selected Online Transaction Processing (OLTP) as it is the most common use of MySQL
server.
If the MySQL server on your development machine is used for decision support such as data
warehousing or data mining, select the first option.
By default, make your selection the same as screenshot below. If port 3306 has been used by
another instance of MySQL server, you can select port 3307 or a different port. This will allow two
instances of MySQL server to be accessed via different ports on the same box.
8. Select the default character set.
By default, the Standard Character Set is selected, but you may want to select the second option -
Best Support For Multilingualism. This allows our database to store text in many different
languages.
9. Install MySQL server as a Windows service.Below is the recommended way to run MySQL
server on Windows. Making the service name as MySQL51 clearly identifies the service as a
MySQL server version 5.1 database engine because you might install other versions of MySQL
server on the same machine.
You might also want to check Include Bin Directory in Windows PATH if you want to operate
MySQL from command line.
10. Set the root password.
Set a new password to the root account. Enter the same password to all three boxes. See below.
Don't select the Create An Anonymous Account checkbox. This can lead to an insecure system.
The configuration file has been created successfully. Click [Finish] to close the wizard.
Happy Configuring!
Creation of databases:
mysql> show databases;
+--------------------+
| Database |
+--------------------+
| information_schema |
| mysql |
| test |
+--------------------+
3 rows in set (0.09 sec)
mysql> create database groupa;
Query OK, 1 row affected (0.01 sec)
mysql> use groupa;
Database changed
Creation of tables:
mysql> create table groupamem(rollno numeric(10),name varchar(15),phone numeric(
10),branch varchar(10));
Query OK, 0 rows affected (0.42 sec)
Bus
mysql> create table bus555(busno varchar(10),bustype varchar(10),primary key(bus
no));
Query OK, 0 rows affected (0.17 sec)
Ticket
mysql> create table ticket555(tic_no numeric(10),joudate date,source varchar(10)
,dest varchar(10),deptime time,reatime time,busnumber varchar(10),primary key(ti
c_no));
Query OK, 0 rows affected (0.08 sec)
mysql> alter table ticket555 add constraint tic_fk foreign key(busnumber) refere
nces bus555(busno);
Query OK, 0 rows affected (0.16 sec)
Records: 0 Duplicates: 0 Warnings: 0
);
Passenger
mysql> alter table passenger add constraint pas_fk foreign key(ticnumber) refere
nces ticket555(tic_no);
Reserve
mysql> alter table reserve add constraint res_fk foreign key(pnrnumber) referenc
es passenger(pnrno);
Query OK, 0 rows affected (0.17 sec)
Records: 0 Duplicates: 0 Warnings: 0
Cancel
mysql> alter table cancel add constraint can_fk foreign key(pnrnumber) reference
s passenger(pnrno);
Query OK, 0 rows affected (0.14 sec)
Records: 0 Duplicates: 0 Warnings: 0
Practicing DML commands:
DML commands are used to for managing data within the schema objects.
Querying: In this week you are going to practice the queries (along with
sub queries) using
ANY, ALL, IN, EXISTS, NOT EXISTS, UNION, INTERSECT, Constraints
etc.
Practice the following queries:
mysql> select tic_no from ticket555 where tic_no=any (select ticnumber from passenger where
pname like 'r%h');
+--------+
| tic_no |
+--------+
| 1111 |
| 2222 |
+--------+
2 rows in set (0.02 sec)
mysql> select pname from passenger where age between 30 and 45;
+-------+
| pname |
+-------+
| subbu |
| nirma |
+-------+
2 rows in set (0.00 sec)
mysql> select all pname from passenger where pname like 'a%';
+---------+
| pname |
+---------+
| subbu |
| achaith |
+---------+
2 rows in set (0.00 sec)
You are going to practice the queries using Aggregate functions (COUNT, SUM, AVG,
MAX and MIN), GROUP BY, HAVING AND Creation of Views.
1. Write a query to display the information present in the Passenger and Cancellation
tables.
mysql> select pnrno from passenger union select pnrnumber from cancel;
+-------+
| pnrno |
+-------+
| 1001 |
| 1002 |
| 1003 |
| 1004 |
| 1005 |
+-------+
5 rows in set (0.00 sec)
mysql> select count(joudate) from ticket555 where busnumber in(select busno from
bus555 where busno='9w01') and joudate between '2010-08-14' and '2010-08-20';
+----------------+
| count(joudate) |
+----------------+
| 2|
+----------------+
1 row in set (0.00 sec)
3. Find the ticket numbers booked for each PNR_no using Group By clause.
5. Find the number of tickets booked by passenger where the number of seats is greater
than1
Mysql>select pnrnumber,sum(noofseats) from reservation group by pnrnumber having
sum(nooseats) > 1
| ap891 | nonac | 8|
| ap8830 | metro | 5|
+--------+---------+--------------+
5 rows in set (0.00 sec)
6.find the total number of cancelled seats
Mysql>select sum(noofseats) as cancelled-seats from cancel where status=’yes’;
Cancled-seats
18
Creation of views:
7.Create a view to display the details of passenger who cancelled their tickets
Create view cancel1 as
Select pname,pnrno
From passenger,cancel
Where pnrno=pnrnumber and status=’yes’;
Experiment -8
create a table for the following schema.
Student(snum:integer,sname:string,major:string,level:string,age:integer)
class(name:string,meets at:time,room:string,fid:integer) enrolled(snum:integer,cname:string)
faculty(fid:integer,fname:string,deptid:integer)
1.find the names of all juniors(level=JR) who are enrolled in aclass taught by I.teacher
2.find the age of all the oldest student who is either a history major or is enrolled in a course
taught by I.teacher.
. SELECT MAX(S.age)
FROM Student S
WHERE (S.major = ‘History’)
OR S.num IN (SELECT E.snum
FROM Class C, Enrolled E, Faculty F
WHERE E.cname = C.name AND C.fid = F.fid
AND F.fname = ‘I.Teach’ );
3.find the names of all classes that either meet in room R128 or more students enrolled
SELECT C.name
FROM Class C
WHERE C.room = ‘R128’
OR C.name IN (SELECT E.cname
FROM Enrolled E
GROUP BY E.cname
HAVING COUNT (*) >= 5);
4.Find the names of all the students who are enrolled in two classes that meet at the same time
5.find the names of all the faculty members who teach in evry room in whioch some class is
taught
SELECT DISTINCT F.fname
FROM Faculty F
WHERE NOT EXISTS (( SELECT *
42 Chapter 5
FROM Class C )
EXCEPT
(SELECTC1.room
FROM Class C1
WHERE C1.fid = F.fid ));
6.find the names of faculty members for whom the combined enrollement of courses that they
teach in less than 5.
SELECT DISTINCT F.fname
FROM Faculty F
WHERE 5 > (SELECT E.snum
FROM Class C, Enrolled E
WHERE C.name = E.cname
AND C.fid = F.fid);
7.print the level and average age of students for the level,for each level.
SELECT S.level, AVG(S.age)
FROM Student S
GROUP BY S.level;
8. print the level and average age of students for the level,for all level except JR.9
SELECT S.level, AVG(S.age)
FROM Student S
WHERE S.level <> ‘JR’
GROUP BY S.level;
9. print the level and average age of students for that level, whose average age is greater that 20
SELECT S.level,AVG(S.age)
FROM Student S
WHERE AVG(S.age)>20;
10. find the names of all the students who are enrolled in the maximum no. of classes
11. find the names of all the students who are not enrolled in the class.
SELECT DISTINCT S.sname
FROM Student S
WHERE S.snum NOT IN (SELECT E.snum
FROM Enrolled E );
13.display all the students whose names starts with the letter”p”
SELECT * FROM Student
WHERE sname like 'p%';
14. display all the teachers whose names starts with the letter”a” or “I” in their names.
Procedures
In this session you are going to learn Creation of stored procedures, execution of procedure
and modification of procedures. Practice the procedures using above database.
A stored procedure is a procedure (like a subprogram in a regular computing language) that is
Stored (in the database). Correctly speaking, MySQL supports "routines" and there are two kinds
of routines: stored procedures which you call, or functions whose return values you use in other
SQL statements the same way that you use pre-installed MySQL functions like pi(). I'll use the
word "stored procedures" more frequently than “routines" because it's what we've used in the
past, and what people expect us to use.
mysql> create procedure p2(p_age int)
-> begin
-> select pname,ticnumber,sex from passenger where age>p_age;
-> end//
Query OK, 0 rows affected (0.00 sec)
| padma | 3333 | f |
| nirma | 5555 | f |
+-------+-----------+------+
3 rows in set (0.00 sec)
Query OK, 0 rows affected (0.00 sec)