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

DBMS_LAB PRACTICAL-by group 3

The document outlines a practical file for a Database Management Systems course, detailing various experiments related to SQL queries, database design, and PL/SQL scripts. It includes specific tasks such as creating databases and tables for airline and sailing club data, along with sample queries to manipulate and retrieve information. Additionally, it describes the design of a database for a wholesale furniture company, focusing on furniture types, customer locations, and sales analysis.

Uploaded by

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

DBMS_LAB PRACTICAL-by group 3

The document outlines a practical file for a Database Management Systems course, detailing various experiments related to SQL queries, database design, and PL/SQL scripts. It includes specific tasks such as creating databases and tables for airline and sailing club data, along with sample queries to manipulate and retrieve information. Additionally, it describes the design of a database for a wholesale furniture company, focusing on furniture types, customer locations, and sales analysis.

Uploaded by

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

PRACTICAL FILE

CSE3001 - Database Management Systems


Class No. BL2024250400784
Slot: A21+A22+A23

Course Instructor
Dr Antima Jain
Assistant Professor Senior Grade 1
School of Computing Science and Engineering
VIT Bhopal University, Sehore
Madhya Pradesh

Name : Tanishk Navlakhe,Ritwik Singh,Shubham


Tripathi,S Dhaush,Anish Dhanajay Pawar,Jesse
Priyanshu Simes
Registration Number :
23BCE10934,23BCE11204,23BCE11262,23BCE11429,
23BCE11329,23BCE11393
INDEX

SN. EXPERIMENT TITLE PAGE NO.


SQL Queries on Airline Database: Explore pilot certifications, aircraft, and
11 flight details.text
3-7
SQL Queries on Sailors Database: Analyze sailors, boats, and reservations
22 8-16h text
data.
Database Design for Wholesale Furniture Company: Categorization and sales
3 analysis.
17-20
PL/SQL Script for Ship Inventory Management: Display and manage expected
44 goods data. 21-24
Transparent Audit System: Track and log updates or deletions in Client Master
55 table.
25-26
Cursor Program for Parts Database: Sequentially process parts and
66 manage transactions.
27-30
Detect Doctor Violations: Identify doctors treating and prescribing for the
177 same patient. 311
Cleaner Details Procedures: Fetch cleaner information and depot
88 location dynamically.
32
Salary Update Procedure: Modify and display cleaner details with a
99 33
10% salary increase.
Trigger to Restrict Updates: Raise custom error messages for
10 unauthorized operations.
34-35
Join Queries for Employee and Department Data: Hierarchy,
11 management, and relationships.
36-38
Experiment - 1
Consider the following relations containing airline flight information: Flights(flno: integer,
from: string, to: string,distance: integer, departs: time, arrives: time) Aircraft(aid: integer,
aname: string, cruisingrange: integer) Certified(eid: integer, aid: integer) Employees(eid:
integer, ename: string, salary: integer) Note that the Employees relation describes pilots
and other kinds of employees as well every pilot is certified for some aircraft (otherwise,
he or she would not qualify as a pilot), and only pilots are certified to fly.
Write the following queries in SQL
1. Find the eids of pilots certified for some Boeing aircraft.
2. Find the names of pilots certified for some Boeing aircraft.
3. Find the aids of all aircraft that can be used on non-stop flights from Bonn to Madras.
4. Identify the flights that can be piloted by every pilot whose salary is more than
$100,000.
5. Find the names of pilots who can operate planes with a range greater than 3,000 miles
but are not certified on any Boeing aircraft.

CREATE DATABASE AND TABLE

-- Create the database


CREATE DATABASE AirlineDB;
USE AirlineDB;

-- Create Flights Table


CREATE TABLE Flights (
flno INT PRIMARY KEY,
from_location VARCHAR(50),
to_location VARCHAR(50),
distance INT,
departs TIME,
arrives TIME
);

-- Create Aircraft Table


CREATE TABLE Aircraft (
aid INT PRIMARY KEY,
aname VARCHAR(100),
cruisingrange INT
);

-- Create Certified Table


CREATE TABLE Certified (
eid
INT,
FOaRidEIGN KEY (eid) REFERENCES Employees(eid),
INT,
FOREIGN KEY (aid) REFERENCES Aircraft(aid),
PRIMARY KEY (eid, aid)
);

-- Create Employees Table


CREATE TABLE Employees (
eid INT PRIMARY KEY,
ename VARCHAR(100),
salary INT
);

Step 2: Insert Sample Data

-- Insert data into Employees Table


INSERT INTO Employees (eid, ename, salary)
VALUES (201, 'Alice', 90000), (202, 'Bob',
120000), (203, 'Charlie', 95000), (204,
'David', 150000);

-- Insert data into Aircraft Table


INSERT INTO Aircraft (aid, aname, cruisingrange)
VALUES
(1, 'Boeing 737', 2500),
(2, 'Airbus A320', 3200),
(3, 'Boeing 747', 4000);

-- Insert data into Flights Table


