0% found this document useful (0 votes)
36 views37 pages

DBMS LAB Manual

Uploaded by

goturi sohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views37 pages

DBMS LAB Manual

Uploaded by

goturi sohan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

DBMS LAB manual

K.samuel Edward
23WU0101082
Panthers CSE

1.Identification of Attributes
Let's assume a scenario: We are designing a database for an online bookstore.

Attributes for Books table: BookID , Title , Author , Genre , Price , PublishedDate .

1.Basic SQL CRUD Operations


a. Create Database

CREATE DATABASE OnlineBookstore;

Output: A new database named OnlineBookstore is created.


b. Create Table

CREATE TABLE Books (


BookID INT PRIMARY KEY,
Title VARCHAR(100),
Author VARCHAR(100),
Genre VARCHAR(50),
Price DECIMAL(5, 2),
PublishedDate DATE
);

Output: A table named Books is created with the specified columns.


c. Insert Data into Table

INSERT INTO Books (BookID, Title, Author, Genre, Price, PublishedDate)


VALUES (1, 'The Great Gatsby', 'F. Scott Fitzgerald', 'Fiction', 10.99, '1925-04-10');

Output: One record is inserted into the Books table.

DBMS LAB manual 1


d. Fetch Data from Table

SELECT * FROM Books;

Output:

e. Update Records in Table

UPDATE Books
SET Price = 12.99
WHERE BookID = 1;
Output: The price of The Great Gatsby is updated to 12.99.
f. Delete Table and Database

DROP TABLE Books;


DROP DATABASE OnlineBookstore;
Output: The Books table and OnlineBookstore database are deleted.
1.More SQL Queries
a. Select DISTINCT

SELECT DISTINCT Genre FROM Books;


Output: Returns unique genres from the Books table.
b. WHERE with AND, OR, NOT

SELECT * FROM Books


WHERE Genre = 'Fiction' AND Price < 15;
Output: Returns all fiction books priced below 15.
c. WHERE with BETWEEN

SELECT * FROM Books


WHERE PublishedDate BETWEEN '1920-01-01' AND '1930-12-31';
DBMS LAB manual 2
Output: Returns books published between 1920 and 1930.
d. ORDER BY ASC|DESC

SELECT * FROM Books


ORDER BY Price DESC;
Output: Returns all books sorted by price in descending order.
1.ALTER Table and Applying Constraints
a. Add AUTO_INCREMENT

ALTER TABLE Books


MODIFY BookID INT AUTO_INCREMENT;
Output: The BookID column is now auto-incremented.
b. Add NOT NULL Constraint

ALTER TABLE Books


MODIFY Title VARCHAR(100) NOT NULL;
Output: The Title column cannot have NULL values.
c. Add UNIQUE Constraint

ALTER TABLE Books


ADD CONSTRAINT unique_author UNIQUE (Author);
Output: The Author column must have unique values.
d. PRIMARY KEY Constraint

ALTER TABLE Books


ADD PRIMARY KEY (BookID);
Output: BookID is set as the primary key.
1.JOINS and Aliases
a. INNER JOIN Example

SELECT Orders.OrderID, Books.Title


FROM Orders
DBMS LAB manual 3
INNER JOIN Books ON Orders.BookID = Books.BookID;
Output: Returns a list of orders with the corresponding book titles.
1.GROUP BY and HAVING
Example: GROUP BY with HAVING

SELECT Genre, COUNT(*) AS TotalBooks


FROM Books
GROUP BY Genre
HAVING COUNT(*) > 5;
Output: Returns genres with more than 5 books.
1.Creating Views

CREATE VIEW FictionBooks AS


SELECT * FROM Books WHERE Genre = 'Fiction';
Output: A view named FictionBooks is created.
1.Scenario-based Questions on MySQL
Assume a scenario: A Customer table is added to manage customer details in
an e-commerce system.
Customer Table:

CREATE TABLE Customers (


CustomerID INT AUTO_INCREMENT PRIMARY KEY,
Name VARCHAR(100) NOT NULL,
Email VARCHAR(100) UNIQUE,
Phone VARCHAR(15),
RegistrationDate DATE DEFAULT CURRENT_DATE
);
Output: Table Customers is created with specified columns and constraints.
1.Introduction to MongoDB and CRUD Operations
MongoDB commands use a different syntax compared to SQL.
a. Create Database
DBMS LAB manual 4
use OnlineStore;
Output: Switched to the OnlineStore database.
b. Create Collection

