0% found this document useful (0 votes)
9 views

DBMS Practical

Uploaded by

rahulpowar6666
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
9 views

DBMS Practical

Uploaded by

rahulpowar6666
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 39

PRACTICAL 1

mysql> use employee

Database changed

/*CREATE TABLE*/

mysql> create Table departments(dept_id int not null primary key, department_name varchar(255));

mysql> create Table emp(id int not null primary key, firstname varchar(255), lastname varchar(255),
dept_id int, salary int, hiredate date, FOREIGN KEY(dept_id) REFERENCES departments (dept_id));

/*INSERT VALUES*/

mysql> INSERT INTO departments values(10, 'IT'), (11, 'HR'), (12, 'Designer');

mysql> INSERT INTO emp VALUES (101, 'Raj','Sharma', 10, 25000, '2024-08-07'), (102,
'Rahul','Bhosale', 10, 20000, '2022-08-07'), (111, 'Om','Birla', 11, 30000, '2022-06-05'), (112,
'Harsh','Bhandare', 11, 35000, '2022-06-12'), (121, 'Sanjay','Sharma', 12, 32000, '2020-12-12'),
(122,'Raj','Bhingare', 12, 32500, '2023-08-07');

/*DISPLAY*/

mysql> SELECT * FROM emp;

+-----+-----------+----------+---------+--------+------------+

| id | firstname | lastname | dept_id | salary | hiredate |

+-----+-----------+----------+---------+--------+------------+

| 101 | Raj | Sharma | 10 | 25000 | 2024-08-07 |

| 102 | Rahul | Bhosale | 10 | 20000 | 2022-08-07 |

| 111 | Om | Birla | 11 | 30000 | 2022-06-05 |

| 112 | Harsh | Bhandare | 11 | 35000 | 2022-06-12 |

| 121 | Sanjay | Sharma | 12 | 32000 | 2020-12-12 |

| 122 | Raj | Bhingare | 12 | 32500 | 2023-08-07 |

+-----+-----------+----------+---------+--------+------------+

mysql> SELECT * FROM departments;

+---------+-----------------+

| dept_id | department_name |

+---------+-----------------+

| 10 | IT |

| 11 | HR |

| 12 | Designer |

+---------+-----------------+
/*ALTER TABLE*/

mysql> ALTER TABLE emp RENAME COLUMN firstname to first_name;

mysql> SELECT * FROM emp;

+-----+------------+----------+---------+--------+------------+

| id | first_name | lastname | dept_id | salary | hiredate |

+-----+------------+----------+---------+--------+------------+

| 101 | Raj | Sharma | 10 | 25000 | 2024-08-07 |

| 102 | Rahul | Bhosale | 10 | 20000 | 2022-08-07 |

| 111 | Om | Birla | 11 | 30000 | 2022-06-05 |

| 112 | Harsh | Bhandare | 11 | 35000 | 2022-06-12 |

| 121 | Sanjay | Sharma | 12 | 32000 | 2020-12-12 |

| 122 | Raj | Bhingare | 12 | 32500 | 2023-08-07 |

+-----+------------+----------+---------+--------+------------+

/*WHERE CONDITION*/

mysql> SELECT * FROM emp WHERE dept_id=10;

+-----+------------+----------+---------+--------+------------+

| id | first_name | lastname | dept_id | salary | hiredate |

+-----+------------+----------+---------+--------+------------+

| 101 | Raj | Sharma | 10 | 25000 | 2024-08-07 |

| 102 | Rahul | Bhosale | 10 | 20000 | 2022-08-07 |

+-----+------------+----------+---------+--------+------------+

/*ORDER BY ASCENDING AND DESCENDING */

mysql> SELECT * FROM emp ORDER BY salary;

+-----+------------+----------+---------+--------+------------+

| id | first_name | lastname | dept_id | salary | hiredate |

+-----+------------+----------+---------+--------+------------+

| 102 | Rahul | Bhosale | 10 | 20000 | 2022-08-07 |

| 101 | Raj | Sharma | 10 | 25000 | 2024-08-07 |

| 111 | Om | Birla | 11 | 30000 | 2022-06-05 |

| 121 | Sanjay | Sharma | 12 | 32000 | 2020-12-12 |

| 122 | Raj | Bhingare | 12 | 32500 | 2023-08-07 |


| 112 | Harsh | Bhandare | 11 | 35000 | 2022-06-12 |

+-----+------------+----------+---------+--------+------------+

mysql> SELECT * FROM emp ORDER BY salary DESC;

+-----+------------+----------+---------+--------+------------+

| id | first_name | lastname | dept_id | salary | hiredate |

+-----+------------+----------+---------+--------+------------+

| 112 | Harsh | Bhandare | 11 | 35000 | 2022-06-12 |

| 122 | Raj | Bhingare | 12 | 32500 | 2023-08-07 |

| 121 | Sanjay | Sharma | 12 | 32000 | 2020-12-12 |

| 111 | Om | Birla | 11 | 30000 | 2022-06-05 |

| 101 | Raj | Sharma | 10 | 25000 | 2024-08-07 |

| 102 | Rahul | Bhosale | 10 | 20000 | 2022-08-07 |

+-----+------------+----------+---------+--------+------------+

/*UPDATE INFO*/

mysql> UPDATE emp SET first_name = 'Alice' WHERE id = 111;

mysql> SELECT * FROM emp;

+-----+------------+----------+---------+--------+------------+

| id | first_name | lastname | dept_id | salary | hiredate |

+-----+------------+----------+---------+--------+------------+

| 101 | Raj | Sharma | 10 | 25000 | 2024-08-07 |

| 102 | Rahul | Bhosale | 10 | 20000 | 2022-08-07 |

| 111 | Alice | Birla | 11 | 30000 | 2022-06-05 |

