Database Management Systems Lab Report
Database Management Systems Lab Report
UNIVERSITY
“JnanaSangama”, Belgaum -590014, Karnataka.
LAB REPORT
on
Submitted by
Mahmad Shahabaz (1BM25CS475-T)
CERTIFICATE
This is to certify that the Lab work entitled “Database Management Systems (23CS3PCDBM)”
carried out by Mahmad Shahabaz (1BM25CS475-T), who is bonafide student of B. M. S.
College of Engineering. It is in partial fulfillment for the award of Bachelor of Engineering in
Computer Science and Engineering of the Visvesvaraya Technological University, Belgaum
during the year 2022. The Lab report has been approved as it satisfies the academic requirements
in respect of a Database Management Systems (23CS3PCDBM) work prescribed for the said
degree.
2
Index
Sl. Date Experiment Title Page No.
No.
1 28-09-25 Insurance Database
3
Experiment 1: Insurance Database
The insurance database must maintain information about drivers, the cars they own, the accidents
reported, and the participation of each driver and car in those accidents. Each driver in the system is
uniquely identified by a driver ID, along with their name and address, and each car is uniquely
identified by its registration number together with details such as model and manufacturing year. The
system must allow storing ownership information that links a driver to one or more cars, while also
allowing a car to be linked to one or more drivers if shared ownership occurs; duplicate ownership
records for the same driver and car must not exist. Accident information must be stored using a
unique report number assigned to each accident, along with the date on which the accident occurred
and the location where it happened. Every accident reported in the system must have at least one
participating driver and car, and this participation is recorded by linking the driver, the involved car,
and the accident report together with the corresponding damage amount for that particular
involvement. A participation record must reference an existing driver, an existing car, and an existing
accident, and no two participation entries may repeat the same combination of driver, car, and
accident report. The database must ensure that damage amounts are non-negative, accident dates are
valid calendar dates, and car manufacturing years fall within reasonable limits. It must also preserve
referential integrity so that ownership or participation entries cannot exist without valid driver, car,
and accident information already present in the system. Deletion policies must prevent removal of
drivers or cars that appear in past accident participation records unless historical consistency is
preserved through controlled deletion rules or archival mechanisms. The system should maintain
accurate links between drivers, cars, and accidents at all times, ensuring reliable retrieval of
ownership histories, accident histories, and damage information for administrative, legal, and
insurance-related purposes.
4
Entity Relationship Diagram
5
Schema Diagram
Create database
create database test;
use test;
Create table
desc
accident;
desc participated;
desc
participated;
desc owns;
8
Inserting Values to the table
("A02","pradeep","rajaji nagar"),
("A03","smith","ashok nagar"),
("A04","venu","nk colony"),
("A05","john","hanuman nagar");
("KA052251","toyota",1957),
("KA052252","honda",1998),
("KA052253","audi",2008), ("KA052254","lambo",2005);
9
insert into owns values("A01","KA052250"),
("A02","KA052251"),
("A03","KA052252"),
("A04","KA052253"),
("A05","KA052254");
10
'KA052251', 12, 20000),
select*from participated;
Queries :
update participated set damage_amount=25000 where report_num=12; insert into
values (16,'2008-03-15','Domlur');
select count(*) CNT from car c,participated p where c.reg_num=p.reg_num and model="audi";
select count( driver_id) CNT from participated a,accident b where a.report_num=b.report_num and
year(b.accident_date)=2003;
11
select * from participated order by damage_amount desc;
Queries
i. Display the entire CAR relation in the ascending order of manufacturing year.
SELECT * FROM car ORDER BY manuf_year;
ii. Find the number of accidents in which cars belonging to a specific model (example 'Lancer')
were involved.
SELECT COUNT(*)
FROM participated p
JOIN car c ON p.reg_num = c.reg_num
WHERE [Link] = 'Lancer';
12
iii. Find the total number of people who owned cars that involved in accidents in 2008.
SELECT COUNT(DISTINCT o.driver_id)
FROM owns o
JOIN participated p ON o.reg_num = p.reg_num
JOIN accident a ON p.report_num = a.report_num
WHERE YEAR(a.accident_date) = 2008;
iv. List the entire participated relation in the Descending Order of Damage Amount.
SELECT * FROM participated ORDER BY damage_amount DESC;
v. Find the Average Damage Amount. vi. Delete the tuple whose Damage Amount is below the
Average Damage Amount
SELECT AVG(damage_amount) FROM participated;
vi. List the name of drivers whose Damage is Greater than the Average Damage Amount.
SELECT DISTINCT [Link]
FROM person pe
JOIN participated pa ON pe.driver_id = pa.driver_id
WHERE pa.damage_amount >
(SELECT AVG(damage_amount) FROM participated);
13
vii. Find Maximum Damage Amount.
SELECT MAX(damage_amount) FROM participated;
The banking system must store information about branches, bank accounts, customers, deposit relationships,
and loans so that branch details (identified by branch name together with city and total assets) are linked to
accounts and loans, each account (identified by an account number) records the branch it belongs to and the
current balance, customers are recorded with their name, street and city, and a depositor relationship associates
a customer with an account; loans are recorded by a unique loan number together with the branch name that
issued the loan and the loan amount. Account numbers and loan numbers must be unique identifiers, branch
names are used to associate accounts and loans to a branch, and customer names (as modeled) are used to
identify customers referenced by depositor entries; every depositor entry must reference an existing customer
and an existing account so that ownership and access relationships are always valid, and duplicate depositor
records linking the same customer and account are disallowed. The system must maintain referential integrity
so accounts cannot reference a non-existent branch, depositor rows cannot reference missing customers or
accounts, and loans must reference an existing branch; deletion of a branch, account, or customer that is
referenced by dependent records should be controlled (either disallowed or handled by archival/controlled
reassignment) to preserve historical transaction and loan consistency. Numeric and temporal constraints must
14
be enforced: account balances should be constrained to valid values (for example non-negative where
overdraft is not allowed), branch assets and loan amounts must be non-negative and within specified business
limits, and updates to balance or loan amounts should be auditable. Cardinality rules implied by the schema
are enforced: a branch may host many accounts and issue many loans, an account belongs to exactly one
branch, a customer may be linked to many accounts through depositor relationships, and an account may have
many depositors if joint accounts are permitted by policy. Implementation must prevent orphaned records,
ensure uniqueness where required, and rely on application logic or database-level triggers to enforce complex
rules such as cascading effects on deletion, business rules about allowed balance operations or overdrafts, and
any required validation when transferring accounts between branches or when converting a customer’s
identifying details; the database should thus reliably support queries for branch-wise account lists, customer
account ownership, account balances, and loan portfolios while preserving historical and referential integrity
for auditing and regulatory reporting.
15
Schema Diagram
16
● Branch (branch-name: String, branch-city: String, assets: real)
● BankAccount(accno: int, branch-name: String, balance: real)
● BankCustomer (customer-name: String, customer-street: String, customer-city:
String)
● Depositer(customer-name: String, accno: int)
● LOAN (loan-number: int, branch-name: String, amount: real)
● Create the above tables by properly specifying the primary keys and the foreign
keys. - Enter at least five tuples for each relation
Create database
create database Bank_db;
use Bank_db;
Create table
17
create table branch(
b_city varchar(40),
assets int);
b_name varchar(45),
balance int,
cus_street varchar(45),
city varchar(45));
cus_name varchar(45),
accno int ,
primary key(cus_name,accno),
b_name varchar(45),
amt int,
desc bankaccount;
desc BankCustomer;
DESC depositor;
desc loan;
19
INSERT INTO BankCustomer VALUES ('Avinash',
'Bull_Temple_Road', 'Bangalore'), ('Dinesh', 'Bannerghatta_Road',
'Bangalore'), ('Mohan', 'NationalCollege_Road', 'Bangalore'), ('Nikil',
'Akbar_Road', 'Delhi'),
20
INSERT INTO depositor VALUES ('Avinash', 1),('Dinesh',
2),('Nikil', 4), ('Ravi', 5),('Avinash', 8),
Queries :
iii. Display the branch name and assets from all branches in lakhs of rupees and rename the assets
column to 'assets in lakhs'.
21
select b_name as 'Branch_Name',assets/100000.0 as 'assets_in_lakhs' from branch;
iv. Find all the customers who have at least two accounts at the same branch (ex.
SBI_ResidencyRoad).
v. Create a view which gives each branch the sum of the amount of all the loans at the branch.
CREATE VIEW Summary AS
FROM loan
GROUP BY b_name;
22
Experiment 4: More Queries on Bank Database
Queries
i. Find all the customers who have an account at all the branches located in a specific city (Ex.
Delhi).
select d.cus_name
where [Link]=[Link] and b_name in (select b_name from branch where b_city='Delhi') group by
d.cus_name;
ii. Find all customers who have both an account and a loan at the Bangalore branch
and b.b_name IN (
);
iv. Find the names of all branches that have greater assets than all branches located in
Bangalore.
SELECT b_name
23
FROM branch
SELECT assets
FROM branch
);
v. Demonstrate how you delete all account tuples at every branch located in a specific city (Ex.
Bombay).
SET SQL_SAFE_UPDATES = 0;
UPDATE BankAccount
SET balance = balance + (balance * 0.05);
SET SQL_SAFE_UPDATES = 1;
The employee database must record each employee’s identifying number, name, manager reference, hire date,
salary, and department affiliation while also tracking departmental details, project assignments (including the
role an employee plays on a project), and any incentive payments given to employees. Every employee is
represented by a unique employee number and has a hire date and salary that must be valid; the manager field
is a self-referencing link that must, if present, point to an existing employee and must never create a circular
management chain or reference the employee themself. Departments are identified by a unique department
number and include a department name and location; every department referenced by an employee or by other
structures must exist in the department table, and departments may contain zero or many employees. Projects
are recorded with a unique project number, project name and project location; employees may be assigned to
multiple projects and each project may have many employees, with each assignment carrying the employee’s
job role for that project — duplicate assignments of the same employee to the same project are disallowed.
Incentive payments are recorded with the employee reference, the incentive date and the incentive amount; an
incentive entry must reference an existing employee and incentive amounts must be non-negative and dated on
or after the employee’s hire date. Referential integrity must be enforced so that employee records cannot
reference non-existent departments, projects, or managers, and assignment and incentive records cannot exist
without corresponding employee, project, or department records as appropriate. Salary, incentive amounts, and
any monetary fields must be constrained to valid numeric ranges and hire/ incentive dates must be valid
calendar dates (and typically not future-dated unless business rules permit). Deletion and update policies must
preserve historical consistency: deleting an employee who appears as a manager, as a project assignee, or in
incentive records should be prevented or should be handled via controlled archival, reassignment, or soft-
delete flags rather than hard deletion to preserve audit trails; similarly, changing a department or project
identifier must either be disallowed if it would orphan historical records or handled by introducing immutable
surrogate keys. Business rules include preventing circular manager chains, ensuring an employee’s manager (if
specified) cannot be the employee themself, disallowing duplicate project-assignments, requiring that
incentive dates fall within the employee’s employment window, and optionally requiring at least one project
assignment or at least one incentive record depending on policy for reporting. Implementation should use
primary-key and foreign-key constraints for identity and linkage, unique constraints to prevent duplicate
assignments, check constraints for monetary and date ranges, and application logic or triggers for complex
temporal or graph constraints (like cycle detection in management relationships and enforcing non-overlap or
other schedule-related rules if assignments gain temporal attributes later). The system must therefore reliably
support queries such as employee reporting lines, department staffing lists, project rosters with job roles,
incentive payment histories, salary analyses, and audit reports while maintaining data integrity, preventing
inconsistent deletions, and preserving a complete historical record for HR and compliance needs.
25
Entity Relationship Diagram
26
Schema Diagram
Create table
CREATE TABLE DEPT (
DNAME VARCHAR(20),
DLOC VARCHAR(20)
);
ENAME VARCHAR(20),
27
MGR_NO INT,
HIREDATE DATE,
SAL INT,
DEPTNO INT,
);
PLOC VARCHAR(50),
PNAME VARCHAR(50)
);
EMPNO INT,
PNO INT,
JOB_ROLE VARCHAR(50),
);
EMPNO INT,
INCENDATE DATE,
INCENAMT DECIMAL(10,2),
);
desc dept;
d
esc employee;
28
desc projectr;
DESC assigned_tor;
desc incentives;
29
SELECT * FROM DEPT;
30
INSERT INTO ASSIGNED_TO VALUES
(101, 10, 'Leader'),
(102, 10, 'Developer'),
(103, 20, 'Analyst'),
(104, 30, 'Tester'),
(105, 40, 'Designer'),
(106, 50, 'Co-ordinator'),
(103, 60, 'Engineer');
SELECT * FROM ASSIGNED_TO;
31
Queries :
iii. Retrieve the employee numbers of all employees who work on project located in
Bengaluru, Hyderabad, or Mysuru
iv. Get Employee ID’s of those employees who didn’t receive incentives
SELECT [Link]
FROM EMPLOYEE e
LEFT JOIN INCENTIVES i ON [Link] = [Link]
WHERE [Link] IS NULL;
v. Write a SQL query to find the employees name, number, dept, job_role, department
location and project location who are working for a project location same as his/her
department location.
32
Experiment 6: More Queries on Employee Database
Queries
i. List the name of the managers with the maximum employees
SELECT [Link]
FROM EMPLOYEE m
JOIN EMPLOYEE e ON [Link] = e.MGR_NO
GROUP BY [Link], [Link]
HAVING COUNT(*) = (
SELECT MAX(cnt)
FROM (
SELECT COUNT(*) cnt
FROM EMPLOYEE
WHERE MGR_NO IS NOT NULL
GROUP BY MGR_NO
)x
);
ii. Display those managers name whose salary is more than average salary of his employee.
SELECT [Link]
FROM EMPLOYEE m
WHERE [Link] > (
SELECT AVG([Link])
FROM EMPLOYEE e
WHERE e.MGR_NO = [Link]
);
33
iii. Find the name of the second top level managers of each department.
iv. Find the employee details who got second maximum incentive in January 2019.
SELECT e.*
FROM EMPLOYEE e
JOIN INCENTIVES i ON [Link] = [Link]
WHERE MONTH([Link])=1
AND YEAR([Link])=2019
AND [Link] = (
SELECT MAX(INCENAMT)
FROM INCENTIVES
WHERE INCENAMT < (
SELECT MAX(INCENAMT)
FROM INCENTIVES
WHERE MONTH(INCENDATE)=1 AND YEAR(INCENDATE)=2019
)
);
v. Display those employees who are working in the same department where his manager is
working.
SELECT e.*
FROM EMPLOYEE e
JOIN EMPLOYEE m ON e.MGR_NO = [Link]
WHERE [Link] = [Link];
34
Experiment 7 : SUPPLIER DATABASE
The supplier database must store information about suppliers, the parts they provide, and the prices at
which each part is offered so that purchasing, analysis, and reporting can be done accurately. Each supplier is
uniquely identified by a supplier ID and is recorded with a name and the city in which the supplier is located;
each part is uniquely identified by a part ID and includes a part name and a color. The system must maintain
a catalog that links suppliers to the parts they supply and records the cost at which a given supplier sells a
given part. Every catalog entry must reference an existing supplier and an existing part, and there must be no
duplicate entries for the same combination of supplier and part, so that at most one current price record
exists per supplier–part pair. Costs must be valid numeric values and strictly non-negative, and business rules
may specify upper limits or currency formats that must be enforced consistently. The data model must
support the possibility that a supplier can provide many different parts, that a part can be supplied by many
different suppliers, and that some suppliers or parts may temporarily have no catalog entries if they are
inactive or not currently traded. Referential integrity must be enforced so that a supplier or part cannot be
deleted while still referenced in the catalog unless such deletion is handled by controlled archival or cascade
rules that preserve historical price information; in general, historical catalog data should not be lost, as it may
be required for audits or trend analysis. The system should allow queries such as “find all suppliers for a given
part,” “list all parts provided by a given supplier,” “retrieve the cheapest supplier for each part,” and “analyze
supplier coverage by city,” and must therefore guarantee that identifiers are unique, relationships between
suppliers, parts, and catalog entries are consistent, and price information is accurate and reliably maintained
over time.
35
Entity Relationship Diagram
36
Schema Diagram
Create table
CREATE TABLE Supplier (
sid INT PRIMARY KEY,
sname VARCHAR(20),
city VARCHAR(20)
);
desc supplier;
desc
parts;
desc catalog;
38
INSERT INTO Parts VALUES
(101, 'bankai', 'Red'),
(102, 'shikai', 'Green'),
(103, 'quincy', 'Red'),
(104, 'espada', 'Blue');
select * from parts;
39
Queries :
[Link] the pnames of parts for which there is some supplier.
SELECT [Link]
FROM Supplier s
JOIN Catalog c ON [Link] = [Link]
GROUP BY [Link]
HAVING COUNT(DISTINCT [Link]) = (SELECT COUNT(*) FROM Parts);
40
SELECT [Link]
FROM Supplier s
JOIN Catalog c ON [Link] = [Link]
JOIN Parts p ON [Link] = [Link]
WHERE [Link] = 'Red'
GROUP BY [Link]
HAVING COUNT(DISTINCT [Link]) = (
SELECT COUNT(*) FROM Parts WHERE color = 'Red' );
vi. Find the pnames of parts supplied by Acme Widget Suppliers and by no one else.
SELECT [Link]
FROM Parts p
JOIN Catalog c ON [Link] = [Link]
JOIN Supplier s ON [Link] = [Link]
GROUP BY [Link]
HAVING COUNT(DISTINCT [Link]) = 1
AND MAX([Link]) = 'Acme Widget Suppliers';
vii. Find the sids of suppliers who charge more for some part than the average cost of that
part (averaged over all the suppliers who supply that part).
viii. For each part, find the sname of the supplier who charges the most for that part.
Supported
● macOS 12+
▶ Windows
2. Run installer
4.
Finish MongoDB runs automatically
43
Experiment 9: NOSQL STUDENT DATABASE
Structure of collection:
45
Queries :
46
i. Write query to update Email-Id of a student with rollno 10
db.student_details.updateOne(
{ Rollno: 10 },
{ $set: { EmailId: "newmail@[Link]" } }
)
iv. Replace the student name from “ABC” to “FEM” of rollno 11.
db.student_details.updateOne(
{ Rollno: 11 },
{ $set: { Name: "FEM" } }
)
Structure of collection:
48
Queries :
49
i. Write a query to display those records whose total account balance is greater than 1200 of
account type ‘C’ for each customer_id.
[Link]([
{ $match: { Acc_Type: "C" } },
{ $group: { _id: "$Cust_id", Total_Balance: { $sum: "$Acc_Bal" } } },
{ $match: { Total_Balance: { $gt: 1200 } } }
])
[Link]([
{
$group: {
_id: "$Cust_id",
Min_Balance: { $min: "$Acc_Bal" },
Max_Balance: { $max: "$Acc_Bal" }
}
}
])
50
vi. Drop the table.
[Link]()
[Link]([
{
restaurant_id: "R101",
name: "Spicy Dragon",
town: "Bangalore",
cuisine: "Chinese",
grades: [ { score: 12 }, { score: 8 } ] },
{
restaurant_id: "R102",
name: "Burger Maharaja",
town: "Delhi",
cuisine: "Fast Food",
grades: [ { score: 9 }, { score: 7 } ] },
{
restaurant_id: "R103",
name: "Curry Kingdom",
town: "Mumbai",
cuisine: "Indian",
grades: [ { score: 15 }, { score: 14 } ] },
{
restaurant_id: "R104",
name: "Pasta Palace",
town: "Bangalore",
cuisine: "Italian",
grades: [ { score: 6 }, { score: 10 } ] },
{
restaurant_id: "R105",
name: "Dosa Junction",
town: "Chennai",
cuisine: "South Indian",
grades: [ { score: 11 }, { score: 9 } ] }
])
Structure of collection:
52
Queries :
53
i. Write a MongoDB query to arrange the name of the restaurants in descending along with all
the columns.
[Link]().sort({ name: -1 })
[Link] a MongoDB query to find the restaurant Id, name, town and cuisine for those
restaurants which achieved a score which is not more than 10.
[Link](
{ "[Link]": { $lte: 10 } },
{ _id: 0, restaurant_id: 1, name: 1, borough: 1, cuisine: 1 }
)
vi. Write a MongoDB query to find the average score for each restaurant.
[Link]([
54
{ $unwind: "$grades" },
{
$group: {
_id: "$restaurant_id",
name: { $first: "$name" },
avgScore: { $avg: "$[Link]" }
}
}
])
Table: Project
+-------------+---------+
| Column Name | Type |
+-------------+---------+
| project_id | int |
| employee_id | int |
+-------------+---------+
Table: Employee
+------------------+---------+
| Column Name | Type |
+------------------+---------+
| employee_id | int |
| name | varchar |
| experience_years | int |
+------------------+---------+
Table: Views
+---------------+---------+
| Column Name | Type |
+---------------+---------+
| article_id | int |
| author_id | int |
| viewer_id | int |
| view_date | date |
+---------------+---------+
58