db.createCollection("Products");
Output: Products collection is created.
c. InsertOne and InsertMany

db.Products.insertOne({ ProductID: 1, Name: "Laptop", Price: 999.99, St


ock: 50 });
db.Products.insertMany([
{ ProductID: 2, Name: "Phone", Price: 599.99, Stock: 100 },
{ ProductID: 3, Name: "Tablet", Price: 299.99, Stock: 75 }
]);
Output: One document inserted with insertOne ; multiple documents inserted

with insertMany . d. Find and FindOne

db.Products.find();
db.Products.findOne({ Name: "Laptop" });
Output: Returns all products for find() ; returns the first matching document for findOne() .

e. UpdateOne and UpdateMany

db.Products.updateOne({ Name: "Laptop" }, { $set: { Price: 899.99 } });


db.Products.updateMany({ Stock: { $lt: 50 } }, { $inc: { Stock:
20 } });
Output: Updates price for Laptop; increments stock for all products with

stock less than 50. f. DeleteOne and DeleteMany

db.Products.deleteOne({ Name: "Tablet" });


db.Products.deleteMany({ Stock: 0 });
Output: Deletes one product named Tablet; deletes all products with stock equal to 0.
1.MongoDB Query Operators
DBMS LAB manual 5
Example using $gt (greater than) and $lt (less than):

db.Products.find({ Price: { $gt: 500, $lt: 1000 } });


Output: Returns all products priced between 500 and 1000.
1.MongoDB Update Operations
a. Update Fields

db.Products.updateOne({ Name: "Phone" }, { $set: { Warranty: "2 years"


} });
Output: Adds or updates the Warranty field for Phone.
b. Update Array Field

db.Products.updateOne({ Name: "Laptop" }, { $push: { Reviews:


"Excellen t performance" } });
Output: Adds a review to the Laptop document.
1.MongoDB Aggregations
a. GROUP Example

db.Products.aggregate([
{ $group: { _id: "$Name", TotalStock: { $sum: "$Stock" } } }
]);
Output: Groups products by Name and calculates the total stock.
b. LIMIT Example

db.Products.find().limit(2);
Output: Returns only the first two products.
c. PROJECT Example

db.Products.find({}, { Name: 1, Price: 1 });


Output: Returns only the Name and Price fields of each document.
d. SORT Example
DBMS LAB manual 6
db.Products.find().sort({ Price: -1 });
Output: Sorts products by Price in descending order.
e. MATCH Example

db.Products.aggregate([{ $match: { Price: { $gt: 500 } } }]);


Output: Filters documents with price greater than 500.
f. COUNT Example

db.Products.countDocuments();
Output: Returns the total number of documents in the Products collection.
g. LOOKUP Example

db.Orders.aggregate([
{
$lookup: {
from: "Customers",
localField: "CustomerID",
foreignField: "CustomerID",
as: "CustomerDetails"
}
}
]);
Output: Performs a join between Orders and Customers collections.
h. OUT Example

db.Products.aggregate([
{ $match: { Stock: { $gt: 50 } } },
{ $out: "HighStockProducts" }
]);
Output: Saves the result of the aggregation into a new collection HighStockProducts.
i. ADDFIELDS Example
db.Products.aggregate([
{ $addFields: { DiscountedPrice: { $subtract: ["$Price", 100] } } }
DBMS LAB manual 7
]);
Output: Adds a new field DiscountedPrice to each product.
1.Search and Index in MongoDB
Creating an Index Example:

db.Products.createIndex({ Name: "text" });


Output: Creates a text index on the Name field.
Text Search Example:

db.Products.find({ $text: { $search: "Laptop" } });


Output: Returns documents that contain the word Laptop in the indexed text fields.
This covers all the questions up to question 13 as specified in your lab
manual. If you need additional details or more examples, feel free to ask!

Query Based Questions


1.SQL Joins
Joins are used to retrieve data from multiple tables based on a related
column. Below are the common types of joins with examples.
Example Tables:
Employees Table:

Departments Table:

DBMS LAB manual 8


a. INNER JOIN

SELECT Employees.Name,
Departments.DepartmentName FROM Employees
INNER JOIN Departments ON Employees.DepartmentID =
Departments.Departme ntID;
Output:

Explanation: Returns only the rows where there is a match in both tables.
b. LEFT JOIN