INSERT INTO Flights (flno, from_location, to_location, distance, departs, arrives)
VALUES (101, 'Bonn', 'Madras', 2000, '10:00:00', '15:00:00'), (102, 'Bonn',
'Madras', 3000, '11:00:00', '16:00:00'), (103, 'Berlin', 'Madras', 4000, '12:00:00',
'18:00:00');

-- Insert data into Certified Table


INSERT INTO Certified (eid, aid) VALUES
(201, 1), -- Alice is certified for Boeing 737
(202, 2), -- Bob is certified for Airbus A320
(203, 3), -- Charlie is certified for Boeing 747
(204, 2); -- David is certified for Airbus A320

Write the following queries in SQL

1. Find the eids of pilots certified for some Boeing aircraft.


SELECT DISTINCT c.eid
FROM Certified c
JOIN Aircraft a ON c.aid = a.aid
WHERE a.aname LIKE '%Boeing%';

2. Find the names of pilots certified for some Boeing aircraft.


SELECT DISTINCT e.ename
FROM Employees e
JOIN Certified c ON e.eid = c.eid
JOIN Aircraft a ON c.aid = a.aid
WHERE a.aname LIKE '%Boeing%';

3. Find the aids of all aircraft that can be used on non-stop flights from Bonn to Madras.
SELECT DISTINCT a.aid
FROM Aircraft a
JOIN Flights f ON a.cruisingrange >= f.distance
WHERE f.from_location = 'Bonn' AND f.to_location = 'Madras';
4. Identify the flights that can be piloted by every pilot whose salary is more than
$100,000.
SELECT f.flno
FROM Flights f
WHERE NOT EXISTS (
SELECT e.eid
FROM Employees e
WHERE e.salary > 100000
AND NOT EXISTS (
SELECT c.aid
FROM Certified c
WHERE c.eid = e.eid AND c.aid = f.aid
)
) ;
5. Find the names of pilots who can operate planes with a range greater than 3,000 miles
but are not certified on any Boeing aircraft.
SELECT DISTINCT e.ename
FROM Employees e JOIN
Certified c ON e.eid = c.eid JOIN
Aircraft a ON c.aid = a.aid
WHERE a.cruisingrange > 3000
AND e.eid NOT IN (
SELECT c1.eid
FROM Certified c1
JOIN Aircraft a1 ON c1.aid = a1.aid
WHERE a1.aname LIKE '%Boeing%'
);
EXPERIMENT- 2
SAILORS (SID:INTEGER, SNAME:STRING, RATING:INTEGER, AGE:REAL)
BOATS (BID:INTEGER, BNAME:STRING, COLOR:STRING)
RESERVES (SID:INTEGER, BID:INTEGER, DAY:DATE)
1. Display names & ages of all sailors.
2. Find all sailors with a rating above 7.
3. Display all the names & colors of the boats.
4. Find all the boats with Red color.
5. Find the names of sailors who have reserved boat number
123.
6. Find SIDs of sailors who have reserved Pink Boat;
7. Find the color of the boats reserved by Rajesh.
8. Find names of the sailors who have reserved at least one
boat.
9. Find the names of sailors who have reserved a red or a green
boat.
10. Find the names of sailors who have reserved boat 103.
11. Find the names of sailors who have not reserved boat 103.
12. Find sailors whose rating is better than some sailor called
Rajesh.
13. Find the sailor's with the highest rating using ALL.
14. To count number SIDs of sailors in Sailors table
15. To count numbers of boats booked in Reserves table.
16. To count number of Boats in Boats table.
17. To find age of Oldest Sailor.
18. To find age of Youngest Sailor.
19. Find the average age of sailors with a rating of 10.
20. Count the number of different sailor names.
21. Find the name and age of the oldest sailor.
22. Count the number of Sailors.
23. Find the names of sailors who are older than the oldest sailor
with a rating of 10.
24. Display all the sailors according to their ages.
25. To display names of sailors according to alphabetical order.
Creating Database

-- Create the database


CREATE DATABASE SailingClub;

-- Use the database


USE SailingClub;

-- Create the SAILORS table


CREATE TABLE SAILORS (
SIDINTPRIMARYKEY, --SailorID
SNAMEVARCHAR(50), --SailorName
RATINGINT, --SailorRating
AGEREAL --SailorAge
);

-- Create the BOATS table


CREATE TABLE BOATS (
BIDINTPRIMARYKEY, --BoatID
BNAMEVARCHAR(50), --BoatName
COLORVARCHAR(20) --BoatColor
);

-- Create the RESERVES table


CREATE TABLE RESERVES (
SIDINT, --SailorID(ForeignKey)
BIDINT, --BoatID(ForeignKey)
DAYDATE, --ReservationDate
PRIMARY KEY (SID, BID, DAY),
FOREIGN KEY (SID) REFERENCES SAILORS(SID),
FOREIGN KEY (BID) REFERENCES BOATS(BID)
);

-- Insert sample data into the SAILORS table INSERT


INTO SAILORS (SID, SNAME, RATING, AGE) VALUES
(1, 'Rajesh', 8, 35.5), (2, 'Suresh', 7, 29.3), (3,
'Mahesh', 9, 40.2), (4, 'Ramesh', 10, 25.8),
(5, 'Lokesh', 6, 32.1);