| 112 | Harsh | Bhandare | 11 | 35000 | 2022-06-12 |

| 121 | Sanjay | Sharma | 12 | 32000 | 2020-12-12 |

| 122 | Raj | Bhingare | 12 | 32500 | 2023-08-07 |

+-----+------------+----------+---------+--------+------------+

/*MODIFY DATA TYPE*/

mysql> ALTER TABLE emp MODIFY COLUMN salary varchar(255);

Query OK, 6 rows affected (0.05 sec)


mysql> DESC EMP;

+------------+--------------+------+-----+---------+-------+

| Field | Type | Null | Key | Default | Extra |

+------------+--------------+------+-----+---------+-------+

| id | int | NO | PRI | NULL | |

| first_name | varchar(255) | YES | | NULL | |

| lastname | varchar(255) | YES | | NULL | |

| dept_id | int | YES | MUL | NULL | |

| salary | varchar(255) | YES | | NULL | |

| hiredate | date | YES | | NULL | |

+------------+--------------+------+-----+---------+-------+

/*LIMIT TOP 2*/

mysql> SELECT * FROM emp LIMIT 2;

+-----+------------+----------+---------+--------+------------+

| id | first_name | lastname | dept_id | salary | hiredate |

+-----+------------+----------+---------+--------+------------+

| 101 | Raj | Sharma | 10 | 25000 | 2024-08-07 |

| 102 | Rahul | Bhosale | 10 | 20000 | 2022-08-07 |

+-----+------------+----------+---------+--------+------------+
PRACTICAL – 2
mysql> use dbms

Database changed

/*CREATE TABLE*/

mysql> create table Products(ProductID INT PRIMARY KEY, ProductName VARCHAR(255) NOT NULL,
Category VARCHAR(255), Price DECIMAL(10, 2), StockQuantity INT);

mysql> CREATE TABLE Orders (OrderID INT PRIMARY KEY, OrderDate DATE );

mysql> CREATE TABLE OrderItems (OrderItemID INT PRIMARY KEY, OrderID INT, ProductID INT,
Quantity INT, FOREIGN KEY (OrderID) REFERENCES Orders(OrderID), FOREIGN KEY (ProductID)
REFERENCES Products(ProductID) );

/*INSERT VALUES*/

mysql> INSERT INTO Products VALUES ((1, 'Laptop', 'Electronics', 1500, 100), (2, 'Smartphone',
'Electronics', 800, 200), (3, 'Headphones', 'Accessories', 150, 300), (4, 'Monitor', 'Electronics', 300,
50), (5, 'Keyboard', 'Accessories', 50, 150));

mysql> INSERT INTO Orders VALUES ((1, '2024-08-25'), (2, '2024-08-26'), (3, '2024-08-27'));

mysql> INSERT INTO OrderItems VALUES ((1, 1, 1, 2), (2, 1, 3, 5), (3, 2, 2, 1), (4, 2, 4, 2), (5, 3, 5,
10));

/*DISPLAY*/

mysql> SELECT * FROM Products;

+-----------+-------------+-------------+---------+---------------+

| ProductID | ProductName | Category | Price | StockQuantity |

+-----------+-------------+-------------+---------+---------------+

| 1 | Laptop | Electronics | 1500.00 | 100 |

| 2 | Smartphone | Electronics | 800.00 | 200 |

| 3 | Headphones | Accessories | 150.00 | 300 |

| 4 | Monitor | Electronics | 300.00 | 50 |

| 5 | Keyboard | Accessories | 50.00 | 150 |

+-----------+-------------+-------------+---------+---------------+
mysql> SELECT * FROM Orders;

+---------+------------+

| OrderID | OrderDate |

+---------+------------+

| 1 | 2024-08-25 |

| 2 | 2024-08-26 |

| 3 | 2024-08-27 |

+---------+------------+

mysql> SELECT * FROM OrderItems;

+-------------+---------+-----------+----------+

| OrderItemID | OrderID | ProductID | Quantity |

+-------------+---------+-----------+----------+

| 1| 1| 1| 2|

| 2| 1| 3| 5|

| 3| 2| 2| 1|

| 4| 2| 4| 2|

| 5| 3| 5| 10 |

+-------------+---------+-----------+----------+

/*UPDATE CREATE DELETE*/

mysql> UPDATE Products

-> SET Price = 1600

-> WHERE ProductID = 1;

Query OK, 1 row affected (0.01 sec)

mysql> INSERT INTO Products (ProductID, ProductName, Category, Price, StockQuantity)

-> VALUES (6, 'Tablet', 'Electronics', 400, 100);

Query OK, 1 row affected (0.01 sec)

mysql> DELETE FROM Products WHERE ProductID = 6;

Query OK, 1 row affected (0.01 sec)


/*ORDER BY DESC STOCKQTY*/

mysql> SELECT * FROM Products ORDER BY StockQuantity DESC;

+-----------+-------------+-------------+---------+---------------+

| ProductID | ProductName | Category | Price | StockQuantity |

+-----------+-------------+-------------+---------+---------------+

| 3 | Headphones | Accessories | 150.00 | 300 |

| 2 | Smartphone | Electronics | 800.00 | 200 |

| 5 | Keyboard | Accessories | 50.00 | 150 |

| 1 | Laptop | Electronics | 1600.00 | 100 |

| 4 | Monitor | Electronics | 300.00 | 50 |

+-----------+-------------+-------------+---------+---------------+

/*Aggregate: Get Total Quantity Sold Per Product*/

mysql> SELECT p.ProductName, SUM(oi.Quantity) AS TotalSold

-> FROM Products p

-> JOIN OrderItems oi ON p.ProductID = oi.ProductID

-> GROUP BY p.ProductName;

+-------------+-----------+

| ProductName | TotalSold |

+-------------+-----------+

| Laptop | 2|