SELECT Employees.Name,
Departments.DepartmentName FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID =
Departments.Departmen tID;
Output:

Explanation: Returns all rows from the left table (Employees), and matched
rows from the right table (Departments). If no match is found, NULL is returned.

c. RIGHT JOIN
DBMS LAB manual 9
SELECT Employees.Name,
Departments.DepartmentName FROM Employees
RIGHT JOIN Departments ON Employees.DepartmentID =
Departments.Departme ntID;
Output:

Explanation: Returns all rows from the right table (Departments), and
matched rows from the left table (Employees). If no match is found, NULL is returned.

d. FULL OUTER JOIN

SELECT Employees.Name,
Departments.DepartmentName FROM Employees
FULL OUTER JOIN Departments ON Employees.DepartmentID =
Departments.Dep artmentID;
Output:

Explanation: Returns all rows when there is a match in either table. If there is
no match, NULL is returned for the unmatched rows.

e. CROSS JOIN
SELECT Employees.Name, Departments.DepartmentName
FROM Employees
CROSS JOIN Departments;
DBMS LAB manual 10
Output:

Explanation: Returns the Cartesian product of both tables, i.e., all possible
combinations of rows.
1.Normalization and Normal Forms
Normalization is the process of organizing data to reduce redundancy
and improve data integrity. Here are the normal forms with examples:
a. First Normal Form (1NF)
Rule: Each column must contain atomic (indivisible) values.
Example:
Before 1NF:

Explanation: The "Subjects" column is split into separate rows.


b. Second Normal Form (2NF)
DBMS LAB manual 11
Rule: The table must be in 1NF and all non-key attributes must be fully
functionally dependent on the primary key.
Example:
Before 2NF:

Explanation: The table is split to eliminate partial dependency.


c. Third Normal Form (3NF)
Rule: The table must be in 2NF and have no transitive dependencies.
Example:
Before 3NF:

Explanation: The transitive dependency between CourseID and Department is removed.

DBMS LAB manual 12


d. Boyce-Codd Normal Form (BCNF)
Rule: The table must be in 3NF, and for every functional dependency, the
left-hand side must be a superkey.
Example:

e. Fourth Normal Form (4NF)


Rule: The table must be in BCNF and have no multivalued dependencies.
Example:

Explanation: Removes multivalued dependencies.


Summary
1NF: No repeating groups, atomic values.
2NF: No partial dependencies.
3NF: No transitive dependencies.
BCNF: Every determinant must be a superkey.
4NF: No multivalued dependencies.
These examples and explanations should help clarify joins and normal
forms with their corresponding SQL queries and outputs. Let me know if you
need further details!
DBMS LAB manual 13
1. SQL Joins
We have already covered various types of joins in SQL. Here’s a recap
with examples and additional explanations:
a. INNER JOIN

SELECT Employees.Name,
Departments.DepartmentName FROM Employees
INNER JOIN Departments ON Employees.DepartmentID =
Departments.Departme ntID;
Output:
| Name | DepartmentName |
|--------------|----------------|
| John Smith | Sales |
| Jane Doe | HR |
| Peter Parker | IT |
Explanation: Returns rows with matching values in both tables.
b. LEFT JOIN

SELECT Employees.Name,
Departments.DepartmentName FROM Employees
LEFT JOIN Departments ON Employees.DepartmentID =
Departments.Departmen tID;
Output:
| Name | DepartmentName |
|--------------|----------------|
| John Smith | Sales |
| Jane Doe | HR |
| Mary Jane | NULL |
| Peter Parker | IT |
Explanation: Returns all records from the left table \Employees), and
matched records from the right table \Departments). Unmatched records have NULL
values.

c. RIGHT JOIN

SELECT Employees.Name,
Departments.DepartmentName FROM Employees
DBMS LAB manual 14
RIGHT JOIN Departments ON Employees.DepartmentID =
Departments.Departme ntID;
Output:
| Name | DepartmentName |
|--------------|----------------|
| John Smith | Sales |
| Jane Doe | HR |
| Peter Parker | IT |
| NULL | Marketing |
d. FULL OUTER JOIN