-- Insert sample data into the BOATS table


INSERT INTO BOATS (BID, BNAME, COLOR)
VALUES (101, 'Titanic', 'Red'), (102, 'Voyager',
'Green'), (103, 'Mariner', 'Blue'), (104,
'Dolphin', 'Pink'), (105, 'Explorer', 'Red');

-- Insert sample data into the RESERVES table


INSERT INTO RESERVES (SID, BID, DAY)
VALUES (1, 101, '2024-01-15'), (2, 102,
'2024-01-16'), (3, 103, '2024-01-17'), (1, 104,
'2024-01-18'), (4, 105, '2024-01-19'), (5, 101,
'2024-01-20');
1. Display names & ages of all sailors.
SELECT SNAME, AGE FROM SAILORS;

2. Find all sailors with a rating above 7.


SELECT * FROM SAILORS WHERE RATING > 7;
3. Display all the names & colors of the boats.
SELECT BNAME, COLOR FROM BOATS;

4. Find all the boats with Red color.


SELECT * FROM BOATS WHERE COLOR = 'Red';

5. Find the names of sailors who have reserved boat number


123.
SELECT S.SNAME
FROM SAILORS S, RESERVES R
WHERE S.SID = R.SID AND R.BID = 123;

No matching Data for output


6. Find SIDs of sailors who have reserved Pink Boat;
SELECT DISTINCT R.SID
FROM RESERVES R
JOIN BOATS B ON R.BID = B.BID
WHERE B.COLOR = 'Pink';
7. Find the color of the boats reserved by Rajesh.
SELECT DISTINCT B.COLOR
FROM SAILORS S
JOIN RESERVES R ON S.SID = R.SID
JOIN BOATS B ON R.BID = B.BID
WHERE S.SNAME = 'Rajesh';

8. Find names of the sailors who have reserved at least one


Boat.
SELECT DISTINCT S.SNAME
FROM SAILORS S
JOIN RESERVES R ON S.SID = R.SID;

9. Find the names of sailors who have reserved a red or a green


Boat.
SELECT DISTINCT S.SNAME
FROM SAILORS S
JOIN RESERVES R ON S.SID = R.SID
JOIN BOATS B ON R.BID = B.BID
WHERE B.COLOR IN ('Red', 'Green');
10. Find the names of sailors who have reserved boat 103.
SELECT DISTINCT S.SNAME
FROM SAILORS S
JOIN RESERVES R ON S.SID = R.SID
WHERE R.BID = 103;

11. Find the names of sailors who have not reserved boat 103.
SELECT DISTINCT S.SNAME
FROM SAILORS S
WHERE S.SID NOT IN (
SELECT R.SID FROM RESERVES R WHERE R.BID = 103
);

12. Find sailors whose rating is better than some sailor called
Rajesh.
SELECT DISTINCT S.SNAME
FROM SAILORS S
WHERES.RATING>(SELECTRATINGFROMSAILORSWHERESNAME='Rajesh');

13. Find the sailor's with the highest rating using ALL.
SELECT SNAME FROM SAILORS WHERE RATING >= ALL
(SELECT RATING FROM SAILORS);
14. To count number SIDs of sailors in Sailors table
SELECT COUNT(*) AS TotalSailors FROM SAILORS;

15. To count numbers of boats booked in Reserves table.


SELECT COUNT(DISTINCT BID) AS TotalBoatsBooked FROM RESERVES;

16. To count number of Boats in Boats table.


SELECT COUNT(*) AS TotalBoats FROM BOATS;

17. To find the age of the Oldest Sailor.


SELECT MAX(AGE) AS OldestAge FROM SAILORS;

18. To find age of Youngest Sailor.


SELECT MIN(AGE) AS YoungestAge FROM SAILORS;

19. Find the average age of sailors with a rating of 10.


SELECT AVG(AGE) AS AvgAge FROM SAILORS WHERE RATING = 10;
20. Count the number of different sailor names.
SELECT COUNT(DISTINCT SNAME) AS UniqueNames FROM SAILORS;

21. Find the name and age of the oldest sailor.


SELECT SNAME, AGE
FROM SAILORS
WHERE AGE = (SELECT MAX(AGE) FROM SAILORS);

22. Count the number of Sailors.


SELECT COUNT(*) AS TotalSailors FROM SAILORS;

23. Find the names of sailors who are older than the oldest sailor
with a rating of 10. SELECT SNAME FROM SAILORS WHERE AGE > (SELECT
MAX(AGE) FROM SAILORS WHERE RATING = 10);
24. Display all the sailors according to their ages.
SELECT * FROM SAILORS ORDER BY AGE;

25. To display names of sailors according to alphabetical order.