| Smartphone | 1|

| Headphones | 5|

| Monitor | 2|

| Keyboard | 10 |

+-------------+-----------+

/*INDEXING*/

mysql> CREATE INDEX idx_productname ON Products (ProductName);

Query OK, 0 rows affected (0.05 sec)


/*UPDATE STOCK QUANTITY AFTER ORDER BEEN PLACED*/

/*ALTERNATIVE 1*/

mysql> UPDATE Products p

-> SET p.StockQuantity = p.StockQuantity - (

-> SELECT SUM(oi.Quantity)

-> FROM OrderItems oi

-> WHERE oi.ProductID = p.ProductID

-> )

-> WHERE p.ProductID IN (

-> SELECT DISTINCT ProductID

-> FROM OrderItems

-> );

/*ALTERNATIVE 2*/

mysql> UPDATE Products p

-> JOIN OrderItems oi ON p.ProductID = oi.ProductID

-> SET p.StockQuantity = p.StockQuantity - oi.Quantity;

/*NOW DISPLAY THE UPDATED TABLE*/

-> JOIN Orders o ON oi.OrderID = o.OrderID;

-> JOIN Orders o ON oi.OrderID = o.OrderID;


+-----------+-------------+-------------+---------+---------------+-------------+---------+-----------+----------+---------+------------+

| ProductID | ProductName | Category | Price | StockQuantity | OrderItemID | OrderID |


ProductID | Quantity | OrderID | OrderDate |
+-----------+-------------+-------------+---------+---------------+-------------+---------+-----------+----------+---------+------------+

| 1 | Laptop | Electronics | 1500.00 | 98 | 1| 1| 1| 2| 1 | 2024-08-25 |

| 3 | Headphones | Accessories | 150.00 | 295 | 2| 1| 3| 5| 1 | 2024-08-25


|

| 2 | Smartphone | Electronics | 800.00 | 199 | 3| 2| 2| 1| 2 | 2024-08-26 |

| 4 | Monitor | Electronics | 300.00 | 48 | 4| 2| 4| 2| 2 | 2024-08-26 |

| 5 | Keyboard | Accessories | 50.00 | 140 | 5| 3| 5| 10 | 3 | 2024-08-27 |

+-----------+-------------+-------------+---------+---------------+-------------+---------+-----------+----------+---------+------------+
PRACTICAL – 3
mysql> use dbms;
Database changed
/*CREATE TABLE*/
mysql> CREATE TABLE Departments (DepartmentID INT PRIMARY KEY,DepartmentName
VARCHAR(100));
mysql> CREATE TABLE Projects (ProjectID INT PRIMARY KEY, ProjectName VARCHAR(100));
mysql> CREATE TABLE Employees (EmployeeID INT PRIMARY KEY, Name VARCHAR(100)
,DepartmentID INT, Salary DECIMAL(10, 2), FOREIGN KEY (DepartmentID) REFERENCES
Departments(DepartmentID));
mysql> CREATE TABLE EmployeeProjects ( EmployeeID INT, ProjectID INT, PRIMARY KEY
(EmployeeID, ProjectID), FOREIGN KEY (EmployeeID) REFERENCES Employees(EmployeeID),
FOREIGN KEY (ProjectID) REFERENCES Projects(ProjectID));

/*INSERT INTO TABLE*/


mysql> INSERT INTO Departments VALUES (1, 'HR'), (2, 'IT'), (3, 'Finance');
mysql> INSERT INTO Employees VALUES (1, 'John Doe', 2, 60000.00), (2, 'Jane Smith', 1,
65000.00), (3, 'Robert Brown', 3, 70000.00), (4, 'Emily Davis', 2
, 75000.00);
mysql> INSERT INTO Projects VALUES (1, 'Alpha'), (2, 'Beta'), (3, 'Gamma');
mysql> INSERT INTO EmployeeProjects VALUES (1, 1), (1, 2), (2, 3), (3, 1), (4, 2);
/*DISPLAY*/
mysql> SELECT * FROM Employees;
+------------+--------------+--------------+----------+
| EmployeeID | Name | DepartmentID | Salary |
+------------+--------------+--------------+----------+
| 1 | John Doe | 2 | 60000.00 |
| 2 | Jane Smith | 1 | 65000.00 |
| 3 | Robert Brown | 3 | 70000.00 |
| 4 | Emily Davis | 2 | 75000.00 |
+------------+--------------+--------------+----------+
mysql> SELECT * FROM Departments;
+--------------+----------------+
| DepartmentID | DepartmentName |
+--------------+----------------+
| 1 | HR |
| 2 | IT |
| 3 | Finance |
+--------------+----------------+

mysql> SELECT * FROM Projects;


+-----------+-------------+
| ProjectID | ProjectName |
+-----------+-------------+
| 1 | Alpha |
| 2 | Beta |
| 3 | Gamma |
+-----------+-------------+

mysql> SELECT * FROM EmployeeProjects;


+------------+-----------+
| EmployeeID | ProjectID |
+------------+-----------+
| 1| 1|
| 3| 1|
| 1| 2|
| 4| 2|
| 2| 3|
+------------+-----------+
/*INNER JOIN*/

mysql> SELECT e.EmployeeID, e.Name, d.DepartmentName FROM Employees e


-> INNER JOIN Departments d ON e.DepartmentID = d.DepartmentID;
+------------+--------------+----------------+
| EmployeeID | Name | DepartmentName |
+------------+--------------+----------------+
| 2 | Jane Smith | HR |
| 1 | John Doe | IT |
| 4 | Emily Davis | IT |
| 3 | Robert Brown | Finance |
+------------+--------------+----------------+

/*LEFT JOIN*/

mysql> SELECT e.EmployeeID, e.Name, p.ProjectName From Employees e


