0% found this document useful (0 votes)
3 views11 pages

DBMS

The document outlines various SQL commands and operations related to database management, including Data Definition Language (DDL) and Data Manipulation Language (DML) commands for different entities like Machines, Restaurants, Categories, and Employees. It also covers advanced topics such as referential integrity, subqueries, joins, functions, and procedures, as well as transaction control commands. The document serves as a comprehensive guide for managing and querying relational databases.

Uploaded by

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

DBMS

The document outlines various SQL commands and operations related to database management, including Data Definition Language (DDL) and Data Manipulation Language (DML) commands for different entities like Machines, Restaurants, Categories, and Employees. It also covers advanced topics such as referential integrity, subqueries, joins, functions, and procedures, as well as transaction control commands. The document serves as a comprehensive guide for managing and querying relational databases.

Uploaded by

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

#week1- DDL and DML commands

#Emily(Machines,Parts)
insert into Machines(MachineID,MachineName,PurchaseDate,MaintenanceDate)
values (1,'Lathe','2018-03-15',NULL), (2,'Drill','2019-05-20','2019-05-20'),
(3,'Milling','2020-07-01',NULL), (4,'CNC','2021-08-25','2024-02-10'),
(5,'Grinder','2022-01-10',NULL);
insert into Parts(PartID,PartName,MachineID,Quantity)
values (201,'Hydraulic Pump',1,15), (202,'Cooling Fan',2,5), (203,'Bearing',3,20), (204,'Drill
Bit',4,8), (205,'Tool Holder',5,12);
insert into MaintenanceLogs(LogID,MachineID,MaintenanceDate,Details)
values (301,1,'2024-01-15',"Routine maintenance performed."), (302,2,'2024-02-20',"Replaced
worn-out parts."), (303,3,'2024-03-01',"Calibrated machine."), (304,4,'2024-04-15',"Updated
software."),(305,5,'2024-05-20',"Checked all components.");
alter table Parts add PartPrice DECIMAL(10,2);
update Machines set MaintenanceDate=DATE_ADD(purchaseDate,INTERVAL 2 HOUR) where
(PurchaseDate < '2020-01-01' and MachineId not in (101,102) and MachineName != 'CNC');
delete from Parts where (Quantity < 10 and PartName != 'Hydraulic' or PartID in(201,202));
rename table MaintenanceLogs to MachineMaintenance;

#Alex(Restaurants and Orders)


insert into Restaurants values (1,'Pasta Paradise','New York','Italian'), (2,'Sushi
World','Tokyo','Japanese'), (3,'Taco Haven','Los Angeles','Mexican'), (4,'Curry
Corner','London','Indian'), (6,'Pasta Express','Chicago','Italian');
insert into Orders values (1,1,101,'2024-07-15',45), (2,2,102,'2024-06-20',55),
(5,5,105,'2024-06-30',25), (6,6,106,'2024-05-15',60), (8,901,108,'2024-07-01',20);
update Restaurants set Location ='Rome' where CuisineType='Italian';
delete from Orders where OrderDate < '2023-12-01';
delete from Orders where RestaurantID=901;

#Create a table named bookings


create table bookings (
id int primary key not null,
customer varchar(50) not null,
room_type varchar(50) not null,
check_in DATE not null,
check_out DATE not null);
desc bookings;

#Write a query to create a table named Employee


create table Employee(
JOB_ID varchar(10) not null,
JOB_TITLE varchar(35) not null,
MINSALARY decimal(6,0),
MAXSALARY decimal(6,0),
check (MAXSALARY<25000));
desc Employee;

#week2 - Referential Integrity


#Write a query to create a table named Employee
create table Employee(
JOB_ID varchar(10) not null,
JOB_TITLE varchar(35) not null,
MINSALARY decimal(6,0),
MAXSALARY decimal(6,0),
check (MAXSALARY<25000));
desc Employee;

#David(Categories, Medicines)
create table Categories( CategoryID int not null,
CategoryName varchar(100) not null,
constraint pk_categories primary key(CategoryID));
create table Medicines( MedicineID int not null,
MedicineName varchar(100) not null,
CategoryID int not null,
Stock int not null,
constraint pk_medicines primary key (MedicineID),
constraint fk_medicines_category foreign key(CategoryID) references Categories(CategoryID)
on delete cascade);
insert into Categories(CategoryID,CategoryName) values
(1,'Painkillers'),(2,'Antibiotics'),(3,'Vitamins'), (4,'Antiseptics'),(5,'Antifungals');
insert into Medicines (MedicineID,MedicineName,CategoryID,Stock) values
(101,'Paracetamol',1,50),(102,'Ibuprofen',1,30), (103,'Amoxicillin',2,40),(104,'Vitamin C',3,60),
(105,'Dettol',4,25);
delete from Categories where CategoryID=2;

#You are working with a database(Flights, Passengers, Bookings)


insert into Flights values (1001,'A101'),(1002,'A102'),(1003,'B103'),(1004,'C104'),(1005,'D105');
insert into Passengers (PassengerID,PassengerName,PassportNumber) values (1201,'John
Doe','P1234567'), (1202,'Jane Smith','P2345678'), (1203,'Alice Johnson','P3456789'),(1204,'Bob
Brown','P4567890'), (1205,'Charlie Davis','P5678901');
insert into Bookings values (2001,1001,1201,'2024-07-15'), (2002,1002,1202,'2024-07-20'),
(2003,1003,1203,'2024-08-01'), (2004,1004,1204,'2024-08-10'), (2005,1005,1205,'2024-08-20');
alter table Flights add SeatCapacity int; update Flights set SeatCapacity = 200 where FlightID
between 1001 and 1010;
delete from Bookings where (BookingDate < '2024-01-21' and (FlightID <> 1101 and FlightID
<>1102)) or (PassengerID =1201 or PassengerID =1202);
alter table Flights rename to AirlineFlights;
#Olivia(Teams, Players)
create table Teams( TeamID int not null,
TeamName varchar(100)not null,
CoachName varchar(100),
constraint pk_teams primary key(TeamID));
create table Players( PlayerID int not null,
TeamID int not null, PlayerName varchar(100)not null,
Position varchar(50), Age int, constraint pk_players primary key(PlayerID),
constraint fk_players_team foreign key(TeamID) references Teams(TeamID)
on delete CASCADE);
insert into Teams (TeamID,TeamName,CoachName)values (1,'Warriors','Coach John'),
(2,'Strikers','Coach Mike'), (3,'Titans','Coach Sarah'), (4,'Falcons','Coach Emma'),
(5,'Dragons','Coach Daniel');
insert into Players(PlayerID,TeamID,PlayerName,Position,Age) values (101,1,'Alice
Johnson','Forward',22), (102,2,'Bob Smith','Goalkeeper',25), (103,3,'Charlie
Brown','Midfielder',23), (104,4,'David Miller','Defender',24), (105,5,'Emma Watson','Striker',21);
delete from Teams where TeamID=2;

#week3 - WHERE Clause and Aggregates


#Dia (an analyst at an electronics retailer)
SELECT AVG(SALE_AMOUNT) as AVG_SALE_AMOUNT FROM SALES_TRANSACTIONS;
SELECT SUM(SALE_AMOUNT) AS TOTAL_SALES_AMOUNT FROM
SALES_TRANSACTIONS;

#Olivia (Players, Games)


select GAME_ID,COUNT(DISTINCT PLAYER_ID) AS number_of_players from
PLAYER_ACTIVITY GROUP BY GAME_ID;
SELECT GAME_ID,MIN(ACTIVITY_TIMESTAMP) AS earliest_activity from PLAYER_ACTIVITY
GROUP BY GAME_ID;
SELECT GAME_ID,MAX(UPDATE_TIMESTAMP) AS latest_update from GAME_UPDATES
GROUP BY GAME_ID;
SELECT GAME_ID,COUNT(*) AS total_activities FROM PLAYER_ACTIVITY GROUP BY
GAME_ID HAVING COUNT(*) >1;

#Olivia (Bookings, Customers)


SELECT DESTINATION,AVG(price) as avg_price from TRAVEL_PACKAGES GROUP BY
destination having avg_price > 1500;
select PACKAGE_ID,sum(number_of_tickets) as total_tickets from BOOKINGS group by
package_id having total_tickets > 5;
select CITY, max(age) as max_age from CUSTOMERS GROUP BY city;
select CUSTOMER_ID,AVG(number_of_tickets) as avg_tickets from BOOKINGS GROUP BY
customer_id having sum(number_of_tickets) > 3 order by customer_id;
#James (Bookings, Customer_Feedback)
select CUSTOMER_ID, avg(RATING) as AVG_RATING from CUSTOMER_FEEDBACK group
by CUSTOMER_ID;
select CUSTOMER_ID,COUNT(*) as TOTAL_BOOKINGS from CUSTOMER_FEEDBACK
GROUP BY CUSTOMER_ID;
select CUSTOMER_ID,MAX(RATING) as HIGHEST_RATING from CUSTOMER_FEEDBACK
group by CUSTOMER_ID;
select CUSTOMER_ID,SUM(NUMBER_OF_TICKETS) as TOTAL_TICKETS_BOOKED from
BOOKINGS group by CUSTOMER_ID;
SELECT CUSTOMER_ID,MIN(RATING) AS MIN_RATING FROM CUSTOMER_FEEDBACK
GROUP BY CUSTOMER_ID;

#week4 - Subqueries and Simple Joins


#Sophia is a business analyst working(Subscriptions, Viewing_logs)
select s.SUBSCRIPTION_ID, s.SUBSCRIBER_ID, v.VIEW_DATE from SUBSCRIPTIONS s join
VIEWING_LOGS v on s.SUBSCRIPTION_ID = v.SUBSCRIPTION_ID;
select s.SUBSCRIBER_ID, sum(v.VIEW_DURATION) as TOTAL_DURATION from
SUBSCRIPTIONS s join VIEWING_LOGS v on s.SUBSCRIPTION_ID = v.SUBSCRIPTION_ID
group by s.SUBSCRIBER_ID;
select v.VIEW_DATE from SUBSCRIPTIONS s join VIEWING_LOGS v on
s.SUBSCRIPTION_ID = v.SUBSCRIPTION_ID where s.TIER = 'Premium';

#Sophia, a data analyst (User_listening, Song_play_history)


SELECT usl.LISTENING_ID, usl.USER_ID, song.PLAY_COUNT FROM USER_LISTENING usl
JOIN SONG_PLAY_HISTORY song ON usl.SONG_ID = song.SONG_ID;
SELECT usl.SONG_ID, SUM(usl.DURATION) AS TOTAL_DURATION FROM
USER_LISTENING usl JOIN SONG_PLAY_HISTORY song ON usl.SONG_ID =
song.SONG_ID GROUP BY usl.SONG_ID;
SELECT usl.SONG_ID, SUM(song.PLAY_COUNT) AS TOTAL_PLAY_COUNT FROM
USER_LISTENING usl JOIN SONG_PLAY_HISTORY song ON usl.SONG_ID =
song.SONG_ID GROUP BY usl.SONG_ID;

#Alex is working on managing data(Restaurants, Orders)


select od.CustomerID from Orders od join Restaurants res on res.RestaurantID =
od.RestaurantID where res.CuisineType = 'Italian';
select res.RestaurantID from Restaurants res left join Orders od on res.RestaurantID =
od.RestaurantID where od.RestaurantID is NULL;
select res.RestaurantName from Orders od join Restaurants res on res.RestaurantID =
od.RestaurantID;

#Diego is working as an intern at a vacation rental company( Rentals, Bookings)


select Location from Rentals where RentalID in (select RentalID from Bookings);
select book.BookingID from Bookings book join Rentals rent on book.RentalID = rent.RentalID
where rent.Location = 'Beach';
select book.CustomerID from Bookings book join Rentals rent on book.RentalID = rent.RentalID
where rent.PricePerNight = 150;

#week5 - Advanced Joins


#Alex a data analyst at an electronics retailer (Products, Returns)
SELECT p.PRODUCT_ID, p.PRODUCT_NAME,
MAX(r.RETURN_AMOUNT) AS MAX_RETURN_AMOUNT,
r.RETURN_DATE FROM PRODUCTS p LEFT OUTER JOIN RETURNS r
ON p.PRODUCT_ID = r.PRODUCT_ID GROUP BY p.PRODUCT_ID,
p.PRODUCT_NAME, r.RETURN_DATE;
SELECT r.RETURN_ID, r.PRODUCT_ID, r.RETURN_AMOUNT, r.RETURN_DATE,
p.PRODUCT_NAME, p.CATEGORY FROM RETURNS r LEFT OUTER JOIN
PRODUCTS p ON r.PRODUCT_ID = p.PRODUCT_ID WHERE r.RETURN_AMOUNT >
(SELECT AVG(RETURN_AMOUNT) FROM RETURNS);
SELECT p.PRODUCT_ID, p.PRODUCT_NAME, r.RETURN_DATE FROM PRODUCTS
p LEFT OUTER JOIN RETURNS r ON p.PRODUCT_ID = r.PRODUCT_ID;

#Emma a data analyst at a social media (Users, Posts)


SELECT p.POST_ID,p.POST_CONTENT,p.POST_DATE,p.USER_ID,u.USERNAME
FROM POSTS p LEFT OUTER JOIN USERS u ON p.USER_ID = u.USER_ID WHERE
p.LIKES > 200 OR p.COMMENTS > 15;
SELECT u.USER_ID,u.USERNAME,p.POST_ID,p.POST_DATE FROM USERS u LEFT
OUTER JOIN POSTS p ON u.USER_ID = p.USER_ID ORDER BY CASE WHEN
p.POST_ID IS NULL THEN 0 ELSE 1 END, p.POST_ID;
SELECT p.POST_DATE,u.USER_ID,u.USERNAME,u.SIGNUP_DATE FROM POSTS p
LEFT OUTER JOIN USERS u ON p.USER_ID = u.USER_ID WHERE u.SIGNUP_DATE
< '2024-03-01';

#James a data analyst at a travel agency (Bookings, Customer_feedback)


select cf.FEEDBACK_ID,cf.FEEDBACK_DATE,b.BOOKING_ID,b.BOOKING_DATE
FROM CUSTOMER_FEEDBACK cf JOIN BOOKINGS b ON cf.CUSTOMER_ID =
b.CUSTOMER_ID AND cf.FEEDBACK_DATE = b.BOOKING_DATE;
SELECT f1.FEEDBACK_ID AS Feedback1_ID, f1.Rating AS
Feedback1_Rating,f2.FEEDBACK_ID AS Feedback2_ID,f2.Rating AS
Feedback2_Rating FROM CUSTOMER_FEEDBACK f1 JOIN
CUSTOMER_FEEDBACK f2 ON f1.Rating = f2.Rating AND f1.FEEDBACK_ID !=
f2.FEEDBACK_ID;
SELECT cf.FEEDBACK_ID,b.BOOKING_ID, cf.CUSTOMER_ID,cf.FEEDBACK_DATE
FROM CUSTOMER_FEEDBACK cf JOIN BOOKINGS b ON cf.CUSTOMER_ID =
b.CUSTOMER_ID AND cf.FEEDBACK_DATE = b.BOOKING_DATE;
SELECT
FEEDBACK_ID,BOOKING_ID,CUSTOMER_ID,FEEDBACK_DATE,PACKAGE_ID
FROM CUSTOMER_FEEDBACK JOIN BOOKINGS USING (CUSTOMER_ID);

#report the names of all the salespersons (Salesperson, Company)


SELECT s.name
FROM SalesPerson s
WHERE s.ID NOT IN (
SELECT DISTINCT o.sales_id
FROM Orders o
JOIN Company c ON o.com_id = c.com_id
WHERE c.NAME = 'RED'
);

#week6 - Functions and Procedures


#John oversees the employee database (employees)
DELIMITER //
create procedure update_salary_by_department(IN p_department_name
VARCHAR(50))
BEGIN
update employees set salary =
case
when p_department_name = 'HR' then salary * 1.10
when p_department_name = 'IT' then salary * 1.15
else salary
end
where department_name = p_department_name;
END //
DELIMITER ;

#Maria, who manages the stock of books in a library (books)


DELIMITER $$
CREATE FUNCTION get_available_copies(p_book_id INT)
RETURNS INT
DETERMINISTIC
BEGIN
DECLARE v_total_copies INT;
DECLARE v_borrowed_copies INT;
DECLARE v_available_copies INT;
SELECT total_copies INTO v_total_copies
FROM books
WHERE book_id = p_book_id;
SELECT IFNULL(SUM(borrowed_copies), 0) INTO v_borrowed_copies
FROM borrowed_books
WHERE book_id = p_book_id;
SET v_available_copies = v_total_copies - v_borrowed_copies;
RETURN v_available_copies;
END $$
DELIMITER ;

#John works in the HR department (employees)


DELIMITER //
CREATE FUNCTION calculate_annual_salary(emp_id INT) RETURNS
DECIMAL(10,2)
DETERMINISTIC
BEGIN
DECLARE monthly DECIMAL(10,2);
DECLARE emp_type VARCHAR(20);
DECLARE annual_salary DECIMAL(10,2);
SELECT monthly_salary, employment_type
INTO monthly, emp_type
FROM employees
WHERE employee_id = emp_id;
SET annual_salary = monthly * 12;
IF emp_type = 'Part-time' THEN
SET annual_salary = annual_salary * 0.5;
END IF;
RETURN annual_salary;
END //
DELIMITER ;

#Emma is responsible for managing the payroll system (employees)


CREATE PROCEDURE calculate_bonus(IN emp_id INT)
BEGIN
DECLARE emp_salary INT;
DECLARE emp_years INT;
DECLARE bonus INT;
DECLARE new_salary INT;
SELECT annual_salary, years_of_service INTO emp_salary, emp_years
FROM employees WHERE employee_id = emp_id;
IF emp_years < 5 THEN
SET bonus = 0;
ELSEIF emp_years BETWEEN 5 AND 10 THEN
SET bonus = emp_salary * 0.05;
ELSE
SET bonus = emp_salary * 0.10;
END IF;
SET new_salary = LEAST(emp_salary + bonus, 200000);
UPDATE employees
SET annual_salary = new_salary
WHERE employee_id = emp_id;
SELECT CONCAT('New annual salary for Employee ID ', emp_id, ': ', new_salary)
AS new_salary;
END $$
DELIMITER ;

#week7 - DCL and TCL Commands


#in a university's course registration system (student_enrollment)
savepoint alt;
update student_enrollment set enrollment_status='Dropped' where (student_id=1 and
course_id=102);
select * from student_enrollment;
rollback to alt;
update student_enrollment set enrollment_status='Enrolled' where (student_id=2 and
course_id=101);

#In a banking application (bank_accounts ,transaction_logs)


update bank_accounts set balance = balance - 100 where account_name =
'Account A';
insert into transaction_logs (account_id, transaction_type, amount) values
(1,'Debit',100.00);
rollback; start transaction;
update bank_accounts set balance = balance + 2000 where account_name =
'Account B';
insert into transaction_logs (account_id, transaction_type, amount)
values (1,'Credit',2000.00);
commit;
#In an Inventory Management System (product_inventory)
update product_inventory set quantity=60 where product_name='Product A';
update product_inventory set price=price*1.05 where product_name='Product A';
savepoint pri;
update product_inventory set quantity=90 where product_name='Product B';
update product_inventory set price=price*0.9 where product_name='Product B';
select * from product_inventory;
rollback to pri;
commit;

#week8 - Triggers
#Before update trigger (customer_account)
DELIMITER //
CREATE TRIGGER update_customer_balance
BEFORE UPDATE ON customer_account
FOR EACH ROW
BEGIN
INSERT INTO mini_statement (acc_no, avail_balance)
VALUES (OLD.acc_no, OLD.avail_balance);
END;
//
DELIMITER;
update customer_account set avail_balance = avail_balance + 2000 where
acc_no = 9001;
update customer_account set avail_balance = avail_balance + 3000 where acc_no =
9004;
update customer_account set avail_balance = avail_balance - 5000 where acc_no =
9001;
update customer_account set avail_balance = avail_balance - 1000 where acc_no =
9001;
select * from mini_statement;

#Create a trigger named employee_ranking_insert (emp_ranking, emp_special_bonus)


DELIMITER //
CREATE TRIGGER employee_ranking_insert
BEFORE INSERT ON emp_ranking
FOR EACH ROW
BEGIN
IF NEW.ranking = 1 THEN
INSERT INTO emp_special_bonus (emp_id, special_bonus)
VALUES (
NEW.emp_id,
CASE
WHEN NEW.emp_designation = 'Developer' THEN 12000
WHEN NEW.emp_designation = 'Technical Assistant' THEN 15000
WHEN NEW.emp_designation = 'Project Manager' THEN 16000
ELSE 0
END
);
END IF;
END;
//
DELIMITER ;
INSERT INTO emp_ranking VALUES (1,"Dave","Developer",1), (2,"Mary","Technical
Assistant",2), (3,"Daisy","Technical Assistant",1), (4,"Teresa","Project Manager",3),
(5,"Jose","Project Manager",1), (6,"Ben","Project Manager",2);
SELECT * FROM emp_special_bonus;

#Create a trigger named user_after_delete (log ,users)


DELIMITER //
CREATE TRIGGER user_after_delete AFTER DELETE ON users
FOR EACH ROW
BEGIN
INSERT INTO log (User_id, comment)
VALUES (OLD.User_id, 'Deleted Sucessfully');
END;
//
DELIMITER ;

#week9 - Views and Indexes


#A sales team at a global corporation (Salesman)
create view TOTAL_COMMISSION_PER_CITY as select CITY,sum(COMMISSION) as
TOTAL_COMMISSION from SALESMAN group by CITY;
create view SALES_MEN_WITH_HIGH_COMMISSION as select
SALESMAN_ID,NAME,CITY,COMMISSION from SALESMAN where
COMMISSION > 0.12;

#Michael is a data analyst working (Station)


create view LONGESTCITY as select CITY, LENGTH(CITY) as LENGTH from
STATION order by LENGTH desc, CITY limit 1;
create view SHORTESTCITY as select CITY, LENGTH(CITY) as LENGTH from
STATION order by LENGTH asc, CITY limit 1;

#Sophia is a business analyst working (OrderDetails)


create view PURCHASE_AMOUNT_VIEW as select
ORDER_NUMBER,sum(QUANTITY_ORDERED * PRICE_EACH) as TOTAL_AMOUNT
from ORDERDETAILS group by ORDER_NUMBER;
create view ORDER_SUMMARY_VIEW as select ORDER_NUMBER,count(*) as
PRODUCT_COUNT, sum(QUANTITY_ORDERED * PRICE_EACH) as
TOTAL_AMOUNT from ORDERDETAILS group by ORDER_NUMBER;

#Sarah is a data analyst working for a global company (Customer)


create view GRADECOUNT as select GRADE,count(*) as GRADE_COUNT from
CUSTOMER group by GRADE;
create view CUSTOMER_SUMMARY as select count(*) as
TOTAL_CUSTOMERS,avg(GRADE) as AVERAGE_GRADE from CUSTOMER;

#Week10- XML
1. Free Formatter
2. Liquid Technologies - XSD Formatter
<bank>
<account>
<account_holder_name>xxxx</account_holder_name>
<account_number>123456789012</account_number>
<account_balance>10000</account_balance>
<contact>9441234578</contact>
</account>
</bank>

You might also like