SELECT SNAME FROM SAILORS ORDER BY SNAME;
EXPERIMENT-3
Design the data base for a wholesale furniture company. The database
has to allow to analyze the company’s situation at least with respect to
the Furniture, Customers and Time. Moreover, the company needs to
analyze:
the furniture with respect to its type (chair, table, wardrobe, cabinet. . . ),
category (kitchen, living room, bedroom, bathroom, office. . . ) and
material (wood, marble. . . ) the customers with respect to their spatial
location, by considering at least cities, regions and states The company is
interested in learning at least the quantity, income and discount of its
Sales.
#Creating Database
CREATE DATABASE WholesaleFurnitureCompany;
USE WholesaleFurnitureCompany;
1. Furniture
CREATE TABLE Furniture (
FurnitureID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100),
Type VARCHAR(50),
Category VARCHAR(50),
Material VARCHAR(50),
Price DECIMAL(10, 2)
);

2. Customers
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY AUTO_INCREMENT,
Name VARCHAR(100),
City VARCHAR(50),
Region VARCHAR(50),
State VARCHAR(50)
);
3. Sales
CREATE TABLE Sales (
SaleID INT PRIMARY KEY AUTO_INCREMENT,
FurnitureID INT,
CustomerID INT,
SaleDateDATE,
Quantity INT,
Discount DECIMAL(5, 2),
TotalIncome DECIMAL(10, 2),
FOREIGN KEY (FurnitureID) REFERENCES Furniture(FurnitureID),
FOREIGN KEY (CustomerID) REFERENCES Customers(CustomerID)
);
#Inserting Sample Data
Furniture Table Data
INSERT INTO Furniture (Name, Type, Category, Material, Price)
VALUES
('Dining Chair', 'Chair', 'Dining Room', 'Wood', 150.00),
('Office Table', 'Table', 'Office', 'Wood', 300.00),
('Wardrobe', 'Wardrobe', 'Bedroom', 'Marble', 800.00),
('Cabinet', 'Cabinet', 'Kitchen', 'Metal', 250.00),
('Sofa', 'Sofa', 'Living Room', 'Fabric', 600.00);

Customers Table Data


INSERT INTO Customers (Name, City, Region, State)
VALUES
('John Doe', 'New York', 'Northeast', 'New York'),
('Jane Smith', 'San Francisco', 'West', 'California'),
('Emma Brown', 'Chicago', 'Midwest', 'Illinois'),
('Oliver White', 'Miami', 'Southeast', 'Florida'),
('Liam Davis', 'Dallas', 'Southwest', 'Texas');

Sales Table Data


INSERT INTO Sales (FurnitureID, CustomerID, SaleDate, Quantity, Discount,
TotalIncome)
VALUES
(1, 1, '2024-01-15', 10, 10.00, 1350.00),
(2, 2, '2024-01-16', 5, 15.00, 1275.00),
(3, 3, '2024-01-17', 2, 5.00, 1520.00),
(4, 4, '2024-01-18', 7, 20.00, 1400.00),
(5, 5, '2024-01-19', 3, 0.00, 1800.00);
#Sample Queries
a) Analyze furniture sales by type and material.
SELECT F.Type, F.Material, SUM(S.Quantity) AS TotalQuantity, SUM(S.TotalIncome)
AS TotalIncome
FROM Furniture F
JOIN Sales S ON F.FurnitureID = S.FurnitureID
GROUP BY F.Type, F.Material;

b) Analyze customer purchases by city.


SELECT C.City, SUM(S.Quantity) AS TotalQuantity, SUM(S.TotalIncome) AS
TotalIncome
FROM Customers C
JOIN Sales S ON C.CustomerID = S.CustomerID
GROUP BY C.City;

c) Analyze sales over time.


SELECT YEAR(S.SaleDate) AS Year, MONTH(S.SaleDate) AS Month,
SUM(S.TotalIncome) AS MonthlyIncome
FROM Sales S
GROUP BY YEAR(S.SaleDate), MONTH(S.SaleDate);
d) Top-selling furniture items.
SELECT F.Name, SUM(S.Quantity) AS TotalSold
FROM Furniture F
JOIN Sales S ON F.FurnitureID = S.FurnitureID
GROUP BY F.Name
ORDER BY TotalSold DESC;

e) Find customers who purchased more than $1,500 worth of furniture.


SELECT C.Name, SUM(S.TotalIncome) AS TotalSpent
FROM Customers C
JOIN Sales S ON C.CustomerID = S.CustomerID
GROUP BY C.Name
HAVING SUM(S.TotalIncome) > 1500;
EXPERIMENT-4
Simple script to backup all SQL server database
Create a database table with the following fields:
Field name Data type
Ship_id Number -- This is the ID of a particular Ship
Date_expected Date --The date at which the goods are expected
to arrive
Qty_expected Number --The quantity that is supposed to arrive
Description Varchar2 --The description of the items
Color Varchar2 --The color of the items
Qty_hand Number –The quantity on hand for these items
Itemrate Number—Price of each item.
Write a PL/SQL program that uses implicit cursor to display the data expected,
quantity expected, item description, color and quantity on hand for any
particular Ship ID number.

#Creating Table Script