-> LEFT JOIN EmployeeProjects ep ON e.EmployeeID = ep.EmployeeID
-> LEFT JOIN Projects p ON ep.ProjectID = p.ProjectID;
+------------+--------------+-------------+
| EmployeeID | Name | ProjectName |
+------------+--------------+-------------+
| 1 | John Doe | Alpha |
| 1 | John Doe | Beta |
| 2 | Jane Smith | Gamma |
| 3 | Robert Brown | Alpha |
| 4 | Emily Davis | Beta |
+------------+--------------+-------------+
/*RIGHT JOIN*/
mysql> SELECT p.ProjectName, e.Name FROM Projects p
-> RIGHT JOIN EmployeeProjects ep ON p.ProjectID = ep.ProjectID
-> RIGHT JOIN Employees e ON ep.EmployeeID = e.EmployeeID;
+-------------+--------------+
| ProjectName | Name |
+-------------+--------------+
| Alpha | John Doe |
| Beta | John Doe |
| Gamma | Jane Smith |
| Alpha | Robert Brown |
| Beta | Emily Davis |
+-------------+--------------+
/*FULL JOIN*/
SELECT e.EmployeeID, e.Name, p.ProjectName From Employees e
-> LEFT JOIN EmployeeProjects ep ON e.EmployeeID = ep.EmployeeID
-> LEFT JOIN Projects p ON ep.ProjectID = p.ProjectID
-> UNION
-> SELECT e.EmployeeID, e.Name, p.ProjectName FROM Projects p
-> LEFT JOIN EmployeeProjects ep ON p.ProjectID = ep.ProjectID
-> LEFT JOIN Employees e ON ep.EmployeeID = e.EmployeeID;
+------------+--------------+-------------+
| EmployeeID | Name | ProjectName |
+------------+--------------+-------------+
| 1 | John Doe | Alpha |
| 1 | John Doe | Beta |
| 2 | Jane Smith | Gamma |
| 3 | Robert Brown | Alpha |
| 4 | Emily Davis | Beta |
/*SUB QUERY*/
mysql> SELECT *
-> FROM Employees
-> WHERE Salary > (
-> SELECT AVG(Salary)
-> FROM Employees
-> );
+------------+--------------+--------------+----------+
| EmployeeID | Name | DepartmentID | Salary |
+------------+--------------+--------------+----------+
| 3 | Robert Brown | 3 | 70000.00 |
| 4 | Emily Davis | 2 | 75000.00 |
+------------+--------------+--------------+----------+

mysql> SELECT DepartmentID, DepartmentName


-> FROM Departments
-> WHERE DepartmentID IN (
-> SELECT DepartmentID
-> FROM Employees
-> GROUP BY DepartmentID
-> HAVING COUNT(*) > 1
-> );
+--------------+----------------+
| DepartmentID | DepartmentName |
+--------------+----------------+
| 2 | IT |
+--------------+----------------+
/*VIEW*/

mysql> CREATE VIEW EmployeeProjectView AS


-> SELECT e.EmployeeID, e.Name, p.ProjectName
-> FROM Employees e
-> JOIN EmployeeProjects ep ON e.EmployeeID = ep.EmployeeID
-> JOIN Projects p ON ep.ProjectID = p.ProjectID;

mysql> SELECT * FROM EmployeeProjectView;


+------------+--------------+-------------+
| EmployeeID | Name | ProjectName |
+------------+--------------+-------------+
| 1 | John Doe | Alpha |
| 3 | Robert Brown | Alpha |
| 1 | John Doe | Beta |
| 4 | Emily Davis | Beta |
| 2 | Jane Smith | Gamma |
+------------+--------------+-------------+
PRACTICAL – 4
mysql> use dbms;
Database changed

/*CREATE TABLE*/

-- Create Products table

mysql> CREATE TABLE Product (ProductID INT AUTO_INCREMENT PRIMARY KEY, ProductName
VARCHAR(255) NOT NULL, Category VARCHAR(255), Price DECIMAL(10, 2), StockQuantity INT );

mysql> CREATE TABLE Order_Info ( OrderID INT AUTO_INCREMENT PRIMARY KEY, OrderDate DATE
NOT NULL );

mysql> CREATE TABLE OrderItem (OrderItemID INT AUTO_INCREMENT PRIMARY KEY, OrderID INT,
ProductID INT, Quantity INT, FOREIGN KEY (OrderID) REFERENCES Orders(OrderID), FOREIGN KEY
(ProductID) REFERENCES Product(ProductID)

);

/*INSERT DATA INTO PRODUCT TABLE*/

mysql> INSERT INTO Product (ProductName, Category, Price, StockQuantity) VALUES ('Laptop',
'Electronics', 1000.00, 50), ('Smartphone', 'Electronics', 500.00, 100), ('Tablet', 'Electronics', 300.00,
30);

/*CREATING PROCEDURE*/

mysql> DELIMITER //

mysql>

mysql> CREATE PROCEDURE process_multiple_orders(

-> IN p_ProductID INT,

-> IN p_Quantity INT

-> )

-> BEGIN

-> DECLARE v_StockQuantity INT;

-> DECLARE v_OrderID INT;

->

/* Check the stock quantity for the given ProductID*/

-> SELECT StockQuantity INTO v_StockQuantity


-> FROM Product

-> WHERE ProductID = p_ProductID;

/*Check if the requested quantity is available*/

-> IF v_StockQuantity >= p_Quantity THEN

/*Update the stock quantity in the Product table*/

-> UPDATE Product

-> SET StockQuantity = StockQuantity - p_Quantity

-> WHERE ProductID = p_ProductID;

->

/*Insert a new record into the Order_Info table*/

-> INSERT INTO Order_Info(OrderDate)

-> VALUES(CURDATE());

->

/*Get the last inserted OrderID*/

-> SET v_OrderID = LAST_INSERT_ID();