SELECT Employees.Name,
Departments.DepartmentName FROM Employees
FULL OUTER JOIN Departments ON Employees.DepartmentID =
Departments.Dep artmentID;
Output:
| Name | DepartmentName |
|--------------|----------------|
| John Smith | Sales |
| Jane Doe | HR |
| Peter Parker | IT |
| Mary Jane | NULL |
| NULL | Marketing |
2. Normalization
First Normal Form (1NF)
Example Before 1NF:
| StudentID | Name | Courses |

DBMS LAB manual 15


Second Normal Form (2NF)
Example Before 2NF:
| StudentID | CourseID | CourseName | Professor |
|-----------|----------|------------|------------|
| 1 | C101 | Math | Prof. Lee |
After 2NF:
1. Student-Course
Table: | StudentID |
CourseID |
|-----------|----------|
|1|C101|
1.Course Table:
| CourseID | CourseName | Professor |
|----------|------------|------------|
| C101 | Math | Prof. Lee |
Third Normal Form (3NF)
Example:
| CourseID | CourseName | Professor | Department |
|----------|------------|------------|------------|
| C101 | Math | Prof. Lee | Mathematics|
After 3NF:
1.Course Table:
| CourseID | CourseName | Professor |
|----------|------------|------------|
| C101 | Math | Prof. Lee |
2. Professor Table:
| Professor | Department |
|------------|-------------|
| Prof. Lee | Mathematics |
3. Functional Dependencies and Normal Forms
Trivial Dependency Example:

EmpID → EmpName, Department


This is trivial because knowing EmpID determines all attributes.
Non-trivial Dependency Example:
DBMS LAB manual 16
CourseID → CourseName
Partial Dependency Example \Violated in 2NF\:

Department → DeptHead
1.Stored Procedure

Example Create a Stored

Procedure:

CREATE PROCEDURE GetEmployeeDetails


@EmployeeID INT
AS
BEGIN
SELECT *
FROM Employees
WHERE EmployeeID = @EmployeeID;
END;
Execute the Procedure:

EXEC GetEmployeeDetails @EmployeeID = 1;


Output:
| EmployeeID | Name | Department | Salary |
|------------|------------|------------|--------|
| 1 | John Smith | HR | 50000 |
1.Temporal Data

Example Schema for

Temporal Data:
CREATE TABLE EmployeeSalary (
EmployeeID INT,
Salary DECIMAL(10, 2),
StartDate DATE,
EndDate DATE
);
DBMS LAB manual 17
Insert Data:

INSERT INTO EmployeeSalary (EmployeeID, Salary, StartDate, EndDate)


VALUES (101, 50000, '2020-01-01', '2021-06-30');
1.MongoDB

Examples Insert

and Query:

db.Products.insertOne({ ProductID: 1, Name: "Laptop", Price: 999.99 });


db.Products.find({ Price: { $gt: 500 } });
Output: Returns all products with price greater than 500.
Update Example:

db.Products.updateOne({ ProductID: 1 }, { $set: { Price: 899.99 } });


1.Views in

SQL Create a

View:

CREATE VIEW IT_Employees AS


SELECT EmployeeID, Name, Salary
FROM Employees
WHERE Department = 'IT';
Query the View:

SELECT * FROM IT_Employees;


Output:
| EmployeeID | Name | Salary |

8. B-Tree and Hashing


Example of a B-Tree Search:
Inserting values 10, 20, 30 into a B-tree of order 3.
DBMS LAB manual 18
Hashing Example:

h(key) = key % 10
Hash Table Example:

1.SQL Query Operators (LIKE, GROUP BY, HAVING)

Examples LIKE Example:

SELECT * FROM Customers WHERE CustomerName LIKE 'John%';


GROUP BY Example:

SELECT Country, COUNT(*) FROM Customers GROUP BY Country;


HAVING Example:

SELECT Country, COUNT(*) FROM Customers GROUP BY Country HAVING COUNT