CREATE TABLE Shipments (
Ship_id NUMBER PRIMARY KEY,
Date_expected DATE,
Qty_expected NUMBER,
Description VARCHAR2(255),
Color VARCHAR2(50),
Qty_hand NUMBER,
Itemrate NUMBER
);
# Inserting Sample Data
INSERT INTO Shipments (Ship_id, Date_expected, Qty_expected, Description, Color,
Qty_hand, Itemrate)
VALUES (1, TO_DATE('2024-12-10', 'YYYY-MM-DD'), 100, 'Office Chairs', 'Blue', 50,
150.00);
INSERT INTO Shipments (Ship_id, Date_expected, Qty_expected, Description, Color,
Qty_hand, Itemrate)
VALUES (2, TO_DATE('2024-12-15', 'YYYY-MM-DD'), 200, 'Wooden Tables', 'Brown',
80, 250.00);

INSERT INTO Shipments (Ship_id, Date_expected, Qty_expected, Description, Color,


Qty_hand, Itemrate)
VALUES (3, TO_DATE('2024-12-20', 'YYYY-MM-DD'), 150, 'Wardrobes', 'White', 30,
800.00);

# PL/SQL Program with Implicit Cursor


DECLARE
v_ship_id NUMBER;
v_description VARCHAR2(255);
v_color VARCHAR2(50);
v_qty_expected NUMBER;
v_qty_hand NUMBER;
BEGIN
-- Assume Ship ID is provided as a parameter
v_ship_id := 1; -- For example, checking for Ship ID 1

-- Use an implicit cursor to fetch data


FOR record IN (SELECT Description, Color, Qty_expected, Qty_hand
FROM Shipments
WHERE Ship_id = v_ship_id)
LOOP
v_description := record.Description;
v_color := record.Color;
v_qty_expected := record.Qty_expected;
v_qty_hand := record.Qty_hand;

-- Display the fetched data


DBMS_OUTPUT.PUT_LINE('Description: ' || v_description);
DBMS_OUTPUT.PUT_LINE('Color: ' || v_color);
cleaner_no IN NUMBER,

cleaner_name OUT VARCHAR2,


cleaner_salary OUT NUMBER

) IS
BEGIN

SELECT name, salary INTO cleaner_name, cleaner_salary


FROM cleaners
WHERE cleaner_number = cleaner_no;

END;
/

CREATE OR REPLACE FUNCTION getCleanersLocation(

cleaner_no IN NUMBER

) RETURN VARCHAR2 IS

cleaner_location VARCHAR2(100);
BEGIN

SELECT depot_address INTO cleaner_location


FROM cleaners
WHERE cleaner_number = cleaner_no;

RETURN cleaner_location;

END;
/

-- Using the function in an SQL statement


DECLARE

cleaner_name VARCHAR2(100);
cleaner_salary NUMBER;
cleaner_location VARCHAR2(100);

BEGIN
getCleanerDetails(113, cleaner_name, cleaner_salary);
DBMS_OUTPUT.PUT_LINE('Expected Quantity: ' || v_qty_expected);
DBMS_OUTPUT.PUT_LINE('Quantity on Hand: ' || v_qty_hand);
END LOOP;
END;
EXPERIMENT-5
Create a transparent audit system for a table Client_master (client_no, name, address, Bal_due). The
system must keep track of the records that are being deleted or updated. The functionality being when a
record is deleted or modified, the original record details and the date of operation are stored in the
auditclient(client_no, name, bal_due, operation, userid, update) table, then the delete or update is allowed
to go through.
-- Create Database
CREATE DATABASE AuditSystem;
USE AuditSystem;

-- Create Tables
CREATE TABLE Client_master (
client_no INT PRIMARY KEY,
name VARCHAR(255),
address VARCHAR(255),
bal_due DECIMAL(10, 2)
);

CREATE TABLE Auditclient (

client_no INT,
name VARCHAR(255),
bal_due DECIMAL(10, 2),
operation VARCHAR(10),
userid VARCHAR(255),
update_time DATETIME DEFAULT CURRENT_TIMESTAMP
);

-- Insert Initial Data


INSERT INTO Client_master (client_no, name, address, bal_due)
VALUES
(1, 'John Doe', '123 Main St', 500.00),
(2, 'Jane Smith', '456 Oak St', 300.00),
(3, 'Alice Brown', '789 Pine St', 200.00);

-- Create Triggers
DELIMITER $$
CREATE TRIGGER after_client_delete
AFTER DELETE ON Client_master
FOR EACH ROW
BEGIN
INSERT INTO Auditclient (client_no, name, bal_due, operation, userid, update_time)
VALUES (OLD.client_no, OLD.name, OLD.bal_due, 'DELETE', USER(), NOW());
END$$

CREATE TRIGGER before_client_update


BEFORE UPDATE ON Client_master
FOR EACH ROW
BEGIN
INSERT INTO Auditclient (client_no, name, bal_due, operation, userid, update_time)
VALUES (OLD.client_no, OLD.name, OLD.bal_due, 'UPDATE', USER(), NOW());
END$$
DELIMITER ;

-- Perform Operations
UPDATE Client_master
SET bal_due = 450.00
WHERE client_no = 1;

DELETE FROM Client_master


WHERE clie nt_no = 2;
-- View Results
SELECT * FROM Client_master;

SELECT * FROM Auditclient;


