DBMS Lab Manual 2020-21 PDF
DBMS Lab Manual 2020-21 PDF
[Updated as on 15/08/20]
SEMESTER :V
Table of contents
SL TITLE PAGE
No. NO.
I Introduction to SQL 3
Consider the schema for College Database: STUDENT (USN, SName, Address, Phone,
Gender) SEMSEC (SSID, Sem, Sec) CLASS(USN, SSID) SUBJECT(Subcode, Title,
Sem, Credits) IAMARKS(USN, Subcode, SSID, Test1, Test2, Test3, FinalIA) Write
SQL queries to 1. List all the student details studying in fourth semester ‘C’ section. 2.
Compute the total number of male and female students in each semester and in each
D
section. 3. Create a view of Test1 marks of student USN ‘1BI15CS101’ in all subjects. 32
4. Calculate the FinalIA (average of best two test marks) and update the corresponding
table for all students. 5. Categorize students based on the following criterion: If FinalIA
= 17 to 20 then CAT = ‘Outstanding’ If FinalIA = 12 to 16 then CAT = ‘Average’ If
FinalIA< 12 then CAT = ‘Weak’ Give these details only for 8th semester A, B, and C
section students.
Consider the schema for Company Database: EMPLOYEE (SSN, Name, Address, Sex,
Salary, SuperSSN, DNo) DEPARTMENT (DNo, DName, MgrSSN, MgrStartDate)
DLOCATION (DNo,DLoc) PROJECT(PNo, PName, PLocation, DNo)
WORKS_ON(SSN, PNo, Hours) Write SQL queries to 1. Make a list of all project
numbers for projects that involve an employee whose last name is ‘Scott’, either as a
worker or as a manager of the department that controls the project. 2. Show the resulting
E
salaries if every employee working on the ‘IoT’ project is given a 10 percent raise. 3. 43
Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as
the maximum salary, the minimum salary, and the average salary in this department 4.
Retrieve the name of each employee who works on all the projects controlled by
department number 5 (use NOT EXISTS operator). 5. For each department that has
more than five employees, retrieve the department number and the number of its
employees who are making more than Rs. 6, 00,000.
VI Case Studies 62
VIII References 80
I. Introduction to SQL
CREATE SCHEMA
Specifies a new database schema by giving it a name
CREATE TABLE
● Specifies a new base relation by giving it a name, and specifying each of its attributes and
their data types
Syntax of CREATE Command:
CREATE TABLE <table name>( <Attribute A1><Data Type D1> [<Constarints>],
<Attribute A2><Data Type D2> [<Constarints>],
…….
<Attribute An><Data Type Dn> [<Constarints>],
DROP TABLE
● Used to remove a relation (base table) and its definition.
● The relation can no longer be used in queries, updates, or any other commands since its
description no longer exists
ALTER TABLE:
● Used to add an attribute to/from one of the base relations drop constraint -- The new
attribute will have NULLs in all the tuples of the relation right after the command is
executed; hence, the NOT NULL constraint is not allowed for such an attribute.
Example: ALTER TABLE EMPLOYEE ADD JOB VARCHAR2(12);
● The database users must still enter a value for the new attribute JOB for each
EMPLOYEE tuple. This can be done using the UPDATE command.
● Hence, an SQL relation (table) is a multi-set (sometimes called a bag) of tuples; it is not a
set of tuples
● SQL relations can be constrained to be sets by using the CREATE UNIQUE INDEX
command, or by using the DISTINCT option
● Basic form of the SQL SELECT statement is called a mapping of a SELECT-FROM-
WHERE block
SELECT <attribute list> FROM <table list> WHERE <condition>
● <attribute list> is a list of attribute names whose values are to be retrieved by the query
● <table list > is a list of the relation names required to process the query
● <condition> is a conditional (Boolean) expression that identifies the tuples to be retrieved
by the query
UNSPECIFIED WHERE-clause
A missing WHERE-clause indicates no condition; hence, all tuples of the relations in the
FROM-clause are selected. This is equivalent to the condition WHERE TRUE
Example:
USE OF *
To retrieve all the attribute values of the selected tuples, a * is used, which stands for all the
attributes
USE OF DISTINCT
SQL does not treat a relation as a set; duplicate tuples can appear. To eliminate duplicate
tuples in a query result, the keyword DISTINCT is used
SET OPERATIONS
SQL has directly incorporated some set operations such as union operation (UNION), set
difference (MINUS) and intersection (INTERSECT) operations. The resulting relations of these
set operations are sets of tuples; duplicate tuples are eliminated from the result. The set
operations apply only to union compatible relations; the two relations must have the same
attributes and the attributes must appear in the same order
NESTING OF QUERIES
A complete SELECT query, called a nested query, can be specified within the WHERE-
clause of another query, called the outer query. Many of the previous queries can be specified in
an alternative form using nesting
EXPLICIT SETS
It is also possible to use an explicit (enumerated) set of values in the WHERE-clause rather than
a nested query
SQL allows queries that check if a value is NULL (missing or undefined or not applicable). SQL
uses IS or IS NOT to compare NULLs because it considers each NULL value distinct from other
NULL values, so equality comparison is not appropriate.
AGGREGATE FUNCTIONS
Include COUNT, SUM, MAX, MIN, and AVG
GROUPING
● In many cases, we want to apply the aggregate functions to subgroups of tuples in a
relation
● Each subgroup of tuples consists of the set of tuples that have the same value for the
grouping attribute(s)
● The function is applied to each subgroup independently
● SQL has a GROUP BY-clause for specifying the grouping attributes, which must also
appear in the SELECT-clause
THE HAVING-CLAUSE
Sometimes we want to retrieve the values of these functions for only those groups that satisfy
certain conditions. The HAVING-clause is used for specifying a selection condition on groups
(rather than on individual tuples)
SUBSTRING COMPARISON
The LIKE comparison operator is used to compare partial strings. Two reserved
characters are used: '%' (or '*' in some implementations) replaces an arbitrary number of
characters, and '_' replaces a single arbitrary character.
ARITHMETIC OPERATIONS
The standard arithmetic operators '+', '-'. '*', and '/' (for addition, subtraction, multiplication, and
division, respectively) can be applied to numeric values in an SQL query result
ORDER BY
The ORDER BYclause is used to sort the tuples in a query result based on the values of some
attribute(s)
The default order is in ascending order of values. We can specify the keyword DESCif
we want a descending order; the keyword ASCcan be used to explicitly specify ascending order,
even though it is the default
There are three SQL commands to modify the database: INSERT, DELETE, and UPDATE.
INSERT
DELETE
● Removes tuples from a relation. Includes a WHERE-clause to select the tuples to be
deleted
● Referential integrity should be enforced
● Tuples are deleted from only one table at a time (unless CASCADE is specified on a
referential integrity constraint)
● A missing WHERE-clause specifies that all tuples in the relation are to be deleted; the
table then becomes an empty table
● The number of tuples deleted depends on the number of tuples in the relation that satisfy
the WHERE-clause
UPDATE
● Used to modify attribute values of one or more selected tuples
● A WHERE-clause selects the tuples to be modified
● An additional SET-clause specifies the attributes to be modified and their new values
● Each command modifies tuples in the same relation
● Referential integrity should be enforced
SQL TRIGGERS
● Objective: to monitor a database and take initiate action when a condition occurs
● Triggers are nothing but the procedures/functions that involve actions and fired/executed
automatically whenever an event occurs such as an insert, delete, or update operation or
pressing a button or when mouse button is clicked
VIEWS IN SQL
● A view is a single virtual table that is derived from other tables. The other tables could be
base tables or previously defined view.
● Allows for limited update operations Since the table may not physically be stored
● Allows full query operations
● A convenience for expressing certain operations
● A view does not necessarily exist in physical form, which limits the possible update
operations that can be applied to views.
Solution:
Entity-Relationship Diagram
Schema Diagram
Book
Book_Authors
Book_i Author_nam
d e
Publisher
Book_Copies
Book_Lending
Library_Branch
Table Creation
ADDRESS VARCHAR(20));
Table Descriptions
DESC PUBLISHER;
DESC BOOK;
DESC BOOK_AUTHORS;
DESC LIBRARY_BRANCH;
DESC BOOK_COPIES;
DESC CARD;
DESC BOOK_LENDING;
Queries:
1. Retrieve details of all books in the library – id, title, name of publisher, authors,
number of copies in each branch, etc.
2. Get the particulars of borrowers who have borrowed more than 3 books, but from
Jan 2017 to Jun 2017.
SELECT CARD_NO
FROM BOOK_LENDING
WHERE DATE_OUT BETWEEN ’01-JAN-2017’ AND ’01-JUL-2017’
GROUP BY CARD_NO
HAVING COUNT (*)>3;
3. Delete a book in BOOK table. Update the contents of other tables to reflect this data
manipulation operation.
4. Partition the BOOK table based on year of publication. Demonstrate its working with a
simple query.
5. Create a view of all books and its number of copies that are currently available in the
Library.
Solution: Diagram bundle so there are three entities 3 tables seems small customer
salesman has salesman ID salesmen ID as primary key name city and Commission mean
city Commission salesman ID
Entity-Relationship Diagram
Schema Diagram
Salesman
Customer
Orders
Ord_N Purchase_Am Ord Date Customer_i Salesman_i
o t d d
Table Creation
ORD_DATE DATE,
PRIMARY KEY (ORD_NO),
CUSTOMER_ID INT,
SALESMAN_ID INT,
FOREIGN KEY(CUSTOMER_ID) REFERENCES CUSTOMER1 (CUSTOMER_ID) ON
DELETE CASCADE,
FOREIGN KEY(SALESMAN_ID) REFERENCES SALESMAN (SALESMAN_ID) ON
DELETE CASCADE);
Table Descriptions
DESC SALESMAN;
DESC CUSTOMER1;
DESC ORDERS;
Queries:
2. Find the name and numbers of all salesmen who had more than one customer.
3. List all salesmen and indicate those who have and don’t have customers in their
cities (Use UNION operation.)
4. Create a view that finds the salesman who has the customer with the highest order
of a day.
5. Demonstrate the DELETE operation by removing salesman with id 1000. All his orders
must also be deleted.
Use ON DELETE CASCADE at the end of foreign key definitions while creating child table
orders and then execute the following:
Use ON DELETE SET NULL at the end of foreign key definitions while creating child table
customers and then executes the following:
Schema Diagram
Actor
Act_id Act_Name Act_Gender
Director
Dir_i Dir_Nam Dir_Phon
d e e
Movies
Mov_i Mov_Titl Mov_Yea Mov_Lan Dir_i
d e r g d
Movie_Cast
Rating
Mov_i Rev_Star
d s
Table Creation
Table Descriptions
DESC ACTOR;
DESC DIRECTOR;
DESC MOVIES;
DESC MOVIE_CAST;
DESC RATING;
Queries:
1. List the titles of all movies directed by ‘Hitchcock’.
SELECT MOV_TITLE
FROM MOVIES
WHERE DIR_ID IN (SELECT DIR_ID
FROM DIRECTOR
WHERE DIR_NAME = ‘HITCHCOCK’);
2. Find the movie names where one or more actors acted in two or more movies.
SELECT MOV_TITLE
FROM MOVIES M, MOVIE_CAST MV
WHERE M.MOV_ID=MV.MOV_ID AND ACT_ID IN (SELECT ACT_ID
FROM MOVIE_CAST GROUP BY ACT_ID
HAVING COUNT (ACT_ID)>1)
GROUP BY MOV_TITLE
HAVING COUNT (*)>1;
3. List all actors who acted in a movie before 2000 and also in a movie after 2015 (use
JOIN operation).
OR
4. Find the title of movies and number of stars for each movie that has at least one
rating and find the highest number of stars that movie received. Sort the result by
movie title.
Schema Diagram
Table Creation
Table Descriptions
DESC STUDENT;
DESC SEMSEC;
DESC CLASS;
DESC SUBJECT;
DESC IAMARKS;
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1OX13IS091','10CS81','ISE8C', 15, 16, 18);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1OX13IS091','10CS82','ISE8C', 12, 19, 14);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1OX13IS091','10CS83','ISE8C', 19, 15, 20);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1OX13IS091','10CS84','ISE8C', 20, 16, 19);
INSERT INTO IAMARKS (USN, SUBCODE, SSID, TEST1, TEST2, TEST3) VALUES
('1OX13IS091','10CS85','ISE8C', 15, 15, 12);
Queries:
1. List all the student details studying in fourth semester ‘C’ section.
SELECT S.*, SS.SEM, SS.SEC
FROM STUDENT S, SEMSEC SS, CLASS C
WHERE S.USN = C.USN AND
SS.SSID = C.SSID AND
SS.SEM = 4 AND SS.SEc=’C’;
2. Compute the total number of male and female students in each semester and in each
section.
4. Calculate the FinalIA (average of best two test marks) and update the
corresponding table for all students.
UPDATE IAMARKS SET
SELECT S.USN,S.SNAME,S.ADDRESS,S.PHONE,S.GENDER,
(CASE
WHEN IA.FINALIA BETWEEN 17 AND 20 THEN 'OUTSTANDING'
WHEN IA.FINALIA BETWEEN 12 AND 16 THEN 'AVERAGE'
ELSE 'WEAK'
END) AS CAT
FROM STUDENT S, SEMSEC SS, IAMARKS IA, SUBJECT SUB
WHERE S.USN = IA.USN AND
SS. SSID = IA.SSID AND
SUB.SUBCODE = IA.SUBCODE AND
SUB.SEM = 8;
2.
3. Show the resulting salaries if every employee working on the ‘IoT’ project is given a
10 percent raise.
4. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well
as the maximum salary, the minimum salary, and the average salary in this
department
5. Retrieve the name of each employee who works on all the projects controlled by
department number 5 (use NOT EXISTS operator). For each department that has
more than five employees, retrieve the department number and the number of its
employees who are making more than Rs. 6,00,000.
Entity-Relationship Diagram
Schema Diagram
Employee
Department
DLocation
DNO DLOC
Project
PN PNam PLocatio DN
O e n O
Works_on
SS PN Hour
N O s
Table Creation
Table Descriptions
DESC EMPLOYEE;
DESC DEPARTMENT;
DESC DLOCATION;
DESC PROJECT;
DESC WORKS_ON;
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXECE01’,’JOHN’,’SCOTT’,’BANGALORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXISE01’,’JAMES’,’SMITH’,’BANGALORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXISE02’,’HEARN’,’BAKER’,’BANGALORE’,’M’, 700000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXISE03’,’EDWARD’,’SCOTT’,’MYSORE’,’M’, 500000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXISE04’,’PAVAN’,’HEGDE’,’MANGALORE’,’M’, 650000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXISE05’,’GIRISH’,’MALYA’,’MYSORE’,’M’, 450000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXISE06’,’NEHA’,’SN’,’BANGALORE’,’F’, 800000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXACC01’,’AHANA’,’K’,’MANGALORE’,’F’, 350000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXACC02’,’SANTHOSH’,’KUMAR’,’MANGALORE’,’M’, 300000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXISE01’,’VEENA’,’M’,’MYSORE’,’M’, 600000);
INSERT INTO EMPLOYEE (SSN, FNAME, LNAME, ADDRESS, SEX, SALARY) VALUES
(‘OXIT01’,’NAGESH’,’HR’,’BANGALORE’,’M’, 500000);
Note: update entries of employee table to fill missing fields SUPERSSN and DNO
DNO=’2’, SUPERSSN
=NULL
WHERE SSN=’OXIT01’;
Queries:
1. Make a list of all project numbers for projects that involve an employee whose last
name is ‘Scott’, either as a worker or as a manager of the department that controls the
project.
2. Show the resulting salaries if every employee working on the ‘IoT’ project is given a 10
percent raise.
3. Find the sum of the salaries of all employees of the ‘Accounts’ department, as well as
the maximum salary, the minimum salary, and the average salary in this department
4. Retrieve the name of each employee who works on all the projects Controlled by
department number 5 (use NOT EXISTS operator).
5. For each department that has more than five employees, retrieve the department
number and the number of its employees who are making more than Rs. 6, 00,000.
5 steps to connect any java application with the database in java using JDBC. They are as
follows:
o Register the driver class
o Creating connection
o Creating statement
o Executing queries
o Closing connection
1. Start Visual Studio and open the Server Explorer window by clicking Viewand
then Server Explorer from the main menu.
2. Right-click the Data Connections node and click Add Connection.
3. From the Add Connection dialog, click change and select the MySQL Database as a
data source.
4. From the Change Data Source dialog, select MySQL Database from the list of data
sources (or the <other> option, if MySQL Database is absent), and leave .NET Framework
Data Provider for MySQL as the data provider.
{
conn.ConnectionString =
"Server=[server_name];Database=[database_name];Trusted_Connection=true";
// using the code here...
}
<?php
$servername = "localhost";
$username = "username";
$password = "password";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";
?>
#!/usr/bin/python
importMySQLdb
Exercise 1: To understand some simple Database Applications and build Conceptual Data
Model.
a) Select an enterprise that you are familiar with (for example,a school, a college, a
company, a small business, a club or association).List all the information that this
enterprise uses.
b) Describe the steps involved in the database design process using E-R Modeling:
Requirements Analysis, Identify Entity Sets, Identify Relationship Sets, Value Sets and
Attributes, Specifying Primary keys, Building E-R diagram, Implementation
c) For the following mini-world example database applications, Design and Develop
Conceptual Data Model (E-R Diagram) with all the necessary entities, attributes,
constraints and relationships.
i. Medical Clinic Database –The clinic has a number of regular patients and new
patients come to the clinic regularly. Patients make appointments to see one of the
doctors; several doctors attend the clinic and they each have their own hours. Some
doctors are General Practitioners (GPs) while others are specialists(cardiologists,
dermatologists etc.,). Patients have families and the family relationships are
important. A medical record of each patient needs to be maintained. Information on
prescriptions, insurance, allergies,etc needs tobe maintained. Different doctors may
charge different fees. Billing has to be done for Patients.
iv. Time Table Preparation - An Engineering College has a number of Branches. Each
Branch has number sections, a number of courses and a number of faculty members
teaching the courses. Each branch has a number of class rooms and laboratories. Each
course may be scheduled in a class room at a particular time.
Exercise 2: Design andbuild Relational Data Model for each of the application scenarios of
exercise 1 specifying all possible constraints. Extend the same for a database application of
students' choice.
Exercise 3 To understand and demonstrate DDL, DML and DCL Commands of SQL
a. Create a table called EMP with the following structure and describe it.
Name Type
-----------------------------------------------------
EMPNO NUMBER(6)
ENAME VARCHAR2(20)
DOB DATE
JOB VARCHAR2(10)
DEPTNO NUMBER(2)
SAL NUMBER(7,2)
Allow NULL for all columns except ENAME and JOB. EMPNO is the Primary
Key
b. Add a column EXPERIENCE of type NUMERIC to the EMP table. Allow NULL to it.
c. Modify the column width of the JOB field of EMP table.
d. Create DEPT table with the following structure and describe it
Name Type
-----------------------------------------------------
DEPTNO NUMBER(2)
DNAME VARCHAR2(15)
LOCN VARCHAR2(10)
DEPTNO is the Primary Key and DNAME cannot be NULL
e. Add constraint to check the SAL value of EMP Table. SAL must be > 6000.
f. Drop a column EXPERIENCE from the EMP table.
g. Insert a single record into DEPT table. Repeat this for inserting at least 3 records
h. Insert more than a record into EMP table using a single insert command. Insert at least 10
records
i. Update the EMP table to set the salary of all employees to Rs. 30000/- for a given JOB
type
j. Create a pseudo table EMPLOYEE with the same structure as the table EMP using
SELECT clause.
k. Delete employees from EMP table for a given JOB type. Delete the first five records of
EMP table
l. Grant all/some privileges of EMP table to DEPT table
m. Revoke some/all privileges of EMP table from DEPT table
n. Truncate the EMP table and drop the DEPT table
o. Demonstrate the use of COMMIT, SAVEPOINT and ROLLBACK commands
FOR loop to insert ten rows into a database table. The values of a loop index, counter variable,
and either of two character strings are inserted. Which string is inserted depends on the value of
the loop index.
Input Table
Not applicable.
WRITE A PL/SQL PROGRAM TO GENERATE FIBONACCI SERIES
declare
a number;
b number;
c number;
n number;
i number;
begin
n:=&n;
a:=0;
b:=1;
dbms_output.put_line(a);
dbms_output.put_line(b);
for i in 1..n-2
loop
c:=a+b;
dbms_output.put_line(c);
a:=b;
b:=c;
end loop;
end;
OUTPUT:
SQL> @ FIBONACCI.sql
21 /
Enter value for n: 5
old 8: n:=&n;
new 8: n:=5;
0
1
1
2
3
3. TRIGGERS
BEFORE TRIGGER
create or replace trigger tday before insert or delete or update on emp
declare
we varchar2(10);
begin
we:=to_char(sysdate,'dy');
if we='sat' or we='sun' then
raise_application_error(-20015,'its a weekend');
end if;
end;
output:-
SQL> @trig1
/
Trigger created.
ERROR at line 1:
ORA-20015: its a weekend
ORA-06512: at "SCOTT.TDAY", line 6
ORA-04088: error during execution of trigger 'SCOTT.TDAY'
AFTER TRIGGER
create or replace trigger ttime after insert or delete or update on emp1 for each row
declare
tt varchar2(5);
begin
tt:=to_char(sysdate,'hh24');
if tt not between 10 and 17 then
raise_application_error(-20010,'not working hours');
end if;
end;
output:-
SQL> @trig2;
10 /
Trigger created.
*
ERROR at line 1:
ORA-20010: not working hours
ORA-06512: at "SCOTT.TTIME", line 6
ORA-04088: error during execution of trigger 'SCOTT.TTIME'
DECLARE
c_id customers.id%type := &cc_id;
c_name customerS.Name%type;
c_addr customers.address%type;
-- user defined exception
ex_invalid_id EXCEPTION;
BEGIN
IF c_id <= 0 THEN
RAISE ex_invalid_id;
ELSE
SELECT name, address INTO c_name, c_addr
FROM customers
WHERE id = c_id;
DBMS_OUTPUT.PUT_LINE ('Name: '|| c_name);
DBMS_OUTPUT.PUT_LINE ('Address: ' || c_addr);
END IF;
EXCEPTION
OUTPUT:
Enter value for cc_id: -6 (let's enter a value -6)
old 2: c_id customers.id%type := &cc_id;
new 2: c_id customers.id%type := -6;
ID must be greater than zero!
PL/SQL procedure successfully completed.
V. Case Studies
Description: In hospital, there are many departments like Orthopedic, Pathology, Emergency,
Dental, Gynecology, Anesthetics, I.C.U., Blood Bank, Operation Theater, Laboratory, M.R.I.,
Neurology, Cardiology, Cancer Department, Corpse, etc. There is an OPD where patients come
and get a card (that is, entry card of the patient) for check up from the concerned doctor. After
making entry in the card, they go to the concerned doctor’s room and the doctor checks up their
ailments. According to the ailments, the doctor either prescribes medicine or admits the patient in
the concerned department. The patient may choose either private or general room according to
his/her need. But before getting admission in the hospital, the patient has to fulfill certain
formalities of the hospital like room charges, etc. After the treatment is completed, the doctor
discharges the patient. Before discharging from the hospital, the patient again has to complete
certain formalities of the hospital like balance charges, test charges, operation charges (if any),
blood charges, doctors’ charges, etc. Next we talk about the doctors of the hospital. There are
two types of the doctors in the hospital, namely, regular doctors and call on doctors. Regular
doctors are those doctors who come to the hospital daily. Calls on doctors are those doctors who
are called by the hospital if the concerned doctor is not available.
Table Description: Following are the tables along with constraints used in Hospital
Management database.
1. DEPARTMENT: This table consists of details about the various departments in the hospital.
The information stored in this table includes department name, department location, and facilities
available in that department.
Constraint: Department name will be unique for each department.
2. ALL_DOCTORS: This table stores information about all the doctors working for the hospital
and the departments they are associated with. Each doctor is given an identity number starting
with DR or DC prefixes only.
Constraint: Identity number is unique for each doctor and the corresponding department should
exist in DEPARTMENT table.
3. DOC_REG: This table stores details of regular doctors working in the hospital. Doctors are
referred to by their doctor number. This table also stores personal details of doctors like name,
qualification, address, phone number, salary, date of joining, etc.
Constraint: Doctor’s number entered should contain DR only as a prefix and must exist in
ALL_DOCTORS table.
4. DOC_ON_CALL: This table stores details of doctors called by hospital when
additionaldoctors are required. Doctors are referred to by their doctor number. Other personal
details like name, qualification, fees per call, payment due, address, phone number, etc., are also
stored.
Constraint: Doctor’s number entered should contain DC only as a prefix and must exist in
ALL_DOCTORS table.
5. PAT_ENTRY: The record in this table is created when any patient arrives in the hospital for a
checkup. When patient arrives, a patient number is generated which acts as a primary key. Other
details like name, age, sex, address, city, phone number, entry date, and name of the doctor
referred to, diagnosis, and department name are also stored. After storing the necessary details
patient is sent to the doctor for checkup.
Constraint: Patient number should begin with prefix PT. Sex should be M or F only. Doctor’s
name and department referred must exist.
6. PAT_CHKUP: This table stores the details about the patients who get treatment from the
doctor referred to. Details like patient number from patient entry table, doctor number, date of
checkup, diagnosis, and treatment are stored. One more field status is used to indicate whether
patient is admitted, referred for operation or is a regular patient to the hospital. If patient is
admitted, further details are stored in PAT_ADMIT table. If patient is referred for operation, the
further details are stored in PAT_OPR table and if patient is a regular patient to the hospital, the
further details are stored in PAT_REG table.
Constraint: Patient number should exist in PAT_ENTRY table and it should be unique.
7. PAT_ADMIT: When patient is admitted, his/her related details are stored in this table.
Information stored includes patient number, advance payment, mode of payment, room number,
department, date of admission, initial condition, diagnosis, treatment, number of the doctor under
whom treatment is done, attendant name, etc.
Constraint: Patient number should exist in PAT_ENTRY table. Department, doctor number,
room number must be valid.
8. PAT_DIS: An entry is made in this table whenever a patient gets discharged from the hospital.
Each entry includes details like patient number, treatment given, treatment advice, payment
made, mode of payment, date of discharge, etc.
E‐R Diagram
Aim: The railway reservation system facilitates the passengers to enquire about the trains
available on the basis of source and destination, booking and cancellation of tickets, enquire
about the status of the booked ticket, etc.
The aim of case study is to design and develop a database maintaining the records of different
trains, train status, and passengers. The record of train includes its number, name, source,
destination, and days on which it is available, whereas record of train status includes dates for
which tickets can be booked, total number of seats available, and number of seats already
booked. The database has been developed and tested on the Oracle.
Description:
Passengers can book their tickets for the train in which seats are available. For this, passenger
has to provide the desired train number and the date for which ticket is to be booked. Before
booking a ticket for a passenger, the validity of train number and booking date is checked. Once
the train number and booking date are validated, it is checked whether the seat is available. If
yes, the ticket is booked with confirm status and corresponding ticket ID is generated which is
stored along with other details of the passenger. After all the available tickets are booked, certain
numbers of tickets are booked with waiting status. If waiting lot is also finished, then tickets are
not booked and a message of non‐availability of seats is displayed.
The ticket once booked can be cancelled at any time. For this, the passenger has to provide the
ticket ID (the unique key). The ticket ID is searched and the corresponding record is deleted.
With this, the first ticket with waiting status also gets confirmed.
List of Assumption
Since the reservation system is very large in reality, it is not feasible to develop the case study to
that extent and prepare documentation at that level. Therefore, a small sample case study has
been created to demonstrate the working of the reservation system. To implement this sample
case study, some assumptions have been made, which are as follows:
1. The number of trains has been restricted to 5.
2. The booking is open only for next seven days from the current date.
3. Only two categories of tickets can be booked, namely, AC and General.
4. The total number of tickets that can be booked in each category (AC and General) is 10.
5. The total number of tickets that can be given the status of waiting is 2.
6. The in‐between stoppage stations and their bookings are not considered.
1. What is SQL?
This data model is based on real world that consists of basic objects called entities and of
relationship among these objects. Entities are described in a database by a set of attributes.
14. What is Object Oriented model?
This model is based on collection of objects. An object contains values stored in instance
variables within the object. An object also contains bodies of code that operate on the object.
These bodies of code are called methods. Objects that contain same types of values and the same
methods are grouped together into classes.
15. What is an Entity?
It is an 'object' in the real world with an independent existence.
16. What is an Entity type?
It is a collection (set) of entities that have same attributes.
17. What is an Entity set?
It is a collection of all entities of particular entity type in the database.
18. What is an Extension of entity type?
The collections of entities of a particular entity type are grouped together into an entity
set.
19. What is an attribute?
It is a particular property, which describes the entity.
20. What is a Relation Schema and a Relation?
A relation Schema denoted by R(A1, A2, …, An) is made up of the relation name
R and the list of attributes Ai that it contains. A relation is defined as a set of tuples. Let r
be the relation which contains set tuples (t1, t2, t3, ...,tn). Each tuple is an ordered list of n-
values t=(v1,v2, ..., vn).
21. What is degree of a Relation?
It is the number of attribute of its relation schema.
22. What is Relationship?
It is an association among two or more entities.
23. What is Relationship set?
The collection (or set) of similar relationships.
24. What is Relationship type?
Relationship type defines a set of associations or a relationship set among a given set of
entity types.
25. What is degree of Relationship type?
It is the number of entity type participating.
SQL Questions:
1. Which is the subset of SQL commands used to manipulate Oracle Database structures,
including tables?
Data Definition Language (DDL)
2. What operator performs pattern matching?
LIKE operator
3. What operator tests column for the absence of data?
IS NULL operator
4. Which command executes the contents of a specified file?
START <filename> or @<filename>
5. What is the parameter substitution symbol used with INSERT INTO command?
&
6. Which command displays the SQL command in the SQL buffer, and then executes
it?
RUN
7. What are the wildcards used for pattern matching?
For single character substitution and % for multi-character substitution
8. State true or false. EXISTS, SOME, ANY are operators in SQL.
True
9. State true or false. !=, <>, ^= all denote the same operation.
True
10. What are the privileges that can be granted on a table by a user to others?
Insert, update, delete, select, references, index, execute, alter, all
11. What command is used to get back the privileges offered by the GRANT command?
REVOKE
12. Which system tables contain information on privileges granted and privileges
obtained?
USER_TAB_PRIVS_MADE, USER_TAB_PRIVS_RECD
13. Which system table contains information on constraints on all the tables created?
USER_CONSTRAINTS
14. TRUNCATE TABLE EMP;
DELETE FROM EMP;
Will the outputs of the above two commands differ?
Both will result in deleting all the rows in the table EMP.
15. What the difference is between TRUNCATE and DELETE commands?
TRUNCATE is a DDL command whereas DELETE is a DML command. Hence
DELETE operation can be rolled back, but TRUNCATE operation cannot be rolled back.
WHERE clause can be used with DELETE and not with TRUNCATE.
16. What command is used to create a table by copying the structure of another table?
Answer:
CREATE TABLE AS SELECT command
Explanation:
To copy only the structure, the WHERE clause of the SELECT command should contain
a FALSE statement as in the following.
CREATE TABLE NEWTABLE AS SELECT * FROM EXISTINGTABLE WHERE
1=2;
If the WHERE condition is true, then all the rows or rows satisfying the condition will be
copied to the new table.
17. What will be the output of the following query?
SELECT REPLACE (TRANSLATE(LTRIM(RTRIM('!! ATHEN !!','!'), '!'), 'AN',
'**'),'*','TROUBLE') FROM DUAL;
TROUBLETHETROUBLE
18. What will be the output of the following query?
SELECT DECODE(TRANSLATE('A','1234567890','1111111111'), '1','YES', 'NO' );
Answer : NO
Explanation :
23. What is the use of the DROP option in the ALTER TABLE command?
It is used to drop constraints specified on the table.
24. What is the value of ‘comm’ and ‘sal’ after executing the following query if the
initial value of ‘sal’ is 10000?
UPDATE EMP SET SAL = SAL + 1000, COMM = SAL*0.1;
sal = 11000, comm = 1000
25. What is the use of DESC in SQL?
DESC has two purposes. It is used to describe a schema as well as to retrieve rows from
table in descending order.The query SELECT * FROM EMP ORDER BY ENAME DESC will
display the output sorted on ENAME in descending order.
26. What is the use of CASCADE CONSTRAINTS?
When this clause is used with the DROP command, a parent table can be dropped even
when a child table exists.
SQL HANDSON
b. EMP:
COLUMN NAME DATATYPE(SIZE)
-----------------------------------------------------------------------------------------------
EMPNO NUMBER(4)
ENAME VARCHAR2(10)
JOB VARCHAR2(9)
MGR NUMBER(4)
HIREDATE DATE
SAL NUMBER(7,2)
COMM NUMBER(7,2)
DEPTNO NUMBER(2)
2. Check the Default Size of a Number, Char and Date Data types.
3. Describe the Structure of the Table and EMP Table.
4. Add two columns to the table EMP with the following information in one single
ALTER COMMAND.
COLUMN NAME DATATYPE(SIZE)
-----------------------------------------------------------------------------------------------
SEX CHAR(1)
PLACE CHAR(15)
5. Modify the column job present in the EMP table with the following information
given below:
b.EMP:
COLUMN NAME DATATYPE(SIZE)
-----------------------------------------------------------------------------------------------
VII. References
1. Database systems Models, Languages, Design and Application Programming, RamezElmasri
and Shamkant B. Navathe, 6th Edition, Pearson.
2. Database management systems, Ramakrishnan, and Gehrke, 3rd Edition, 2014,McGraw Hill
3. SilberschatzKorth and Sudharshan: Database System Concepts, 6th Edition, Mc-Graw Hill,
2013.