DBMS Lab Manual
DBMS Lab Manual
TECHNOLOGY
(Approved by AICTE and Affiliated to RTU, Kota)
LABORATORY MANUAL
(2019-2020)
DBMS LAB
1
SYLLABUS
Objectives: At the end of the semester, the students should have clearly understood and
implemented the following:
1. Stating a database design & application problem.
2. Preparing ER diagram
3. Finding the data fields to be used in the database.
4. Selecting fields for keys.
5. Normalizing the database including analysis of functional dependencies.
6. Installing and configuring the database server and the front end tools.
7. Designing database and writing applications for manipulation of data for a standalone
and shared data base including concepts like concurrency control, transaction roll back,
logging, report generation etc.
8. Get acquainted with SQL.
In order to achieve the above objectives, it is expected that each students will chose one
problem. The implementation shall being with the statement of the objectives to be
achieved, preparing ER diagram, designing of database, normalization and finally
manipulation of the database including generation of reports, views etc. The problem may
first be implemented for a standalone system to be used by a single user.
All the above steps may then be followed for development of a database application to be
used by multiple users in a client server environment with access control. The application
shall NOT use web techniques.
One exercise may be assigned on creation of table, manipulation of data and report
generation using SQL.
Indicative List of exercises:
1. Student information system for your college.
2. Student grievance registration and redressal system.
3. A video library management system for a shop.
4. Inventory management system for a hardware/ sanitary item shop.
5. Inventory management system for your college.
6. Guarantee management system for the equipments in your college.
2
SOFTWARE AND HARDWARE REQUIREMENTS
Hardware Requirements:
1. Processor: Pentium IV
2. RAM: 256 MB
3. Hard Disk: 40 GB
Software Requirements:
3
RATIONAL BEHIND DBMS LAB
Objectives
Upon successful completion of this Lab the student will be able to:
Performing database operations (create, update, modify, retrieve, etc.,) using front-
end tools.
4
INTRODUCTION TO DATABASE SYSTEMS
Database
A database is a collection of related data, typically describing the activities of one or
more related organizations.
For example, a university database might contain information about the following:
Entitiessuch as students, faculty and courses.
Relationshipsbetween entities, such as students' enrollment in courses, and faculty
teaching courses.
5
Databases are widely used. Some applications of database systems are given below:
1. Banking: For customer information, accounts, and loans, and banking
transactions.
2. Airlines: For reservations and schedule information.
3. Universities: For student information, course registrations, and grades.
4. Credit card transactions: For purchases on credit cards and generation of
monthly statements.
5. Telecommunication: For keeping records of calls made, generating monthly
bills, maintaining balances on prepaid calling cards, and storing information about
the communication networks.
6. Finance: For storing information about holdings, sales, and purchases of financial
instruments such as stocks and bonds.
7. Sales: For customer, product, and purchase information.
8. Manufacturing: For management of supply chain and for tracking production of
items in factories, inventories of items in warehouses/stores, and orders for items.
9. Human resources: For information about employees, salaries, payroll taxes and
benefits, and for generation of paychecks.
Advantages of DBMS
Using a DBMS to manage data has following advantages:
1. Data independence: Application programs should be as independent as possible
from details of data representation and storage. The DBMS can provide an
abstract view of the data to insulate application code from such details.
2. Efficient data access: A DBMS utilizes a variety of sophisticated techniques to
store and retrieve data efficiently. This feature is especially important if the data is
stored on external storage devices.
3. Data integrity and security: If data is always accessed through the DBMS, the
DBMS can enforce integrity constraints on the data. For example, before inserting
salary information for an employee, the DBMS can check that the department
budget is not exceeded. Also, the DBMS can enforce access controls that govern
what data is visible to different classes of users.
6
4. Data administration: When several users share the data, centralizing the
administration of data can offer significant improvements. Experienced
professionals, who understand the nature of the data being managed, and how
different groups of users use it, can be responsible for organizing the data
representation to minimize redundancy and for fine-tuning the storage of the data
to make retrieval efficient.
5. Concurrent access and crash recovery: A DBMS schedules concurrent accesses
to the data in such a manner that users can think of the data as being accessed by
only one user at a time. Further, the DBMS protects users from the effects of
system failures.
6. Reduced application development time: Clearly, the DBMS supports many
important functions that are common to many applications accessing data stored
in the DBMS. This, in conjunction with the high-level interface to the data,
facilitates quick development of applications. Such applications are also likely to
be more robust than applications developed from scratch because many important
tasks are handled by the DBMS instead of being implemented by the application.
7
tools that DBMS vendors provide. (Such tools include report writers,
spreadsheets, etc.)
Database administrator (DBA): The DBA is responsible for authorizing access to the
database, for coordinating and monitoring its use, and for acquiring software and
hardware resources as needed. The DBA is accountable for problems such as breach of
security or poor system response time.
8
ENTITY-RELATIONSHIP MODEL
Entity:A real-world object that can be distinctly identified may represent some real physical
object. May represent some conceptual idea E.g., SC304 is a course; Semester 1 2001/2002 is a
semester An entity is an object that exists and is distinguishable from other objects.
Example: specific person, company, event, plant
Entity set:An entity set is a set of entities of the same type that share the same properties.
Example: set of all persons, companies, trees, holidays.
Attribute types:
• Simple and composite attributes.
• Single-valued and multi-valued attributes
• Null attributes
• Derived attributes
9
• Identifiers (Key) attributes
Symbol Meaning
ENTITY TYPE
RELATIONSHIP
IDENTIFYING RELATIONSHIP
ATTRIBUTE
MULTIVALUED ATTRIBUTE
COMPOSITE ATTRIBUTE
DERIVED ATTRIBUTE
KEY ATTRIBUTE
E1 R E2 TOTAL PARTICIPATION OF
E2 IN R
10
E1 R NCARDINALITY
E2 RATIO 1:N FOR E1:E2 IN R ENTITY
TYPE
Example of ER Diagram:
INTRODUCTION TO SQL
11
SQL stands for Structured Query Language. Oracle provides many extensions to ANSI
SQL.SQL is standard language for interacting with a relational database.
A table is primary database object of SQL, which is used to store the data in the form of
rows and columns. SQL developed by IBM is used as standard language to access data
from database. In order to communicate with database SQL has been divided into four
sub languages and each sub language consists of different commands, they are:
1. Data Definition Language (DDL): DDL commands are used to define the database
structure or schema.
Different DDL commands are:
CREATE - to create objects in the database
ALTER - alters the structure of the database
DROP - delete objects from the database
TRUNCATE - remove all records from a table, including all spaces allocated for the
records are removed
RENAME - rename an object
2. Data Manipulation Language (DML): DMLcommands are used for managing data
within schema objects.
Different DML commands are:
SELECT - retrieve data from the a database
INSERT - insert data into a table
UPDATE - updates existing data within a table
DELETE - deletes all records from a table, the space for the records remain
3. Data Control Language (DCL): DCL commands are used to control the access to
the database objects.
Different DCL commands are:
GRANT - gives user's access privileges to database
REVOKE - withdraw access privileges given with the GRANT command
12
4. Transaction Control Language (TCL): TCL commands are used to manage the
changes made by DML statements. It allows statements to be grouped together into
logical transactions.
Different TCL commands are:
COMMIT - save work done
SAVEPOINT - identify a point in a transaction to which you can later roll back
ROLLBACK - restore database to original since the last COMMIT
13
DDL COMMANDS
14
Ex:
Alter table emp rename column ename to empname;
d) Removing existing columns
Syntax:
Alter table<table name> drop column <col>;
Ex:
Alter table empdrop column sal;
5. Destroying tables
Syntax:
Drop table<table name>;
Ex:
Drop table emp1;
15
WORKING WITH CONSTRAINTS
Constraints are rules for a database that limit the acceptable data values for a table. They
are the optional schema objects that depend on a table. The existence of a table without
any constraint is possible, but the existence of a constraint without any table is not
possible. Constraints enforce the business rules in a database. Constraints can be created
along with the table in the CREATE TABLE statement. Addition and deletion of
constraints can be done in the ALTER TABLE statement.
UNIQUE
It ensures that columns protected by this constraint cannot have duplicate values.
PRIMARY KEY
It is responsible for uniquely identifying a row in a table. A table can have only one
PRIMARY KEY constraint. A PRIMARY KEY constraint completely includes both the
NOT NULL and UNIQUE constraints. It is enforced with an index on all columns.
FOREIGN KEY
It is also known as referential integrity constraint. It enforces that values referenced in
one table are defined in another table. It establishes a parent-child or reference-dependent
relationship between the two tables.
CHECK
It enforces that columns must meet a specific condition that is evaluated to a Boolean
16
value. If the value evaluates to false, then the database will raise an exception, and not
allow the INSERT and UPDATE statements to operate on columns.
2. Unique constraint
a) Creating Table with unique constraint at column level
Syntax:
Create table<table name> (<col1><data type>(<size>) unique,<col2><data
type>(<size>));
Ex:
Create table empl (empnonumber(4), ename char(10) unique,city char(10));
17
Syntax:
Create table<table name>(<col1><data type>(<size>) primary key);
Ex:
Create table empl (empnonumber(4) primary key, ename char(10), city char(10));
18
5. Check Constraints
a) Creating Table with check constraint at column level
Syntax:
Create table<table name>(<col1><data type>(<size>) check(<logical
expression>);
Ex:
Create table mgr (mgrno number, deptno number, age number check(age between
1 and 100));
19
DML COMMANDS
20
b)Removalof specified rows
Syntax:
Delete from <table name> where <condition>;
Ex:
Delete from emp where ename=’Ajay’ and city=’Jaipur’;
b)Updatingselected records
Syntax:
Update<tablename>set<col>=<exp>,<col>=<exp>where <condition>;
Ex:
Update emp set ename=’Ram’ where city=’Udaipur’;
21
SELECT COMMAND
b)Using select *
Syntax:
Select * from tablename;
Ex:
Select * from emp;
2. Filtering table data: While viewing data from a table, it is rare that all the data from
table will be required each time. Hence, SQL must give us a method of filtering out data
that is not required data.
22
c)Selectingrecords that fulfill a specified criterion (where clause)
Syntax:
Select */<col1>,<col2> from <tablename> where <condition>;
Ex:
Select * from emp where empnoin(2,4,6,7);
e)Selecting data across multiple records and group the results by one or more
columns(group by clause)
Syntax:
Select <col1>,<col2>,<aggregate function on column> from <tablename> group
by<col>;
Ex:
Select deptno,max(salary) from emp group by deptno ;
f)Selecting data across multiple records and group the results by one or more
columns according to some conditions (having clause)
Syntax:
Select <col1>,<col2>,<aggregate function on column> from <tablename> group
by <col> having <condition>;
Ex:
Select deptno,max(salary) from emp group by deptno having max(sal)>20000 ;
23
DCL COMMANDS
Oracle provides extensive feature in order to safeguard information stored in its tables
from unauthorized viewing and damage.The rights that allow the user of some or all
oracle resources on the server are called privileges.
24
TCL COMMANDS
A transaction is a set of SQL statements which Oracle treats as a Single Unit. i.e. all the
statements should execute successfully or none of the statements should execute.
To control transactions Oracle does not made permanent any DML statements unless you
commit it. If you don’t commit the transaction and power goes off or system crashes then
the transaction is roll backed.
2. ROLLBACK
To rollback the changes done in a transaction give rollback statement. Rollback restore
the state of the database to the last commit point.
Syntax:
Rollabck/ Rollback to savepoint<savepointname>;
Ex:
delete from emp;
rollback; /* undo the changes */
3. SAVEPOINT
Specify a point in a transaction to which later you can roll back.
25
Syntax:
Savepoint<savepointname>;
Ex:
insert into emp (empno,ename,sal) values (109,’Sami’,3000);
savepoint a;
insert into dept values (10,’Sales’,’Hyd’);
savepoint b;
insert into salgrade values (‘III’,9000,12000);
Now if you give
rollback to a;
Then row from salgrade table and dept will be roll backed. Now you can commit
the row inserted into emp table or rollback the transaction.
If you give
rollback to b;
Then row inserted into salgrade table will be roll backed. Now you can commit
the row inserted into dept table and emp table or rollback to savepoint a or
completely roll backed the transaction.
If you give
rollback;
Then the whole transaction is roll backed.
If you give
commit;
Then the whole transaction is committed and all savepoints are removed.
26
EXERCISE WITH SQL QUERIES
Exercise1: Consider the insurance database, where the primary keys are underlined.
Construct the following SQL queries for this relational database.
person (driver-id, name, address)
car (license, model, year)
accident (report-number, date, location)
owns (driver-id, license)
participated (driver-id, car, report-number, damage-amount)
(a) Find the total number of people who owned cars that were involved in accidents in
1989.
(b) Find the number of accidents in which the cars belonging to “Ajay Singh” were
involved.
(c) Add a new accident to the database; assume any values for required attributes.
(d) Delete the Mazda belonging to “Ajay Singh”.
(e) Update the damage amount for the car with license number “AABB2000” in the
accident with report number “AR2197” to Rs. 3000.
(f) Add one more column named mobile_no to the person table.
(g) Rename the column named mobile_no in the person table to contact_no.
(h) Remove the column named contact_no from the person table.
Solutions-:
(a) Find the total number of people who owned cars that were involved in accidents in
1989.
Note: this is not the same as the total number of accidents in 1989. We must count people
with several accidents only once.
selectcount (distinct name)
fromaccident, participated, person
whereaccident.report-number = participated.report-number
andparticipated.driver-id = person.driver-id
anddate between date ’1989-00-00’ and date ’1989-12-31’;
27
(b) Find the number of accidents in which the cars belonging to “Ajay Singh” were
involved.
selectcount (distinct *)
fromaccident
where exists (select * from participated, person
whereparticipated.driver-id = person.driver-id
and person.name = ‘Ajay Singh’
andaccident.report-number = participated.report-number);
(c)Add a new accidentto the database; assume any values for required attributes.
insert into accident
values (4007, ’2001-09-01’, ’Berkeley’);
(e) Update the damage amount for the car with license number “AABB2000” in the
accident with report number “AR2197” to Rs. 3000.
update participated
set damage-amount = 3000
where report-number = “AR2197” and driver-id in
(select driver-id
from owns
where license = “AABB2000”);
(f) Add one more column named mobile_no to the person table.
alter table personadd(mobile_no number);
28
(g) Rename the column named mobile_no in the person table to contact_no.
alter table person
rename column mobile_no to contact_no;
(h) Remove the column named contact_no from the person table.
alter table person drop column contact_no;
Exercise2: Consider the employee database, where the primary keys are underlined. Give
an expression in SQL for each of the following queries.
employee (employee-name, street, city)
works (employee-name, company-name, salary)
company (company-name, city)
manages (employee-name, manager-name)
(a) Find the names of all employees who work for First Bank Corporation.
(b) Find the names and cities of residence of all employees who work for first bank
Corporation.
(c) Find the names, street addresses, and cities of residence of all employees who work
for First Bank Corporation and earn more than Rs. 10,000.
(d) Find all employees in the database who live in the same cities as the companies for
which they work.
(e) Find all employees in the database who live in the same cities and on the same streets
as do their managers.
(f) Find all employees in the database who do not work for First Bank Corporation.
(g) Find all employees in the database who earn more than each employee of Small Bank
Corporation.
(h) Assume that the companies may be located in several cities. Find all companies
located in every city in which Small Bank Corporation is located.
(i) Find all employees who earn more than the average salary of all employees of their
company.
(j) Find the company that has the most employees.
(k) Find the company that has the smallest payroll.
29
(l) Find those companies whose employees earn a higher salary, on average, than the
average salary at First Bank Corporation.
Solutions-:
(a) Find the names of all employees who work for First Bank Corporation.
select employee-name
from works
where company-name = ’First Bank Corporation’;
(b) Find the names and cities of residence of all employees who work for First Bank
Corporation.
selecte.employee-name, city
from employee e, works w
wherew.company-name = ’First Bank Corporation’ and
w.employee-name = e.employee-name;
(c) Find the names, street address, and cities of residence of all employees who work for
First Bank Corporation and earn more than Rs. 10,000.
select *
from employee
where employee-name in
(select employee-name
from works
where company-name = ’First Bank Corporation’ and salary >
10000);
(d) Find all employees in the database who live in the same cities as the comapanies for
which they work.
selecte.employee-name
from employee e, works w, company c
wheree.employee-name = w.employee-name and e.city = c.city and
30
w.company -name = c.company–name;
(e) Find all employees in the database who live in the same cities and on the same streets
as do their managers.
selectP.employee-name
from employee P, employee R, manages M
whereP.employee-name = M.employee-name and
M.manager-name = R.employee-name and
P.street = R.street and P.city = R.city;
(f) Find all employees in the database who do not work for First Bank Corporation.
select employee-name
from works
where company-name <>’First Bank Corporation’;
(g) Find all employees in the database who earn more than every employee of Small
Bank Corporation.
select employee-name
from works
where salary > all
(select salary
from works
where company-name = ’Small Bank Corporation’);
(h) Assume that the companies may be located in several cities. Find all companies
located in every city in which Small Bank Corporation is located.
selectT.company-name
from company T
where (select R.city
from company R
whereR.company-name = T.company-name)
31
contains
(selectS.city
from company S
where S.company-name = ’Small Bank Corporation’);
(i) Find all employees who earn more than the average salary of all employees of their
company.
select employee-name
from works T
where salary > (select avg (salary)
from works S
whereT.company-name = S.company-name);
32
select company-name
from works
group by company-name
havingavg (salary) > (select avg (salary)
from works
where company-name = ’First Bank Corporation’);
33
REFERENCES
34
Viva Questions:
1. What is database?
A database is a collection of information that is organized. So that it can easily be
accessed, managed, and updated.
2. What is DBMS?
DBMS stands for Database Management System. It is a collection of programs that
enables user to create and maintain a database.
5. What is normalization?
It is a process of analysing the given relation schemas based on their Functional
Dependencies (FDs) and primary key to achieve the properties
(1).Minimizing redundancy, (2). Minimizing insertion, deletion and update anomalies.
9. What is an Entity?
An entity is a thing or object of importance about which data must be captured.
35
11. What is DML (Data Manipulation Language)?
This language that enable user to access or manipulate data as organised by appropriate
data model. Procedural DML or Low level: DML requires a user to specify what data are
needed and how to get those data. Non-Procedural DML or High level: DML requires a
user to specify what data are needed without specifying how to get those data
36
A table is in fifth normal form (5NF) or Project-Join Normal Form (PJNF) if it is in 4NF
and it cannot have a lossless decomposition into any number of smaller tables.
37
Intension -It is a constant value that gives the name, structure of table and the constraints
laid on it.
38
41. Describe the difference between homogeneous and heterogeneous distributed
database?
A homogenous database is one that uses the same DBMS at each node. A heterogeneous
database is one that may have a different DBMS at each node.
39
Logical level: The next higher level of abstraction, describes what data are stored in
database and what relationship among those data.
View level: The highest level of abstraction describes only part of entire database.
40