EXPERIMENT-6
Using the supplier and parts database, write an cursor program to read and print all parts
in part number, deleting every tenth one as you go, and begin a I new transaction after
every tenth row. You can use the foreign key delete CASCADE rule from
parts,commit,rollback and savepoint .

-- Step 1: Create the Database


CREATE DATABASE SupplierPartsDB;
USE SupplierPartsDB;

-- Step 2: Create Tables


CREATE TABLE Supplier (
supplier_id INT PRIMARY KEY,
supplier_name VARCHAR(255) );

CREATE TABLE Parts (


part_id INT PRIMARY KEY,
part_name VARCHAR(255),
supplier_id INT,
FOREIGN KEY (supplier_id) REFERENCES Supplier(supplier_id) ON DELETE CASCADE
);
-- Step 3 : Insert Sample Data
INSERT INTO Supplier (supplier_id, supplier_name)
VALUES

(1, 'Supplier A'),


(2, 'Supplier B');

INSERT INTO Parts (part_id, part_name, supplier_id)


VALUES
(1, 'Part 1', 1), (2, 'Part 2', 1), (3, 'Part 3', 1), (4,
'Part 4', 1), (5, 'Part 5', 1), (6, 'Part 6', 1), (7, 'Part
7', 1), (8, 'Part 8', 1), (9, 'Part 9', 1), (10, 'Part 10',
1), (11, 'Part 11', 1), (12, 'Part 12', 1);
-- Step 4: Create the Procedure
DELIMITER $$

CREATE PROCEDURE ManageParts()


BEGIN
DECLARE done INT DEFAULT 0; -- Handler to indicate the end of cursor
DECLARE row_counter INT DEFAULT 0; -- Counter to track rows
DECLARE p_id INT; -- Variable to hold part_id
DECLARE p_name VARCHAR(255); -- Variable to hold part_name

-- Cursor declaration to fetch all parts


DECLARE parts_cursor CURSOR FOR
SELECT pa rt_id, part_name FROM Parts ORDER BY part_id;

-- Handler for end of cursor


DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;

-- Open the cursor


OPEN parts_cursor;

-- Iterate through parts using the cursor


read_loop: LOOP
FETCH parts_cursor INTO p_id, p_name; -- Fetch the next row

IF done THEN -- Exit loop if no more rows


LEAVE read_loop;
END IF;

-- Print the current part details


SELECT CONCAT('Processing Part ID: ', p_id, ', Part Name: ', p_name) AS PartDetails;

SET row_counter = row_counter + 1; -- Increment row counter

-- Check if it's the 10th row


IF row_counter % 10 = 0 THEN
-- Delete the 10th part
DELETE FROM Parts WHERE part_id = p_id;

-- Commit the transaction after deleting


COMMIT;

SELECT CONCAT('Deleted Part ID: ', p_id) AS DeletedPart;


END IF;
END LOOP;

-- Close the cursor


CLOSE parts_cursor;
END$$

DELIMITER ;

-- Step 5: Execute the Procedure


CALL ManageParts();
- Step 6: Verify the Remaining Data in the Parts
Table SELECT * FROM Parts;
Experiment-7
Assuming a patient should not receive both treatment and prescription from the same doctor,
write a program to find out all the doctor who provide both treatment and prescription to the
same patient. In addition, raise and display an exception if this situation occurs

DECLARE

CURSOR doctor_cursor IS
SELECT doctor_id, patient_id
FROM treatments
INTERSECT
SELECT doctor_id, patient_id
FROM prescriptions;

v_doctor_id treatments.doctor_id%TYPE;
v_patient_id treatments.patient_id%TYPE;

exception_occurred EXCEPTION;

BEGIN

OPEN doctor_cursor;
LOOP

FETCH doctor_cursor INTO v_doctor_id, v_patient_id;


EXIT WHEN doctor_cursor%NOTFOUND;

DBMS_OUTPUT.PUT_LINE('Doctor ID ' || v_doctor_id ||

' provides both treatment and prescription to Patient ID ' || v_patient_id || '.');

END LOOP;
CLOSE doctor_cursor;

END;
/
EXPERIMENT-8
Write a PL/SQL block which includes a procedure getCleanerDetails which accepts a cleaner number and
returns the cleaners name and salary. Create a stored function called getCleanersLocation. This function
takes as input a cleaner’s number and returns the cleaner’s depot address. Call the function from within an
SQL statement to select the cleaner’s name and location for a particular cleaner

CREATE OR REPLACE PROCEDURE getCleanerDetails(

cleaner_no IN NUMBER,
cleaner_name OUT VARCHAR2
, cleaner_salary OUT NUMBER
) IS
BEGIN
SELECT name, salary INTO cleaner_name, cleaner_salary
FROM cleaners
WHERE cleaner_number = cleaner_no
; END;
/
CREATE OR REPLACE FUNCTION getCleanersLocation( cleaner_no IN NUMBER )
RETURN VARCHAR2 IS
cleaner_location VARCHAR2(100);
BEGIN
SELECT depot_address INTO cleaner_location
FROM cleaners
WHERE cleaner_number = cleaner_no;
RETURN cleaner_location;
END;
/
-- Using the function in an SQL statement
DECLARE
cleaner_name VARCHAR2(100);
cleaner_salary NUMBER;
cleaner_location VARCHAR2(100);
BEGIN
getCleanerDetails(113, cleaner_name, cleaner_salary);
cleaner_location := getCleanersLocation(113);
DBMS_OUTPUT.PUT_LINE('Cleaner Name: ' || cleaner_name);
DBMS_OUTPUT.PUT_LINE('Cleaner Location: ' || cleaner_location);
END;
/