/*Insert a new record into the OrderItem table*/

-> INSERT INTO OrderItem(OrderID, ProductID, Quantity)

-> VALUES(v_OrderID, p_ProductID, p_Quantity);

-> ELSE

/*Raise an error if the requested quantity is not available*/

-> SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient stock available';

-> END IF;

-> END //

Query OK, 0 rows affected (0.01 sec)

mysql>

mysql> DELIMITER ;

mysql> CALL process_multiple_orders(1,10);

mysql> CALL process_multiple_orders(2,25);

mysql> CALL process_multiple_orders(3,40);

ERROR 1644 (45000): Insufficient stock available


mysql> SELECT * FROM Product;

+-----------+-------------+-------------+---------+---------------+

| ProductID | ProductName | Category | Price | StockQuantity |

+-----------+-------------+-------------+---------+---------------+

| 1 | Laptop | Electronics | 1000.00 | 40 |

| 2 | Smartphone | Electronics | 500.00 | 75 |

| 3 | Tablet | Electronics | 300.00 | 30 |

+-----------+-------------+-------------+---------+---------------+

mysql> SELECT * FROM Order_Info;

+---------+------------+

| OrderID | OrderDate |

+---------+------------+

| 1 | 2024-08-26 |

| 2 | 2024-08-26 |

+---------+------------+

mysql> SELECT * FROM OrderItem;

+-------------+---------+-----------+----------+

| OrderItemID | OrderID | ProductID | Quantity |

+-------------+---------+-----------+----------+

| 1| 1| 1| 10 |

| 2| 2| 2| 25 |

+-------------+---------+-----------+----------+
PRACTICAL – 5
mysql> use dbms;
Database changed

/*CREATE TABLE*/
mysql> CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(100) NOT
NULL);
mysql> CREATE TABLE Courses (CourseID INT PRIMARY KEY, CourseName VARCHAR(100)
NOT NULL);

mysql> CREATE TABLE Grades (GradeID INT AUTO_INCREMENT PRIMARY KEY, StudentID
INT, CourseID INT, Grade Float NOT NULL, CreditHours INT NOT NULL, FOREIGN KEY
(StudentID) REFERENCES Students(StudentID), FOREIGN KEY (CourseID) REFERENCES
Courses(CourseID));

/*INSERT DATA INTO TABLES*/


