DBMS Practical - College Management System, Fitness Tracking System, Restaurant System Query & Solution
DBMS Practical - College Management System, Fitness Tracking System, Restaurant System Query & Solution
Part A:
1) Create a stored procedure to get the average marks of a specific class.
DELIMITER //
CREATE PROCEDURE GetAverageClassMarks(IN classId VARCHAR(10))
BEGIN
SELECT c.class_name,
AVG(m.marks) AS average_marks
FROM Marks m
JOIN
Students s ON m.student_ID = s.student_ID
JOIN
Classes c ON s.class_ID = c.class_ID
WHERE s.class_ID = classId
GROUP BY
c.class_name; -- Add GROUP BY clause for the non-aggregated column
END //
DELIMITER ;
CALL GetAverageClassMarks('SE');
3)Display the student ID, Name, Class Name and Marks of a student having highest
Marks in given subject.
SELECT s.student_ID,
s.name AS student_name,
c.class_name, m.marks
FROM Students s
JOIN
Classes c ON s.class_ID = c.class_ID
JOIN
Marks m ON s.student_ID = m.student_ID
WHERE
m.subject_ID = 'SUB01' -- Specify the subject ID here
AND m.marks = (
SELECT MAX(marks)
FROM Marks
WHERE subject_ID = 'SUB01' -- Ensure the subject ID matches
);
4)List the names and dates of birth of all students born in the month of March.
5) Find the average marks for each subject across all students for a specific exam.
SELECT sub.subject_name,
AVG(m.marks) AS average_marks
FROM Marks m
JOIN
Subjects sub ON m.subject_ID = sub.subject_ID
WHERE
m.exam_name = 'Midterm' -- Specify the exam name you are interested in
GROUP BY sub.subject_name;
6)Write an SQL query to find the total number of students in each class.
SELECT c.class_name,
COUNT(s.student_ID) AS total_students
FROM Classes c
LEFT JOIN
Students s ON c.class_ID = s.class_ID
GROUP BY c.class_name;
SC1 Part B
1) Define a function to calculate the number of absent days for a given student in a
specific month.
DELIMITER //
CREATE FUNCTION CalculateAbsentDays (
studentID VARCHAR(20),
month1 varchar(20) )
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE absent int;
2) Combine a list of all students in class 'SE' who have scored more than 20 marks in
any subject.
4) Calculate the average attendance percentage for all students in class 'FY' for the
month of March.
SELECT AVG(a.No_Of_Days_Present) AS average_attendance_percentage
FROM
Attendance a
JOIN Students s on s.student_ID=a.student_ID
WHERE
s.class_ID = 'FY'
AND a.month='April';
5) List the names of students who have scored below 10 marks in any subject.
6) List the names of all students in the 'SE' class and their corresponding total marks
in the "Midterm" exam.
SELECT s.name,
SUM(m.marks) AS total_midterm_marks
FROM Students s
JOIN
Marks m ON s.student_ID = m.student_ID
WHERE m.class_ID = 'SE'
AND m.exam_name = 'Midterm'
GROUP BY
s.student_ID, s.name
ORDER BY
total_midterm_marks DESC;
SC1 Part C
SELECT
c.class_name,
COUNT(s.student_ID) AS number_of_students
FROM
Classes c
LEFT JOIN
Students s ON c.class_ID = s.class_ID
GROUP BY
c.class_name
ORDER BY
c.class_name;
3) Retrieve the names and student IDs of all students whose names begin with the
letter 'D'.
4) Write a query to find the total number of subjects offered in the school.
5)Create a trigger to insert the student name , old class id , new class id and timestamp
automatically in StudentClassHistory table when a student is moved to a different
class.
DELIMITER //
END IF;
END//
DELIMITER ;
6) Generate a combined list of the top 3 highest marks in the "Midterm" exam across
all subjects
SELECT
s.name AS student_name,
m.subject_ID,
sub.subject_name,
m.marks
FROM Marks m
JOIN
Students s ON m.student_ID = s.student_ID
JOIN
Subjects sub ON m.subject_ID = sub.subject_ID
WHERE
m.exam_name = 'Midterm'
ORDER BY m.marks DESC
LIMIT 3;
SC2) Imagine a popular mobile application called "Fitness Tracking" used by fitness enthusiasts in the city.
This application allows users to log their workouts, track their steps, monitor their heart rate, and set fitness
goals. The application uses a MySQL database to store user data. Entities are given below:
Part A
1) Find the total duration of workouts for each user.
SELECT
u.name AS user_name,
SUM(w.duration_in_minutes) AS total_workout_duration_minutes
FROM Users u
JOIN
Workouts w ON u.user_ID = w.user_ID
GROUP BY u.user_ID, u.name;
2) Create a stored procedure to retrieve all workouts for a specific user within a given
date range.
DELIMITER //
DELIMITER ;
SELECT
u.name AS User_Name,
COUNT(w.workout_ID) AS Total_Workouts
FROM Users u
LEFT JOIN
Workouts w ON u.user_ID = w.user_ID
GROUP BY u.user_ID, u.name
ORDER BY Total_Workouts DESC;
4) Create a view that shows a summary of each user's workouts. This should include
the user's name, workout type and total duration of all workouts.
5) Retrieve all users who have set a goal to lose weight (use the goal_type field to
identify weight loss goals).
SELECT u.user_ID,
u.name, u.email,
u.registration_date
FROM Users u
JOIN
Users_Goal ug ON u.user_ID = ug.user_ID
WHERE
ug.goal_type = 'Lose Weight';
SC2 Part B
1) Retrieve users who have a 'Improve Endurance' goal and have logged 'Running' or
'Cycling' workouts.
SELECT DISTINCT
u.user_ID, u.name, u.email
FROM Users u
JOIN
Users_Goal ug ON u.user_ID = ug.user_ID
JOIN
Workouts w ON u.user_ID = w.user_ID
WHERE
ug.goal_type = 'Improve Endurance'
AND w.workout_type IN ('Running', 'Cycling');
SELECT u.user_ID,
u.name AS User_Name,
AVG(s.step_count) AS Average_Daily_Steps
FROM Users u
LEFT JOIN
Steps s ON u.user_ID = s.user_ID
GROUP BY
u.user_ID, u.name
ORDER BY
Average_Daily_Steps DESC;
3) List users who logged a workout on a day they also tracked more than 8,000 steps.
SELECT DISTINCT
u.user_ID, u.name, u.email
FROM Users u
JOIN
Workouts w ON u.user_ID = w.user_ID
JOIN
Steps s ON u.user_ID = s.user_ID
WHERE
DATE(w.start_time) = s.tracking_date
AND s.step_count > 5000;
4)Create a view showing each user's name and the date of their most recent workout.
5) Create a Trigger to ensure that the end_time of a workout in the Workouts table is
always after the start_time.
DELIMITER //
DELIMITER ;
6) Identify users who have set a 'Lose Weight' goal and have logged more than 1
workouts.
2) Find all users who have set a specific fitness goal type ( 'Increase Flexibility").
SELECT DISTINCT
u.user_ID, u.name, u.email
FROM Users u
JOIN
Users_Goal ug ON u.user_ID = ug.user_ID
WHERE
ug.goal_type = 'Increase Flexibility';
4) Create a Function to calculate the total steps taken by a user within a specific date
range.
DELIMITER //
SELECT SUM(step_count)
INTO totalSteps
FROM Steps
WHERE user_ID = userId
AND tracking_date >= startDate
AND tracking_date <= endDate;
DELIMITER ;
5) Retrieve all workouts where the duration was greater than 60 minutes.
6) Retrieve all workout sessions performed by a specific user on a given date, including
the workout type, start time, and end time.
SELECT w.workout_type,
w.start_time, w.end_time
FROM Workouts w
WHERE
w.user_ID = 1 AND DATE(w.start_time) = '2025-04-11';
SC 2 Part D
SELECT DISTINCT
u.user_ID, u.name
FROM Users u
WHERE
u.user_ID IN (SELECT user_ID FROM Workouts WHERE DATE(start_time) = '2025-04-11')
OR u.user_ID IN (SELECT user_ID FROM Steps WHERE tracking_date = '2025-04-11');
SELECT g.goal_type,
COUNT(ug.user_ID) AS user_count
FROM Goals g
JOIN
Users_Goal ug ON g.goal_ID = ug.goal_ID
GROUP BY g.goal_type
ORDER BY user_count DESC
LIMIT 1;
4)Create a view to get a summary of each user's workouts, including their name, the
workout type, and the duration.
5) Create a cursor for the first three users listed in the Users table (based on their
user_ID), display their user_ID and name
mysql> CREATE PROCEDURE ListFirstThreeUsers()
-> BEGIN
-> -- Declare variables
-> DECLARE done INT DEFAULT FALSE;
-> DECLARE user_id_var INT;
-> DECLARE user_name_var VARCHAR(255);
-> DECLARE counter INT DEFAULT 0;
-> DECLARE limit_count INT DEFAULT 3;
->
-> -- Declare a cursor for the first three users
-> DECLARE user_cursor CURSOR FOR
-> SELECT user_ID, name
-> FROM Users
-> ORDER BY user_ID
-> LIMIT 3;
->
-> -- Declare handler for when the cursor is finished
-> DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
->
-> -- Open the cursor
-> OPEN user_cursor;
->
-> -- Loop through the first three users
-> user_loop: LOOP
-> FETCH user_cursor INTO user_id_var, user_name_var;
->
-> IF done THEN
-> LEAVE user_loop;
-> END IF;
->
-> -- Display the user ID and name
-> SELECT CONCAT('User ID: ', user_id_var, ', Name: ', user_name_var);
->
-> END LOOP user_loop;
->
-> -- Close the cursor
-> CLOSE user_cursor;
->
-> END //
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> DELIMITER ;
mysql> CALL ListFirstThreeUsers();
+-------------------------------------------------------------+
| CONCAT('User ID: ', user_id_var, ', Name: ', user_name_var) |
+-------------------------------------------------------------+
| User ID: 1, Name: PQR |
+-------------------------------------------------------------+
1 row in set (0.03 sec)
+-------------------------------------------------------------+
| CONCAT('User ID: ', user_id_var, ', Name: ', user_name_var) |
+-------------------------------------------------------------+
| User ID: 2, Name: ABC |
+-------------------------------------------------------------+
1 row in set (0.04 sec)
+-------------------------------------------------------------+
| CONCAT('User ID: ', user_id_var, ', Name: ', user_name_var) |
+-------------------------------------------------------------+
| User ID: 3, Name: XYZ |
+-------------------------------------------------------------+
1 row in set (0.04 sec)
SC3 Imagine a online restaurant needs a system to manage the menu, track customer orders and generate
sales reports. They use a MySQL database for this. Entities are as follows:
Menu: Stores details of all the items offered by the restaurant (item_ID, item_name, category,
price).
Customers: Stores information about registered customers (customer_ID, name, contact_number).
Orders: Records details of each order placed (order_ID, customer_ID, order_date_time).
OrderItems: Lists the individual items included in each order (order_ID, item_ID, quantity,
unit_price).
Part A
1)Find the total sales for each menu category.
SELECT m.category,
SUM(oi.quantity * oi.unit_price) AS total_sales
FROM Menu m
JOIN
OrderItems oi ON m.item_ID = oi.item_ID
GROUP BY m.category
ORDER BY total_sales DESC;
2) Create a stored procedure to retrieve the details of a specific order given its order
ID.
DELIMITER //
CREATE PROCEDURE GetOrderDetails(IN order_id_param INT)
BEGIN
SELECT o.order_ID, c.name AS customer_name,
c.contact_number AS customer_contact,
o.order_date_time, m.item_name, oi.quantity,
oi.unit_price, (oi.quantity * oi.unit_price) AS item_total
FROM Orders o
JOIN
Customers c ON o.customer_ID = c.customer_ID
JOIN
OrderItems oi ON o.order_ID = oi.order_ID
JOIN
Menu m ON oi.item_ID = m.item_ID
WHERE o.order_ID = order_id_param;
END //
DELIMITER ;
CALL GetOrderDetails(1);
SELECT m.item_name
FROM Menu m
LEFT JOIN OrderItems oi ON m.item_ID = oi.item_ID
WHERE oi.item_ID IS NULL;
SELECT o.order_ID,
c.name AS customer_name,
o.order_date_time
FROM Orders o
LEFT JOIN
Customers c ON o.customer_ID = c.customer_ID
WHERE
DATE(o.order_date_time) = CURDATE();
SC3 Part B
3)Create a view that shows the order ID, item name, quantity, and the total price for
each item in an order.
4) Find the names of customers who have placed orders containing items from both the
'Pizza' and 'Burgers' categories.
5)Find the menu items that have never been included in any order.
SELECT item_name
FROM Menu
WHERE item_ID NOT IN (SELECT DISTINCT item_ID FROM OrderItems WHERE item_ID IS NOT
NULL);
DELIMITER //
CREATE FUNCTION IsItemInCategory(item_name VARCHAR(255), category_name VARCHAR(100))
RETURNS VARCHAR(200)
DETERMINISTIC
BEGIN
DECLARE item_count INT;
SC3 Part C)
1) Create a stored procedure that takes an item name, category, and price as input and
inserts a new record into the Menu table.
DELIMITER //
CREATE PROCEDURE AddNewMenuItem (
IN item_name VARCHAR(255),
IN category VARCHAR(100),
IN price DECIMAL(10, 2)
)
BEGIN
-- Insert the new menu item into the Menu table
INSERT INTO Menu (item_name, category, price)
VALUES (item_name, category, price);
END //
DELIMITER ;
2) Find the highest and lowest price from the Menu table, along with the names of the
items.
SELECT
MAX(price) AS highest_price,
(SELECT item_name FROM Menu ORDER BY price DESC LIMIT 1) AS highest_price_item,
MIN(price) AS lowest_price,
(SELECT item_name FROM Menu ORDER BY price ASC LIMIT 1) AS lowest_price_item
FROM Menu;
SELECT category,
COUNT(*) AS number_of_items
FROM Menu
GROUP BY category;
SELECT
AVG(item_count) AS average_items_per_order
FROM ( SELECT order_ID,
COUNT(*) AS item_count
FROM OrderItems
GROUP BY order_ID ) AS items_per_order;
5)Create a view that summarizes the sales of each menu item, including the item name,
the total quantity sold, and the total revenue generated.
6)Get the names of all items in a specific order, given the order ID.
SELECT oi.item_name
FROM OrderItems oi
WHERE oi.order_ID = 1;
SC4 Imagine an online marketplace manages a vast inventory of Home appliances products, process
customer orders, and track the fulfillment process. They use a MySQL database to manage their products,
inventory, orders, and shipping information. Entities are listed below:
Products: Stores detailed information about each product listed on the platform (product_ID,
name, description, price, category_ID).
Categories: Lists the different product categories (category_ID, category_name).
Inventory: Tracks the stock levels for each product in their warehouse(s) (inventory_ID,
product_ID, warehouse_ID, quantity_in_stock, last_stock_update).
Warehouses: Lists the different warehouse locations (warehouse_ID, warehouse_name, address).
Orders: Records customer orders (order_ID, customer_ID, order_date, shipping_address,
order_status).
OrderItems: Lists the individual products included in each order (order_item_ID, order_ID,
product_ID, quantity_ordered, unit_price).
Shipments: Tracks the shipment details for each order (shipment_ID, order_ID, shipping_carrier,
tracking_number, shipment_date).
Part A
1) Find how many products are listed under each category.
SELECT c.category_name,
COUNT(p.product_ID) AS product_count
FROM Categories c
JOIN
Products p ON c.category_ID = p.category_ID
GROUP BY c.category_name
ORDER BY product_count DESC;
2) Create a stored procedure to retrieve the current stock level of a specific product in
a given warehouse.
DELIMITER //
CREATE PROCEDURE GetProductStockLevel (
IN p_id INT, IN wr_id INT )
BEGIN
SELECT quantity_in_stock
FROM Inventory
WHERE p_ID = product_id AND wr_ID = warehouse_id;
END //
DELIMITER ;
3) Retrieve a list of all orders along with the names of the products ordered in each
order.
SELECT o.order_ID,
o.order_date, o.customer_ID,
GROUP_CONCAT(p.name SEPARATOR ', ') AS products_ordered
FROM Orders o
JOIN
OrderItems oi ON o.order_ID = oi.order_ID
JOIN
Products p ON oi.product_ID = p.product_ID
GROUP BY
o.order_ID, o.order_date, o.customer_ID
ORDER BY o.order_ID;
4) Create a view to show products with low stock (less than 10 units total)
5)Count how many orders exist in each status (e.g., Pending, Shipped, Delivered).
SELECT order_status,
COUNT(*) AS order_count
FROM Orders
GROUP BY order_status
ORDER BY order_count DESC;
1) Find the total quantity in stock for each product across all warehouses.
SELECT p.product_ID,
p.name, SUM(i.quantity_in_stock) AS total_quantity_in_stock
FROM Products p
JOIN
Inventory i ON p.product_ID = i.product_ID
GROUP BY p.product_ID, p.name
ORDER BY total_quantity_in_stock DESC;
3) Combine a list of products in the 'Refrigerators' category and a list of products that
have a price greater than 1000.
SELECT product_ID, name, price
FROM Products
WHERE category_ID = (SELECT category_ID FROM Categories WHERE category_name =
'Refrigerators')
UNION
SELECT product_ID, name, price
FROM Products
WHERE price > 700;
4) Create a cursor to loop through products and display their total stock.
DELIMITER //
CREATE PROCEDURE DisplayProductStock()
BEGIN
DECLARE product_id INT;
DECLARE product_name VARCHAR(255);
DECLARE total_stock INT;
DECLARE done INT DEFAULT FALSE;
OPEN product_cursor;
read_loop: LOOP
FETCH product_cursor INTO product_id, product_name;
IF done THEN
LEAVE read_loop;
END IF;
CLOSE product_cursor;
END //
DELIMITER ;
CALL DisplayProductStock();
6) Calculate the total sales for each product based on the quantity ordered and unit
price.
SELECT p.product_ID,
p.name AS product_name,
SUM(oi.quantity_ordered * oi.unit_price) AS total_sales
FROM Products p
JOIN
OrderItems oi ON p.product_ID = oi.product_ID
GROUP BY p.product_ID, p.name
ORDER BY total_sales DESC;
SC 4 Part C)
// Additional enteries
INSERT INTO Shipments (shipment_ID, order_ID, shipping_carrier, tracking_number, shipment_date)
VALUES
(4, 1004, 'FedEx', '1234567893', '2023-01-22');
3) Create a trigger to prevent orders from being created if the quantity of products
ordered exceeds the quantity in stock.
DELIMITER //
CREATE TRIGGER prevent_order_exceed_stock
BEFORE INSERT ON OrderItems
FOR EACH ROW
BEGIN
DECLARE available_stock INT;
SELECT quantity_in_stock INTO available_stock
FROM Inventory
WHERE product_ID = NEW.product_ID;
IF NEW.quantity_ordered > available_stock THEN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Insufficient stock available for this product.';
END IF;
END //
DELIMITER ;
4) Create a view to display the product name, current quantity in stock, and the name
of the warehouse for all products.
SELECT product_ID,
AVG(quantity_ordered) AS average_quantity
FROM OrderItems
GROUP BY product_ID;
SC4 Part D
1)Define a function to check if a product is currently out of stock (total quantity across
all warehouses is zero).
DELIMITER //
CREATE FUNCTION IsProductOutOfStock(product_id INT) RETURNS VARCHAR(20)
DETERMINISTIC
BEGIN
DECLARE total_stock INT;
IF total_stock = 0 THEN
RETURN 'Out of Stock';
ELSE
RETURN 'Available';
END IF;
END //
DELIMITER ;
SELECT IsProductOutOfStock(101);
SELECT c.category_name,
SUM(oi.quantity_ordered * oi.unit_price) AS total_sales
FROM Categories c
JOIN
Products p ON c.category_ID = p.category_ID
JOIN
OrderItems oi ON p.product_ID = oi.product_ID
GROUP BY c.category_name;
DELIMITER //
CREATE TRIGGER decrease_stock_on_order
AFTER INSERT ON OrderItems
FOR EACH ROW
BEGIN
UPDATE Inventory
SET quantity_in_stock = quantity_in_stock - NEW.quantity_ordered
WHERE product_ID = NEW.product_ID;
END //
DELIMITER ;
4)Combine a list of products in the 'Washing Machines' category and a list of products
that have a price greater than 900.