Added content.

- Notes
- Practical (Databases, Handouts, Queries, Softcopies, Write-ups)
- Question Papers
- DISCLAIMER file and motto
Lastly, updated README file.
This commit is contained in:
K 2025-01-07 16:34:41 +05:30
parent 375dc7e391
commit 3049887277
Signed by: notkshitij
GPG Key ID: C5B8BC7530F8F43F
97 changed files with 5262 additions and 0 deletions

13
DISCLAIMER.md Normal file
View File

@ -0,0 +1,13 @@
# DISCLAIMER
Disclaimer for [DatabaseManagementSystems](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems) repository under [sppu-te-comp-content](https://git.kska.io/sppu-te-comp-content) organization.
---
- Please be advised that this repository ([DatabaseManagementSystems](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems)), its organization ([sppu-te-comp-content](https://git.kska.io/sppu-te-comp-content)), and all of its content are entirely independent and not associated to, and/or affiliated with SPPU (Savitrbai Phule Pune University, Pune) and/or any of its colleges, nor with [KSKA Git](https://git.kska.io). The materials provided within, including assignments from our contributors and notes from our professors, are solely for educational purposes and convenience.
- KSKA Git serves merely as a platform for this content and does not imply any association and/or endorsement from SPPU or KSKA Git. It is important to recognize that the organization (sppu-te-comp-content) and all of its repositories in KSKA Git operates independently, and any references to educational institutions or platforms are purely for informational clarity.
- Furthermore, it is emphasized that the content available within this repository remains meticulously curated to align with the latest 2019 SPPU syllabus for computer engineering. Our commitment to accuracy ensures that the materials provided reflect the current academic standards prescribed by SPPU, offering students a reliable resource to supplement their studies.
---

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,185 @@
-- MySQL dump 10.13 Distrib 9.0.1, for Linux (x86_64)
--
-- Host: localhost Database: Database_A2
-- ------------------------------------------------------
-- Server version 9.0.1
/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
/*!50503 SET NAMES utf8mb4 */;
/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;
/*!40103 SET TIME_ZONE='+00:00' */;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
--
-- Table structure for table `Account`
--
DROP TABLE IF EXISTS `Account`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `Account` (
`acc_no` int NOT NULL,
`branch_name` varchar(255) DEFAULT NULL,
`balance` int DEFAULT NULL,
PRIMARY KEY (`acc_no`),
KEY `branch_name` (`branch_name`),
CONSTRAINT `Account_ibfk_1` FOREIGN KEY (`branch_name`) REFERENCES `Branch` (`branch_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Account`
--
LOCK TABLES `Account` WRITE;
/*!40000 ALTER TABLE `Account` DISABLE KEYS */;
INSERT INTO `Account` VALUES (101,'Akurdi',15000),(102,'Nigdi',8000),(103,'Kharadi',20000),(104,'Hadapsar',12000),(105,'Viman Nagar',5000);
/*!40000 ALTER TABLE `Account` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Borrower`
--
DROP TABLE IF EXISTS `Borrower`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `Borrower` (
`cust_name` varchar(255) DEFAULT NULL,
`loan_no` int DEFAULT NULL,
KEY `cust_name` (`cust_name`),
KEY `loan_no` (`loan_no`),
CONSTRAINT `Borrower_ibfk_1` FOREIGN KEY (`cust_name`) REFERENCES `Customer` (`cust_name`),
CONSTRAINT `Borrower_ibfk_2` FOREIGN KEY (`loan_no`) REFERENCES `Loan` (`loan_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Borrower`
--
LOCK TABLES `Borrower` WRITE;
/*!40000 ALTER TABLE `Borrower` DISABLE KEYS */;
INSERT INTO `Borrower` VALUES ('Mehul',202),('Tanmay',203),('Aditya',205);
/*!40000 ALTER TABLE `Borrower` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Branch`
--
DROP TABLE IF EXISTS `Branch`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `Branch` (
`branch_name` varchar(255) NOT NULL,
`branch_city` varchar(255) DEFAULT NULL,
`assets` int DEFAULT NULL,
PRIMARY KEY (`branch_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Branch`
--
LOCK TABLES `Branch` WRITE;
/*!40000 ALTER TABLE `Branch` DISABLE KEYS */;
INSERT INTO `Branch` VALUES ('Akurdi','Pune',5000000),('Hadapsar','Pune',3500000),('Kharadi','Pune',4000000),('Nigdi','Pune',3000000),('Viman Nagar','Pune',4500000);
/*!40000 ALTER TABLE `Branch` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Customer`
--
DROP TABLE IF EXISTS `Customer`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `Customer` (
`cust_name` varchar(255) NOT NULL,
`cust_street` varchar(255) DEFAULT NULL,
`cust_city` varchar(255) DEFAULT NULL,
PRIMARY KEY (`cust_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Customer`
--
LOCK TABLES `Customer` WRITE;
/*!40000 ALTER TABLE `Customer` DISABLE KEYS */;
INSERT INTO `Customer` VALUES ('Aditya','Street 5','Pune'),('Kalas','Street 1','Pune'),('Kshitij','Street 4','Pune'),('Mehul','Street 2','Pune'),('Tanmay','Street 3','Pune');
/*!40000 ALTER TABLE `Customer` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Depositor`
--
DROP TABLE IF EXISTS `Depositor`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `Depositor` (
`cust_name` varchar(255) DEFAULT NULL,
`acc_no` int DEFAULT NULL,
KEY `cust_name` (`cust_name`),
KEY `acc_no` (`acc_no`),
CONSTRAINT `Depositor_ibfk_1` FOREIGN KEY (`cust_name`) REFERENCES `Customer` (`cust_name`),
CONSTRAINT `Depositor_ibfk_2` FOREIGN KEY (`acc_no`) REFERENCES `Account` (`acc_no`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Depositor`
--
LOCK TABLES `Depositor` WRITE;
/*!40000 ALTER TABLE `Depositor` DISABLE KEYS */;
INSERT INTO `Depositor` VALUES ('Kalas',101),('Mehul',102),('Tanmay',103),('Kshitij',101),('Aditya',104);
/*!40000 ALTER TABLE `Depositor` ENABLE KEYS */;
UNLOCK TABLES;
--
-- Table structure for table `Loan`
--
DROP TABLE IF EXISTS `Loan`;
/*!40101 SET @saved_cs_client = @@character_set_client */;
/*!50503 SET character_set_client = utf8mb4 */;
CREATE TABLE `Loan` (
`loan_no` int NOT NULL,
`branch_name` varchar(255) DEFAULT NULL,
`amount` int DEFAULT NULL,
PRIMARY KEY (`loan_no`),
KEY `branch_name` (`branch_name`),
CONSTRAINT `Loan_ibfk_1` FOREIGN KEY (`branch_name`) REFERENCES `Branch` (`branch_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci;
/*!40101 SET character_set_client = @saved_cs_client */;
--
-- Dumping data for table `Loan`
--
LOCK TABLES `Loan` WRITE;
/*!40000 ALTER TABLE `Loan` DISABLE KEYS */;
INSERT INTO `Loan` VALUES (201,'Akurdi',15000),(202,'Nigdi',13000),(203,'Kharadi',25000),(204,'Hadapsar',18000),(205,'Akurdi',1400);
/*!40000 ALTER TABLE `Loan` ENABLE KEYS */;
UNLOCK TABLES;
/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;
-- Dump completed on 2024-10-31 20:54:27

Binary file not shown.

View File

@ -0,0 +1,238 @@
# Database Queries for Assignment-A2
This file contains all the queries required to build the [database](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Assignment-A2/Database_A2.sql)
## Creating database
```sql
CREATE DATABASE Database_A2;
USE Database_A2;
```
## Creating tables and specify primary keys:
```sql
CREATE TABLE Account (
acc_no INT,
branch_name VARCHAR(255),
balance INT,
PRIMARY KEY (acc_no)
);
CREATE TABLE Branch (
branch_name VARCHAR(255),
branch_city VARCHAR(255),
assets INT,
PRIMARY KEY (branch_name)
);
CREATE TABLE Customer (
cust_name VARCHAR(255),
cust_street VARCHAR(255),
cust_city VARCHAR(255),
PRIMARY KEY (cust_name)
);
CREATE TABLE Depositor (
cust_name VARCHAR(255),
acc_no INT
);
CREATE TABLE Loan (
loan_no INT,
branch_name VARCHAR(255),
amount INT,
PRIMARY KEY (loan_no)
);
CREATE TABLE Borrower (
cust_name VARCHAR(255),
loan_no INT
);
```
## Altering tables to specify foreign keys
```sql
ALTER TABLE Account ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Depositor ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Depositor ADD FOREIGN KEY (acc_no) REFERENCES Account (acc_no);
ALTER TABLE Loan ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Borrower ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Borrower ADD FOREIGN KEY (loan_no) REFERENCES Loan (loan_no);
```
## Adding data
```sql
INSERT INTO Branch (branch_name, branch_city, assets) VALUES
('Akurdi', 'Pune', 5000000),
('Nigdi', 'Pune', 3000000),
('Kharadi', 'Pune', 4000000),
('Hadapsar', 'Pune', 3500000),
('Viman Nagar', 'Pune', 4500000);
INSERT INTO Account (acc_no, branch_name, balance) VALUES
(101, 'Akurdi', 15000),
(102, 'Nigdi', 8000),
(103, 'Kharadi', 20000),
(104, 'Hadapsar', 12000),
(105, 'Viman Nagar', 5000);
INSERT INTO Customer (cust_name, cust_street, cust_city) VALUES
('Kalas', 'Street 1', 'Pune'),
('Mehul', 'Street 2', 'Pune'),
('Tanmay', 'Street 3', 'Pune'),
('Kshitij', 'Street 4', 'Pune'),
('Aditya', 'Street 5', 'Pune');
INSERT INTO Depositor (cust_name, acc_no) VALUES
('Kalas', 101),
('Mehul', 102),
('Tanmay', 103),
('Kshitij', 101),
('Aditya', 104);
INSERT INTO Loan (loan_no, branch_name, amount) VALUES
(201, 'Akurdi', 15000),
(202, 'Nigdi', 13000),
(203, 'Kharadi', 25000),
(204, 'Hadapsar', 18000),
(205, 'Akurdi', 1400);
INSERT INTO Borrower (cust_name, loan_no) VALUES
('Mehul', 202),
('Tanmay', 203),
('Aditya', 205);
```
---
## Running queries
1. Find the names of all branches in loan relation.
```sql
SELECT DISTINCT branch_name FROM Loan;
```
2. Find all loan numbers for loans made at Akurdi Branch with loan amount > 12000.
```sql
SELECT loan_no FROM Loan WHERE branch_name = 'Akurdi' AND amount > 12000;
```
3. Find all customers who have a loan from bank. Find their names,loan_no and loan amount.
```sql
SELECT * from Borrower;
SELECT Borrower.cust_name, Borrower.loan_no, Loan.amount FROM Borrower INNER JOIN Loan ON Borrower.loan_no = Loan.loan_no;
```
4. List all customers in alphabetical order who have loan from Akurdi branch.
```sql
SELECT cust_name FROM Borrower INNER JOIN Loan ON Borrower.loan_no = Loan.loan_no WHERE branch_name = 'Akurdi' ORDER BY cust_name;
```
5. Find all customers who have an account or loan or both at bank.
```sql
SELECT cust_name FROM Depositor UNION SELECT cust_name FROM Borrower;
```
6. Find all customers who have both account and loan at bank.
```sql
SELECT cust_name FROM Depositor INTERSECT SELECT cust_name FROM Borrower;
```
7. Find all customers who have account but no loan at the bank.
```sql
SELECT cust_name FROM Depositor WHERE cust_name NOT IN (SELECT cust_name FROM Borrower);
-- OR YOU CAN RUN THE BELOW COMMAND IF YOU ARE FEELING FANCY
-- SELECT Customer.cust_name FROM Customer INNER JOIN Depositor ON Customer.cust_name = Depositor.cust_name LEFT JOIN Borrower ON Customer.cust_name = Borrower.cust_name WHERE Borrower.cust_name IS NULL;
```
8. Find the average account balance at each branch
```sql
SELECT branch_name, AVG(balance) FROM Account GROUP BY branch_name;
```
9. Find no. of depositors at each branch.
```sql
SELECT branch_name, COUNT(*) FROM Account INNER JOIN Depositor ON Account.acc_no = Depositor.acc_no GROUP BY branch_name;
```
10. Find name of Customer and city where customer name starts with Letter K.
```sql
SELECT cust_name, cust_city FROM Customer WHERE cust_name LIKE 'K%';
```
11. Display distinct cities of branch.
```sql
SELECT DISTINCT branch_city FROM Branch;
```
12. Find the branches where average account balance > 1200
```sql
SELECT branch_name FROM Account GROUP BY branch_name HAVING AVG(balance) > 12000;
```
13. Find number of tuples in customer relation.
```sql
SELECT COUNT(*) FROM Customer;
```
14. Calculate total loan amount given by bank.
```sql
SELECT SUM(amount) FROM Loan;
```
15. Delete all loans with loan amount between 1300 and 1500.
```sql
DELETE FROM Borrower WHERE loan_no IN (SELECT loan_no FROM Loan WHERE amount BETWEEN 1300 AND 1500);
DELETE FROM Loan WHERE amount BETWEEN 1300 AND 1500;
```
16. Delete all tuples at every branch located in Nigdi.
```sql
DELETE FROM Borrower WHERE loan_no IN (SELECT loan_no FROM Loan WHERE branch_name = 'Nigdi');
DELETE FROM Loan WHERE branch_name = 'Nigdi';
DELETE FROM Depositor WHERE acc_no IN (SELECT acc_no FROM Account WHERE branch_name = 'Nigdi');
DELETE FROM Account WHERE branch_name = 'Nigdi';
DELETE FROM Branch WHERE branch_name = 'Nigdi';
```
---

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,275 @@
# Database Queries for Assignment-A3
## Creating database
```sql
CREATE DATABASE Database_A3;
USE Database_A3;
```
## Creating tables and specify primary keys:
```sql
CREATE TABLE Account(acc_no INT, branch_name VARCHAR(50), balance INT, PRIMARY KEY (acc_no));
CREATE TABLE Branch(branch_name VARCHAR(50), branch_city VARCHAR(50), assets INT, PRIMARY KEY (branch_name));
CREATE TABLE Customer (cust_name VARCHAR(50), cust_street VARCHAR(50), cust_city VARCHAR(50), PRIMARY KEY (cust_name));
CREATE TABLE Depositor (cust_name VARCHAR(50), acc_no INT);
CREATE TABLE Loan (loan_no INT, branch_name VARCHAR(50), amount INT, PRIMARY KEY (loan_no));
CREATE TABLE Borrower (cust_name VARCHAR(50), loan_no INT);
```
## Altering tables to specify foreign keys
```sql
ALTER TABLE Account ADD FOREIGN KEY (branch_name) REFERENCES Branch(branch_name);
ALTER TABLE Depositor ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Depositor ADD FOREIGN KEY (acc_no) REFERENCES Account (acc_no);
ALTER TABLE Loan ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Borrower ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Borrower ADD FOREIGN KEY (loan_no) REFERENCES Loan (loan_no);
```
## Adding data
```sql
INSERT INTO Branch (branch_name, branch_city, assets) VALUES
("Pune_Station", "Pune", 5000),
("Hadapsar", "Pune", 20000),
("Dhole_Patil", "Mumbai", 7500),
("Nagarwala", "Nandurbar", 3200);
INSERT INTO Customer (cust_name, cust_street, cust_city) VALUES
("Kalas", "Airport Road", "Pune"),
("Mehul", "Shahdha", "Nandurbar"),
("Tanmay", "Porwal Road", "Pune"),
("Kshitij", "Hadapasar", "Pune"),
("Aditya", "Mira RD", "Mumbai"),
("Himanshu", "Smart City", "Nandurbar");
INSERT INTO Account (acc_no, branch_name, balance) VALUES
(2501, "Dhole_Patil", 5000),
(2511, "Pune_Station", 1500),
(2521, "Hadapsar", 2000),
(2512, "Nagarwala", 5000),
(2531, "Pune_Station", 1000);
INSERT INTO Loan (loan_no, branch_name, amount) VALUES
(155, "Dhole_Patil", 500),
(156, "Pune_Station", 250),
(157, "Hadapsar", 600),
(158, "Nagarwala", 1400),
(159, "Pune_Station", 25000);
INSERT INTO Borrower VALUES
("Kalas", 156),
("Mehul", 158),
("Tanmay", 155),
("Kshitij", 157),
("Aditya", 159),
("Himanshu", 158);
INSERT INTO Depositor VALUES
("Kalas", 2511),
("Mehul", 2512),
("Tanmay", 2501),
("Kshitij", 2521),
("Aditya", 2531),
("Himanshu", 2512);
```
## Queries
### Part 1 (Borrower):
1. Create a View1 to display List all customers in alphabetical order who have loan from
Pune_Station branch
```sql
CREATE VIEW View1 AS
SELECT cust_name
FROM Borrower
INNER JOIN Loan ON Borrower.loan_no = Loan.loan_no
WHERE branch_name = "Pune_Station"
ORDER BY cust_name;
SELECT * FROM View1;
```
2. Create View2 on branch table by selecting any two columns and perform insert
update delete operations.
```sql
CREATE VIEW View2 AS
SELECT branch_name, branch_city
FROM Branch;
SELECT * FROM View2;
-- Insert operation
INSERT INTO View2 (branch_name, branch_city) VALUES ('Yerwada', 'Pune');
SELECT * FROM View2;
-- Update operation
UPDATE View2 SET branch_name = 'Peachtree' WHERE branch_name = 'Yerwada';
SELECT * FROM View2;
-- Delete operation
DELETE FROM View2 WHERE branch_name = 'Peachtree';
SELECT * FROM View2;
```
3. Create View3 on borrower and depositor table by selecting any one column from each
table perform insert update delete operations.
```sql
CREATE VIEW View3 AS
SELECT Borrower.cust_name, Depositor.acc_no
FROM Borrower JOIN Depositor ON Borrower.cust_name = Depositor.cust_name;
SELECT * FROM View3;
-- Insert operation
INSERT INTO Customer (cust_name, cust_street, cust_city) VALUES ("Macho", "Pedgaon", "Ahemadnagar");
INSERT INTO Account (acc_no, branch_name, balance) VALUES (2502, "Hadapsar", 3000);
INSERT INTO Loan (loan_no, branch_name, amount) VALUES (160, "Hadapsar", 500);
INSERT INTO Borrower (cust_name, loan_no) VALUES ("Macho", 160);
INSERT INTO Depositor(cust_name, Acc_no) VALUES("Macho", 2502);
SELECT * FROM View3;
-- Update operation
INSERT INTO Account (acc_no, branch_name, balance) VALUES (2566, 'Hadapsar', 3000);
UPDATE Depositor SET acc_no = 2566 WHERE cust_name = 'Macho';
SELECT * FROM View3;
-- Delete operation
DELETE FROM Borrower WHERE cust_name = 'Macho';
DELETE FROM Depositor WHERE cust_name = 'Macho';
SELECT * FROM View3;
```
4. Create Union of left and right joint for all customers who have an account or loan or both at bank
```sql
SELECT DISTINCT Customer.cust_name
FROM Customer
LEFT JOIN Depositor ON Customer.cust_name = Depositor.cust_name
LEFT JOIN Borrower ON Customer.cust_name = Borrower.cust_name
WHERE Depositor.acc_no IS NOT NULL OR Borrower.loan_no IS NOT NULL;
```
5. Display content of View1, View2, View3
```sql
SELECT * FROM View1;
SELECT * FROM View2;
SELECT * FROM View3;
```
6. Create Simple and Unique index
```sql
-- Simple Index
CREATE INDEX cust_ind ON Customer (cust_city);
-- Unique Index
CREATE UNIQUE INDEX branch_ind ON Branch (branch_name);
```
7. Display index Information
```sql
SHOW INDEX FROM Customer;
SHOW INDEX FROM Branch;
```
8. Truncate table Customer
```sql
DROP TABLE Depositor;
DROP TABLE Borrower;
TRUNCATE TABLE Customer;
```
### Part 2:
#### Create tables
```sql
CREATE TABLE Companies(comp_id varchar(50), name varchar(50), cost int, year int);
CREATE TABLE Orders(comp_id varchar(50), domain varchar(50), quantity int);
```
#### Insert values
```sql
INSERT INTO Companies (comp_id, name, cost, year) VALUES
("C001", "ONGC", 2000, 2010),
("C002", "HPCL", 2500, 2012),
("C005", "IOCL", 1000, 2014),
("C006", "BHEL", 3000, 2015);
INSERT INTO Orders (comp_id, domain, quantity) VALUES
("C001", "Oil", 109),
("C002", "Gas", 121),
("C005", "Telecom", 115);
```
#### Queries
1. Find names, costs, domains and quantities for companies using inner join.
```sql
SELECT name, cost, domain, quantity FROM Companies INNER JOIN Orders on Companies.comp_id = Orders.comp_id;
```
2. Find names, costs, domains and quantities for companies using left outer join.
```sql
SELECT name, cost, domain, quantity FROM Companies lEFT OUTER JOIN Orders ON Companies.comp_id = Orders.comp_id;
```
3. Find names, costs, domains and quantities for companies using right outer join.
```sql
SELECT name, cost, domain, quantity FROM Companies RIGHT OUTER JOIN Orders ON Companies.comp_id = Orders.comp_id;
```
4. Find names, costs, domains and quantities for companies using Union operator.
```sql
SELECT name, cost FROM Companies UNION SELECT domain, quantity FROM Orders;
```
5. Create View View1 by selecting both tables to show company name and quantities.
```sql
CREATE VIEW view1 AS SELECT name, quantity FROM Companies JOIN Orders ON Companies.comp_id = Orders.comp_id;
SELECT * FROM view1;
```
6. Create View2 on branch table by selecting any two columns and perform insert update delete operations.
```sql
CREATE VIEW view2 AS SELECT name, cost FROM Companies;
SELECT * FROM view2;
-- Insert operation
INSERT INTO view2 (name, cost) VALUES ("BCCC", 3100);
SELECT * FROM view2;
-- Update operation
UPDATE view2 SET cost = 3500 WHERE name = "BCCC";
SELECT * FROM view2;
-- Delete operation
DELETE FROM view2 WHERE name = "BCCC";
SELECT * FROM view2;
```
7. Display content of View1, View2.
```sql
SELECT * from view1;
SELECT * FROM view2;
```
---

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,86 @@
# Database Queries for Assignment-A4
## Creating tables
```sql
CREATE TABLE Borrower (
roll_no INT,
issuer_name VARCHAR(255),
issue_date DATE,
book_name VARCHAR(255),
status VARCHAR(1),
PRIMARY KEY (roll_no)
);
CREATE TABLE Fine (
roll_no INT,
return_date DATE,
amt INT,
FOREIGN KEY (roll_no) REFERENCES Borrower (roll_no)
);
```
## Inserting data
```sql
INSERT INTO Borrower VALUES (1, 'Kalas', TO_DATE('2024-10-19', 'YYYY-MM-DD'), 'DBMS', 'I');
INSERT INTO Borrower VALUES (2, 'Himanshu', TO_DATE('2024-10-01', 'YYYY-MM-DD'), 'TOC', 'I');
INSERT INTO Borrower VALUES (3, 'MEPA', TO_DATE('2024-10-25', 'YYYY-MM-DD'), 'IoT', 'I');
INSERT INTO Borrower VALUES (4, 'Kshitij', TO_DATE('2024-10-29', 'YYYY-MM-DD'), '1984', 'I');
```
## Procedure
```sql
DECLARE
p_roll NUMBER; -- specify roll number here since Live SQL cannot take input from user
-- Eg. p_roll NUMBER := 1; will take roll number 1 as input
p_book VARCHAR2(255); -- specify book name here since Live SQL cannot take input from user
-- Eg. p_book VARCHAR2(255) := 'DBMS';
p_issueDate DATE;
totalDays NUMBER;
currentDate DATE;
fineAmt NUMBER;
nodata EXCEPTION;
BEGIN
-- Check if roll number is valid
IF (p_roll <= 0) THEN
RAISE nodata;
END IF;
-- Storing values from table in variables
SELECT issue_date INTO p_issueDate FROM Borrower WHERE roll_no = p_roll AND book_name = p_book;
-- Getting the total days since book issue
SELECT TRUNC(SYSDATE) - p_issueDate INTO totalDays FROM dual;
-- Calculating fine
IF (totalDays > 30) THEN
fineAmt := totalDays * 50; -- Rs. 50 per day for total days greater than 30
ELSIF (totalDays BETWEEN 15 AND 30) THEN
fineAmt := totalDays * 5; -- Rs. 5 per day for total days between 15 and 30
ELSE
fineAmt := 0;
END IF;
-- Inserting data into Fine table
IF fineAmt > 0 THEN
DBMS_OUTPUT.PUT_LINE('Roll no. ' || p_roll || ' has been fined Rs. ' || fineAmt || ' for being ' || totalDays || ' days late.');
INSERT INTO Fine VALUES (p_roll, SYSDATE, fineAmt);
ELSE
DBMS_OUTPUT.PUT_LINE('Roll no. ' || p_roll || ' does not have to pay any fine.');
END IF;
UPDATE Borrower SET status = 'R' WHERE roll_no = p_roll AND book_name = p_book;
EXCEPTION
WHEN nodata THEN
DBMS_OUTPUT.PUT_LINE('Roll number' || p_roll || ' not found.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occured. Error: ' || SQLERRM);
END;
/
```

View File

@ -0,0 +1,54 @@
# Queries for Assignment-A5
> [!NOTE]
> Problem Statment: Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 5 to 9. Store the radius and the corresponding values of calculated area in an empty table named areas, consisting of two columns, radius and area.
> Note: Instructor will frame the problem statement for writing PL/SQL block in line with above statement.
## Creating table
```sql
CREATE TABLE areas (
radius INT NOT NULL,
area INT
);
```
## Procedure
```sql
DECLARE
v_radius NUMBER; -- specify radius here since Live SQL cannot take input from user
-- Eg. v_radius NUMBER := 5 will take radius 5 as input
calcedArea NUMBER;
invalidData EXCEPTION;
psError EXCEPTION;
BEGIN
-- if radius is less than 0, raise exception
IF (v_radius < 0) THEN
RAISE invalidData;
ELSIF (v_radius NOT BETWEEN 5 AND 9) THEN
RAISE psError;
END IF;
-- calc area
calcedArea := 3.14 * v_radius * v_radius;
DBMS_OUTPUT.PUT_LINE('For radius ' || v_radius || ' cm, the area is ' || calcedArea || ' sq. cm.');
-- add data to table
INSERT INTO areas VALUES (v_radius, calcedArea);
DBMS_OUTPUT.PUT_LINE('Inserted values to areas database.');
EXCEPTION
WHEN invalidData THEN
DBMS_OUTPUT.PUT_LINE('Radius cannot be less than 0 cms. Please enter a valid value.');
WHEN psError THEN
DBMS_OUTPUT.PUT_LINE('Problem statement requires the radius to be between 5 and 9 cms.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('An error occured. Error: ' || SQLERRM);
END;
/
```

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,80 @@
# Database Queries for Assignment-A6
## Creating tables
```sql
CREATE TABLE Stud_Marks (
roll INT,
name VARCHAR(255),
total_marks INT,
PRIMARY KEY (roll)
);
CREATE TABLE Result (
roll INT,
name VARCHAR(255),
class VARCHAR(255),
FOREIGN KEY (roll) REFERENCES Stud_Marks (roll)
);
```
## Inserting data
```sql
INSERT INTO Stud_Marks VALUES (1, 'Kshitij', 1400);
INSERT INTO Stud_Marks VALUES (2, 'Kalas', 500);
INSERT INTO Stud_Marks VALUES (3, 'Himanshu', 995);
INSERT INTO Stud_Marks VALUES (4, 'MEPA', 850);
INSERT INTO Stud_Marks VALUES (5, 'Macho', 900);
```
## Procedure
```sql
CREATE OR REPLACE PROCEDURE proc_Grade (roll_no IN NUMBER) AS
-- declare section
p_roll Stud_Marks.roll%TYPE;
p_name Stud_Marks.name%TYPE;
p_total NUMBER;
BEGIN
SELECT roll, name, total_marks INTO p_roll, p_name, p_total FROM Stud_Marks WHERE roll = roll_no;
IF (p_total <= 1500 AND p_total >= 990) THEN
INSERT INTO Result VALUES (p_roll, p_name, 'Distinction');
DBMS_OUTPUT.PUT_LINE(p_name || ' (roll no. ' || p_roll || ') has been placed in the DISTINCTION category.');
ELSIF (p_total BETWEEN 900 AND 989) THEN
INSERT INTO Result VALUES (p_roll, p_name, 'First Class');
DBMS_OUTPUT.PUT_LINE(p_name || ' (roll no. ' || p_roll || ') has been placed in the FIRST CLASS.');
ELSIF (p_total BETWEEN 825 AND 899) THEN
INSERT INTO Result VALUES (p_roll, p_name, 'Higher Second Class');
DBMS_OUTPUT.PUT_LINE(p_name || ' (roll no. ' || p_roll || ') has been placed in the HIGHER SECOND CLASS.');
ELSE
INSERT INTO Result VALUES (p_roll, p_name, 'Fail');
DBMS_OUTPUT.PUT_LINE(p_name || ' (roll no. ' || p_roll || ') has FAILED.');
END IF;
EXCEPTION
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('No entry for this roll number in the Stud_Marks database.');
END proc_Grade;
/
```
## Calling procedure
```sql
DECLARE
roll_no NUMBER;
BEGIN
roll_no := &roll_no; -- replace &roll_no with a number for Live SQL since it does not support user input.
proc_Grade(roll_no);
END;
/
```

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,110 @@
# Database Queries for Assignment-A7
## Creating tables
`O_RollCall` table:
```sql
CREATE TABLE O_RollCall(
name VARCHAR(255),
roll NUMBER(14),
class VARCHAR(255)
);
```
`N_RollCall` table:
```sql
CREATE TABLE N_RollCall(
name VARCHAR(255),
roll NUMBER(14),
class VARCHAR(255)
);
```
## Inserting data
`O_RollCall` table:
```sql
INSERT INTO O_RollCall VALUES ('Stewie', 1, 'Comp 1');
INSERT INTO O_RollCall VALUES ('Edie', 2, 'Comp 2');
INSERT INTO O_RollCall VALUES ('Stomp', 3, 'Comp 3');
INSERT INTO O_RollCall VALUES ('Lara', 4, 'Comp 1');
INSERT INTO O_RollCall VALUES ('Foxy', 5, 'Comp 2');
```
`N_RollCall` table:
```sql
INSERT INTO N_RollCall VALUES ('Stewie', 1, 'Comp 1');
INSERT INTO N_RollCall VALUES ('Edie', 2, 'Comp 2');
INSERT INTO N_RollCall VALUES ('Stomp', 3, 'Comp 3');
INSERT INTO N_RollCall VALUES ('Lara', 4, 'Comp 1');
INSERT INTO N_RollCall VALUES ('Foxy', 5, 'Comp 2');
INSERT INTO N_RollCall VALUES ('Gundeti', 6, 'Comp 3');
INSERT INTO N_RollCall VALUES ('Kalas', 7, 'Comp 2');
```
## Procedure
### Explicit cursor
```sql
DECLARE
p_name VARCHAR(255);
p_rollno NUMBER(15);
p_class VARCHAR(255);
CURSOR cc1 IS SELECT * FROM N_RollCall WHERE roll NOT IN (SELECT roll FROM O_RollCall);
BEGIN
OPEN cc1;
LOOP
FETCH cc1 INTO p_name, p_rollno, p_class;
INSERT INTO O_RollCall VALUES (p_name, p_rollno, p_class);
EXIT WHEN cc1%notfound;
DBMS_OUTPUT.PUT_LINE(p_name || ' ' || p_rollno || ' ' || p_class);
END LOOP;
CLOSE cc1;
END;
/
```
### Parameterized cursor
```sql
DECLARE
p_name VARCHAR(255);
p_rollno NUMBER(15);
p_class VARCHAR(255);
CURSOR pp1(roll1 NUMBER) IS SELECT * FROM N_RollCall WHERE roll > roll1;
BEGIN
OPEN pp1(3);
LOOP
FETCH pp1 INTO p_name, p_rollno, p_class;
EXIT WHEN pp1%notfound;
DBMS_OUTPUT.PUT_LINE(p_name || ' ' || p_rollno || ' ' || p_class);
END LOOP;
CLOSE pp1;
END;
/
```
### Implicit Cursor
```sql
DECLARE
total_rows NUMBER(2);
BEGIN
UPDATE N_RollCall SET roll = roll + 1;
IF sql%notfound THEN
dbms_output.put_line('no roll was updated');
ELSIF sql%found THEN
total_rows := sql%rowcount;
DBMS_OUTPUT.PUT_LINE( total_rows || ' roll calls were affected ');
END IF;
END;
/
```

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,93 @@
# Database Queries for Assignment-A8
## Creating tables
`Library` table:
```sql
CREATE TABLE Library(
id NUMBER(12),
title VARCHAR(255),
dateofissue DATE,
author VARCHAR(255)
);
```
`Library_Audit` table:
```sql
CREATE TABLE Library_Audit(
id NUMBER(12),
title VARCHAR(255),
dateofaction DATE,
author VARCHAR(255),
status VARCHAR(255)
);
```
## Inserting values
`Library` table:
```sql
INSERT INTO Library VALUES (1, 'Berserk', TO_DATE('2024-07-28','YYYY-MM-DD'), 'Prashant');
INSERT INTO Library VALUES (2, 'Dark', TO_DATE('2024-07-15','YYYY-MM-DD'), 'Rajendra');
INSERT INTO Library VALUES (3, 'Hannibal', TO_DATE('2024-07-20','YYYY-MM-DD'), 'Manoj');
INSERT INTO Library VALUES (4, 'AOT', TO_DATE('2024-07-30','YYYY-MM-DD'), 'Rajesh');
INSERT INTO Library VALUES (5, 'GOT', TO_DATE('2024-07-19','YYYY-MM-DD'), 'Anil');
```
## Trigger
```sql
CREATE OR REPLACE TRIGGER library_action
AFTER INSERT OR UPDATE OR DELETE ON Library
FOR EACH ROW
BEGIN
IF INSERTING THEN
INSERT INTO Library_Audit (id, title, dateofaction, author, status) VALUES (:NEW.id, :NEW.title, current_timestamp, :NEW.author, 'Insert');
ELSIF UPDATING THEN
INSERT INTO Library_Audit (id, title, dateofaction, author, status) VALUES (:OLD.id, :OLD.title, current_timestamp, :OLD.author, 'Update');
ELSIF DELETING THEN
INSERT INTO Library_Audit (id, title, dateofaction, author, status) VALUES (:OLD.id, :OLD.title, current_timestamp, :OLD.author, 'Delete');
END IF;
END;
/
```
## Testing trigger
### Insert operation
```sql
INSERT INTO Library VALUES (15, 'CREW', TO_DATE('2024-07-22','YYYY-MM-DD'), 'Ramesh');
INSERT INTO Library VALUES (14, 'Ninteen Eighty Four', TO_DATE('2024-07-01','YYYY-MM-DD'), 'Omkar');
SELECT * FROM Library;
SELECT * FROM Library_Audit;
```
### Update operation
```sql
UPDATE Library SET id = 6, title = 'Sherlock', author = 'Deepak' where id = 3;
UPDATE Library SET id = 7, title = 'MR. ROBOT', author = 'Varad' where id = 4;
SELECT * FROM Library;
SELECT * FROM Library_Audit;
```
### Delete operation
```sql
DELETE FROM Library WHERE id = 1;
DELETE FROM Library WHERE id = 5;
SELECT * FROM Library;
SELECT * FROM Library_Audit;
```
---

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,24 @@
sudo python3 -m pip install pymongo
###Open mongo
use test1
db.createCollection("emp")
###Open Python
from pymongo import MongoClient
client=MongoClient("mongodb://127.0.0.1:27017")
database=client.test1
collection=database.emp
collection.insert_one({"name":"smartphone","quantity":"10","price":"50000"})
print("inserted")
client.close()
## check output in mongo
Dr.S.K.Wagh (MES's Wadia COE,Pune)

View File

@ -0,0 +1,21 @@
sudo python3 -m pip install pymongo
###Open mongo
use test1
db.createCollection("emp")
###Open Python
from pymongo import MongoClient
client=MongoClient("mongodb://127.0.0.1:27017")
database=client.test1
collection=database.emp
collection.insert_one({"name":"smartphone","quantity":"10","price":"50000"})
print("inserted")
client.close()
## check output in mongo

Binary file not shown.

View File

@ -0,0 +1,217 @@
# Queries-B1
## Creation
```mongodb
use empDB
db.createCollection("Employee")
```
## Inserting data
```mongodb
db.Employee.insertMany([
{
Empid: 1,
Name: { FName: "Ayush", LName: "Kalaskar" },
Company_name: "Oscorp",
Salary: 50000,
Designation: "Programmer",
Age: 28,
Expertise: ["Java", "Spring", "MongoDB"],
DOB: "1995-04-15",
Email_id: "ayush.kalaskar@oscorp.com",
Contact: "9876543210",
Address: [{ PAddr: "123, Street A, Pune", LAddr: "Maharashtra" }]
},
{
Empid: 2,
Name: { FName: "Himanshu", LName: "Patil" },
Company_name: "Hammer Industries",
Salary: 60000,
Designation: "Developer",
Age: 30,
Expertise: ["JavaScript", "React", "Node.js"],
DOB: "1993-06-25",
Email_id: "himanshu.patil@hammerindustries.com",
Contact: "9876543211",
Address: [{ PAddr: "234, Street B, Bangalore", LAddr: "Karnataka" }]
},
{
Empid: 3,
Name: { FName: "Mehul", LName: "Patil" },
Company_name: "Lex Corp.",
Salary: 45000,
Designation: "Tester",
Age: 29,
Expertise: ["Selenium", "Python"],
DOB: "1994-08-12",
Email_id: "mehul.patil@lexcorp.org",
Contact: "9876543212",
Address: [{ PAddr: "345, Street C, Hyderabad", LAddr: "Telangana" }]
},
{
Empid: 4,
Name: { FName: "Tanmay", LName: "Machkar" },
Company_name: "Wayne Industries",
Salary: 70000,
Designation: "Project Manager",
Age: 35,
Expertise: ["Agile", "Scrum"],
DOB: "1988-02-20",
Email_id: "tanmay.machkar@batmobile.com",
Contact: "9876543213",
Address: [{ PAddr: "456, Street D, Chennai", LAddr: "Tamil Nadu" }]
},
{
Empid: 5,
Name: { FName: "Rajendra", LName: "Patil" },
Company_name: "Stark Industries",
Salary: 32000,
Designation: "Programmer",
Age: 27,
Expertise: ["Java", "Angular"],
DOB: "1996-03-30",
Email_id: "rajendra.patil@starkindustries.com",
Contact: "9876543214",
Address: [{ PAddr: "567, Street E, Delhi", LAddr: "Delhi" }]
},
{
Empid: 6,
Name: { FName: "Rajesh", LName: "Patil" },
Company_name: "Roxonn",
Salary: 50000,
Designation: "Designer",
Age: 32,
Expertise: ["Photoshop", "Illustrator"],
DOB: "1991-11-11",
Email_id: "rajesh.patil@roxonn.com",
Contact: "9876543215",
Address: [{ PAddr: "678, Street F, Kolkata", LAddr: "West Bengal" }]
},
{
Empid: 7,
Name: { FName: "Prashant", LName: "Kalaskar" },
Company_name: "Y-Space",
Salary: 45000,
Designation: "Tester",
Age: 26,
Expertise: ["Selenium", "Java"],
DOB: "1997-07-07",
Email_id: "prashant.kalaskar@y-space.com",
Contact: "9876543216",
Address: [{ PAddr: "789, Street G, Pune", LAddr: "Maharashtra" }]
},
{
Empid: 8,
Name: { FName: "Aditya", LName: "Gundeti" },
Company_name: "SNASA",
Salary: 80000,
Designation: "Architect",
Age: 33,
Expertise: ["Cloud", "Microservices"],
DOB: "1990-01-01",
Email_id: "aditya.gundeti@snasa.org",
Contact: "9876543217",
Address: [{ PAddr: "890, Street H, Noida", LAddr: "Uttar Pradesh" }]
},
{
Empid: 9,
Name: { FName: "Manoj", LName: "Patil" },
Company_name: "MEPA",
Salary: 40000,
Designation: "Developer",
Age: 31,
Expertise: ["C#", ".NET"],
DOB: "1992-05-05",
Email_id: "manoj.patil@mepa.com",
Contact: "9876543218",
Address: [{ PAddr: "901, Street I, Jaipur", LAddr: "Rajasthan" }]
},
{
Empid: 10,
Name: { FName: "Afan", LName: "Shaikh" },
Company_name: "Vought",
Salary: 39000,
Designation: "HR",
Age: 29,
Expertise: ["Recruitment", "Employee Relations"],
DOB: "1994-09-09",
Email_id: "afan.shaikh@vought.com",
Contact: "9876543219",
Address: [{ PAddr: "1234, Street J, Ahmedabad", LAddr: "Gujarat" }]
}
])
```
## Queries
1. Select all documents where Designation is "Programmer" and Salary > 30000:
```mongodb
db.Employee.find({ Designation: "Programmer", Salary: { $gt: 30000 } })
```
2. Create a new document if no document contains `{Designation: "Tester", Company_name: "Y-Space", Age: 25}`:
```mongodb
db.Employee.update(
{ Designation: "Tester", Company_name: "Y-Space", Age: 25 },
{ $setOnInsert: { Empid: 11, Name: { FName: "Anil", LName: "Salvi" }, Salary: 30000, DOB: "1998-01-01", Email_id: "anil.salvi@y-space.com", Contact: "9876543220", Address: [{ PAddr: "123 Street", LAddr: "Mumbai" }] } },
{ upsert: true }
)
```
3. Select all documents where Age < 30 or Salary > 40000:
```mongodb
db.Employee.find({ $or: [{ Age: { $lt: 30 } }, { Salary: { $gt: 40000 } }] })
```
4. Match documents where Address contains city "Pune" and Pin_code "411001":
```mongodb
db.Employee.find({ Address: { $elemMatch: { city: "Pune", Pin_code: "411001" } } })
```
5. Find all documents with Company_name "Oscorp" and modify their salary by 2000:
```mongodb
db.Employee.updateMany(
{ Company_name: "Oscorp" },
{ $inc: { Salary: 2000 } }
)
```
6. Find documents where Designation is not equal to "Developer":
```mongodb
db.Employee.find({ Designation: { $ne: "Developer" } })
```
7. Find _id, Designation, Address, and Name where Company_name is "Wayne Industries":
```mongodb
db.Employee.find(
{ Company_name: "Wayne Industries" },
{ _id: 1, Designation: 1, Address: 1, Name: 1 }
)
```
8. Select all documents where Designation is either "Developer" or "Tester":
```mongodb
db.Employee.find({ Designation: { $in: ["Developer", "Tester"] } })
```
9. Find all documents with exact match on Expertise array:
```mongodb
db.Employee.find({ Expertise: { $all: ["Cloud", "Microservices"] } })
```
10. Drop single documents where Designation is "Developer":
```mongodb
db.Employee.deleteMany({ Designation: "Developer" })
```

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,206 @@
## Queries-B2
### Group A
> [!NOTE]
> Use Employee database created in Assignment B-01 and perform following aggregation operation
> Refer [Queries-B1](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Assignment-B1/Queries-B1.md)
1. Return Designation with Total Salary Above 20000:
```mongodb
db.Employee.aggregate([
{
$group: {
_id: "$Designation",
TotalSalary: { $sum: "$Salary" }
}
},
{
$match: {
TotalSalary: { $gt: 20000 }
}
}
])
```
2. Find Employee with Total Salary for Each City with Designation "Developer":
```mongodb
db.Employee.aggregate([
{
$match: {
Designation: "Developer"
}
},
{
$group: {
_id: "$Address.PAddr",
Total: { $sum: "$Salary" }
}
}
])
```
3. Find Total Salary of Employee with Designation "Tester" for Each Company:
```mongodb
db.Employee.aggregate([
{
$match: { Designation: "Tester" }
},
{
$group: {
_id: "$Company_name",
TotalSalary: { $sum: "$Salary" }
}
}
])
```
4. Returns Names and _id in Upper Case and in Alphabetical Order:
```mongodb
db.Employee.aggregate([
{
$project: {
_id: 1,
Name: { $toUpper: { $concat: ["$Name.FName", " ", "$Name.LName"] } }
}
},
{
$sort: { Name: 1 }
}
])
```
5. Count All Records from Collection:
```mongodb
db.Employee.countDocuments()
```
6. For Each Unique Designation, Find Avg Salary and Output Sorted by AvgSal:
```mongodb
db.Employee.aggregate([
{
$group: {
_id: "$Designation",
AvgSalary: { $avg: "$Salary" }
}
},
{
$sort: { AvgSalary: 1 }
}
])
```
7. Return Separate Value in the Expertise Array Where Name of Employee is "Aditya":
```mongodb
db.Employee.aggregate([
{
$match: { "Name.FName": "Aditya" }
},
{
$unwind: "$Expertise"
},
{
$project: { Expertise: 1 }
}
])
```
8. Return Separate Value in the Expertise Array and Return Sum of Each Element of Array:
```mongodb
db.Employee.aggregate([
{
$unwind: "$Expertise"
},
{
$group: {
_id: "$Expertise",
TotalCount: { $sum: 1 }
}
}
])
```
9. Return Array for Designation Whose Address is "Pune":
```mongodb
db.Employee.aggregate([
{
$match: { "Address.PAddr": { $regex: "Pune" } }
},
{
$project: { Designation: 1 }
}
])
```
10. Return Max and Min Salary for Each Company:
```mongodb
db.Employee.aggregate([
{
$group: {
_id: "$Company_name",
MaxSalary: { $max: "$Salary" },
MinSalary: { $min: "$Salary" }
}
}
])
```
### Group B
> [!NOTE]
> Use Employee database created in Assignment B-01 and perform following aggregation operation
> Refer [Queries-B1](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Assignment-B1/Queries-B1.md)
1. Create Single Field Indexes on Designation:
```mongodb
db.Employee.createIndex({ Designation: 1 })
```
2. Create Compound Indexes on Name and Age:
```mongodb
db.Employee.createIndex({ "Name.FName": 1, Age: -1 })
```
3. Create Multikey Indexes on Expertise Array:
```mongodb
db.Employee.createIndex({ Expertise: 1 })
```
4. Return a List of All Indexes on Collection:
```mongodb
db.Employee.getIndexes()
```
5. Rebuild Indexes:
```mongodb
db.Employee.reIndex()
```
6. Drop Index on Remove Specific Index:
```mongodb
db.Employee.dropIndex("Designation_1")
```
7. Remove All Indexes Except for the _id Index from a Collection:
```mongodb
db.Employee.dropIndexes()
```

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,105 @@
## Queries-B3
> [!NOTE]
> Use Employee database created in Assignment B-01 and perform following aggregation operation
> Refer [Queries-B1](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Assignment-B1/Queries-B1.md)
1. Return the Total Salary of per Company
```mongodb
db.Employee.mapReduce(
function() {
emit(this.Company_name, this.Salary);
},
function(key, values) {
return Array.sum(values);
},
{ out: "total_salary_per_company" }
);
```
2. Return the Total Salary of Company Name:"Oscorp"
```mongodb
db.Employee.mapReduce(
function() {
if (this.Company_name === "Oscorp") {
emit(this.Company_name, this.Salary);
}
},
function(key, values) {
return Array.sum(values);
},
{ out: "total_salary_oscorp" }
);
```
3. Return the Avg Salary of Company whose address is “Pune".
```mongodb
db.Employee.mapReduce(
function() {
if (this.Address.some(addr => addr.PAddr.includes("Pune"))) {
emit("Pune", this.Salary);
}
},
function(key, values) {
return Array.avg(values);
},
{ out: "avg_salary_pune" }
);
```
4. Return the Total Salary for each Designation of `Wayne Industries`.
```mongodb
db.Employee.mapReduce(
function() {
if (this.Company_name === "Wayne Industries") {
emit(this.Designation, this.Salary);
}
},
function(key, values) {
return Array.sum(values);
},
{ out: "total_salary_wayne" }
);
```
5. Return total count for “State=Maharashtra”
```mongodb
db.Employee.mapReduce(
function() {
this.Address.forEach(function(addr) {
if (addr.LAddr === "Maharashtra") {
emit("Maharashtra", 1);
}
});
},
function(key, values) {
return Array.sum(values);
},
{ out: "count_state_maharashtra" }
);
```
6. Return Count for State Telangana and Age greater than 40.
```mongodb
db.Employee.mapReduce(
function() {
if (this.Age > 40) {
this.Address.forEach(function(addr) {
if (addr.LAddr === "Telangana") {
emit("Telangana_Age_Above_40", 1);
}
});
}
},
function(key, values) {
return Array.sum(values);
},
{ out: "count_telangana_age_above_40" }
);
```

Binary file not shown.

Binary file not shown.

View File

@ -0,0 +1,75 @@
# C1 - MongoDB Connectivity
**Problem Statement:** Write a program to implement MongoDB database connectivity with PHP /python /Java Implement Database navigation CRUD operations (add, delete, edit etc.)
---
## Pre-requisites (with installation command for Ubuntu):
1. Python3 - `sudo apt install python3`
2. pip - `sudo apt install python3-pip`
3. pymongo - `pip3 install pymongo` OR `pip3 install pymongo --break-system-packages` (installs it system-wide)
## Instructions
1. First, open the Terminal and log in to MongoDB:
```shell
mongo
```
2. Now, in Mongo we need to initialize the database and tables:
```json
// Create database
use connectMe;
// Create collection
db.createCollection("students");
// exit
exit
```
> We need to `exit` from Mongo shell since the work there is done for now.
3. Create a new file `connectMongo.py` with the following contents:
```python
from pymongo import MongoClient
client = MongoClient("mongodb://127.0.0.1:27017")
database = client.connectMe
collection = database.students
collection.insert_one({"roll":"21", "name":"Stewie"}) # insert operation
print("Inserted")
collection.insert_one({"roll":"22", "name":"Foxy"}) # insert operation
print("Inserted")
collection.update_one({"roll": "21"}, {"$set": {"roll": "20"}}) # update operation
print("Updated")
collection.delete_one({"roll": "22"})
print("Deleted")
client.close()
```
4. Open Terminal and run the above program:
```shell
python3 connectMongo.py
```
> [!NOTE]
> This step assume you have stored the file in home directory or you know how to change the current working directory.
5. That's it! You can view the changes in Mongo by logging in using `mongo` and viewing the table:
```json
USE connectMe;
db.students.find();
```
> [!Tip]
> This guide assumes your `mongo` shell does not have any password for root user.
> [!WARNING]
> Never use `root` as password in production. Use a strong password. This guide uses `root` as password for simplicity and educational purposes.
---

View File

@ -0,0 +1,103 @@
# C2 - MySQL Connectivity
**Problem Statement:** Implement MYSQL/Oracle database connectivity with PHP /python /Java Implement Database navigation operations (add, delete, edit,).
---
## Pre-requisites (with installation command for Ubuntu):
1. Python3 - `sudo apt install python3`
2. pip - `sudo apt install python3-pip`
3. mysql-connector - `pip3 install mysql-connector` OR `pip3 install mysql-connector --break-system-packages` (installs it system-wide)
## Instructions
1. First, open the Terminal and log in to MySQL:
```shell
mysql -u root -p
```
> [!NOTE]
> Usually the password in our labs is `root`. If you don't know the password, try running `sudo mysql`. This will run the `mysql` command as root.
2. Whether you logged in as root or not, run this command to set the password for `root` user in mysql which is required for connecting to the database:
```sql
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'root';
FLUSH PRIVILEGES;
```
3. Now, in MySQL we need to initialize the database and tables:
```sql
-- Creating the database
CREATE DATABASE connectMe;
USE connectMe;
-- Creating a table
CREATE TABLE students (
roll INT,
name VARCHAR(255)
);
-- Exit
exit
```
> We need to `exit` from MySQL shell since the work there is done for now.
5. Create a new file `connectSQL.py` with the following contents:
```python
import mysql.connector
# Connecting to MySQL database
db = mysql.connector.connect(
host="localhost",
user="root",
password="root", # Password of root user we set in step 2
database="connectMe" # Name of the database we created in step 3
)
Cursor = db.cursor()
sqlInsert = "INSERT INTO students (roll, name) VALUES (21, 'Stewie')" # insert operation
Cursor.execute(sqlInsert)
print(Cursor.rowcount, "record added to database.")
Cursor.execute(sqlInsert)
sqlInsert = "INSERT INTO students (roll, name) VALUES (22, 'Foxy')" # insert operation
print(Cursor.rowcount, "record added to database.")
sqlUpdate = "UPDATE students SET roll = 21 WHERE roll = 20" # update operation
Cursor.execute(sqlUpdate)
print(Cursor.rowcount, "record updated.")
sqlDelete = "DELETE FROM students WHERE roll = 20" # delete operation
Cursor.execute(sqlDelete)
print(Cursor.rowcount, "record deleted.")
db.commit()
Cursor.close()
db.close()
```
6. Open Terminal and run the above program:
```shell
python3 connectSQL.py
```
> [!NOTE]
> This step assume you have stored the file in home directory or you know how to change the current working directory.
7. That's it! You can view the changes in MySQL by logging in using `mysql -u root -p` (Password: `root`) and viewing the table:
```sql
USE connectMe;
SELECT * FROM students;
```
> [!WARNING]
> Never use `root` as password in production. Use a strong password. This guide uses `root` as password for simplicity and educational purposes.
---

View File

@ -0,0 +1,149 @@
# M1 - Crud Operations
**Problem Statement:**
Design and Develop MongoDB Queries using CRUD operations:
Create Employee collection by considering following Fields:
i. Name: Embedded Doc (FName, LName)
ii. Company Name: String
iii. Salary: Number
iv. Designation: String
v. Age: Number
vi. Expertise: Array
vii. DOB: String or Date
viii. Email id: String
ix. Contact: String
x. Address: Array of Embedded Doc (PAddr, LAddr)
Insert at least 5 documents in collection by considering above attribute and execute following queries:
1. Select all documents where the Designation field has the value
"Programmer" and the value of the salary field is greater than
30000.
2. Creates a new document if no document in the employee collection
contains
{Designation: "Tester", Company_name: "TCS", Age: 25}
3. Increase salary of each Employee working with “Infosys" 10000.
4. Finds all employees working with "TCS" and reduce their salary
by 5000.
5. Return documents where Designation is not equal to "Tester".
6. Find all employee with Exact Match on an Array having Expertise:
['Mongodb','Mysql','Cassandra']
---
## Creating database & collection:
```json
use empDB1
db.createCollection("Employee")
```
## Inserting data:
```json
db.Employee.insertMany([
{
Name: {FName: "Ayush", LName: "Kalaskar"},
Company: "TCS",
Salary: 45000,
Designation: "Programmer",
Age: 55,
Expertise: ['Docker', 'Linux', 'Networking', 'Politics'],
DOB: new Date("1969-03-12"),
Email: "ayush.k@tcs.com",
Contact: 9972410427,
Address: [{PAddr: "Kokan, Maharashtra"}, {LAddr: "Lohegaon, Pune"}]
},
{
Name: {FName: "Mehul", LName: "Patil"},
Company: "MEPA",
Salary: 55000,
Designation: "Tester",
Age: 60,
Expertise: ['HTML', 'CSS', 'Javascript', 'Teaching'],
DOB: new Date("1964-06-22"),
Email: "mehul.p@mepa.com",
Contact: 9972410426,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune"}]
},
{
Name: {FName: "Himanshu", LName: "Patil"},
Company: "Infosys",
Salary: 85000,
Designation: "Developer",
Age: 67,
Expertise: ['Mongodb', 'Mysql', 'Cassandra', 'Farming'],
DOB: new Date("1957-04-28"),
Email: "himanshu.p@infosys.com",
Contact: 9972410425,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune"}]
}
])
```
## Queries
1. Select all documents where the Designation field has the value "Programmer" and the value of the salary field is greater than 30000.
```json
db.Employee.find(
{ Designation: "Programmer", Salary: { $gt: 30000 } }
)
```
2. Creates a new document if no document in the employee collection contains `{Designation: "Tester", Company_name: "TCS", Age: 25}`
```json
db.Employee.updateOne(
{ Designation: "Tester", Company: "TCS", Age: 25 },
{ $setOnInsert: {
Name: {FName: "Karan", LName: "Salvi"},
Salary: 67500,
Expertise: ['Blockchain', 'C++', 'Python', 'Fishing'],
DOB: new Date("1999-11-01"),
Email: "karan.s@tcs.com",
Contact: 9972410424,
Address: [{PAddr: "Kolhapur, Maharashtra"}, {LAddr: "Viman Nagar, Pune"}]
}
},
{ upsert: true }
)
```
3. Increase salary of each Employee working with “Infosys" 10000.
```json
db.Employee.updateMany(
{ Company: "Infosys" },
{ $inc: { Salary: 10000 } }
)
```
4. Finds all employees working with "TCS" and reduce their salary by 5000.
```json
db.Employee.updateMany(
{ Company: "TCS" },
{ $inc: { Salary: -5000 } }
)
```
5. Return documents where Designation is not equal to "Tester".
```json
db.Employee.find(
{ Designation: { $ne: "Tester"} }
)
```
6. Find all employee with Exact Match on an Array having Expertise: `['Mongodb','Mysql','Cassandra']`
```json
db.Employee.find(
{ Expertise: { $all: ['Mongodb', 'Mysql', 'Cassandra'] } }
)
```
---

View File

@ -0,0 +1,160 @@
# M2 - Crud Operations
**Problem Statement:**
Design and Develop MongoDB Queries using CRUD operations:
Create Employee collection by considering following Fields:
i. Name: Embedded Doc (FName, LName)
ii. Company Name: String
iii. Salary: Number
iv. Designation: String
v. Age: Number
vi. Expertise: Array
vii. DOB: String or Date
viii. Email id: String
ix. Contact: String
x. Address: Array of Embedded Doc (PAddr, LAddr)
Insert at least 5 documents in collection by considering above
attribute and execute following queries:
1. Final name of Employee where age is less than 30 and salary more
than 50000.
2. Creates a new document if no document in the employee collection
contains
{Designation: "Tester", Company_name: "TCS", Age: 25}
3. Selects all documents in the collection where the field age has
a value less than 30 or the value of the salary field is greater
than 40000.
4. Find documents where Designation is not equal to "Developer".
5. Find _id, Designation, Address and Name from all documents where
Company_name is "Infosys".
6. Display only FName and LName of all Employees
---
## Creating database & collection:
```json
use empDB1
db.createCollection("Employee")
```
## Inserting data:
```json
db.Employee.insertMany([
{
Name: {FName: "Ayush", LName: "Kalaskar"},
Company: "TCS",
Salary: 45000,
Designation: "Programmer",
Age: 24,
Expertise: ['Docker', 'Linux', 'Networking', 'Politics'],
DOB: new Date("1998-03-12"),
Email: "ayush.k@tcs.com",
Contact: 9972410427,
Address: [{PAddr: "Kokan, Maharashtra"}, {LAddr: "Lohegaon, Pune"}]
},
{
Name: {FName: "Mehul", LName: "Patil"},
Company: "MEPA",
Salary: 55000,
Designation: "Tester",
Age: 20,
Expertise: ['HTML', 'CSS', 'Javascript', 'Teaching'],
DOB: new Date("1964-06-22"),
Email: "mehul.p@mepa.com",
Contact: 9972410426,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune"}]
},
{
Name: {FName: "Himanshu", LName: "Patil"},
Company: "Infosys",
Salary: 85000,
Designation: "Developer",
Age: 67,
Expertise: ['Mongodb', 'Mysql', 'Cassandra', 'Farming'],
DOB: new Date("1957-04-28"),
Email: "himanshu.p@infosys.com",
Contact: 9972410425,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune"}]
}
])
```
## Queries
1. Final name of Employee where age is less than 30 and salary more than 50000.
```json
db.Employee.find(
{
Age: { $lt: 30 },
Salary: { $gt: 50000 }
}
)
```
2. Creates a new document if no document in the employee collection contains `{Designation: "Tester", Company_name: "TCS", Age: 25}`
```json
db.Employee.updateOne(
{Designation: "Tester", Company: "TCS", Age: 25},
{ $setOnInsert:
{
Name: {FName: "Karan", LName: "Salvi"},
Salary: 35000,
Expertise: ['Blockchain', 'C++', 'Python', 'Fishing'],
DOB: new Date("1999-11-01"),
Email: "karan.s@tcs.com",
Contact: 9972410424,
Address: [{PAddr: "Kolhapur, Maharashtra"}, {LAddr: "Viman Nagar, Pune"}]
}
},
{ upsert: true }
)
```
3. Selects all documents in the collection where the field age has a value less than 30 or the value of the salary field is greater than 40000.
```json
db.Employee.find(
{ $or:
[
{ Age: { $lt: 30 } },
{ Salary: { $gt: 40000 } }
]
}
)
```
4. Find documents where Designation is not equal to "Developer".
```json
db.Employee.find(
{
Designation: { $ne: "Developer" }
}
)
```
5. Find _id, Designation, Address and Name from all documents where Company_name is "Infosys".
```json
db.Employee.find(
{ Company: "Infosys" },
{ _id: 1, Designation: 1, Address: 1, Name: 1 }
)
```
6. Display only FName and LName of all Employees.
```json
db.Employee.find(
{},
{"Name.FName": 1, "Name.LName": 1}
)
```
---

View File

@ -0,0 +1,158 @@
# M3 - Crud Operations
**Problem Statement:**
Design and Develop MongoDB Queries using CRUD operations:
Create Employee collection by considering following Fields:
i. Emp_id : Number
ii. Name: Embedded Doc (FName, LName)
iii. Company Name: String
iv. Salary: Number
v. Designation: String
vi. Age: Number
vii. Expertise: Array
viii. DOB: String or Date
ix. Email id: String
x. Contact: String
xi. Address: Array of Embedded Doc (PAddr, LAddr)
Insert at least 5 documents in collection by considering above
attribute and execute following queries:
1. Creates a new document if no document in the employee collection
contains
{Designation: "Tester", Company_name: "TCS", Age: 25}
2. Finds all employees working with Company_name: "TCS" and
increase their salary by 2000.
3. Matches all documents where the value of the field Address is an
embedded document that contains only the field city with the
value "Pune" and the field Pin_code with the value "411001".
4. Find employee details who are working as "Developer" or
"Tester".
5. Drop Single documents where designation="Developer".
6. Count number of documents in employee collection.
---
## Creating database & collection:
```json
use empDB3
db.createCollection("Employee")
```
## Inserting data:
```json
db.Employee.insertMany([
{
Name: {FName: "Ayush", LName: "Kalaskar"},
Company: "TCS",
Salary: 45000,
Designation: "Programmer",
Age: 24,
Expertise: ['Docker', 'Linux', 'Networking', 'Politics'],
DOB: new Date("1998-03-12"),
Email: "ayush.k@tcs.com",
Contact: 9972410427,
Address: [{PAddr: "Kokan, Maharashtra"}, {LAddr: "Lohegaon, Pune", Pin_code: 411014}]
},
{
Name: {FName: "Mehul", LName: "Patil"},
Company: "MEPA",
Salary: 55000,
Designation: "Tester",
Age: 20,
Expertise: ['HTML', 'CSS', 'Javascript', 'Teaching'],
DOB: new Date("1964-06-22"),
Email: "mehul.p@mepa.com",
Contact: 9972410426,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune", Pin_code: 411001}]
},
{
Name: {FName: "Himanshu", LName: "Patil"},
Company: "Infosys",
Salary: 85000,
Designation: "Developer",
Age: 67,
Expertise: ['Mongodb', 'Mysql', 'Cassandra', 'Farming'],
DOB: new Date("1957-04-28"),
Email: "himanshu.p@infosys.com",
Contact: 9972410425,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune", Pin_code: 411001}]
}
])
```
## Queries
1. Creates a new document if no document in the employee collection contains `{Designation: "Tester", Company_name: "TCS", Age: 25}`
```json
db.Employee.updateOne(
{Designation: "Tester", Company: "TCS", Age: 25},
{ $setOnInsert: {
Name: {FName: "Karan", LName: "Salvi"},
Salary: 67500,
Expertise: ['Blockchain', 'C++', 'Python', 'Fishing'],
DOB: new Date("1999-11-01"),
Email: "karan.s@tcs.com",
Contact: 9972410424,
Address: [{PAddr: "Kolhapur, Maharashtra"}, {LAddr: "Viman Nagar, Pune", Pin_code: 411014}]
}
},
{ upsert: true }
)
```
2. Finds all employees working with Company_name: "TCS" and increase their salary by 2000.
```json
db.Employee.updateMany(
{ Company: "TCS" },
{ $inc: { Salary: 2000 } }
)
```
3. Matches all documents where the value of the field Address is an embedded document that contains only the field city with the value "Pune" and the field Pin_code with the value "411001".
```json
db.Employee.find(
{ $or: [
{
"Address.Pin_code": 411001,
"Address.LAddr": { $regex: /Pune/i }
},
{
"Address.Pin_code": 411001,
"Address.PAddr": { $regex: /Pune/i }
}
]
}
)
```
4. Find employee details who are working as "Developer" or "Tester".
```json
db.Employee.find(
{ $or: [
{ Designation: "Developer" },
{ Designation: "Tester" }
]
}
)
```
5. Drop Single documents where Designation="Developer"
```json
db.Employee.deleteOne( { Designation: "Developer" } )
```
6. Count number of documents in employee collection.
```json
db.Employee.countDocuments();
```
---

View File

@ -0,0 +1,205 @@
# M4 - Aggregation and Indexing
**Problem Statement:**
Design and Develop MongoDB Queries using Aggregation operations:
Create Employee collection by considering following Fields:
i. Emp_id : Number
ii. Name: Embedded Doc (FName, LName)
iii. Company Name: String
iv. Salary: Number
v. Designation: String
vi. Age: Number
vii. Expertise: Array
viii. DOB: String or Date
ix. Email id: String
x. Contact: String
xi. Address: Array of Embedded Doc (PAddr, LAddr)
Insert at least 5 documents in collection by considering above
attribute and execute following:
1. Using aggregation Return Designation with Total Salary is Above
200000.
2. Using Aggregate method returns names and _id in upper case and
in alphabetical order.
3. Using aggregation method find Employee with Total Salary for
Each City with Designation="DBA".
4. Create Single Field Indexes on Designation field of employee
collection
5. To Create Multikey Indexes on Expertise field of employee
collection.
6. Create an Index on Emp_id field, compare the time require to
search Emp_id before and after creating an index. (Hint Add at
least 10000 Documents)
7. Return a List of Indexes on created on employee Collection.
---
## Creating database & collection:
```json
use empDB2
db.createCollection("Employee")
```
## Inserting data:
```json
db.Employee.insertMany([
{
Name: {FName: "Ayush", LName: "Kalaskar"},
Company: "TCS",
Salary: 45000,
Designation: "Programmer",
Age: 24,
Expertise: ['Docker', 'Linux', 'Networking', 'Politics'],
DOB: new Date("1998-03-12"),
Email: "ayush.k@tcs.com",
Contact: 9972410427,
Address: [{PAddr: "Kokan, Maharashtra"}, {LAddr: "Lohegaon, Pune", Pin_code: 411014}]
},
{
Name: {FName: "Mehul", LName: "Patil"},
Company: "MEPA",
Salary: 55000,
Designation: "Tester",
Age: 20,
Expertise: ['HTML', 'CSS', 'Javascript', 'Teaching'],
DOB: new Date("1964-06-22"),
Email: "mehul.p@mepa.com",
Contact: 9972410426,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune", Pin_code: 411001}]
},
{
Name: {FName: "Himanshu", LName: "Patil"},
Company: "Infosys",
Salary: 85000,
Designation: "Developer",
Age: 67,
Expertise: ['Mongodb', 'Mysql', 'Cassandra', 'Farming'],
DOB: new Date("1957-04-28"),
Email: "himanshu.p@infosys.com",
Contact: 9972410425,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune", Pin_code: 411001}]
},
{
Name: {FName: "Tanmay", LName: "Macho"},
Company: "Wayne Industries",
Salary: 95000,
Designation: "DBA",
Age: 75,
Expertise: ['Blockchain', 'Hashing', 'Encryption', 'Nerd'],
DOB: new Date("1949-12-28"),
Email: "tanmay.m@wayne.com",
Contact: 9972410426,
Address: [{PAddr: "Viman Nagar, Pune"}, {LAddr: "Viman Nagar, Pune", Pin_code: 411001}]
}
])
```
## Queries
1. Using aggregation Return Designation with Total Salary is Above 200000.
```json
db.Employee.aggregate([
{
$group: {
_id: "$Designation",
TotalSalary: { $sum: "$Salary" }
}
},
{
$match: {
TotalSalary: { $gt: 20000 }
}
}
])
```
2. Using Aggregate method returns names and _id in upper case and in alphabetical order.
```json
db.Employee.aggregate([
{
$project: {
_id: 1,
Name: { $toUpper: { $concat: [ "$Name.FName", " ", "$Name.LName" ] } }
}
},
{ $sort: { Name: 1 } }
])
```
3. Using aggregation method find Employee with Total Salary for Each City with Designation="DBA".
```json
db.Employee.aggregate([
{
$match: {
Designation: "DBA"
}
},
{
$group: {
_id: "$Address.PAddr",
Salary: { $sum: "$Salary" }
}
}
])
```
4. Create Single Field Indexes on Designation field of employee collection
```json
db.Employee.createIndex( { Designation: 1 } )
```
5. To Create Multikey Indexes on Expertise field of employee collection.
```json
db.Employee.createIndex( { Expertise: 1 } )
```
6. Create an Index on Emp_id field, compare the time require to search Emp_id before and after creating an index. (Hint Add at least 10000 Documents)
```json
// Adding 1000 employees
for (let i = 1; i <= 10000; i++) {
db.Employee.insertOne({
Emp_id: i,
Name: `Employee ${i}`,
Designation: `Work ${i*5}`
});
}
// Wait for it to insert 10000 documents!
// Time without index
let startTime = new Date();
db.Employee.find({ Emp_id: 7500 })
let endTime = new Date();
print("Time taken to search without index: " + (endTime - startTime) + " ms");
// Creating index on Emp_id
db.Employee.createIndex( { Emp_id: 1 });
// Time with index
startTime = new Date();
db.Employee.find({ Emp_id: 7500 })
endTime = new Date();
print("Time taken to search with index: " + (endTime - startTime) + " ms");
```
<details>
<summary>Output for query 6:</summary>
Time taken to search without index: 41 ms<br>
Time taken to search with index: 29 ms<br>
</details>
7. Return a List of Indexes on created on employee Collection.
```sql
db.Employee.getIndexes()
```
---

View File

@ -0,0 +1,217 @@
# M5 - Aggregation and Indexing
**Problem Statement:**
Design and Develop MongoDB Queries using Aggregation operations:
Create Employee collection by considering following Fields:
i. Emp_id : Number
ii. Name: Embedded Doc (FName, LName)
iii. Company Name: String
iv. Salary: Number
v. Designation: String
vi. Age: Number
vii. Expertise: Array
viii. DOB: String or Date
ix. Email id: String
x. Contact: String
xi. Address: Array of Embedded Doc (PAddr, LAddr)
Insert at least 5 documents in collection by considering above
attribute and execute following:
1. Using aggregation Return separates value in the Expertise array
and return sum of each element of array.
2. Using Aggregate method return Max and Min Salary for each
company.
3. Using Aggregate method find Employee with Total Salary for Each
City with Designation="DBA".
4. Using aggregation method Return separates value in the Expertise
array for employee name where Swapnil Jadhav
5. To Create Compound Indexes on Name: 1, Age: -1
6. Create an Index on Emp_id field, compare the time require to
search Emp_id before and after creating an index. (Hint Add at
least 10000 Documents)
7. Return a List of Indexes on created on employee Collection.
---
## Creating database & collection:
```json
use empDB3
db.createCollection("Employee")
```
## Inserting data:
```json
db.Employee.insertMany([
{
Name: {FName: "Ayush", LName: "Kalaskar"},
Company: "TCS",
Salary: 45000,
Designation: "Programmer",
Age: 24,
Expertise: ['Docker', 'Linux', 'Networking', 'Politics'],
DOB: new Date("1998-03-12"),
Email: "ayush.k@tcs.com",
Contact: 9972410427,
Address: [{PAddr: "Kokan, Maharashtra"}, {LAddr: "Lohegaon, Pune", Pin_code: 411014}]
},
{
Name: {FName: "Mehul", LName: "Patil"},
Company: "MEPA",
Salary: 55000,
Designation: "Tester",
Age: 20,
Expertise: ['HTML', 'CSS', 'Javascript', 'Teaching'],
DOB: new Date("1964-06-22"),
Email: "mehul.p@mepa.com",
Contact: 9972410426,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune", Pin_code: 411001}]
},
{
Name: {FName: "Himanshu", LName: "Patil"},
Company: "Infosys",
Salary: 85000,
Designation: "Developer",
Age: 67,
Expertise: ['Mongodb', 'Mysql', 'Cassandra', 'Farming'],
DOB: new Date("1957-04-28"),
Email: "himanshu.p@infosys.com",
Contact: 9972410425,
Address: [{PAddr: "NDB, Maharashtra"}, {LAddr: "Camp, Pune", Pin_code: 411001}]
},
{
Name: {FName: "Swapnil", LName: "Jadhav"},
Company: "Wayne Industries",
Salary: 95000,
Designation: "DBA",
Age: 75,
Expertise: ['Blockchain', 'Hashing', 'Encryption', 'Nerd'],
DOB: new Date("1949-12-28"),
Email: "swapnil.j@wayne.com",
Contact: 9972410427,
Address: [{PAddr: "Viman Nagar, Pune"}, {LAddr: "Viman Nagar, Pune", Pin_code: 411001}]
}
])
```
## Queries
1. Using aggregation Return separates value in the Expertise array and return sum of each element of array.
```json
db.Employee.aggregate([
{
$unwind: "$Expertise"
},
{
$group: {
_id: "$Expertise",
count: { $sum: 1 }
}
}
])
```
2. Using Aggregate method return Max and Min Salary for each company.
```json
db.Employee.aggregate([
{
$group: {
_id: "$Company",
MIN: { $min: "$Salary" },
MAX: { $max: "$Salary" }
}
}
])
```
3. Using Aggregate method find Employee with Total Salary for Each City with Designation="DBA".
```json
db.Employee.aggregate([
{
$match: {
Designation: "DBA"
}
},
{
$group: {
_id: "$Address.PAddr",
Total: { $sum: "$Salary" }
}
}
])
```
4. Using aggregation method Return separates value in the Expertise array for employee name where Swapnil Jadhav
```json
db.Employee.aggregate([
{
$match: {
"Name.FName": "Swapnil",
"Name.LName": "Jadhav"
}
},
{
$unwind: "$Expertise"
},
{
$group: {
_id: "$Expertise"
}
}
])
```
5. To Create Compound Indexes on Name: 1, Age: -1
```json
db.Employee.createIndex({Name: 1, Age: -1})
```
6. Create an Index on Emp_id field, compare the time require to search Emp_id before and after creating an index. (Hint Add at least 10000 Documents)
```json
// Creating 10000 documents
for (let i=1; i<=10000; i++) {
db.Employee.insertOne({
Emp_id: i,
Name: `Employee ${i}`,
Designation: `Work ${i*5}`
});
}
// Wait for it to insert 10000 documents!
// Time without index
let startTime = new Date();
db.Employee.find( { Emp_id: 7500 } );
let endTime = new Date();
print("Time taken to search before index: " + (endTime - startTime) + "ms");
// Creating index on Emp_id
db.Employee.createIndex( { Emp_id: 1 } )
// Time with index
startTime = new Date();
db.Employee.find( { Emp_id: 7500 } );
endTime = new Date();
print("Time taken to search after index: " + (endTime - startTime) + "ms")
```
<details>
<summary>Output for query 6:</summary>
Time taken to search before index: 57ms<br>
Time taken to search after index: 35ms
</details>
7. Return a List of Indexes on created on employee Collection.
```json
db.Employee.getIndexes();
```
---

View File

@ -0,0 +1,178 @@
# M6 - Map-reduce
**Problem statement:**
Design MongoDB database and perform following Map reduce operation:
Create Employee collection by considering following Fields:
i. Name: Embedded Doc (FName, LName)
ii. Company Name: String
iii. Salary: Number
iv. Designation: String
v. Age: Number
vi. Expertise: Array
vii. DOB: String or Date
viii. Email id: String
ix. Contact: String
x. Address: Array of Embedded Doc (PAddr, LAddr)
Execute the following query:
---
## Creating database
```mongo
use mapred;
```
## Inserting data:
```mongo
db.emp.insertMany([
{
Name: {FName: "Tanmay", LName: "Machkar"},
Company: "TCS",
Salary: 40000,
Designation: "Tester",
Age: 25,
Expertise: ['Mongodb','Mysql','Cassandra'],
DOB: new Date("2003-12-02"),
Email: "xyz@gmail.com",
Contact: 1234567890,
Address: [{PAddr: {City: "Pune", Rd: "Bharatmata"}}, {LAddr: {Pin_code: 411001}}]
},
{
Name: {FName: "Rajesh", LName: "Machkar"},
Company: "Infosys",
Salary: 50000,
Designation: "Programmer",
Age: 29,
Expertise: ['Mongodb','Mysql'],
DOB: new Date("1990-12-02"),
Email: "xy@gmail.com",
Contact: 1234567809,
Address: [{PAddr: {City: "Pune", Rd: "JM"}}, {LAddr: {Pin_code: 411047}}]
},
{
Name: {FName: "Tejas", LName: "Machkar"},
Company: "TCS",
Salary: 20000,
Designation: "Developer",
Age: 35,
Expertise: ['Mongodb'],
DOB: new Date("2000-11-22"),
Email: "x@gmail.com",
Contact: 1234567089,
Address: [{PAddr: {City: "Mumbai", Rd: "Airport"}}, {LAddr: {Pin_code: 411030}}]
},
{
Name: {FName: "Deepali", LName: "Machkar"},
Company: "Persistent",
Salary: 40000,
Designation: "Tester",
Age: 30,
Expertise: ['Mysql'],
DOB: new Date("1978-02-12"),
Email: "y@gmail.com",
Contact: 1234506789,
Address: [{PAddr: {City: "Phaltan", Rd: "Highway"}}, {LAddr: {Pin_code: 411012}}]
},
{
Name: {FName: "Om", LName: "Deokar"},
Company: "Persistent",
Salary: 25000,
Designation: "Programmer",
Age: 39,
Expertise: ['Cassandra'],
DOB: new Date("2007-03-15"),
Email: "z@gmail.com",
Contact: 1234567890,
Address: [{PAddr: {City: "Jaipur", Rd: "Pink"}}, {LAddr: {Pin_code: 411056}}]
},
])
```
## Queries
1. Display the total salary of per company.
```mongo
db.emp.mapReduce(
function(){
emit(this.Company, this.Salary);
},
function(key, values){
return Array.sum(values);
},
{ out: "query1"}
)
db.query1.find()
```
2. Display the total salary of company Name:"TCS".
```mongo
db.emp.mapReduce(
function(){
if(this.Company == "TCS"){
emit(this.Company, this.Salary);
}
},
function(key, values){
return Array.sum(values);
},
{ out: "query2"}
)
db.query2.find()
```
3. Return the average salary of company whose address is “Pune".
```mongo
db.emp.mapReduce(
function(){
if(this.Address[0].PAddr.City === "Pune"){
emit(this.Company, this.Salary);
}
},
function(key, values){
return Array.avg(values);
},
{ out: "query3"}
)
db.query3.find()
```
4. Display total count for “City=Pune”.
```mongo
db.emp.mapReduce(
function(){
if(this.Address[0].PAddr.City === "Pune"){
emit("Count", 1);
}
},
function(key, values){
return Array.sum(values);
},
{ out: "query4"}
)
db.query4.find()
```
5. Return count for city pune and age greater than 40.
```mongo
db.emp.mapReduce(
function(){
if(this.Address[0].PAddr.City === "Pune" && this.Age > 25){
emit("Count", 1);
}
},
function(key, values){
return Array.sum(values);
},
{ out: "query5"}
)
db.query5.find()
```
---

View File

@ -0,0 +1,32 @@
# P1 - PL-SQL code
**Problem Statement:** Write a PL/SQL code block to calculate the area of a circle for a value of radius varying from 5 to 9. Store the radius and the corresponding values of calculated area in an empty table named areas, consisting of two columns, radius and area.
---
## Procedure
```plsql
DECLARE
radius NUMBER;
area NUMBER;
nodata EXCEPTION;
BEGIN
DBMS_OUTPUT.PUT_LINE('Enter radius: ');
radius := &radius; -- for Live SQL, specify a value. Eg. radius := 5;
IF NOT (radius BETWEEN 5 AND 9) THEN
raise nodata;
END IF;
area := 3.14 * radius * radius;
DBMS_OUTPUT.PUT_LINE('Area of circle with radius ' || radius || ' cm is ' || area || ' sq.cm.');
EXCEPTION
WHEN nodata THEN
DBMS_OUTPUT.PUT_LINE('Radius should be between 5 and 9.');
END;
/
```
---

View File

@ -0,0 +1,87 @@
# P10 - Trigger
**Problem Statement:** Trigger: Write a after trigger for Insert, update and delete event considering following requirement:
Emp(Emp_no, Emp_name, Emp_salary)
a) Trigger should be initiated when salary tried to be inserted is less than Rs.50,000/-
b) Trigger should be initiated when salary tried to be updated for value less than Rs. 50,000/-
Also the new values expected to be inserted will be stored in new table Tracking(Emp_no,Emp_salary).
---
## Creating tables:
```sql
CREATE TABLE Emp(
Emp_no NUMBER(14),
Emp_name VARCHAR(255),
Emp_salary NUMBER(14)
);
CREATE TABLE Tracking(
Emp_no NUMBER(14),
Emp_salary NUMBER(14)
);
```
## Trigger
```sql
CREATE OR REPLACE TRIGGER P10
AFTER INSERT OR UPDATE ON Emp
FOR EACH ROW
BEGIN
IF inserting THEN
IF (:New.Emp_salary < 50000) THEN
insert into Tracking (Emp_no, Emp_salary) VALUES (:New.Emp_no, :New.Emp_salary);
DBMS_OUTPUT.PUT_LINE('Inserting record with salary < 50000');
END IF;
ELSIF updating THEN
IF (:New.Emp_salary < 50000) THEN
UPDATE Tracking SET Emp_salary = :New.Emp_salary WHERE Emp_no = :Old.Emp_no;
DBMS_OUTPUT.PUT_LINE('Updated value of salary < 50000 for a record');
END IF;
END IF;
END;
/
```
1. After performing insertion operation:
```sql
INSERT INTO Emp VALUES (1, 'Tanmay', 45000);
INSERT INTO Emp VALUES (2, 'Rajesh', 35000);
```
<details>
<summary>Output</summary>
1 row(s) inserted.<br>
Inserting record with salary < 50000<br>
<br>
1 row(s) inserted.<br>
Inserting record with salary < 50000<br>
<br>
Tracking:<br>
EMP_NO EMP_SALARY<br>
1 45000<br>
2 35000<br>
</details>
2. After performing update operation:
```sql
UPDATE Emp SET Emp_salary = 43000 WHERE Emp_no = 1;
```
<details>
<summary>Output</summary>
1 row(s) updated.<br>
Updated value of salary < 50000 for a record<br>
<br>
Tracking:<br>
EMP_NO EMP_SALARY<br>
1 43000<br>
2 35000<br>
</details>
---

View File

@ -0,0 +1,102 @@
# P2 - Unamed PL-SQL
**Problem Statement:**
Write an Unnamed PL/SQL of code for the following requirements: -
Schema:
Borrower (Rollin, Name, DateofIssue, NameofBook, Status)
Fine (Roll_no,Date,Amt)
Accept roll_no & name of book from user.
Check the number of days (from date of issue).
1. If days are between 15 to 30 then fine amounts will be Rs 5 per
day.
2. If no. of days>30, per day fine will be Rs 50 per day & for days
less than 30, Rs. 5 per day.
3. After submitting the book, status will change from I to R.
4. If condition of fine is true, then details will be stored into
fine table.
---
## Creating tables
```plsql
CREATE TABLE Borrower (
rollin NUMBER,
Name VARCHAR2(255),
DateofIssue DATE,
NameofBook VARCHAR2(255),
Status VARCHAR2(255),
PRIMARY KEY (rollin)
);
CREATE TABLE Fine (
Roll_no NUMBER,
DateofReturn DATE,
Amt NUMBER,
FOREIGN KEY (Roll_no) REFERENCES Borrower (rollin)
);
```
> [!WARNING]
> Notice inconsistent naming for columns? We're just doing it by the books. Blame the one who made these [problem statements](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Practical%20Exam/DBMSL%20-%20Problem%20Statements%20for%20Practical%20Exam%20%28November%202024%29.pdf).
## Inserting data
```plsql
INSERT INTO Borrower VALUES (1, 'Kalas', TO_DATE('2024-10-19', 'YYYY-MM-DD'), 'DBMS', 'I');
INSERT INTO Borrower VALUES (2, 'Himanshu', TO_DATE('2024-11-01', 'YYYY-MM-DD'), 'IOT', 'I');
INSERT INTO Borrower VALUES (3, 'Mepa', TO_DATE('2024-10-29', 'YYYY-MM-DD'), 'TOC', 'I');
INSERT INTO Borrower VALUES (4, 'Jambo', TO_DATE('2024-10-20', 'YYYY-MM-DD'), 'CNS', 'I');
```
## Procedure
```plsql
DECLARE
p_roll NUMBER;
p_book VARCHAR2(255);
p_issueDate DATE;
totalDays INT;
fineAmt INT;
nodata EXCEPTION;
BEGIN
DBMS_OUTPUT.PUT_LINE('Enter roll number: ');
p_roll := &p_roll; -- specify value directly for Live SQL. Eg.: p_roll := 1;
DBMS_OUTPUT.PUT_LINE('Enter book name: ');
p_book := '&p_book'; -- specify value directly for Live SQL. Eg.: p_roll := 'DBMS';
IF (p_roll <= 0) THEN
RAISE nodata;
END IF;
SELECT DateofIssue INTO p_issueDate FROM Borrower WHERE rollin = p_roll AND NameofBook = p_book;
SELECT TRUNC(SYSDATE) - p_issueDate INTO totalDays FROM dual;
IF (totalDays > 30) THEN
fineAmt := (15 * 5) + ((totalDays - 15) * 50); -- Rs 5 for first 15 days, Rs 50 for remaining
DBMS_OUTPUT.PUT_LINE('Roll no. ' || p_roll || ' has been fined Rs. ' || fineAmt);
INSERT INTO Fine VALUES (p_roll, SYSDATE, fineAmt);
UPDATE Borrower SET Status = 'R' WHERE Rollin = p_roll AND NameofBook = p_book;
ELSIF (totalDays BETWEEN 15 AND 30) THEN
fineAmt := totalDays * 5;
DBMS_OUTPUT.PUT_LINE('Roll no. '|| p_roll || ' has been fined Rs. ' || fineAmt);
INSERT INTO Fine VALUES (p_roll, SYSDATE, fineAmt);
UPDATE Borrower SET Status = 'R' WHERE Rollin = p_roll AND NameofBook = p_book;
ELSE
fineAmt := 0;
DBMS_OUTPUT.PUT_LINE('No fine for roll no. '|| p_roll);
INSERT INTO Fine VALUES (p_roll, SYSDATE, fineAmt);
UPDATE Borrower SET Status = 'R' WHERE Rollin = p_roll AND NameofBook = p_book;
END IF;
EXCEPTION
WHEN nodata THEN
DBMS_OUTPUT.PUT_LINE('Please enter a valid roll number.');
WHEN NO_DATA_FOUND THEN
DBMS_OUTPUT.PUT_LINE('Something went wrong. Please check input data.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error occured. Error: ' || SQLERRM);
END;
/
```
---

View File

@ -0,0 +1,58 @@
# P3 - Cursor
**Problem Statement:** Write a PL/SQL block of code using Cursor that will merge the data available in the newly created table N_Roll Call with the data available in the table O_RollCall. If the data in the first table already exist in the second table, then that data should be skipped.
---
## Creating tables
```plsql
CREATE TABLE O_RollCall (
roll NUMBER NOT NULL,
name VARCHAR2(255),
class VARCHAR2(255)
);
CREATE TABLE N_RollCall (
roll NUMBER NOT NULL,
name VARCHAR2(255),
class VARCHAR2(255)
);
```
## Inserting values
```plsql
INSERT INTO O_RollCall VALUES (2, 'Eddie', 'COMP-2');
INSERT INTO O_RollCall VALUES (3, 'Foxy', 'COMP-1');
INSERT INTO O_RollCall VALUES (5, 'Stomp', 'COMP-3');
INSERT INTO N_RollCall VALUES (1, 'Stewie', 'COMP-1');
INSERT INTO N_RollCall VALUES (2, 'Eddie', 'COMP-2');
INSERT INTO N_RollCall VALUES (3, 'Foxy', 'COMP-1');
INSERT INTO N_RollCall VALUES (4, 'Lara', 'COMP-3');
INSERT INTO N_RollCall VALUES (5, 'Stomp', 'COMP-3');
```
## Procedure
```plsql
DECLARE
p_roll NUMBER;
p_name VARCHAR2(255);
p_class VARCHAR2(255);
CURSOR c1 IS SELECT * FROM N_RollCall WHERE roll NOT IN (SELECT roll FROM O_RollCall);
BEGIN
OPEN c1;
LOOP
FETCH c1 INTO p_roll, p_name, p_class;
INSERT INTO O_RollCall VALUES (p_roll, p_name, p_class);
EXIT WHEN c1%NOTFOUND;
DBMS_OUTPUT.PUT_LINE('Inserted ' || p_name || ' having roll no. ' || p_roll || ' in class ' || p_class || '.');
END LOOP;
CLOSE c1;
END;
/
```
---

View File

@ -0,0 +1,74 @@
# P4 - PL/SQL block
**Problem Statement:** Write a PL/SQL block for following requirements and handle the exceptions. Roll no. of students will be entered by the user. Attendance of roll no. entered by user will be checked in the Stud table. If attendance is less than 75% then display the message “Term not granted” and set the status in stud table as “Detained”. Otherwise display message “Term granted” and set the status in stud table as “Not Detained”. Student (Roll, Name, Attendance, Status)
---
## Creating table
```sql
CREATE TABLE Student(
Roll NUMBER(14),
Name VARCHAR(255),
Attendance NUMBER(14),
Status VARCHAR(255)
);
```
## Inserting data
```sql
INSERT INTO Student VALUES (1, 'Tanmay', 76, NULL);
INSERT INTO Student VALUES (2, 'Rajesh', 80, NULL);
INSERT INTO Student VALUES (3, 'Tejas', 88, NULL);
INSERT INTO Student VALUES (4, 'Machkar', 35, NULL);
INSERT INTO Student VALUES (5, 'Jayashree', 74, NULL);
```
## Procedure
```sql
DECLARE
p_att Student.Attendance%type;
p_roll Student.Roll%type;
nodata EXCEPTION;
BEGIN
p_roll := &p_roll; -- specify value directly for Live SQL. Eg.: p_roll := 1;
IF (p_roll < 0) THEN
raise nodata;
END IF;
SELECT Attendance INTO p_att FROM Student WHERE Roll = p_roll;
IF (p_att < 75) THEN
DBMS_OUTPUT.PUT_LINE('Term not granted to roll no. ' || p_roll);
UPDATE Student SET Status = 'Detained' WHERE Roll = p_roll;
ELSIF (p_att >= 75) THEN
DBMS_OUTPUT.PUT_LINE('Term granted to roll no. ' || p_roll);
UPDATE Student SET Status = 'Not Detained' WHERE Roll = p_roll;
END IF;
EXCEPTION
WHEN nodata THEN
DBMS_OUTPUT.PUT_LINE('Please enter a valid roll number.');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error occured. Error: ' || SQLERRM);
END;
/
```
<details>
<summary>Output</summary>
After entering every Roll no:
ROLL NAME ATTENDANCE STATUS<br>
1 Tanmay 76 Not Detained<br>
2 Rajesh 80 Not Detained<br>
3 Tejas 88 Not Detained<br>
4 Machkar 35 Detained<br>
5 Jayashree 74 Detained<br>
</details>
---

View File

@ -0,0 +1,68 @@
# P5 - PL-SQL Block
**Problem Statement:** Write a PL/SQL Block to increase the salary of employees by 10% of existing salary, who are having salary less than average salary of organization, whenever such salary updates take place, a record for same is maintained in the increment_salary table.
emp(emp_no, salary)
increment_salary(emp_no, salary)
---
## Creating tables:
```sql
CREATE TABLE emp(
emp_no NUMBER(14),
salary NUMBER(14)
);
CREATE table increment_salary(
emp_no NUMBER(14),
salary NUMBER(14)
);
```
## Inserting values:
```sql
INSERT INTO emp VALUES (1, 1000);
INSERT INTO emp VALUES (2, 8000);
INSERT INTO emp VALUES (3, 2000);
INSERT INTO emp VALUES (4, 5000);
INSERT INTO emp VALUES (5, 7000);
```
## Procedure
```sql
DECLARE
avg_salary NUMBER(14, 4);
BEGIN
SELECT AVG(salary) INTO avg_salary FROM emp;
FOR emp_record IN (select emp_no, salary FROM emp WHERE salary < avg_salary)
LOOP
insert into increment_salary(emp_no, salary) values (emp_record.emp_no, emp_record.salary);
UPDATE emp SET salary = emp_record.salary * 1.10 WHERE emp_no = emp_record.emp_no;
END LOOP;
EXCEPTION
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error: ' || SQLERRM);
end;
/
```
<details>
<summary><strong>OUTPUT</strong>: After PL/SQL Block:</summary>
emp:<br>
EMP_NO SALARY<br>
1 1100<br>
2 8000<br>
3 2200<br>
4 5000<br>
5 7000<br>
<br>
increment_emp:<br>
EMP_NO SALARY<br>
1 1000<br>
3 2000<br>
</details>
---

View File

@ -0,0 +1,89 @@
# P6 - Stored Procedure
**Problem Statement:** Write a Stored Procedure namely proc_Grade for the categorization of student. If marks scored by students in examination is <=1500 and marks>=990 then student will be placed in distinction category if marks scored are between 989 and 900 categories is first class, if marks 899 and 825 category is Higher Second Class. Write a PL/SQL block for using procedure created with above requirement.
Stud_Marks(name, total_marks),
Result (Roll,Name, Class)
---
## Creating tables
```plsql
CREATE TABLE Stud_Marks (
name VARCHAR2(255),
total_marks NUMBER,
PRIMARY KEY (name)
);
CREATE TABLE Result (
Roll NUMBER NOT NULL UNIQUE,
Name VARCHAR2(255),
Class VARCHAR2(255),
FOREIGN KEY (Name) REFERENCES Stud_Marks (name)
);
```
## Inserting values
```plsql
INSERT INTO Stud_Marks VALUES ('Kalas', 1300);
INSERT INTO Stud_Marks VALUES ('Himanshu', 800);
INSERT INTO Stud_Marks VALUES ('Mehul', 950);
INSERT INTO Stud_Marks VALUES ('Gundeti', 875);
```
## Procedure
```plsql
CREATE OR REPLACE PROCEDURE proc_Grade (p_roll IN NUMBER, p_name IN VARCHAR2) IS
-- declare section
marks NUMBER;
nodata EXCEPTION;
BEGIN
IF (p_name IS NULL) THEN
raise nodata;
END IF;
SELECT total_marks INTO marks FROM Stud_Marks WHERE name = p_name;
IF (marks >= 990 AND marks <= 1500) THEN
DBMS_OUTPUT.PUT_LINE(p_name || ' has been placed in the distinction category.');
INSERT INTO Result VALUES (p_roll, p_name, 'DISTINCTION');
ELSIF (marks BETWEEN 900 AND 989) THEN
DBMS_OUTPUT.PUT_LINE(p_name || ' has been placed in the first class category.');
INSERT INTO Result VALUES (p_roll, p_name, 'FIRST CLASS');
ELSIF (marks BETWEEN 825 AND 899) THEN
DBMS_OUTPUT.PUT_LINE(p_name || ' has been placed in the higher second class category.');
INSERT INTO Result VALUES (p_roll, p_name, 'HIGHER SECOND CLASS');
ELSE
DBMS_OUTPUT.PUT_LINE(p_name || ' has failed.');
INSERT INTO Result VALUES (p_roll, p_name, 'FAIL');
END IF;
EXCEPTION
WHEN nodata THEN
DBMS_OUTPUT.PUT_LINE('Please enter a name');
WHEN OTHERS THEN
DBMS_OUTPUT.PUT_LINE('Error occurred. Error: ' || SQLERRM);
END proc_Grade;
/
```
## Calling procedure
```plsql
DECLARE
p_roll NUMBER;
p_name VARCHAR2(255);
BEGIN
DBMS_OUTPUT.PUT_LINE('Enter roll number: ');
p_roll := &p_roll;
DBMS_OUTPUT.PUT_LINE('Enter name: ');
p_name := '&p_name';
proc_Grade(p_roll, p_name);
END;
/
```
---

View File

@ -0,0 +1,58 @@
# P7 - Age_calc function
**Problem statement:** Create a stored function titled 'Age_calc'. Accept the date of birth of a person as a parameter. Calculate the age of the person in years, months and days e.g. 3 years, 2months, 10 days. Return the age in years directly (with the help of Return statement). The months and days are to be returned indirectly in the form of OUT parameters.
## Creating function
```sql
CREATE OR REPLACE FUNCTION Age_calc(
dob IN DATE,
f_month OUT NUMBER,
f_day OUT NUMBER
)
RETURN NUMBER
IS
current_date DATE := SYSDATE;
year_diff NUMBER;
month_diff NUMBER;
day_diff NUMBER;
BEGIN
year_diff := EXTRACT(YEAR FROM current_date) - EXTRACT(YEAR FROM dob);
month_diff := EXTRACT(MONTH FROM current_date) - EXTRACT(MONTH FROM dob);
day_diff := EXTRACT(DAY FROM current_date) - EXTRACT(DAY FROM dob);
IF (day_diff < 0) THEN
month_diff := month_diff - 1;
day_diff := day_diff + EXTRACT(DAY FROM last_day(add_months(SYSDATE, -1)));
END IF;
IF (month_diff < 0) THEN
year_diff := year_diff - 1;
month_diff := month_diff + 12;
END IF;
f_month := month_diff;
f_day := day_diff;
RETURN year_diff;
END;
/
```
## Calling function
```sql
DECLARE
years NUMBER;
months NUMBER;
days NUMBER;
BEGIN
years := Age_calc(TO_DATE('2003-12-02', 'YYYY-MM-DD'), months, days);
DBMS_OUTPUT.PUT_LINE('Age: ' || years || ' Years ' || months || ' Months ' || days || ' Days.');
END;
/
```
---

View File

@ -0,0 +1,91 @@
# P8 - Trigger
**Problem Statement:** Write a Row Level Before and After Trigger on Library table. The System should keep track of the records that are being updated or deleted. The old value of updated or deleted records should be added in Library_Audit table.
## Creating tables
```plsql
CREATE TABLE Library(
id NUMBER(12),
title VARCHAR(255),
dateofissue DATE,
author VARCHAR(255)
);
CREATE TABLE Library_Audit(
id NUMBER(12),
title VARCHAR(255),
dateofaction DATE,
author VARCHAR(255),
status VARCHAR(255)
);
```
## Inserting values
```plsql
INSERT INTO Library VALUES (1, 'Berserk', TO_DATE('2024-07-28','YYYY-MM-DD'), 'Prashant');
INSERT INTO Library VALUES (2, 'Dark', TO_DATE('2024-07-15','YYYY-MM-DD'), 'Rajendra');
INSERT INTO Library VALUES (3, 'Hannibal', TO_DATE('2024-07-20','YYYY-MM-DD'), 'Manoj');
INSERT INTO Library VALUES (4, 'AOT', TO_DATE('2024-07-30','YYYY-MM-DD'), 'Rajesh');
INSERT INTO Library VALUES (5, 'GOT', TO_DATE('2024-07-19','YYYY-MM-DD'), 'Anil');
```
## Trigger
```sql
CREATE OR REPLACE TRIGGER library_action
AFTER INSERT OR UPDATE OR DELETE
ON Library
FOR EACH ROW
BEGIN
IF INSERTING THEN
INSERT INTO Library_Audit (id, title, dateofaction, author, status) VALUES (:NEW.id, :NEW.title, current_timestamp, :NEW.author, 'Insert');
ELSIF UPDATING THEN
INSERT INTO Library_Audit (id, title, dateofaction, author, status) VALUES (:OLD.id, :OLD.title, current_timestamp, :OLD.author, 'Update');
ELSIF DELETING THEN
INSERT INTO Library_Audit (id, title, dateofaction, author, status) VALUES (:OLD.id, :OLD.title, current_timestamp, :OLD.author, 'Delete');
END IF;
END;
/
```
## Testing trigger
### Insert operation
```sql
INSERT INTO Library VALUES (15, 'CREW', TO_DATE('2024-07-22','YYYY-MM-DD'), 'Ramesh');
INSERT INTO Library VALUES (14, 'Ninteen Eighty Four', TO_DATE('2024-07-01','YYYY-MM-DD'), 'Omkar');
SELECT * FROM Library;
SELECT * FROM Library_Audit;
```
### Update operation
```sql
UPDATE Library SET id = 6, title = 'Sherlock', author = 'Deepak' where id = 3;
UPDATE Library SET id = 7, title = 'MR. ROBOT', author = 'Varad' where id = 4;
SELECT * FROM Library;
SELECT * FROM Library_Audit;
```
### Delete operation
```sql
DELETE FROM Library WHERE id = 1;
DELETE FROM Library WHERE id = 5;
SELECT * FROM Library;
SELECT * FROM Library_Audit;
```
---

View File

@ -0,0 +1,93 @@
# P9 - Trigger
**Problem Statement:** Trigger: Create a row level trigger for the CUSTOMERS table that would fire INSERT or UPDATE or DELETE operations performed on the CUSTOMERS table. This trigger will display the salary difference between the old values and new values.
---
## Creating table:
```sql
CREATE TABLE Customers(
name VARCHAR(255),
id NUMBER(14),
salary NUMBER(14)
);
```
## Procedure
```sql
CREATE OR REPLACE TRIGGER P
AFTER INSERT OR UPDATE OR DELETE ON Customers
FOR EACH ROW
DECLARE
diff NUMBER(14);
BEGIN
IF INSERTING THEN
DBMS_OUTPUT.PUT_LINE('New salary with value inserted: ' || :NEW.salary);
ELSIF UPDATING THEN
if :New.salary > :old.salary then diff := :New.salary - :Old.salary;
elsif :New.salary < :old.salary then diff := :Old.salary - :New.salary;
end if;
DBMS_OUTPUT.PUT_LINE('Salary difference: ' || diff);
ELSIF DELETING THEN
DBMS_OUTPUT.PUT_LINE('Salary with value deleted: ' || :OLD.salary);
END IF;
END;
/
```
## Queries
1. Insert operation:
```sql
INSERT INTO Customers VALUES ('Tanmay', 1, 20000);
INSERT INTO Customers VALUES ('Rajesh', 2, 30000);
```
<details>
<summary>Output</summary>
1 row(s) inserted.<br>
New salary with value inserted: 20000<br>
1 row(s) inserted.<br>
New salary with value inserted: 30000<br>
</details>
2. Update operation:
```sql
UPDATE Customers SET salary = 10000 WHERE id = 1;
UPDATE Customers SET salary = 35000 WHERE id = 2;
```
<details>
<summary>Output</summary>
1 row(s) updated.<br>
Salary difference: 10000<br>
1 row(s) updated.<br>
Salary difference: 5000<br>
</details>
3. Delete operation:
```sql
DELETE FROM Customers WHERE id = 1;
DELETE FROM Customers WHERE id = 2;
```
<details>
<summary>Output</summary>
1 row(s) deleted.<br>
Salary with value deleted: 10000<br>
1 row(s) deleted.<br>
Salary with value deleted: 35000<br>
</details>
---

View File

@ -0,0 +1,21 @@
# Practical Exam
This folder contains all the problem statements expected for practical examination (2024).
---
##### [All problem statements](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Practical%20Exam/DBMSL%20-%20Problem%20Statements%20for%20Practical%20Exam%20%28November%202024%29.pdf).
- [SQL](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Practical%20Exam/SQL) // 9 problem statements
- [PL-SQL](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Practical%20Exam/PL-SQL) // 10 problem statements
- [MongoDB](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Practical%20Exam/MongoDB) // 6 problem statements
- [Connectivity](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Practical%20Exam/Connectivity) // 2 problem statements
---
##### Contributors:
- [notkshitij](https://git.kska.io/notkshitij)
- [TanmaySpamzzz](https://git.kska.io/TanmaySpamzzz)
- [just a little, Afan Shaikh (shh_itsourlittlesecret)](https://git.kska.io/shh_itsourlittlesecret)

View File

@ -0,0 +1,158 @@
# S1 - SQL Queries (in MySQL)
**Problem Statement:**
Consider following Relation
Account (Acc_no, branch_name,balance)
Branch(branch_name,branch_city,assets)
Customer(cust_name,cust_street,cust_city)
Depositor(cust_name,acc_no)
Loan(loan_no,branch_name,amount)
Borrower(cust_name,loan_no)
Create above tables with appropriate constraints like primary key,
foreign key, not null etc.
1. Find the names of all branches in loan relation.
2. Find all loan numbers for loans made at Wadia College Branch
with loan amount > 12000.
3. Find all customers who have a loan from bank. Find their
names,loan_no and loan amount.
4. List all customers in alphabetical order who have loan from
Wadia College branch.
5. Display distinct cities of branch.
---
## Creating the database
```sql
CREATE DATABASE Bank1;
USE Bank1;
```
## Creating tables:
```sql
CREATE TABLE Account (
acc_no INT,
branch_name VARCHAR(255),
balance INT,
PRIMARY KEY (acc_no)
);
CREATE TABLE Branch (
branch_name VARCHAR(255),
branch_city VARCHAR(255),
assets INT,
PRIMARY KEY (branch_name)
);
CREATE TABLE Customer (
cust_name VARCHAR(255),
cust_street VARCHAR(255),
cust_city VARCHAR(255),
PRIMARY KEY (cust_name)
);
CREATE TABLE Depositor (
cust_name VARCHAR(255),
acc_no INT
);
CREATE TABLE Loan (
loan_no INT,
branch_name VARCHAR(255),
amount INT,
PRIMARY KEY (loan_no)
);
CREATE TABLE Borrower (
cust_name VARCHAR(255),
loan_no INT
);
```
## Declaring foreign keys
```sql
ALTER TABLE Account ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Depositor ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Depositor ADD FOREIGN KEY (acc_no) REFERENCES Account (acc_no);
ALTER TABLE Loan ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Borrower ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Borrower ADD FOREIGN KEY (loan_no) REFERENCES Loan (loan_no);
```
## Inserting data
```sql
INSERT INTO Branch VALUES
('Wadia College', 'Pune', 50000),
('PES', 'Pune', 65000),
('Lohegaon', 'Pune', 350000),
('Viman Nagar', 'Pune', 850000);
INSERT INTO Customer VALUES
('Kalas', 'Street 12', 'Pune'),
('Himanshu', 'Street 15', 'Pune'),
('Mehul', 'Street 29', 'Pune'),
('Macho', 'Street 59', 'Mumbai'),
('Gundeti', 'Street 40', 'Mumbai'),
('Salvi', 'Street 8', 'Pune');
INSERT INTO Account VALUES
(101, 'Lohegaon', 5500),
(102, 'PES', 4324),
(103, 'PES', 5467),
(104, 'Viman Nagar', 5433),
(105, 'Wadia College', 6462);
INSERT INTO Depositor VALUES
('Kalas', 101),
('Gundeti', 105);
INSERT INTO Loan VALUES
(201, 'Wadia College', 18000),
(202, 'PES', 8500),
(203, 'PES', 15000),
(204, 'Wadia College', 5322);
INSERT INTO Borrower VALUES
('Macho', 201),
('Mehul', 202),
('Himanshu', 203),
('Salvi', 204);
```
## Queries
1. Find the names of all branches in loan relation.
```sql
SELECT DISTINCT branch_name FROM Loan;
```
2. Find all loan numbers for loans made at Wadia College Branch with loan amount > 12000.
```sql
SELECT loan_no FROM Loan WHERE branch_name = 'Wadia College' AND amount > 12000;
```
3. Find all customers who have a loan from bank. Find their names,loan_no and loan amount.
```sql
SELECT Borrower.cust_name, Borrower.loan_no, Loan.amount FROM Borrower INNER JOIN Loan ON Borrower.loan_no = Loan.loan_no;
```
4. List all customers in alphabetical order who have loan from Wadia College branch.
```sql
SELECT cust_name FROM Borrower INNER JOIN Loan on Borrower.loan_no = Loan.loan_no WHERE Loan.branch_name = 'Wadia College' ORDER BY cust_name;
```
5. Display distinct cities of branch.
```sql
SELECT DISTINCT branch_city FROM Branch;
```

View File

@ -0,0 +1,159 @@
# S2 - SQL Queries (in MySQL)
**Problem Statement:**
Consider following Relation
Account (Acc_no, branch_name,balance)
Branch(branch_name,branch_city,assets)
Customer(cust_name,cust_street,cust_city)
Depositor(cust_name,acc_no)
Loan(loan_no,branch_name,amount)
Borrower(cust_name,loan_no)
Create above tables with appropriate constraints like primary key,
foreign key, not null etc.
1. Find all customers who have both account and loan at bank.
2. Find all customers who have an account or loan or both at bank.
3. Find all customers who have account but no loan at the bank.
4. Find average account balance at Wadia College branch.
5. Find no. of depositors at each branch
---
## Creating the database
```sql
CREATE DATABASE Bank2;
USE Bank2;
```
## Creating tables:
```sql
CREATE TABLE Account (
acc_no INT,
branch_name VARCHAR(255),
balance INT,
PRIMARY KEY (acc_no)
);
CREATE TABLE Branch (
branch_name VARCHAR(255),
branch_city VARCHAR(255),
assets INT,
PRIMARY KEY (branch_name)
);
CREATE TABLE Customer (
cust_name VARCHAR(255),
cust_street VARCHAR(255),
cust_city VARCHAR(255),
PRIMARY KEY (cust_name)
);
CREATE TABLE Depositor (
cust_name VARCHAR(255),
acc_no INT
);
CREATE TABLE Loan (
loan_no INT,
branch_name VARCHAR(255),
amount INT,
PRIMARY KEY (loan_no)
);
CREATE TABLE Borrower (
cust_name VARCHAR(255),
loan_no INT
);
```
## Declaring foreign keys
```sql
ALTER TABLE Account ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Depositor ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Depositor ADD FOREIGN KEY (acc_no) REFERENCES Account (acc_no);
ALTER TABLE Loan ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Borrower ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Borrower ADD FOREIGN KEY (loan_no) REFERENCES Loan (loan_no);
```
## Inserting data
```sql
INSERT INTO Branch VALUES
('Wadia College', 'Pune', 50000),
('PES', 'Pune', 65000),
('Lohegaon', 'Pune', 350000),
('Viman Nagar', 'Pune', 850000);
INSERT INTO Customer VALUES
('Kalas', 'Street 12', 'Pune'),
('Himanshu', 'Street 15', 'Pune'),
('Mehul', 'Street 29', 'Pune'),
('Macho', 'Street 59', 'Mumbai'),
('Gundeti', 'Street 40', 'Mumbai'),
('Salvi', 'Street 8', 'Pune');
INSERT INTO Account VALUES
(101, 'Lohegaon', 5500),
(102, 'PES', 4324),
(103, 'PES', 5467),
(104, 'Viman Nagar', 5433),
(105, 'Wadia College', 6462);
INSERT INTO Depositor VALUES
('Kalas', 101),
('Macho', 104),
('Gundeti', 105),
('Salvi', 105);
INSERT INTO Loan VALUES
(201, 'Wadia College', 18000),
(202, 'PES', 8500),
(203, 'PES', 15000),
(204, 'Wadia College', 5322);
INSERT INTO Borrower VALUES
('Macho', 201),
('Mehul', 202),
('Himanshu', 203),
('Salvi', 204);
```
## Queries
1. Find all customers who have both account and loan at bank.
```sql
SELECT cust_name FROM Depositor INTERSECT SELECT cust_name FROM Borrower;
```
2. Find all customers who have an account or loan or both at bank.
```sql
SELECT cust_name FROM Depositor UNION SELECT cust_name FROM Borrower;
```
3. Find all customers who have account but no loan at the bank.
```sql
SELECT cust_name FROM Depositor WHERE cust_name NOT IN (SELECT cust_name FROM Borrower);
```
4. Find average account balance at Wadia College branch.
```sql
SELECT AVG(balance) FROM Account WHERE branch_name = 'Wadia College';
```
5. Find no. of depositors at each branch
```sql
SELECT Account.branch_name, COUNT(*) AS total FROM Account INNER JOIN Depositor ON Account.acc_no = Depositor.acc_no GROUP BY branch_name;
```
---

View File

@ -0,0 +1,181 @@
# S3 - SQL Queries (in MySQL)
**Problem Statement:**
Consider following Relation
Account (Acc_no, branch_name,balance)
Branch(branch_name,branch_city,assets)
Customer(cust_name,cust_street,cust_city)
Depositor(cust_name,acc_no)
Loan(loan_no,branch_name,amount)
Borrower(cust_name,loan_no)
Create above tables with appropriate constraints like primary key,
foreign key, not null etc.
1. Find the branches where average account balance > 15000.
2. Find number of tuples in customer relation.
3. Calculate total loan amount given by bank.
4. Delete all loans with loan amount between 1300 and 1500.
5. Find the average account balance at each branch
6. Find name of Customer and city where customer name starts with
Letter P.
---
## Creating the database
```sql
CREATE DATABASE Bank3;
USE Bank3;
```
## Creating tables:
```sql
CREATE TABLE Account (
acc_no INT,
branch_name VARCHAR(255),
balance INT,
PRIMARY KEY (acc_no)
);
CREATE TABLE Branch (
branch_name VARCHAR(255),
branch_city VARCHAR(255),
assets INT,
PRIMARY KEY (branch_name)
);
CREATE TABLE Customer (
cust_name VARCHAR(255),
cust_street VARCHAR(255),
cust_city VARCHAR(255),
PRIMARY KEY (cust_name)
);
CREATE TABLE Depositor (
cust_name VARCHAR(255),
acc_no INT
);
CREATE TABLE Loan (
loan_no INT,
branch_name VARCHAR(255),
amount INT,
PRIMARY KEY (loan_no)
);
CREATE TABLE Borrower (
cust_name VARCHAR(255),
loan_no INT
);
```
## Declaring foreign keys
```sql
ALTER TABLE Account ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Depositor ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Depositor ADD FOREIGN KEY (acc_no) REFERENCES Account (acc_no);
ALTER TABLE Loan ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Borrower ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Borrower ADD FOREIGN KEY (loan_no) REFERENCES Loan (loan_no);
```
## Inserting data
```sql
INSERT INTO Branch VALUES
('Wadia College', 'Pune', 50000),
('PES', 'Pune', 65000),
('Lohegaon', 'Pune', 350000),
('Viman Nagar', 'Pune', 850000);
INSERT INTO Customer VALUES
('Kalas', 'Street 12', 'Pune'),
('Himanshu', 'Street 15', 'Pune'),
('Mehul', 'Street 29', 'Pune'),
('Macho', 'Street 59', 'Mumbai'),
('Gundeti', 'Street 40', 'Mumbai'),
('Salvi', 'Street 8', 'Pune'),
('Pintu', 'Street 55', 'Ahemadnagar'),
('Piyush', 'Street 21', 'Assam');
INSERT INTO Account VALUES
(101, 'Lohegaon', 67000),
(102, 'PES', 4324),
(103, 'PES', 54670),
(104, 'Viman Nagar', 5433),
(105, 'Wadia College', 6462);
INSERT INTO Depositor VALUES
('Kalas', 101),
('Macho', 104),
('Gundeti', 105),
('Salvi', 105);
INSERT INTO Loan VALUES
(201, 'Wadia College', 1800),
(202, 'PES', 8500),
(203, 'PES', 15000),
(204, 'Wadia College', 5322),
(205, 'Viman Nagar', 1300),
(206, 'Lohegaon', 1450);
INSERT INTO Borrower VALUES
('Macho', 201),
('Mehul', 202),
('Himanshu', 203),
('Salvi', 204);
```
## Queries
1. Find the branches where average account balance > 15000.
```sql
SELECT branch_name FROM Account GROUP BY branch_name HAVING AVG(balance) > 15000 ;
```
2. Find number of tuples in customer relation.
```sql
SELECT COUNT(*) FROM Customer;
```
3. Calculate total loan amount given by bank.
```sql
SELECT SUM(amount) FROM Loan;
```
4. Delete all loans with loan amount between 1300 and 1500.
- Delete the dependent records first(due to foreign key constraints):
```sql
DELETE FROM Borrower
WHERE loan_no IN (
SELECT loan_no
FROM Loan
WHERE amount BETWEEN 1300 AND 1500
);
```
- Now delete the Loan table Records:
```sql
DELETE FROM Loan WHERE amount BETWEEN 1300 AND 1500;
```
5. Find the average account balance at each branch
```sql
SELECT branch_name, AVG(balance) FROM Account GROUP BY branch_name;
```
6. Find name of Customer and city where customer name starts with letter P.
```sql
SELECT cust_name, cust_city FROM Customer WHERE cust_name LIKE "P%";
```
---

View File

@ -0,0 +1,159 @@
# S4 - SQL Queries (in MySQL)
**Problem Statement:**
SQL Queries:
Create following tables with suitable constraints (primary key,
foreign key, not null etc).
Insert record and solve the following queries:
Create table Cust_Master(Cust_no, Cust_name, Cust_addr)
Create table Order(Order_no, Cust_no, Order_date, Qty_Ordered)
Create Product (Product_no, Product_name, Order_no)
1. List names of customers having 'A' as second letter in their
name.
2. Display order from Customer no C1002, C1005, C1007 and C1008
3. List Clients who stay in either 'Banglore or 'Manglore'
4. Display name of customers& the product_name they have purchase
5. Create view View1 consisting of Cust_name, Product_name.
6. Disply product_name and quantity purchase by each customer
7. Perform different joint operation.
---
## Creating the database
```sql
CREATE DATABASE Store1;
USE Store1;
```
## Creating tables:
```sql
CREATE TABLE Cust_Master (
Cust_no VARCHAR(255) NOT NULL,
Cust_name VARCHAR(255),
Cust_addr VARCHAR(255),
PRIMARY KEY (cust_no)
);
CREATE TABLE Orders (
-- Cannot have 'Order' as table name since it is a keyword reserved for 'ORDER BY' cause
Order_no INT,
Cust_no VARCHAR(255),
Order_date DATE,
Qty_Ordered INT,
PRIMARY KEY (Order_no)
);
CREATE TABLE Product (
Product_no INT,
Product_name VARCHAR(255),
Order_no INT
);
```
## Declaring foreign keys
```sql
ALTER TABLE Orders ADD FOREIGN KEY (Cust_no) REFERENCES Cust_Master (Cust_no);
ALTER TABLE Product ADD FOREIGN KEY (Order_no) REFERENCES Orders (Order_no);
```
## Inserting data
```sql
INSERT INTO Cust_Master VALUES
('C1001', 'Kalas', 'Pune'),
('C1002', 'Macho', 'Banglore'),
('C1003', 'Gundeti', 'Chennai'),
('C1005', 'Salvi', 'Manglore'),
('C1006', 'Kshitij', 'Assam'),
('C1007', 'Himashu', 'Banglore'),
('C1008', 'Mehul', 'Mumbai');
INSERT INTO Orders VALUES
(1, 'C1001', '2024-11-09', 10),
(2, 'C1003', '2024-11-01', 5),
(3, 'C1005', '2024-11-05', 45),
(4, 'C1002', '2024-10-29', 3),
(5, 'C1007', '2024-10-15', 2),
(6, 'C1008', '2024-11-10', 7),
(7, 'C1006', '2024-11-09', 1);
INSERT INTO Product VALUES
('101', 'Political Stamps', 1),
('204', 'Fashion Accessory', 2),
('438', 'Complan', 3),
('327', 'ID Card Strap', 4),
('243', 'Face and Hair Wash', 5),
('373', 'Fat Reducer 6000', 6),
('327', 'Personality', 7);
```
## Queries
1. List names of customers having 'A' as second letter in their name.
```sql
SELECT Cust_name FROM Cust_Master WHERE Cust_name LIKE "_a%";
```
2. Display order from Customer no C1002, C1005, C1007 and C1008
```sql
SELECT * FROM Orders WHERE Cust_no IN ('C1002', 'C1005', 'C1007', 'C1008');
```
3. List Clients who stay in either 'Banglore or 'Manglore'
```sql
SELECT Cust_name FROM Cust_Master WHERE Cust_addr = 'Banglore' OR Cust_addr = 'Manglore';
```
4. Display name of customers & the product_name they have purchase
```sql
SELECT Cust_Master.Cust_name, Product.Product_name FROM Product INNER JOIN Orders ON Product.Order_no = Orders.Order_no INNER JOIN Cust_Master ON Orders.Cust_no = Cust_Master.Cust_no;
```
5. Create view View1 consisting of Cust_name, Product_name.
```sql
CREATE VIEW View1 AS SELECT Cust_Master.Cust_name, Product.Product_name FROM Product INNER JOIN Orders ON Product.Order_no = Orders.Order_no INNER JOIN Cust_Master ON Orders.Cust_no = Cust_Master.Cust_no;
SELECT * FROM View1;
```
6. Disply product_name and quantity purchase by each customer
```sql
SELECT Cust_Master.Cust_name, Product.Product_name, Orders.Qty_Ordered FROM Product INNER JOIN Orders ON Product.Order_no = Orders.Order_no INNER JOIN Cust_Master ON Orders.Cust_no = Cust_Master.Cust_no;
```
7. Perform different joint operation.
- INNER JOIN:
```sql
SELECT Cust_Master.Cust_name, Product.Product_name FROM Product INNER JOIN Orders ON Product.Order_no = Orders.Order_no INNER JOIN Cust_Master ON Orders.Cust_no = Cust_Master.Cust_no;
```
- OUTER LEFT JOIN:
```sql
SELECT Cust_Master.Cust_name, Orders.Order_no, Orders.Order_date FROM Cust_Master LEFT JOIN Orders ON Cust_Master.Cust_no = Orders.Cust_no;
```
- OUTER RIGHT JOIN:
```sql
SELECT Orders.Order_no, Orders.Order_date, Cust_Master.Cust_name FROM Orders RIGHT JOIN Cust_Master ON Orders.Cust_no = Cust_Master.Cust_no;
```
---

View File

@ -0,0 +1,137 @@
# S5 - SQL Queries (in MySQL)
**Problem Statement:**
Consider following Relation
Employee(emp_id,employee_name,street,city)
Works(employee_name,company_name,salary)
Company(company_name,city)
Manages(employee_name,manager_name)
Create above tables with appropriate constraints like primary key,
foreign key, not null etc.
1. Find the names of all employees who work for TCS.
2. Find the names and company names of all employees sorted in
ascending order of company name and descending order of employee
names of that company.
3. Change the city of employee working with InfoSys to Bangalore
4. Find the names, street address, and cities of residence for all
employees who work for 'TechM' and earn more than $10,000.
5. Add Column Asset to Company table.
---
## Creating the database
```sql
CREATE DATABASE Companies1;
USE Companies1;
```
## Creating tables:
```sql
CREATE TABLE Employee (
emp_id INT UNIQUE NOT NULL, -- can be set to auto increment using AUTO_INCREMENT
employee_name VARCHAR(255),
street VARCHAR(255),
city VARCHAR(255),
PRIMARY KEY (employee_name)
);
CREATE TABLE Works (
employee_name VARCHAR(255),
company_name VARCHAR(255),
salary INT -- use FLOAT if you are feeling fancy and pay your employees in Paise
);
CREATE TABLE Company (
company_name VARCHAR(255),
city VARCHAR(255),
PRIMARY KEY (company_name)
);
CREATE TABLE Manages (
employee_name VARCHAR(255),
manager_name VARCHAR(255)
);
```
## Declaring foreign keys
```sql
ALTER TABLE Works ADD FOREIGN KEY (employee_name) REFERENCES Employee (employee_name);
ALTER TABLE Works ADD FOREIGN KEY (company_name) REFERENCES Company (company_name);
ALTER TABLE Manages ADD FOREIGN KEY (employee_name) REFERENCES Employee (employee_name);
```
## Inserting data
```sql
INSERT INTO Employee VALUES
(1, 'Mehul', 'Street 42', 'Pune'),
(2, 'Himanshu', 'Street 74', 'Mumbai'),
(3, 'Gundeti', 'Street 14', 'Pune'),
(4, 'Salvi', 'Street 38', 'Pune'),
(5, 'Afan', 'Steet 98', 'Pune');
INSERT INTO Company VALUES
('TCS', 'Pune'),
('Infosys', 'Mumbai'),
('TechM', 'Pune'),
('MEPA', 'Pune');
INSERT INTO Works VALUES
('Mehul', 'MEPA', 15000),
('Himanshu', 'TCS', 25000),
('Gundeti', 'TCS', 21500),
('Salvi', 'TechM', 11000),
('Afan', 'Infosys', 13000);
INSERT INTO Manages VALUES
('Mehul', 'Kalas'),
('Himanshu', 'Kshitij'),
('Gundeti', 'Macho'),
('Salvi', 'Kshitij'),
('Afan', 'Kalas');
```
## Queries
1. Find the names of all employees who work for TCS.
```sql
SELECT employee_name FROM Works WHERE company_name = "TCS";
```
2. Find the names and company names of all employees sorted in ascending order of company name and descending order of employee names of that company.
```sql
SELECT company_name, employee_name FROM Works ORDER BY company_name ASC, employee_name DESC;
```
3. Change the city of employee working with InfoSys to Bangalore
```sql
update Employee set city = "Banglore" where employee_name in (select employee_name from Works where company_name = "Infosys");
select * from Employee;
```
4. Find the names, street address, and cities of residence for all employees who work for 'TechM' and earn more than $10,000.
```sql
SELECT Employee.employee_name, Employee.street, Employee.city FROM Employee INNER JOIN Works ON Employee.employee_name = Works.employee_name WHERE Works.company_name = "TechM" AND Works.salary > 10000;
```
5. Add Column Asset to Company table.
```sql
ALTER TABLE Company ADD assets INT;
DESCRIBE Company;
```
---

View File

@ -0,0 +1,150 @@
# S6 - SQL Queries (in MySQL)
**Problem Statement:**
Consider following Relation
Employee(emp_id,employee_name,street,city)
Works(employee_name,company_name,salary)
Company(company_name,city)
Manages(employee_name,manager_name)
Create above tables with appropriate constraints like primary key,
foreign key, not null etc.
1. Change the city of employee working with InfoSys to Bangalore
2. Find the names of all employees who earn more than the average
salary of all employees of their company. Assume that all people
work for at most one company.
3. Find the names, street address, and cities of residence for all
employees who work for 'TechM' and earn more than $10,000.
4. Change name of table Manages to Management.
5. Create Simple and Unique index on employee table.
6. Display index Information
---
## Creating the database
```sql
CREATE DATABASE Companies2;
USE Companies2;
```
## Creating tables:
```sql
CREATE TABLE Employee (
emp_id INT UNIQUE NOT NULL, -- can be set to auto increment using AUTO_INCREMENT
employee_name VARCHAR(255),
street VARCHAR(255),
city VARCHAR(255),
PRIMARY KEY (employee_name)
);
CREATE TABLE Works (
employee_name VARCHAR(255),
company_name VARCHAR(255),
salary INT -- use FLOAT if you are feeling fancy and pay your employees in Paise
);
CREATE TABLE Company (
company_name VARCHAR(255),
city VARCHAR(255),
PRIMARY KEY (company_name)
);
CREATE TABLE Manages (
employee_name VARCHAR(255),
manager_name VARCHAR(255)
);
```
## Declaring foreign keys
```sql
ALTER TABLE Works ADD FOREIGN KEY (employee_name) REFERENCES Employee (employee_name);
ALTER TABLE Works ADD FOREIGN KEY (company_name) REFERENCES Company (company_name);
ALTER TABLE Manages ADD FOREIGN KEY (employee_name) REFERENCES Employee (employee_name);
```
## Inserting data
```sql
INSERT INTO Employee VALUES
(1, 'Mehul', 'Street 42', 'Pune'),
(2, 'Himanshu', 'Street 74', 'Mumbai'),
(3, 'Gundeti', 'Street 14', 'Pune'),
(4, 'Salvi', 'Street 38', 'Pune'),
(5, 'Afan', 'Steet 98', 'Pune'),
(6, 'Jambo', 'Street 23', 'Mumbai');
INSERT INTO Company VALUES
('TCS', 'Pune'),
('Infosys', 'Mumbai'),
('TechM', 'Pune'),
('MEPA', 'Pune');
INSERT INTO Works VALUES
('Mehul', 'MEPA', 15000),
('Himanshu', 'TCS', 25000),
('Gundeti', 'TCS', 9000),
('Salvi', 'TechM', 8000),
('Afan', 'Infosys', 13000),
('Jambo', 'MEPA', 28000);
INSERT INTO Manages VALUES
('Mehul', 'Kalas'),
('Himanshu', 'Kshitij'),
('Gundeti', 'Macho'),
('Salvi', 'Kshitij'),
('Afan', 'Kalas'),
('Jambo', 'Macho');
```
## Queries
1. Change the city of employee working with InfoSys to Bangalore
```sql
UPDATE Company SET city = "Bangalore" WHERE company_name = "Infosys";
SELECT * FROM Company;
```
2. Find the names of all employees who earn more than the average salary of all employees of their company. Assume that all people work for at most one company.
```sql
SELECT employee_name, salary, company_name FROM Works as W WHERE salary > (SELECT AVG(salary) FROM Works WHERE company_name = W.company_name);
```
3. Find the names, street address, and cities of residence for all employees who work for 'TechM' and earn more than $10,000.
```sql
SELECT Employee.employee_name, street, city FROM Employee INNER JOIN Works ON Employee.employee_name = Works.employee_name WHERE salary > 10000;
```
4. Change name of table Manages to Management.
```sql
ALTER TABLE Manages RENAME TO Management;
SHOW TABLES;
```
5. Create Simple and Unique index on employee table.
```sql
-- Simple Index
CREATE INDEX emp_index ON Employee(employee_name);
-- Unique Index
CREATE UNIQUE INDEX emp_uniqueIndex ON Employee(emp_id);
```
6. Display index Information
```sql
SHOW INDEX FROM Employee;
```
---

View File

@ -0,0 +1,206 @@
# S7 - SQL Queries (in MySQL)
**Problem Statement:**
Consider following Relation
Account (Acc_no, branch_name,balance)
Branch(branch_name,branch_city,assets)
Customer(cust_name,cust_street,cust_city)
Depositor(cust_name,acc_no)
Loan(loan_no,branch_name,amount)
Borrower(cust_name,loan_no)
1. Create a View1 to display List all customers in alphabetical order who have loan from Pune_Station branch.
2. Create View2 on branch table by selecting any two columns and perform insert update delete operations.
3. Create View3 on borrower and depositor table by selecting any one column from each table perform insert update delete operations.
4. Create Union of left and right joint for all customers who have an account or loan or both at bank
5. Create Simple and Unique index.
6. Display index Information.
---
## Creating the database
```sql
CREATE DATABASE Bank4;
USE Bank4;
```
## Creating tables:
```sql
CREATE TABLE Account (
acc_no INT,
branch_name VARCHAR(255),
balance INT,
PRIMARY KEY (acc_no)
);
CREATE TABLE Branch (
branch_name VARCHAR(255),
branch_city VARCHAR(255),
assets INT,
PRIMARY KEY (branch_name)
);
CREATE TABLE Customer (
cust_name VARCHAR(255),
cust_street VARCHAR(255),
cust_city VARCHAR(255),
PRIMARY KEY (cust_name)
);
CREATE TABLE Depositor (
cust_name VARCHAR(255),
acc_no INT
);
CREATE TABLE Loan (
loan_no INT,
branch_name VARCHAR(255),
amount INT,
PRIMARY KEY (loan_no)
);
CREATE TABLE Borrower (
cust_name VARCHAR(255),
loan_no INT
);
```
## Declaring foreign keys
```sql
ALTER TABLE Account ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Depositor ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Depositor ADD FOREIGN KEY (acc_no) REFERENCES Account (acc_no);
ALTER TABLE Loan ADD FOREIGN KEY (branch_name) REFERENCES Branch (branch_name);
ALTER TABLE Borrower ADD FOREIGN KEY (cust_name) REFERENCES Customer (cust_name);
ALTER TABLE Borrower ADD FOREIGN KEY (loan_no) REFERENCES Loan (loan_no);
```
## Inserting data
```sql
INSERT INTO Branch VALUES
('Pune_Station', 'Pune', 50000),
('PES', 'Pune', 65000),
('Lohegaon', 'Pune', 350000),
('Viman Nagar', 'Pune', 850000);
INSERT INTO Customer VALUES
('Kalas', 'Street 12', 'Pune'),
('Himanshu', 'Street 15', 'Pune'),
('Mehul', 'Street 29', 'Pune'),
('Macho', 'Street 59', 'Mumbai'),
('Gundeti', 'Street 40', 'Mumbai'),
('Salvi', 'Street 8', 'Pune'),
('Pintu', 'Street 55', 'Ahemadnagar'),
('Piyush', 'Street 21', 'Assam');
INSERT INTO Account VALUES
(101, 'Lohegaon', 67000),
(102, 'PES', 4324),
(103, 'PES', 54670),
(104, 'Viman Nagar', 5433),
(105, 'Pune_Station', 6462);
INSERT INTO Depositor VALUES
('Kalas', 101),
('Macho', 104),
('Gundeti', 105),
('Salvi', 105);
INSERT INTO Loan VALUES
(201, 'Pune_Station', 1800),
(202, 'PES', 8500),
(203, 'PES', 15000),
(204, 'Pune_Station', 5322),
(205, 'Viman Nagar', 1300),
(206, 'Lohegaon', 1450);
INSERT INTO Borrower VALUES
('Macho', 201),
('Mehul', 202),
('Himanshu', 203),
('Salvi', 204);
```
## Queries
1. Create a View1 to display List all customers in alphabetical order who have loan from Pune_Station branch.
```sql
CREATE VIEW View1 AS SELECT cust_name FROM Borrower INNER JOIN Loan ON Borrower.loan_no = Loan.loan_no WHERE branch_name = "Pune_Station" ORDER BY cust_name;
SELECT * FROM View1;
```
2. Create View2 on branch table by selecting any two columns and perform insert update delete operations.
```sql
-- Creating view
CREATE VIEW View2 AS SELECT branch_name, assets FROM Branch;
SELECT * FROM View2;
-- Insert operation
INSERT INTO View2 VALUES ('Kharadi', 594000);
INSERT INTO View2 VALUES ('Yerwada', 34004);
SELECT * FROM View2;
-- Update operation
UPDATE View2 SET assets = 590000 WHERE branch_name = "Kharadi";
UPDATE View2 SET assets = 24000 WHERE branch_name = "Yerwada";
SELECT * FROM View2;
-- Delete
DELETE FROM View2 WHERE branch_name = "Yerwada";
SELECT * FROM View2;
```
3. Create View3 on borrower and depositor table by selecting any one column from each table perform insert update delete operations.
```sql
-- Creating view
CREATE VIEW View3 AS SELECT Borrower.cust_name, Depositor.acc_no FROM Borrower JOIN Depositor ON Borrower.cust_name = Depositor.cust_name;
SELECT * FROM View3;
-- Insert operation
INSERT INTO Borrower (cust_name, loan_no) VALUES ('Pintu', 205);
INSERT INTO Depositor (cust_name, acc_no) VALUES ('Pintu', 102);
SELECT * FROM View3;
-- Update operation
UPDATE View3 SET cust_name = "Piyush" WHERE cust_name = "Pintu";
SELECT * FROM View3;
-- Delete operation
DELETE FROM Borrower WHERE cust_name = 'Macho';
-- This will also remove it from View3. We cannot perform delete operation directly View3 since it is created using join clause
SELECT * FROM View3;
```
4. Create Union of left and right joint for all customers who have an account or loan or both at bank
```sql
SELECT Borrower.cust_name FROM Borrower LEFT JOIN Loan ON Borrower.loan_no = Loan.loan_no UNION SELECT Depositor.cust_name FROM Depositor RIGHT JOIN Account ON Depositor.acc_no = Account.acc_no;
```
5. Create Simple and Unique index.
```sql
-- Simple Index
CREATE INDEX loaners ON Borrower(cust_name);
-- Unique Index
CREATE UNIQUE INDEX depos ON Depositor(cust_name);
```
6. Display index Information.
```sql
SHOW INDEX FROM Borrower;
SHOW INDEX FROM Depositor;
```
---

View File

@ -0,0 +1,133 @@
# S8 - SQL Queries (in MySQL)
**Problem Statement:**
Consider following Relation:
Companies (comp_id, name, cost, year)
Orders (comp_id, domain, quantity)
Execute the following query:
1. Find names, costs, domains and quantities for companies using
inner join.
2. Find names, costs, domains and quantities for companies using
left outer join.
3. Find names, costs, domains and quantities for companies using
right outer join.
4. Find names, costs, domains and quantities for companies using
Union operator.
5. Create View View1 by selecting both tables to show company name
and quantities.
6. Create View View2 by selecting any two columns and perform
insert update delete operations.
7. Display content of View1, View2.
---
## Creating the database
```sql
CREATE DATABASE Store2;
USE Store2;
```
## Creating tables:
```sql
CREATE TABLE Companies (
comp_id INT,
name VARCHAR(255),
cost INT,
year INT,
PRIMARY KEY (comp_id)
);
CREATE TABLE Orders (
comp_id INT,
domain VARCHAR(255),
quantity INT,
FOREIGN KEY (comp_id) REFERENCES Companies (comp_id)
);
```
## Inserting data
```sql
INSERT INTO Companies VALUES
(1, 'MEPA', 40500, 2024),
(2, 'Wayne Industries', 950000, 2000),
(3, 'Oscorp', 64600, 2013),
(4, 'Lex Corp', 28500, 2001),
(5, 'Vought', 77335, 2020);
INSERT INTO Orders VALUES
(1, 'Healthcare', 45),
(2, 'Kevlar', 30),
(3, 'Goblin masks', 62),
(4, 'Haircare', 23),
(5, 'Spandex', 9);
```
## Queries
1. Find names, costs, domains and quantities for companies using inner join.
```sql
SELECT name, cost, domain, quantity FROM Companies INNER JOIN Orders ON Companies.comp_id = Orders.comp_id;
SELECT DISTINCT name, cost, domain, quantity FROM Companies, Orders;
```
2. Find names, costs, domains and quantities for companies using left outer join.
```sql
SELECT name, cost, domain, quantity FROM Companies LEFT JOIN Orders ON Companies.comp_id = Orders.comp_id;
```
3. Find names, costs, domains and quantities for companies using right outer join.
```sql
SELECT name, cost, domain, quantity FROM Companies RIGHT JOIN Orders on Companies.comp_id = Orders.comp_id;
```
4. Find names, costs, domains and quantities for companies using Union operator.
```sql
SELECT name AS info, cost AS value FROM Companies UNION SELECT domain AS info, quantity AS value FROM Orders;
```
5. Create View View1 by selecting both tables to show company name and quantities.
```sql
CREATE VIEW View1 AS SELECT name, quantity FROM Companies INNER JOIN Orders ON Companies.comp_id = Orders.comp_id;
SELECT * FROM View1;
```
6. Create View View2 by selecting any two columns and perform insert update delete operations.
```sql
-- Creating view
CREATE VIEW View2 AS SELECT Companies.comp_id, domain FROM Companies INNER JOIN Orders ON Companies.comp_id = Orders.comp_id;
SELECT * FROM View2;
-- Insert operation
INSERT INTO Companies VALUES (6, 'Stark Industries', 54322, 2012);
INSERT INTO Orders VALUES (6, 'Vibranium', 66);
SELECT * FROM View2;
-- Update operation
UPDATE View2 SET domain = 'Iridium' WHERE comp_id = 6;
SELECT * FROM View2;
-- Delete operation
DELETE FROM Orders WHERE comp_id = 8;
DELETE FROM Companies WHERE comp_id = 8;
SELECT * FROM View2;
```
7. Display content of View1, View2.
```sql
SELECT * FROM View1;
SELECT * FROM View2;
```
---

View File

@ -0,0 +1,135 @@
# S9 - SQL Queries (in MySQL)
**Problem Statement:**
SQL Queries
Create following tables with suitable constraints. Insert data and
solve the following queries:
CUSTOMERS(_CNo_, Cname, Ccity, CMobile)
ITEMS(_INo_, Iname, Itype, Iprice, Icount)
PURCHASE(_PNo_, Pdate, Pquantity, Cno, INo)
1. List all stationary items with price between 400/- to 1000/-
2. Change the mobile number of customer “Gopal”
3. Display the item with maximum price
4. Display all purchases sorted from the most recent to the oldest
5. Count the number of customers in every city
6. Display all purchased quantity of Customer Maya
7. Create view which shows Iname, Price and Count of all stationary
items in descending order of price.
---
## Creating the database
```sql
CREATE DATABASE Store3;
USE Store3;
```
## Creating tables:
```sql
CREATE TABLE Customers (
CNo INT,
Cname VARCHAR(255),
Ccity VARCHAR(255),
Cmobile BIGINT,
PRIMARY KEY (CNo)
);
CREATE TABLE Items (
INo INT,
Iname VARCHAR(255),
Itype VARCHAR(255),
Iprice INT,
Icount INT,
PRIMARY KEY (Icount)
);
CREATE TABLE Purchase (
PNo INT,
Pdate DATE,
Pquantity INT,
Cno INT,
INo INT,
PRIMARY KEY (PNo),
FOREIGN KEY (Cno) REFERENCES Customers (CNo)
);
```
> [!WARNING]
> Notice inconsistent naming for columns? We're just doing it by the books. Blame the one who made these [problem statements](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Practical%20Exam/DBMSL%20-%20Problem%20Statements%20for%20Practical%20Exam%20%28November%202024%29.pdf).
## Inserting data
```sql
INSERT INTO Customers VALUES
(1, 'Kalas', 'Pune', 9857265240),
(2, 'Himanshu', 'Chennai', 9857265241),
(3, 'Gopal', 'Mumbai', 9857265245),
(4, 'Maya', 'Mumbai', 9857265243),
(5, 'Mehul', 'Pune', 9857265244);
INSERT INTO Items VALUES
(101, 'Stamp', 'Collectables', 850, 10),
(102, 'Pen', 'Instruments', 549, 50),
(103, 'Sticky notes', 'Writing', 150, 200),
(104, 'Geometry box', 'Instruments', 1350, 70),
(105, 'Pencil', 'Instruments', 670, 45);
INSERT INTO Purchase VALUES
(201, '2024-11-05', 4, 1, 101),
(202, '2024-11-07', 3, 2, 102),
(203, '2024-11-08', 20, 3, 103),
(204, '2024-10-29', 1, 4, 104),
(205, '2024-11-10', 7, 5, 105);
```
## Queries
1. List all stationary items with price between 400/- to 1000/-
```sql
SELECT Iname FROM Items WHERE Iprice BETWEEN 400 AND 1000;
```
2. Change the mobile number of customer “Gopal”
```sql
UPDATE Customers SET CMobile = 9857265242 WHERE Cname = "Gopal";
SELECT * FROM Customers WHERE Cname = "Gopal";
```
3. Display the item with maximum price
```sql
SELECT Iname FROM Items WHERE Iprice = (SELECT MAX(Iprice) FROM Items);
```
4. Display all purchases sorted from the most recent to the oldest
```sql
SELECT * FROM Purchase ORDER BY Pdate DESC;
```
5. Count the number of customers in every city
```sql
SELECT COUNT(*), Ccity FROM Customers GROUP BY Ccity;
```
6. Display all purchased quantity of Customer Maya
```sql
SELECT Iname, Pquantity FROM Purchase INNER JOIN Customers ON Purchase.Cno = Customers.CNo INNER JOIN Items ON Purchase.INo = Items.INo WHERE Cname = "Maya";
```
7. Create view which shows Iname, Price and Count of all stationary items in descending order of price.
```sql
CREATE VIEW itemView AS SELECT Iname, Iprice, Icount FROM Items ORDER BY Iprice DESC;
SELECT * FROM itemView;
```
---

54
Practical/README.md Normal file
View File

@ -0,0 +1,54 @@
# How to import database in MySQL
This is a guide for importing a database in MySQL using the terminal.
## Prerequisites
- Have MySQL installed on your machine.
## Guide
1. Download the database file from this repository. These database files have `.sql` extension and can be found in the Assignment folders within the [Practical folder](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical).
2. After downloading the file, locate it in the `Files` app. The downloaded file will mostly likely be preset in the _Downloads_ folder.
3. Right click in a empty space in the `Files` app window, and click on `Open in Terminal` (or something along those lines).
4. Now, start `mysql`
```shell
sudo mysql -u root -p
```
5. Create an empty database & exit:
```sql
CREATE DATABASE database_name;
exit
```
> `database_name` is the name of your database in which all the tables, data, etc. will be imported.
6. Lastly, import the database from `database.sql` file:
```shell
sudo mysql -u root -p database_name < database.sql
```
## Example
Let's consider I want to import the database for Assignment-A2. The database file is present in [Practical/Assignment-A2](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Assignment-A2) folder.
1. First download the [Database_A2.sql](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/src/branch/main/Practical/Assignment-A2/Database_A2.sql) file.
2. Locate the file in `Files` app, mostly likely present in the _Downloads_ folder.
3. Right click in an empty space in the **Files** app window and click **Open in Terminal**.
4. Start mysql: `sudo mysql -u root -p`
5. Create an empty database: `CREATE DATABASE Database_A2`
6. Exit from mysql: `exit`
7. Lastly, import the file: `sudo mysql -u root -p Database_A2 < Database_A2.sql`
8. That's it! Your database has been imported in MySQL.
---

View File

@ -1,3 +1,68 @@
# Database Management Systems (DBMS)
A one-stop Git repository for third year SPPU Computer Engineering students following the 2019 pattern. Access theory and practical resources covering E-R modeling, SQL/PL-SQL queries, NoSQL databases, database design, transaction management, and more for mastering Database Management System (DBMS) concepts.
---
> [!TIP]
> Want to contribute? Start by [opening an issue](https://git.kska.io/sppu-te-comp-content/DatabaseManagementSystems/issues) in this repository!
## Index
### Notes
1. [Unit 1 - Introduction to Database Management Systems and ER Model](Notes/Unit%201)
2. [Unit 2 - SQL and PL/SQL](Notes/Unit%202)
3. [Unit 3 - Relational Database Design](Notes/Unit%203)
4. [Unit 4 - Database Transaction Management](Notes/Unit%204)
5. [Unit 5 - NoSQL Databases](Notes/Unit%205)
6. [Unit 6 - Advances in Databases](Notes/Unit%206)
### Practical
> [!IMPORTANT]
> Queries for all problem statements expected for practical examination (2024) are in the ["Practical Exam"](Practical/Practical%20Exam) folder.
> Each folder contains **handout**, **write-up**, **database** and **softcopy** (i.e. code + output).
1. [Assignment-A2](Practical/Assignment-A2)
2. [Assignment-A3](Practical/Assignment-A3)
3. [Assignment-A4+A5](Practical/Assignment-A4+A5)
4. [Assignment-A6](Practical/Assignment-A6)
5. [Assignment-A7](Practical/Assignment-A7)
6. [Assignment-A8](Practical/Assignment-A8)
7. [Assignment-B1](Practical/Assignment-B1)
8. [Assignment-B2](Practical/Assignment-B2)
9. [Assignment-B3](Practical/Assignment-B3)
10. [Assignment-A9+B4+C1 (Mini Project)](Practical/Assignment-A9+B4+C1%20%28Mini%20Project%29)
### Question Papers
- [IN-SEM](Question%20Papers/IN-SEM)
- [END-SEM](Question%20Papers/END-SEM)
> [Sample IN-SEM Unit Test Paper](Question%20Papers/DBMS%20-%20Unit%20Test%20Sample%20Paper%20%28IN-SEM%2C%202019%20Pattern%29.pdf)
---
## Miscellaneous
**-> Disclaimer:** Please read the [DISCLAIMER](DISCLAIMER.md) file for important information regarding the contents of this repository.
**-> Note:** Content such as databases, queries, softcopies, write-ups and question papers is provided by us, i.e. our contributors. You are free to use this content however you wish, without any restrictions. Some of the notes and handouts have been provided by our professors, thus to use them for anything other than educational purposes, please contact them.
**-> Maintained by:**
- [TanmaySpamzzz](https://git.kska.io/TanmaySpamzzz)
- [notkshitij](https://git.kska.io/notkshitij)
**->** Repository icon from [Icons8](https://icons8.com/).
**-> Motto:**
![Making information freely accessible to everyone.](motto.jpg)
**-> Keywords:**
SPPU, Savitribai Phule Pune University, Pune University, Computer Engineering, COMP, Third Year, TE, Semester 5, SEM-5, Database Management Systems, DBMS, dbms queries, DBMS databases, DBMS softcopy, DBMS practical softcopy, DBMS write-ups, DBMS question papers, DBMS pyqs, DBMS handouts
---

BIN
motto.jpg Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 22 KiB