OUTPUT :
Experiment-9

Write a PL/SQL block which includes a procedure getCleanerDetails which accepts a cleaner
number and returns the cleaners name and salary. The main block should call the procedure with
cleaner number ‘113’ and output this cleaner’s details including the salary which has been
increased by 10%.

CREATE OR REPLACE PROCEDURE getCleanerDetailsWithIncrement(


cleaner_no IN NUMBER,

cleaner_name OUT VARCHAR2,

cleaner_salary OUT NUMBER

) IS

BEGIN

SELECT name, salary INTO cleaner_name, cleaner_salary

FROM cleaners
WHERE cleaner_number = cleaner_no;

-- Increase salary by 10%

cleaner_salary := cleaner_salary * 1.1;

END;

-- Main block to call the procedure

DECLARE

cleaner_name VARCHAR2(100);

cleaner_salary NUMBER;

BEGIN

getCleanerDetailsWithIncrement(113, cleaner_name, cleaner_salary);

DBMS_OUTPUT.PUT_LINE('Cleaner Name: ' || cleaner_name);


DBMS_OUTPUT.PUT_LINE('Updated Salary: ' || cleaner_salary);

END;
/

OUTPUT :
Experiment 10

Create a Trigger that raises an User Defined Error Message and does not allow the
update and Insert operation in the database.

Explanation:
In MySQL, triggers can be used to define actions that occur automatically when certain database
events (like INSERT, UPDATE, or DELETE) take place. To raise a user-defined error message
and block the operation, we use the SIGNAL statement in the trigger.
Trigger Code:

CODE:

DELIMITER $$

CREATE TRIGGER prevent_modifications


BEFORE INSERT ON your_table_name
FOR EACH ROW
BEGIN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Insert operation is not allowed on this table.’;
END$$

DELIMITER ;

Similarly, for an UPDATE trigger:


CODE:

DELIMITER $$

CREATE TRIGGER prevent_update


BEFORE UPDATE ON your_table_name
FOR EACH ROW
BEGIN
SIGNAL SQLSTATE '45000'
SET MESSAGE_TEXT = 'Update operation is not allowed on this table.';
END$$
DELIMITER ;
Process:
1. Replaceyour_table_name with the actual table name where you want to prevent the
operations.
2. Use theSIGNAL statement to specify a custom error message (MESSAGE_TEXT).
Next Steps:

I will now execute this query in MySQL and capture screenshots of the following:

1. The trigger creation process.

2. INSERT andUPDATE queries to confirm the functionality.


Testing the triggers with

INSERT:-

UPDATE:-
Experiment 11

Join Queries : Assume necessary database schema


• Display the name of each employee with his department name.
• Display a list of all departments with the employees in each department.
• Display all the departments with the manager for that department.
• Display the names of each employee with the name of his/her boss.
• Display the names of each employee with the name of his/her boss with a blank
for the boss of the president.

Assumed Schema:

1. Employees Table:
◦ ◦ eid: Employee ID (Primary Key)
◦ ◦ ename: Employee Name
did: Department ID (Foreign Key)
manager_id: Employee ID of the manager (Foreign Key referring to the same
table)

2. Departments Table:
◦ ◦ did: Department ID (Primary Key)
◦ dname: Department Name
manager_id: Manager ID (Foreign Key referencing Employees.eid)

Queries and Explanations:


1. Display the name of each employee with their department name:

CODE:

SELECT e.ename AS Employee_Name, d.dname AS Department_Name


FROM Employees e
JOIN Departments d ON e.did = d.did;

2. Display a list of all departments with the employees in each departmen:t

CODE:

SELECT d.dname AS Department_Name, e.ename AS Employee_Name


FROM Departments d
LEFT JOIN Employees e ON d.did = e.did
ORDER BY d.dname, e.ename;
3. Display all the departments with the manager for that department:

CODE:

SELECT d.dname AS Department_Name, e.ename AS Manager_Name


FROM Departments d
JOIN Employees e ON d.manager_id = e.eid;

4. Display the names of each employee with the name of his/her boss:

CODE:

SELECT e.ename AS Employee_Name, m.ename AS Boss_Name


FROM Employees e
LEFT JOIN Employees m ON e.manager_id = m.eid;

5. Display the names of each employee with the name of his/her boss, with a blank for the boss
of the president:
CODE:

SELECT e.ename AS Employee_Name,


COALESCE(m.ename, '') AS Boss_Name
FROM Employees e
LEFT JOIN Employees m ON e.manager_id = m.eid;
Steps:

1. Create the database and tables.