mysql> INSERT INTO Students VALUES (1, 'John Doe'), (2, 'Jane Smith'), (3, '
Alice Johnson');
mysql> INSERT INTO Courses VALUES (101, 'Mathematics'), (102, 'Physics'), (103, 'Computer
Science');
mysql> INSERT INTO Grades (StudentID, CourseID, Grade, CreditHours) VALUES (1, 101, 3.5,
4), (1, 102, 3.0, 3), (1, 103, 3.8, 4), (2, 101, 3.2, 4), (2, 103, 3.6, 4), (3, 102, 2.9, 3), (3, 103,
3.5, 4);
/*Displaying table*/
mysql> SELECT * FROM Students;
+-----------+---------------+
| StudentID | Name |
+-----------+---------------+
| 1 | John Doe |
| 2 | Jane Smith |
| 3 | Alice Johnson |
+-----------+---------------+
mysql> SELECT * FROM Courses;
+----------+------------------+
| CourseID | CourseName |
+----------+------------------+
| 101 | Mathematics |
| 102 | Physics |
| 103 | Computer Science |
+----------+------------------+

mysql> SELECT * FROM Grades;


+---------+-----------+----------+-------+-------------+
| GradeID | StudentID | CourseID | Grade | CreditHours |
+---------+-----------+----------+-------+-------------+
| 1| 1| 101 | 3.5 | 4|
| 2| 1| 102 | 3| 3|
| 3| 1| 103 | 3.8 | 4|
| 4| 2| 101 | 3.2 | 4|
| 5| 2| 103 | 3.6 | 4|
| 6| 3| 102 | 2.9 | 3|
| 7| 3| 103 | 3.5 | 4|
+---------+-----------+----------+-------+-------------+

/*DEFINING FUNCTION*/
mysql> DELIMITER //
mysql>
mysql> CREATE FUNCTION CalculateGPA(p_StudentID INT)
-> RETURNS FLOAT
-> DETERMINISTIC
-> BEGIN
-> DECLARE v_GPA FLOAT;
-> DECLARE v_TotalPoints FLOAT;
-> DECLARE v_TotalCreditHours INT;
->
-> /*Initialize total points and credit hours*/
-> SET v_TotalPoints = 0;
-> SET v_TotalCreditHours = 0;
->
-> /*Calculate total points and total credit hours*/
-> SELECT SUM(Grade * CreditHours) INTO v_TotalPoints
-> FROM Grades
-> WHERE StudentID = p_StudentID;
->
-> SELECT SUM(CreditHours) INTO v_TotalCreditHours
-> FROM Grades
-> WHERE StudentID = p_StudentID;
->
-> /*Calculate GPA*/
-> IF v_TotalCreditHours > 0 THEN
-> SET v_GPA = v_TotalPoints / v_TotalCreditHours;
-> /*Round GPA to 2 decimal places*/
-> SET v_GPA = ROUND(v_GPA, 2);
-> ELSE
-> SET v_GPA = NULL; /*No grades available*/
-> END IF;
->
-> RETURN v_GPA;
-> END //
Query OK, 0 rows affected (0.01 sec)
mysql>
mysql> DELIMITER ;
mysql>
mysql> /*Query to get StudentID, StudentName, and GPA*/
mysql> SELECT
-> s.StudentID,
-> s.Name AS StudentName,
-> CalculateGPA(s.StudentID) AS GPA
-> FROM
-> Students s;
+-----------+---------------+------+
| StudentID | StudentName | GPA |
+-----------+---------------+------+
| 1 | John Doe | 3.47 |
| 2 | Jane Smith | 3.4 |
| 3 | Alice Johnson | 3.24 |
+-----------+---------------+------+
PRACTICAL – 6
mysql> use dbms;
Database changed

/*CREATE TABLE*/
mysql> CREATE TABLE Customers (CustomerID INT PRIMARY KEY, FirstName VARCHAR(50)
NOT NULL, LastName VARCHAR(50) NOT NULL, TotalPurchases DECIMAL(10, 2) DEFAULT
0.00, LoyaltyPoints INT DEFAULT 0);

mysql> CREATE TABLE OrderDetails (OrderID INT AUTO_INCREMENT PRIMARY KEY,


CustomerID INT, OrderDate DATE NOT NULL, OrderAmount DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID));

/*INSERT DATA INTO TABLES*/


mysql> INSERT INTO Customers VALUES (1, 'John', 'Doe', 150.00, 15), (2, 'Jane', 'Smith',
250.00, 25), (3, 'Alice', 'Johnson', 100.00, 10);

mysql> INSERT INTO OrderDetails VALUES (1, '2024-08-26', 50.00), (2, '2024-08-25',
100.00), (3, '2024-08-24', 20.00);

/*Displaying table*/
mysql> SELECT * FROM Customers;
+------------+-----------+----------+----------------+---------------+
| CustomerID | FirstName | LastName | TotalPurchases | LoyaltyPoints |
+------------+-----------+----------+----------------+---------------+
| 1 | John | Doe | 150.00 | 15 |
| 2 | Jane | Smith | 250.00 | 25 |
| 3 | Alice | Johnson | 100.00 | 10 |
+------------+-----------+----------+----------------+---------------+
mysql> SELECT * FROM OrderDetails;
+---------+------------+------------+-------------+
| OrderID | CustomerID | OrderDate | OrderAmount |
+---------+------------+------------+-------------+
| 1| 1 | 2024-08-26 | 50.00 |
| 2| 2 | 2024-08-25 | 100.00 |
| 3| 3 | 2024-08-24 | 20.00 |
+---------+------------+------------+-------------+

/*CREATING TRIGGER FUNCTION*/


mysql> DELIMITER //
mysql>
mysql> /* Create a trigger to update loyalty points after an order is inserted */
mysql> CREATE TRIGGER UpdateLoyaltyPoints
-> AFTER INSERT ON OrderDetails
-> FOR EACH ROW
-> BEGIN
-> DECLARE v_Points INT;
->
-> /* Calculate points based on OrderAmount (1 point per $10 spent) */
-> SET v_Points = FLOOR(NEW.OrderAmount / 10);
->
-> /* Update the customer's loyalty points */
-> UPDATE Customers
-> SET LoyaltyPoints = LoyaltyPoints + v_Points
-> WHERE CustomerID = NEW.CustomerID;
-> END //
mysql>
mysql> DELIMITER ;
/*Placing New Order So LoyaltyPoints Gets Updated*/
mysql> INSERT INTO OrderDetails (CustomerID, OrderDate, OrderAmount) VALUES (1,
'2024-08-26', 100.00);
mysql> INSERT INTO OrderDetails (CustomerID, OrderDate, OrderAmount) VALUES (2,
'2024-08-25', 75.00);
mysql> INSERT INTO OrderDetails (CustomerID, OrderDate, OrderAmount) VALUES (3,
'2024-08-27', 50.00);

mysql> SELECT * FROM Customers;


+------------+-----------+----------+----------------+---------------+
| CustomerID | FirstName | LastName | TotalPurchases | LoyaltyPoints |
+------------+-----------+----------+----------------+---------------+
| 1 | John | Doe | 150.00 | 25 |
| 2 | Jane | Smith | 250.00 | 32 |
| 3 | Alice | Johnson | 100.00 | 15 |
+------------+-----------+----------+----------------+---------------+

mysql> SELECT * FROM OrderDetails;


+---------+------------+------------+-------------+
| OrderID | CustomerID | OrderDate | OrderAmount |
+---------+------------+------------+-------------+
| 1| 1 | 2024-08-26 | 50.00 |
| 2| 2 | 2024-08-25 | 100.00 |
| 3| 3 | 2024-08-24 | 20.00 |
| 4| 1 | 2024-08-26 | 100.00 |
| 5| 2 | 2024-08-25 | 75.00 |
| 6| 3 | 2024-08-27 | 50.00 |
+---------+------------+------------+-------------+
PRACTICAL – 7
mysql> use dbms;
Database changed

/*CREATE TABLE*/
mysql> CREATE TABLE Employee_info (EmployeeID INT PRIMARY KEY, FirstName
VARCHAR(50) NOT NULL, LastName VARCHAR(50) NOT NULL, Salary DECIMAL(10, 2) NOT
NULL);

mysql> CREATE TABLE SalaryUpdates (UpdateID INT AUTO_INCREMENT PRIMARY KEY,


EmployeeID INT, NewSalary DECIMAL(10, 2) NOT NULL, UpdateDate DATE NOT NULL,
FOREIGN KEY (EmployeeID) REFERENCES employee_info(EmployeeID));

/*INSERTING DATA*/
mysql> INSERT INTO employee_info VALUES (1, 'John', 'Doe', 50000.00), (2, 'Jane', 'Smith',
60000.00), (3, 'Alice', 'Johnson', 55000.00);

mysql>INSERT INTO SalaryUpdates (EmployeeID, NewSalary, UpdateDate) VALUES (1,


52000.00, '2024-08-26'), (3, 58000.00, '2024-08-26');

/*Displaying Data*/
mysql> SELECT * FROM Employee_Info;
+------------+-----------+----------+----------+
| EmployeeID | FirstName | LastName | Salary |
+------------+-----------+----------+----------+
| 1 | John | Doe | 50000.00 |
| 2 | Jane | Smith | 60000.00 |
| 3 | Alice | Johnson | 55000.00 |
+------------+-----------+----------+----------+
mysql> SELECT * FROM SalaryUpdates;
+----------+------------+-----------+------------+
| UpdateID | EmployeeID | NewSalary | UpdateDate |
+----------+------------+-----------+------------+
| 1| 1 | 52000.00 | 2024-08-26 |
| 2| 3 | 58000.00 | 2024-08-26 |
+----------+------------+-----------+------------+
mysql> DELIMITER //
mysql> CREATE PROCEDURE update_employee_salaries()
-> BEGIN
-> DECLARE emp_id INT;
-> DECLARE new_salary DECIMAL(10,2);
-> DECLARE done INT DEFAULT 0;
-> -- Declare cursor to iterate through employees
-> DECLARE employee_cursor CURSOR FOR SELECT EmployeeID FROM Employee_Info;
-> -- Declare a handler for when no more rows are found
-> DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
-> -- Open the cursor
-> OPEN employee_cursor;
-> -- Loop through employees
-> employee_loop: LOOP
-> -- Fetch the next employee ID
-> FETCH employee_cursor INTO emp_id;
-> -- Exit the loop if no more rows are found
-> IF done = 1 THEN
-> LEAVE employee_loop;
-> END IF;
-> -- Check if there is a corresponding record in SalaryUpdates
-> IF EXISTS (SELECT 1 FROM SalaryUpdates WHERE EmployeeID = emp_id) THEN
-> -- Fetch the new salary
-> SELECT NewSalary INTO new_salary
-> FROM SalaryUpdates
-> WHERE EmployeeID = emp_id;
->
-> -- Update salary if new salary exists
-> IF new_salary IS NOT NULL THEN
-> UPDATE Employee_Info
-> SET Salary = new_salary
-> WHERE EmployeeID = emp_id;
-> END IF;
-> END IF;
-> END LOOP employee_loop;
-> -- Close the cursor
-> CLOSE employee_cursor;
-> END //
Query OK, 0 rows affected (0.01 sec)
mysql> DELIMITER ;
/*Displaying Updated Result*/
mysql> CALL update_employee_salaries();
Query OK, 0 rows affected (0.01 sec)
mysql> SELECT * FROM Employee_Info;
+------------+-----------+----------+----------+
| EmployeeID | FirstName | LastName | Salary |
+------------+-----------+----------+----------+
| 1 | John | Doe | 52000.00 |
| 2 | Jane | Smith | 60000.00 |
| 3 | Alice | Johnson | 58000.00 |
+------------+-----------+----------+----------+
GROUP B
PRACTICAL - 1
test> show dbs
admin 40.00 KiB
config 72.00 KiB
local 72.00 KiB

test> use onlinestore


switched to db onlinestore

onlinestore> db.products.insertMany([
... {name: "Laptop", price: 10000, quantity: 50},
... {name: "Smartphone", price: 8000, quantity: 100},
... {name: "Tablet", price: 4000, quantity: 800},
... {name: "Earphones", price: 450, quantity: 25},
... {name: "Pendrive", price: 350, quantity: 10},
... ])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('66f4d4fd05be71de06c73bf8'),
'1': ObjectId('66f4d4fd05be71de06c73bf9'),
'2': ObjectId('66f4d4fd05be71de06c73bfa'),
'3': ObjectId('66f4d4fd05be71de06c73bfb'),
'4': ObjectId('66f4d4fd05be71de06c73bfc')
}
}
onlinestore> db.products.find().pretty()
[
{
_id: ObjectId('66f4d4fd05be71de06c73bf8'),
name: 'Laptop',
price: 10000,
quantity: 50
},
{
_id: ObjectId('66f4d4fd05be71de06c73bf9'),
name: 'Smartphone',
price: 8000,
quantity: 100
},
{
_id: ObjectId('66f4d4fd05be71de06c73bfa'),
name: 'Tablet',
price: 4000,
quantity: 800
},
{
_id: ObjectId('66f4d4fd05be71de06c73bfb'),
name: 'Earphones',
price: 450,
quantity: 25
},
{
_id: ObjectId('66f4d4fd05be71de06c73bfc'),
name: 'Pendrive',
price: 350,
quantity: 10 } ]
onlinestore> db.products.find({price: {$gt: 500} }) //Read Operation
[
{
_id: ObjectId('66f4d4fd05be71de06c73bf8'),
name: 'Laptop',
price: 10000,
quantity: 50
},
{
_id: ObjectId('66f4d4fd05be71de06c73bf9'),
name: 'Smartphone',
price: 8000,
quantity: 100
},
{
_id: ObjectId('66f4d4fd05be71de06c73bfa'),
name: 'Tablet',
price: 4000,
quantity: 800
}
]
onlinestore> db.products.updateOne({name: "Laptop"}, { $set: { price: 25000} })//Update
Operation
{
acknowledged: true,
insertedId: null,
matchedCount: 1,
modifiedCount: 1,
upsertedCount: 0
}
onlinestore> db.products.deleteOne({ name: "Earphones" }) //Delete
{ acknowledged: true, deletedCount: 1 }
onlinestore> db.products.insertOne({ name: "Mouse", price: 325, quantity: 100}) //Insert
Operation
{
acknowledged: true,
insertedId: ObjectId('66f4d72b05be71de06c73bfd')
}