1.
( > 1;
1.Example of MongoDB Aggregation

db.Products.aggregate([{ $group: { _id: "$Category", Total: { $sum: "$P


rice" } } }]);
Output: Groups products by category and calculates the total price.
DBMS LAB manual 19
Problem Based questions
Problem 1: Create Two Tables ( Students and Faculty )

and Insert Data Solution:

CREATE TABLE Faculty (


FacultyID INT PRIMARY KEY,
FacultyName VARCHAR(100),
Department VARCHAR(50)
);
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
DateOfBirth DATE,
FacultyID INT,
FOREIGN KEY (FacultyID) REFERENCES Faculty(FacultyID)
);
-- Inserting data into Faculty table
INSERT INTO Faculty (FacultyID, FacultyName, Department)
VALUES (1, 'Dr. Smith', 'Computer Science'),
(2, 'Dr. Johnson', 'Mathematics');
-- Inserting data into Students table
INSERT INTO Students (StudentID, FirstName, LastName, DateOfBirth,
Facu ltyID)
VALUES (1, 'John', 'Doe', '2000-01-15',
1), (2, 'Jane', 'Smith', '1999-06-22', 2), (3, 'Alice',
'Johnson', '2001-03-10', 1), (4, 'Michael', 'Brown',
'2002-07-15', 1), (5, 'Emily', 'Davis', '2001-12-03',
2), (6, 'Daniel', 'Wilson', '2000-09-25', 1);
- Query to check data in Faculty table
SELECT * FROM Faculty;
DBMS LAB manual 20
- Query to check data in Students table
SELECT * FROM Students;
Expected Output:
Faculty Table:
| FacultyID | FacultyName | Department |
|-----------|-------------|------------------|
| 1 | Dr. Smith | Computer Science |
| 2 | Dr. Johnson | Mathematics |
Students Table:
| StudentID | FirstName | LastName | DateOfBirth | FacultyID |

Problem 2: Using Different Types of Joins


a. INNER JOIN Example

SELECT Students.FirstName, Faculty.FacultyName


FROM Students
INNER JOIN Faculty ON Students.FacultyID = Faculty.FacultyID;
Expected Output:

b. LEFT JOIN Example

SELECT Students.FirstName, Faculty.FacultyName


FROM Students
LEFT JOIN Faculty ON Students.FacultyID = Faculty.FacultyID;
Expected Output:

FacultyName
irstName
DBMS LAB manual 21
Problem 3: Aggregate Functions with

Employees Table Solution:

CREATE TABLE Employees (


EmployeeID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Salary DECIMAL(10, 2),
HireDate DATE
);
-- Inserting data
INSERT INTO Employees (EmployeeID, FirstName, LastName, Salary,
HireDat e)
VALUES (1, 'John', 'Doe', 50000, '2020-01-15'),
(2, 'Jane', 'Smith', 60000, '2019-06-22'),
(3, 'Alice', 'Johnson', 55000, '2021-03-10'),
(4, 'Bob', 'Brown', 70000, '2018-08-30'),
(5, 'Charlie', 'Davis', 65000, '2020-11-05');
-- Aggregate functions
SELECT MIN(Salary) AS MinimumSalary FROM
Employees; SELECT MAX(Salary) AS MaximumSalary FROM
Employees; SELECT AVG(Salary) AS AverageSalary FROM
Employees; SELECT SUM(Salary) AS TotalSalary FROM
Employees; SELECT COUNT(*) AS NumberOfEmployees FROM
Employees;
Expected Output:
Minimum Salary: 50000
Maximum Salary: 70000
Average Salary: 60000
DBMS LAB manual 22
Total Salary: 300000
Number of Employees: 5
Problem 4: Normalization Example
Convert the given table into 2NF:
Original Table:

After Normalization:
1. Student-Course
Table: | StudentID |
CourseID |
|-----------|----------| |1|
C101|
2.Course Table:
| CourseID |
CourseName | Professor |
|----------|------------|------------|
| C101 | Math | Prof. Lee |
Problem 5: MongoDB CRUD Operations
a. Create Database and Collection

use OnlineStore;
db.createCollection("Products");
b. Insert Documents

db.Products.insertMany([
{ ProductID: 1, Name: "Laptop", Price: 999.99 },
{ ProductID: 2, Name: "Phone", Price: 599.99 },
{ ProductID: 3, Name: "Tablet", Price: 299.99 }
]);
c. Query Documents
DBMS LAB manual 23
db.Products.find({ Price: { $gt: 500 } });
Expected Output:

d. Update Document

db.Products.updateOne({ ProductID: 1 }, { $set: { Price: 899.99 } });


e. Delete Document

db.Products.deleteOne({ ProductID: 3 });


Problem 6: Stored Procedure Example
SQL Code:

CREATE PROCEDURE GetHighSalaryEmployees()


BEGIN
SELECT FirstName, LastName, Salary
FROM Employees
WHERE Salary > 60000;
END;
-- Execute the procedure
CALL GetHighSalaryEmployees();
Expected Output:

DBMS LAB manual 24

You might also like