2. Insert sample data to reflect the relationships between employees, departments, and
managers.
3. Output
Task-----Create the following schema and answer the given
queries, create a document of your work with screenshot
and then submit (Query with result).
-- Step 1: Create Database
CREATE DATABASE LabAssessment;
USE LabAssessment;

Table Name:- Employee


Empid EmpName Department ContactNo EmailId EmpHeadId
101 Isha E-101 1234567890 [email protected] 105
102 Priya E-104 1234567890 [email protected] 103
103 Neha E-101 1234567890 [email protected] 101
104 Rahul E-102 1234567890 [email protected] 105
105 Abhishek E-101 1234567890 [email protected] 102

-- Employee Table
CREATE TABLE Employee (
EmpId INT PRIMARY KEY,
EmpName VARCHAR(50),
Department VARCHAR(10),
ContactNo VARCHAR(15),
EmailId VARCHAR(50),
EmpHeadId INT );

Table :- EmpDept
DeptId DeptName Dept_off DeptHead
E-101 HR Monday 105
E-102 Development Tuesday 101
E-103 Hous Keeping Saturday 103
E-104 Sales Sunday 104
E-105 Purchage Tuesday 104

CREATE TABLE EmpDept (


DeptId VARCHAR(10) PRIMARY KEY,
DeptName VARCHAR(50),
Dept_off VARCHAR(20),
DeptHead INT
);

Table :- EmpSalary
EmpId Salary IsPermanent
101 2000 Yes
102 10000 Yes
103 5000 No
104 1900 Yes
105 2300 Yes

CREATE TABLE EmpSalary (


EmpId INT PRIMARY KEY,
Salary INT,
IsPermanent VARCHAR(3)
);
Table :- Project
ProjectId Duration
p-1 23
p-2 15
p-3 45
p-4 2
p-5 30
CREATE TABLE Project (
ProjectId VARCHAR(10) PRIMARY KEY,
Duration INT
);
Table :- Country
cid cname
c-1 India
c-2 USA
c-3 China
c-4 Pakistan
c-5 Russia

CREATE TABLE Country (


cid VARCHAR(10) PRIMARY KEY,
cname VARCHAR(50)
);
Table :- ClientTable
ClientId ClientName cid
cl-1 ABC Group c-1
cl-2 PQR c-1
cl-3 XYZ c-2
cl-4 tech altum c-3
cl-5 mnp c-5

CREATE TABLE ClientTable (


ClientId VARCHAR(10) PRIMARY KEY,
ClientName VARCHAR(50),
cid VARCHAR(10),
FOREIGN KEY (cid) REFERENCES Country(cid)
);
Table :- EmpProject

EmpId ProjectId ClientID StartYear EndYear


101 p-1 Cl-1 2010 2010
102 p-2 Cl-2 2010 2012
103 p-1 Cl-3 2013
104 p-4 Cl-1 2014 2015
105 p-4 Cl-5 2015

CREATE TABLE EmpProject (


EmpId INT,
ProjectId VARCHAR(10),
ClientID VARCHAR(10),
StartYear INT,
EndYear INT,
FOREIGN KEY (EmpId) REFERENCES Employee(EmpId),
FOREIGN KEY (ProjectId) REFERENCES Project(ProjectId),
FOREIGN KEY (ClientID) REFERENCES ClientTable(ClientId)
);

Q-1 Find all the name of the employee whose name's 3rd
character is 'h'.
SELECT EmpName
FROM Employee
WHERE SUBSTRING(EmpName, 3, 1) = 'h';
Q-2 Find employee whose department off is Monday.
SELECT EmpName
FROM Employee
WHERE EmpHeadId IN (
SELECT DeptHead FROM EmpDept WHERE Dept_off =
'Monday'
);

Q-3 Find all details of all employee working in


development department.
SELECT Employee.*
FROM Employee
JOIN EmpDept
ON Employee.Department = EmpDept.DeptId
WHERE EmpDept.DeptName = 'Development';

Q-4 Select the name and email of the Dept Head who is
not Permanent.
SELECT EmpName, EmailId
FROM Employee
WHERE EmpId IN (
SELECT DeptHead FROM EmpDept
) AND EmpId IN (
SELECT EmpId
FROM EmpSalary
WHERE IsPermanent = 'No'
);
Q-6 How many project started and finished in the same
year.
SELECT COUNT(*) AS Projects_Same_Year
FROM EmpProject
WHERE StartYear = EndYear;

Q-7 Find the department name of the company which is


assigned to the employee whose employee id is grater
103.
SELECT DeptName
FROM EmpDept
WHERE DeptId IN (
SELECT Department
FROM Employee
WHERE EmpId > 103
);
Q-8 Select the name of the employee who is working
under Abhishek.
SELECT EmpName
FROM Employee
WHERE EmpHeadId = (
SELECT EmpId
FROM Employee
WHERE EmpName = 'Abhishek'
);

Q-9 List name of all employees whose name ends with a.


SELECT EmpName
FROM Employee
WHERE EmpName LIKE '%a';
Q-10 the details of the employee who work either for
department E-104 or E-102.
SELECT *
FROM Employee
WHERE Department IN ('E-104', 'E-102');

You might also like