onlinestore> db.products.find().pretty()
[
{
_id: ObjectId('66f4d4fd05be71de06c73bf8'),
name: 'Laptop',
price: 25000,
quantity: 50
},
{
_id: ObjectId('66f4d4fd05be71de06c73bf9'),
name: 'Smartphone',
price: 8000,
quantity: 100
},
{
_id: ObjectId('66f4d4fd05be71de06c73bfa'),
name: 'Tablet',
price: 4000,
quantity: 800
},
{
_id: ObjectId('66f4d4fd05be71de06c73bfc'),
name: 'Pendrive',
price: 350,
quantity: 10
},
{
_id: ObjectId('66f4d72b05be71de06c73bfd'),
name: 'Mouse',
price: 325,
quantity: 100
}
]

PRACTICAL – 2
test> use onlinestores
switched to db onlinestores
onlinestores> db.orders.insertMany([
... {product:"Asus Laptop",quantity:2,stock:15,price:250000},
... {product:"Earphone",quantity:5,stock:25,price:850},
... {product:"Mobile",quantity:3,stock:10,price:15000},
... {product:"Asus Laptop",quantity:1,stock:15,price:250000},
... {product:"HP Laptop",quantity:5,stock:20,price:200000},
... {product:"Mobile",quantity:2,stock:10,price:15000},
... {product:"Earphone",quantity:3,stock:25,price:850},
... {product:"HP Laptop",quantity:4,stock:20,price:200000}
... ])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('66fb66a81b4a4234dbc73bf8'),
'1': ObjectId('66fb66a81b4a4234dbc73bf9'),
'2': ObjectId('66fb66a81b4a4234dbc73bfa'),
'3': ObjectId('66fb66a81b4a4234dbc73bfb'),
'4': ObjectId('66fb66a81b4a4234dbc73bfc'),
'5': ObjectId('66fb66a81b4a4234dbc73bfd'),
'6': ObjectId('66fb66a81b4a4234dbc73bfe'),
'7': ObjectId('66fb66a81b4a4234dbc73bff')
}
}
onlinestores> db.orders.find()
[
{
_id: ObjectId('66fb66a81b4a4234dbc73bf8'),
product: 'Asus Laptop',
quantity: 2,
stock: 15,
price: 250000
},
{
_id: ObjectId('66fb66a81b4a4234dbc73bf9'),
product: 'Earphone',
quantity: 5,
stock: 25,
price: 850
},
{
_id: ObjectId('66fb66a81b4a4234dbc73bfa'),
product: 'Mobile',
quantity: 3,
stock: 10,
price: 15000
},
{
_id: ObjectId('66fb66a81b4a4234dbc73bfb'),
product: 'Asus Laptop',
quantity: 1,
stock: 15,
price: 250000
},
{
_id: ObjectId('66fb66a81b4a4234dbc73bfc'),
product: 'HP Laptop',
quantity: 5,
stock: 20,
price: 200000
},
{
_id: ObjectId('66fb66a81b4a4234dbc73bfd'),
product: 'Mobile',
quantity: 2,
stock: 10,
price: 15000
},
{
_id: ObjectId('66fb66a81b4a4234dbc73bfe'),
product: 'Earphone',
quantity: 3,
stock: 25,
price: 850
},
{
_id: ObjectId('66fb66a81b4a4234dbc73bff'),
product: 'HP Laptop',
quantity: 4,
stock: 20,
price: 200000
}
]

