DBMSL Lab Manual Final RVS
DBMSL Lab Manual Final RVS
Lab Manual
DATABASE MANAGEMENT SYSTEMS LAB
Lab Manual
Semester-IV
Objective: To understand the concept of ER model and convert into relational tables.
Theory:
What is ER Diagram?
The Entity Relational Model is a model for identifying entities to be represented in the database and
representation of how those entities are related. The ER data model specifies an enterprise schema that
represents the overall logical structure of a database graphically.
The Entity Relationship Diagram explains the relationship among the entities present in the
database. ER models are used to model real-world objects like a person, a car, or a company and the
relation between these real-world objects. In short, ER Diagram is the structural format of the database.
● ER diagrams are used to represent the E-R model in a database, which makes them easy to be
converted into relations (tables).
● ER diagrams provide the purpose of real-world modeling of objects which makes them intently useful.
● ER diagrams require no technical knowledge and no hardware support.
● These diagrams are very easy to understand and easy to create even for a naive user.
● It gives a standard solution for visualizing the data logically.
ER Model is used to model the logical view of the system from a data perspective which consists of
these symbols:
❖ Entity :
An Entity may be an object with a physical existence – a particular person, car, house, or employee –
or it may be an object with a conceptual existence – a company, a job, or a university course.
1. Strong Entity
A Strong Entity is a type of entity that has a key Attribute. Strong Entity does not depend on other
Entity in the Schema. It has a primary key, that helps in identifying it uniquely, and it is represented by
a rectangle. These are called Strong Entity Types.
2. Weak Entity
An Entity type has a key attribute that uniquely identifies each entity in the entity set. But some entity
type exists for which key attributes can’t be defined. These are called Weak Entity types.
❖ Attributes :
Attributes are the properties that define the entity type. For example, Roll_No, Name, DOB, Age,
Address, and Mobile_No are the attributes that define entity type Student.
1. Key Attribute
The attribute which uniquely identifies each entity in the entity set is called the key attribute. For
example, Roll_No will be unique for each student.
2. Composite Attribute
An attribute composed of many other attributes is called a composite attribute. For example, the
Address attribute of the student Entity type consists of Street, City, State, and Country.
Savitribai Phule Pune University
than one for a given student).
4. Derived Attribute
An attribute that can be derived from other attributes of the entity type is known as a derived attribute.
e.g.; Age (can be derived from DOB).
Relationship:
A Relationship represents the association between entity types.
E-R
Model Bus
● BusNo
● Source
● Destination
● CoachType
SCHEMA
Savitribai Phule Pune University
TicketTicketNo
● DOJ
● Address
● ContactNo
● BusNo
● SeatNo
● Source
● Destination
●
SCHEMA
Passenger
● PassportID
● TicketNo
● Name
● ContactNo
● Age
● Sex
● Address
Savitribai Phule Pune University
Reservation
● PNRNo
● DOJ
● No_of_seats
● Address
● ContactNo
● BusNo
● SeatNo
SCHEMA
Cancellation
● PNRNo
● DOJ
● SeatNo
● ContactNo
● Status
SCHEMA
Savitribai Phule Pune University
CONCEPT DESIGN WITH E-R MODEL
Savitribai Phule Pune University
★ To Represent all the entities (Strong, Weak) in tabular fashion. Represent relationships in a tabular fashion.
Bus:
Ticket:
Passenger:
Type of Attributes
ColumnName Datatype Constraints
PassportID Varchar(15) Primary Key Single-valued
Reservation:
Savitribai Phule Pune University
Cancellation:
Conclusion: Here we understood the concept of ER model and relational model representation from ER.
Savitribai Phule Pune University
Assignment No 2
Title: SQL Queries:
Write and execute SQL Data Definition Language (DDL) commands such as CREATE, ALTER, DROP,
RENAME, and TRUNCATE to define and modify tables. Insert data into the tables and apply appropriate
integrity constraints such as NOT NULL, UNIQUE, PRIMARY KEY, FOREIGN KEY, and CHECK
Objective: Understand the concept of DDL & DML Commands and its operations with Operators, functions.
SQL stands for Structured Query Language. SQL is used to communicate with a database. According to
ANSI (American National Standards Institute), it is the standard language for relational database
management systems. SQL statements are used to perform tasks such as update data on a database, or
retrieve data from a database. Some common relational database management systems that use SQL are:
Oracle, Sybase, Microsoft SQL Server, Access, Ingres, etc. Although most database systems use SQL,
most of them also have their own additional proprietary extensions that are usually only used on their
system. However, the standard SQL commands such as "Select", "Insert", "Update", "Delete", "Create",
and "Drop" can be used to accomplish almost everything that one needs to do with a database.
SQL Languages:
1. Create operation:-
a) Create database :- The CREATE DATABASE statement is used to create a new SQL
database.
Syntax:- CREATE DATABASE databasename;
b) Create Table :- It is used to Create a Table.
Syntax:- CREATE TABLE table_name ( column1 datatype, column2 datatype, column3
datatype);
2. Alter Table :- The ALTER TABLE statement is used to add, delete, or modify columns in an existing
table. The ALTER TABLE statement is also used to add and drop various constraints on an existing table
and alters the structure of the database
Savitribai Phule Pune University
To add a column in a table, use the following syntax :-ALTER TABLE table_name
ADD column_name datatype;
3. Drop Table :- The DROP TABLE statement is used to drop an existing table in a database.
4. Truncate Table :- The TRUNCATE TABLE statement is used to delete the data inside a table, but
not the table itself.
5. Rename Table :- It is used to rename an object . It is used for give another name to the
table. Syntax :- Rename old_table_name to New_table_name ;
SQL Objects :-
1) Table: A table is a collection of related data held in a structure format within a database it consists
of column and row a table is a set of data elements using a model of vertical column and horizontal
rows the cell being the init where a row and column insert .
2) View: In SQL, a view is a virtual table based on the result-set of an SQL statement.A view
contains rows and columns, just like a real table. The fields in a view are fields from one or more
real tables in the database.
a) CREATE VIEW:
c) SQL Dropping a View: You can delete a view with the DROP
VIEW command. Syntax:- DROP VIEW view_name;
Savitribai Phule Pune University
3) Index: Indexes are used to retrieve data from the database very fast. The users cannot see the indexes,
they are just used to speed up searches/queries.
b) CREATE UNIQUE INDEX :-Creates a unique index on a table. Duplicate values are
not allowed: Syntax:- CREATE UNIQUE INDEX index_name
ON table_name (column1, column2, ...);
4) Sequence :- Auto-increment allows a unique number to be generated automatically when a new record is
inserted into a table. Often this is the primary key field that we would like to be created automatically every
time a new record is inserted.
Syntax :- Create table < table_name > (variable_name datatype primary key auto increment ,
variable_name data type);
5) INSERT
6)Integrity Constraints
a. NOT NULL
b. UNIQUE
c. PRIMARY KEY
d. FOREIGN KEY
Savitribai Phule Pune University
Establishes a relationship between two tables by referencing the primary key of another table.
Syntax
FOREIGN KEY (column) REFERENCES parent_table(column)
Example
CREATE TABLE Enrollment (
EnrollID INT PRIMARY KEY,
StudentID INT,
FOREIGN KEY (StudentID) REFERENCES Student(StudentID)
);
e. CHECK
Conclusion: - Here we understood the DDL Commands and its operations with Integrity Constraints.
Savitribai Phule Pune University
Assignment No 3
Title: SQL Queries for Data Manipulation, Access Control, and Transaction
Management
SQL Queries for Data Manipulation, Access Control, and Transactions Design and run SQL
queries to demonstrate the following:
a) Data Manipulation (DML): Use SQL statements to INSERT, UPDATE, and DELETE
records. Apply arithmetic, logical, set operators, pattern matching, and string functions.
b) Access Control (DCL): Use GRANT, REVOKE, and ROLE commands to manage user
access.
c) Transaction Control (TCL): Apply START TRANSACTION, COMMIT, ROLLBACK,
and SAVEPOINT commands to manage transactions.
Objective: Understand the concept of DML & DCL, TCL Commands and its operations.
Software Required
Theory
Structured Query Language (SQL) is divided into several sub-languages based on the nature
of the operations performed. This lab focuses on manipulating data content, securing access
to that data, and ensuring data consistency during complex operations.
TCL commands manage the changes made by DML statements. They ensure the ACID
properties (Atomicity, Consistency, Isolation, Durability) of the database.
-- STRING FUNCTIONS: Convert Name to uppercase and extract first 3 letters of Dept
SELECT UPPER(Name) as EmployeeName, SUBSTR(Department, 1, 3) as DeptCode
FROM Employees;
4. Deleting Records
-- Create a role
CREATE ROLE 'app_developer';
2. Granting Privileges
3. Revoking Privileges
-- Verify grants
SHOW GRANTS FOR 'lab_user'@'localhost';
Scenario: We will insert a new record, set a savepoint, delete a record mistakenly, and then
recover the deleted record using rollback.
Conclusion
In this lab, we successfully implemented the essential SQL commands required for database
management.
Savitribai Phule Pune University
1. DML: We manipulated table data using INSERT, UPDATE, and DELETE, and
queried it using arithmetic logic and string functions.
2. DCL: We secured the database by creating users/roles and strictly controlling their
permissions using GRANT and REVOKE.
3. TCL: We maintained data integrity by grouping operations into transactions, utilizing
SAVEPOINT and ROLLBACK to recover from errors before finalizing changes with
COMMIT.
Savitribai Phule Pune University
Assignment No 4
To understand and implement advanced data retrieval techniques that summarize large
datasets.
Software Required
Theory
1. Aggregate Functions
These functions take a collection of values (an entire column or a group of rows) and return a
single summary value.
2. GROUP BY Clause
The GROUP BY statement groups rows that have the same values into summary rows. It is
almost always used with aggregate functions.
3. HAVING Clause
The HAVING clause is used to filter groups after the GROUP BY operation has occurred.
Savitribai Phule Pune University
Difference from WHERE:
o WHERE filters individual rows before grouping.
o HAVING filters groups after grouping (because WHERE cannot work with
aggregate functions like SUM or COUNT).
Pre-requisite: Create a dataset suitable for grouping. We will use a Sales_Data table.
1. Calculate Overall Statistics We use aggregates on the entire table without grouping to get
global totals.
Output will show one row for North, South, East, and West with their respective sums.
Note: We use HAVING because we are filtering based on the result of SUM(), which is an
aggregate.
Scenario: Calculate the average sale amount for 'Laptop' products only, grouped by
region, but only show regions where that average is greater than $500.
Conclusion
To understand how to combine data from multiple tables and create virtual tables for
simplified access.
1. JOIN Operations: Retrieve data from two or more tables based on a related column
between them.
2. Database Views: Create, query, and manage virtual tables (Views) to abstract
complex queries and enhance security.
Software Required
Theory
Relational databases are designed to store data in separate tables to reduce redundancy. To
retrieve meaningful information, these tables must be linked.
1. JOIN Operations
A JOIN clause is used to combine rows from two or more tables, based on a related column
between them (usually a Primary Key and Foreign Key).
INNER JOIN: Returns records that have matching values in both tables.
LEFT (OUTER) JOIN: Returns all records from the left table, and the matched
records from the right table. (Returns NULL if no match is found).
RIGHT (OUTER) JOIN: Returns all records from the right table, and the matched
records from the left table.
CROSS JOIN: Returns the Cartesian product (all combinations of rows) between
tables.
2. Database Views
Virtual: It contains rows and columns like a real table, but the fields are from one or
more real tables in the database.
Abstraction: Views simplify complex queries (e.g., complex Joins) by hiding the
complexity from the user.
Savitribai Phule Pune University
Security: Views can restrict access to specific columns in a table while hiding others
(like salaries or passwords).
Practical Demonstration
-- Table 1: Customers
CREATE TABLE Customers (
CustID INT PRIMARY KEY,
Name VARCHAR(50),
City VARCHAR(50)
);
-- Table 2: Orders
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustID INT,
Amount DECIMAL(10, 2),
FOREIGN KEY (CustID) REFERENCES Customers(CustID)
);
-- Insert Data
-- Note: 'Charlie' makes no orders. 'OrderID 103' is assigned to CustID 99 (orphan record for
demo).
INSERT INTO Customers VALUES (1, 'Alice', 'New York'), (2, 'Bob', 'London'), (3,
'Charlie', 'Paris');
INSERT INTO Orders VALUES (101, 1, 500.00), (102, 2, 300.00), (103, 99, 150.00);
1. INNER JOIN Retrieve a list of customers who have actually placed an order, along with
their order details.
2. LEFT JOIN Retrieve a list of all customers, showing order details if they exist, or NULL
if they don't.
Savitribai Phule Pune University
SELECT [Link], [Link]
FROM Customers
LEFT JOIN Orders ON [Link] = [Link];
3. RIGHT JOIN Retrieve a list of all orders, showing the customer name if it exists.
Observation: Order 103 appears even though Customer 99 does not exist in our Customers
table (returns NULL for Name).
4. CROSS JOIN Create a combination of every customer with every order (Cartesian
Product).
1. Creating a View Create a view named Customer_Order_Summary that hides the IDs and
only shows readable names and amounts for fulfilled orders.
3. Updating a View (Simple View) If a view maps directly to a table without aggregates or
groups, it can be updated. (Note: This updates the underlying Customers table).
UPDATE City_View
Savitribai Phule Pune University
SET City = 'Tokyo'
WHERE Name = 'Alice';
Conclusion
1. Joins: We utilized INNER JOIN to find intersections, LEFT JOIN to prioritize the
main entity (Customers), and RIGHT JOIN to prioritize the transactional entity
(Orders). This allowed us to generate reports that handle missing or mismatched data
gracefully.
2. Views: We created a View to act as a saved query. This demonstrated how to
encapsulate complex join logic into a simple, reusable object
(Customer_Order_Summary), improving both query simplicity and data security.
Savitribai Phule Pune University
Assignment No 6
Title: Subqueries
Write and execute subqueries to retrieve data from one table based on results from another.
Objective:
Software Required
Theory
A Subquery (also known as a nested query or inner query) is a query nested inside another
SQL query. It is used to return data that will be used in the main query as a condition to
further restrict the data to be retrieved.
1. Types of Subqueries
Single-Row Subquery: Returns zero or one row to the outer SQL statement. It is
typically used with comparison operators like =, >, <, >=, <=, or <>.
Multi-Row Subquery: Returns more than one row to the outer SQL statement. It is
used with multiple-value operators such as IN, ANY, or ALL.
Correlated Subquery: A subquery that uses values from the outer query. The
subquery is executed once for each row processed by the outer query.
2. Execution Flow
In a standard (non-correlated) subquery, the inner query executes first, and its result is
passed to the outer query.
Structure:
SELECT column_name
FROM table_name
WHERE column_name OPERATOR (SELECT column_name FROM table_name
WHERE condition);
Savitribai Phule Pune University
Practical
-- Insert Data
INSERT INTO Departments VALUES (1, 'IT'), (2, 'HR'), (3, 'Sales');
INSERT INTO Employees VALUES
(101, 'Alice', 90000, 1),
(102, 'Bob', 40000, 2),
(103, 'Charlie', 85000, 1),
(104, 'David', 45000, 2),
(105, 'Eve', 70000, 3);
Part A: Single-Row Subqueries
1. Using Comparison Operators Retrieve details of employees who earn more than 'David'.
Logic: The inner query finds David's salary (45000). The outer query finds everyone earning
> 45000.
2. Using Aggregate Functions Find employees who earn more than the average salary of the
entire company.
SELECT Name
FROM Employees
WHERE DeptID IN (SELECT DeptID FROM Departments WHERE DeptName IN ('IT',
'Sales'));
Logic: The inner query returns a list (1, 3). The outer query matches any DeptID present in
that list.
4. Using ANY/ALL Operators Find employees who earn more than all employees in the HR
department.
Logic: Finds employees whose salary is strictly higher than the highest salary in Dept 2 (HR).
5. Dependent Subquery Find employees who earn more than the average salary of their own
department.
Logic: For every row processed in the outer query (e1), the inner query calculates the average
for that specific department ID.
Conclusion
Software Required:
Theory:
Standard SQL statements work on sets of data (all rows at once), but sometimes applications
require procedural logic to process data row-by-row or to encapsulate complex business
rules.
2. Cursors
A Cursor is a database object used to retrieve, manipulate, and traverse a result set one row
at a time.
Practical Demonstration
1. Creating a Procedure Create a procedure to update a staff member's salary based on their
ID.
DELIMITER //
DELIMITER ;
2. Calling a Procedure
3. Creating a Function Create a function that calculates the annual tax (assuming 10%) for a
given salary.
DELIMITER //
DELIMITER ;
4. Using a Function
Part C: Cursors
5. Implementing a Cursor Create a procedure that iterates through the Staff table. If the
salary is below 50,000, give a 10% bonus; otherwise, give a 5% bonus.
DELIMITER //
-- 2. Declare Cursor
DECLARE cur CURSOR FOR SELECT StaffID, Salary FROM Staff;
-- 4. Open Cursor
OPEN cur;
read_loop: LOOP
-- 5. Fetch Row
FETCH cur INTO s_id, s_salary;
-- 7. Close Cursor
CLOSE cur;
END //
DELIMITER ;
CALL ProcessBonuses();
SELECT * FROM Staff;
Conclusion
Software Required:
Theory:
A Trigger is a named database object (a set of SQL statements) that is stored in the database
and automatically invoked ("fired") by the database engine when a specific event occurs on a
table.
1. Trigger Timing
BEFORE: Executes the logic before the modification is applied to the database.
Useful for validation or formatting data.
AFTER: Executes the logic after the modification is successfully applied. Useful for
logging, auditing, or cascading changes to other tables.
2. Trigger Events
3. Key Keywords
NEW: Refers to the new row being inserted or the new version of an updated row.
OLD: Refers to the row being deleted or the original version of a row before an
update.
1. Create the Trigger Ensure that no product can be inserted with a negative stock value. If a
user tries to insert a negative number, force it to 0.
DELIMITER //
DELIMITER ;
DELIMITER //
DELIMITER ;
5. Create the Trigger Prevent the deletion of any product that still has stock remaining.
DELIMITER //
DELIMITER ;
-- This should fail because stock is 0 (from previous step, unless updated)
Savitribai Phule Pune University
-- Let's update stock first to test the error
UPDATE Products SET Stock = 10 WHERE ProdID = 101;
-- Try to delete
DELETE FROM Products WHERE ProdID = 101;
-- Output: Error Code: 1644. Error: Cannot delete product with existing stock.
Conclusion
We successfully demonstrated that triggers are a vital mechanism for enforcing business rules
and maintaining data integrity directly at the database layer.
Savitribai Phule Pune University
Assignment No 9
Title: CRUD Operations using MongoDB
Design and implement basic Create, Read, Update, and Delete (CRUD) operations using
MongoDB. Use the save method and logical operators where necessary.
Objective:
1. CRUD Operations: Create, Read, Update, and Delete documents within a collection.
2. Operators: Apply logical ($and, $or) and comparison ($gt, $lt) operators to filter
data.
3. Methods: Utilize insert, save, update, and remove methods for data manipulation.
Software Required:
Theory:
Document: Data is stored in BSON (Binary JSON) format, which consists of field-
value pairs (e.g., {"name": "Alice", "age": 25}).
CRUD Syntax:
o Create: insertOne(), insertMany(), or save().
o Read: find() returns documents matching a query.
o Update: updateOne(), updateMany(), or save() (replaces existing document).
o Delete: deleteOne(), deleteMany(), or remove().
Practical Demonstration
[Link]([
{ "_id": 1, "name": "Alice", "course": "CSE", "marks": 85 },
{ "_id": 2, "name": "Bob", "course": "ECE", "marks": 60 },
{ "_id": 3, "name": "Charlie", "course": "CSE", "marks": 92 },
{ "_id": 4, "name": "David", "course": "MECH", "marks": 75 }
Savitribai Phule Pune University
]);
If the document contains an _id that already exists, it updates/replaces the document.
If the _id is new or missing, it inserts a new document.
4. Using Comparison Operators ($gt) Find students with marks greater than 80.
5. Using Logical Operators ($and, $or) Find students who are in 'CSE' AND have marks
greater than 90, OR are in 'IT'.
[Link]({
$or: [
{ $and: [ { "course": "CSE" }, { "marks": { $gt: 90 } } ] },
{ "course": "IT" }
]
});
6. Using updateOne() with $set Update Bob's marks to 65. The $set operator modifies only
the specific field without overwriting the whole document.
[Link](
{ "name": "Bob" },
{ $set: { "marks": 65 } }
);
7. Using save() to Update Replace David's entire document with new data.
8. Deleting Documents Remove the student named 'Bob' from the collection.
Conclusion
Software Required
Theory
As databases grow, simple CRUD operations are insufficient for data analysis and
performance.
1. Aggregation Framework
The aggregation framework models data processing as a Pipeline. Documents enter a multi-
stage pipeline that transforms the documents into aggregated results.
2. Indexing
Indexes are special data structures that store a small portion of the collection's data in an
easy-to-traverse form.
Without Index: MongoDB must perform a collection scan (scan every document) to
select those that match the query.
With Index: MongoDB limits the inspection to those documents identified by the
index (Index Scan).
Savitribai Phule Pune University
Trade-off: Indexes speed up Read operations but slightly slow down Write
operations (insert/update).
Practical Demonstration
use LabSessionAggIndex
[Link]([
{ _id: 1, product: "Laptop", category: "Electronics", price: 1000, quantity: 5 },
{ _id: 2, product: "Mouse", category: "Electronics", price: 50, quantity: 20 },
{ _id: 3, product: "Chair", category: "Furniture", price: 150, quantity: 10 },
{ _id: 4, product: "Table", category: "Furniture", price: 300, quantity: 5 },
{ _id: 5, product: "Phone", category: "Electronics", price: 800, quantity: 8 },
{ _id: 6, product: "Monitor", category: "Electronics", price: 200, quantity: 10 }
]);
[Link]([
{ $match: { category: "Electronics" } }
]);
2. Multi-Stage Pipeline ($match + $group + $sum) Calculate the total revenue (price *
quantity) for the 'Electronics' category.
[Link]([
{ $match: { category: "Electronics" } },
{
$group: {
_id: "$category",
TotalRevenue: { $sum: { $multiply: ["$price", "$quantity"] } }
}
}
]);
3. Grouping and Sorting ($group + $sort) Count how many products exist in each category
and sort by count descending.
Savitribai Phule Pune University
[Link]([
{
$group: {
_id: "$category",
ProductCount: { $sum: 1 }
}
},
{ $sort: { ProductCount: -1 } }
]);
Observation: Look for totalDocsExamined. If it equals the total number of documents in the
collection (6), it performed a COLLSCAN (Collection Scan), which is inefficient for large
datasets.
6. Analyzing Query Performance (After Indexing) Run the exact same explain query
again.
Conclusion
We effectively utilized the Aggregation Framework to process raw data into meaningful
statistical summaries using multi-stage pipelines.
Savitribai Phule Pune University
Assignment No. 11
Title: Mini Project
Objective:
Software Required
This mini-project follows the Software Development Life Cycle (SDLC). The final report
must document the following phases in detail.
Problem Statement: Clearly define what the system does (e.g., "Library
Management System").
Functional Requirements: What features must the system have? (e.g., "Login",
"Add Book", "Issue Book").
Non-Functional Requirements: Performance, Security, Reliability.
Phase 4: Testing
Manual Testing: Manually execute test cases (e.g., "Enter invalid password ->
System should deny access").
Validation: Check if constraints (like unique emails or positive prices) are enforced
by the database.