onlinestores> db.orders.aggregate([
...
... {
... $group: {
... _id: "$product",
... totalSales: { $sum: "$quantity" }, // Sum up the "quantity" field
... totalBill: { $sum: { $multiply: ["$quantity", "$price"] } },
... stock: { $first: "$stock" } // Preserve the stock value for each product group
... }
... },
... {
... $addFields: {
... available: { $subtract: ["$stock", "$totalSales"] } // Calculate available stock
... }
... }
... ])
[
{
_id: 'Earphone',
totalSales: 8,
totalBill: 6800,
stock: 25,
available: 17
},
{
_id: 'HP Laptop',
totalSales: 9,
totalBill: 1800000,
stock: 20,
available: 11
},
{
_id: 'Mobile',
totalSales: 5,
totalBill: 75000,
stock: 10,
available: 5
},
{
_id: 'Asus Laptop',
totalSales: 3,
totalBill: 750000,
stock: 15,
available: 12
}
]

PRACTICAL – 3
test> use onlinestore
switched to db onlinestore
onlinestore> db.sales.insertMany([
... { product: "Laptop", quantity: 5 },
... { product: "Smartphone", quantity: 3 },
... { product: "Laptop", quantity: 1 },
... { product: "Tablet", quantity: 4 }
... ])
{
acknowledged: true,
insertedIds: {
'0': ObjectId('66f4dae48620515566c73bf8'),
'1': ObjectId('66f4dae48620515566c73bf9'),
'2': ObjectId('66f4dae48620515566c73bfa'),
'3': ObjectId('66f4dae48620515566c73bfb')
}
}
onlinestore> var mapFunction = function() {
... emit(this.product, this.quantity);
... };
onlinestore> var reduceFunction = function(keyProduct, valuesQuantities) {
... return Array.sum(valuesQuantities);
... };

onlinestore> db.sales.mapReduce(mapFunction, reduceFunction, { out: "totalQuantities" })


DeprecationWarning: Collection.mapReduce() is deprecated. Use an aggregation instead.
See https://docs.mongodb.com/manual/core/map-reduce for details.
{ result: 'totalQuantities', ok: 1 }
onlinestore> db.totalQuantities.find().pretty()
[
{ _id: 'Tablet', value: 4 },
{ _id: 'Smartphone', value: 3 },
{ _id: 'Laptop', value: 6 }
]
onlinestore> db.sales.aggregate([
... {
... $group: {
... _id: "$product", // Group by product
... totalQuantity: { $sum: "$quantity" } // Sum up the quantities
... }
... }
... ])
[
{ _id: 'Laptop', totalQuantity: 6 },
{ _id: 'Smartphone', totalQuantity: 3 },
{ _id: 'Tablet', totalQuantity: 4 }
]

You might also like