0% found this document useful (0 votes)
16 views91 pages

Answer

The document outlines various database designs for different systems including a Movie Ticket Reservation System, Voting System, Real-Time Sports Scoring System, Travel Booking System, Online Learning System, Library System, Job Portal, Real-Time Sales Analytics, Restaurant Reservation System, and Healthcare System. Each system includes tables for managing relevant entities, SQL code for creating these tables, and additional features such as triggers and stored procedures for specific functionalities. The designs aim to facilitate efficient data management and operations within each respective domain.

Uploaded by

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

Answer

The document outlines various database designs for different systems including a Movie Ticket Reservation System, Voting System, Real-Time Sports Scoring System, Travel Booking System, Online Learning System, Library System, Job Portal, Real-Time Sales Analytics, Restaurant Reservation System, and Healthcare System. Each system includes tables for managing relevant entities, SQL code for creating these tables, and additional features such as triggers and stored procedures for specific functionalities. The designs aim to facilitate efficient data management and operations within each respective domain.

Uploaded by

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

1.

Movie Ticket Reservation System Database


Tables:
 Users (for customer profiles)
 Movies
 Theatres
 Showtimes
 Bookings
 Reviews
SQL Code:
SQL
Copyedit
-- Create Users Table
CREATE TABLE Users (
user_id INT PRIMARY KEY AUTO_INCREMENT,
username VARCHAR(100) UNIQUE,
email VARCHAR(100),
password VARCHAR(100),
phone_number VARCHAR(15)
);

-- Create Movies Table


CREATE TABLE Movies (
movie_id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
genre VARCHAR(50),
duration INT, -- Duration in minutes
rating DECIMAL(3, 1)
);

-- Create Theaters Table


CREATE TABLE Theaters (
theater_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(200),
location VARCHAR(200)
);

-- Create Showtimes Table


CREATE TABLE Showtimes (
showtime_id INT PRIMARY KEY AUTO_INCREMENT,
movie_id INT,
theater_id INT,
showtime DATETIME,
FOREIGN KEY (movie_id) REFERENCES
Movies(movie_id),
FOREIGN KEY (theater_id) REFERENCES
Theaters(theater_id)
);

-- Create Bookings Table


CREATE TABLE Bookings (
booking_id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
showtime_id INT,
seats_booked INT,
booking_date DATE,
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (showtime_id) REFERENCES
Showtimes(showtime_id)
);

-- Create Reviews Table


CREATE TABLE Reviews (
review_id INT PRIMARY KEY AUTO_INCREMENT,
user_id INT,
movie_id INT,
rating INT,
review_text TEXT,
review_date DATE,
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (movie_id) REFERENCES
Movies(movie_id)
);
Most Booked Movie Query:
sql
CopyEdit
SELECT m.title, COUNT(b.booking_id) AS
bookings_count
FROM Movies m
JOIN Showtimes s ON m.movie_id = s.movie_id
JOIN Bookings b ON s.showtime_id = b.showtime_id
WHERE b.booking_date > CURDATE() - INTERVAL 1
MONTH
GROUP BY m.movie_id
ORDER BY bookings_count DESC
LIMIT 1;
Stored Procedure for Reminders:
sql
CopyEdit
DELIMITER //

CREATE PROCEDURE send_reminder_for_booking()


BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE booking_id INT;
DECLARE user_id INT;
DECLARE showtime_id INT;
DECLARE cur CURSOR FOR
SELECT b.booking_id, b.user_id, b.showtime_id
FROM Bookings b
WHERE b.booking_date = CURDATE() - INTERVAL 1
DAY;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET
done = TRUE;

OPEN cur;

read_loop: LOOP
FETCH cur INTO booking_id, user_id, showtime_id;
IF done THEN
LEAVE read_loop;
END IF;

-- Send email or reminder logic goes here


-- E.g., SEND EMAIL to user with booking_id,
showtime_id

END LOOP;

CLOSE cur;
END //

DELIMITER ;

2. Voting System Database


Tables:
 Students
 Candidates
 Elections
 Votes
SQL Code:
sql
CopyEdit
-- Create Students Table
CREATE TABLE Students (
student_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
dob DATE
);

-- Create Candidates Table


CREATE TABLE Candidates (
candidate_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
party VARCHAR(100)
);

-- Create Elections Table


CREATE TABLE Elections (
election_id INT PRIMARY KEY AUTO_INCREMENT,
election_name VARCHAR(100),
start_date DATE,
end_date DATE
);

-- Create Votes Table


CREATE TABLE Votes (
vote_id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT,
candidate_id INT,
election_id INT,
vote_date DATE,
FOREIGN KEY (student_id) REFERENCES
Students(student_id),
FOREIGN KEY (candidate_id) REFERENCES
Candidates(candidate_id),
FOREIGN KEY (election_id) REFERENCES
Elections(election_id)
);
Trigger to Ensure One Vote Per Student:
sql
CopyEdit
CREATE TRIGGER check_student_vote
BEFORE INSERT ON Votes
FOR EACH ROW
BEGIN
DECLARE student_vote_count INT;
-- Check if student has already voted
SELECT COUNT(*) INTO student_vote_count
FROM Votes
WHERE student_id = NEW.student_id AND election_id
= NEW.election_id;

IF student_vote_count > 0 THEN


SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT =
'Student has already voted in this election';
END IF;
END;

3. Real-Time Sports Scoring System Database


Tables:
 Teams
 Players
 Matches
 Scores
 Statistics
SQL Code:
sql
CopyEdit
-- Create Teams Table
CREATE TABLE Teams (
team_id INT PRIMARY KEY AUTO_INCREMENT,
team_name VARCHAR(100)
);

-- Create Players Table


CREATE TABLE Players (
player_id INT PRIMARY KEY AUTO_INCREMENT,
player_name VARCHAR(100),
team_id INT,
FOREIGN KEY (team_id) REFERENCES
Teams(team_id)
);

-- Create Matches Table


CREATE TABLE Matches (
match_id INT PRIMARY KEY AUTO_INCREMENT,
team1_id INT,
team2_id INT,
match_date DATETIME,
FOREIGN KEY (team1_id) REFERENCES
Teams(team_id),
FOREIGN KEY (team2_id) REFERENCES
Teams(team_id)
);

-- Create Scores Table


CREATE TABLE Scores (
score_id INT PRIMARY KEY AUTO_INCREMENT,
match_id INT,
team_id INT,
points INT,
FOREIGN KEY (match_id) REFERENCES
Matches(match_id),
FOREIGN KEY (team_id) REFERENCES
Teams(team_id)
);

-- Create Player Statistics Table


CREATE TABLE Player_Statistics (
stat_id INT PRIMARY KEY AUTO_INCREMENT,
player_id INT,
match_id INT,
goals INT,
assists INT,
FOREIGN KEY (player_id) REFERENCES
Players(player_id),
FOREIGN KEY (match_id) REFERENCES
Matches(match_id)
);

4. Travel Booking System Database


Tables:
 Customers
 Flights
 Hotels
 Car Rentals
 Reservations
 Payments
SQL Code:
sql
CopyEdit
-- Create Customers Table
CREATE TABLE Customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15)
);

-- Create Flights Table


CREATE TABLE Flights (
flight_id INT PRIMARY KEY AUTO_INCREMENT,
flight_number VARCHAR(100),
departure_city VARCHAR(100),
arrival_city VARCHAR(100),
departure_time DATETIME,
arrival_time DATETIME
);
-- Create Hotels Table
CREATE TABLE Hotels (
hotel_id INT PRIMARY KEY AUTO_INCREMENT,
hotel_name VARCHAR(100),
location VARCHAR(100)
);

-- Create Car Rentals Table


CREATE TABLE Car_Rentals (
car_id INT PRIMARY KEY AUTO_INCREMENT,
car_model VARCHAR(100),
car_type VARCHAR(50),
rental_rate DECIMAL(10, 2)
);

-- Create Reservations Table


CREATE TABLE Reservations (
reservation_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
flight_id INT,
hotel_id INT,
car_id INT,
reservation_date DATE,
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id),
FOREIGN KEY (flight_id) REFERENCES
Flights(flight_id),
FOREIGN KEY (hotel_id) REFERENCES
Hotels(hotel_id),
FOREIGN KEY (car_id) REFERENCES
Car_Rentals(car_id)
);

-- Create Payments Table


CREATE TABLE Payments (
payment_id INT PRIMARY KEY AUTO_INCREMENT,
reservation_id INT,
amount DECIMAL(10, 2),
payment_date DATE,
FOREIGN KEY (reservation_id) REFERENCES
Reservations(reservation_id)
);

5. Online Learning System Database


Tables:
 Students
 Courses
 Instructors
 Enrollments
 Assignments
SQL Code:
sql
CopyEdit
-- Create Students Table
CREATE TABLE Students (
student_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);

-- Create Courses Table


CREATE TABLE Courses (
course_id INT PRIMARY KEY AUTO_INCREMENT,
course_name VARCHAR(100),
course_description TEXT
);

-- Create Instructors Table


CREATE TABLE Instructors (
instructor_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100)
);
-- Create Enrollments Table
CREATE TABLE Enrollments (
enrollment_id INT PRIMARY KEY AUTO_INCREMENT,
student_id INT,
course_id INT,
enrollment_date DATE,
FOREIGN KEY (student_id) REFERENCES
Students(student_id),
FOREIGN KEY (course_id) REFERENCES
Courses(course_id)
);

-- Create Assignments Table


CREATE TABLE Assignments (
assignment_id INT PRIMARY KEY AUTO_INCREMENT,
course_id INT,
assignment_title VARCHAR(200),
due_date DATE,
FOREIGN KEY (course_id) REFERENCES
Courses(course_id)
);
Apologies for the earlier confusion! Below are the SQL
database designs and queries for questions 6-10 from
scratch.

6. Library System with Book Reservation


Tables:
 Books
 Members
 Reservations
 Borrow Transactions
 Fines
SQL Code:
-- Create Books Table
CREATE TABLE Books (
book_id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
author VARCHAR(100),
isbn VARCHAR(50) UNIQUE,
available_copies INT
);

-- Create Members Table


CREATE TABLE Members (
member_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
phone_number VARCHAR(15),
membership_date DATE
);
-- Create Reservations Table
CREATE TABLE Reservations (
reservation_id INT PRIMARY KEY AUTO_INCREMENT,
member_id INT,
book_id INT,
reservation_date DATE,
status ENUM('Reserved', 'Canceled', 'Picked up'),
FOREIGN KEY (member_id) REFERENCES
Members(member_id),
FOREIGN KEY (book_id) REFERENCES Books(book_id)
);

-- Create Borrow Transactions Table


CREATE TABLE Borrow_Transactions (
borrow_id INT PRIMARY KEY AUTO_INCREMENT,
member_id INT,
book_id INT,
borrow_date DATE,
due_date DATE,
return_date DATE,
FOREIGN KEY (member_id) REFERENCES
Members(member_id),
FOREIGN KEY (book_id) REFERENCES Books(book_id)
);
-- Create Fines Table
CREATE TABLE Fines (
fine_id INT PRIMARY KEY AUTO_INCREMENT,
member_id INT,
fine_amount DECIMAL(10, 2),
fine_date DATE,
FOREIGN KEY (member_id) REFERENCES
Members(member_id)
);
Trigger for Automatic Fine Application:
CREATE TRIGGER apply_fine
AFTER UPDATE ON Borrow_Transactions
FOR EACH ROW
BEGIN
DECLARE overdue INT;
DECLARE fine DECIMAL(10,2);
SET overdue = DATEDIFF(CURRENT_DATE,
NEW.due_date);

IF overdue > 0 THEN


SET fine = overdue * 2; -- $2 fine for each overdue
day
INSERT INTO Fines (member_id, fine_amount,
fine_date)
VALUES (NEW.member_id, fine, CURRENT_DATE);
END IF;
END;
Query to List Overdue Books and Calculate Fines:
SELECT bt.member_id, b.title,
DATEDIFF(CURRENT_DATE, bt.due_date) AS
overdue_days,
DATEDIFF(CURRENT_DATE, bt.due_date) * 2 AS fine
FROM Borrow_Transactions bt
JOIN Books b ON bt.book_id = b.book_id
WHERE bt.return_date IS NULL AND
DATEDIFF(CURRENT_DATE, bt.due_date) > 0;

7. Job Portal Database


Tables:
 Employers
 Job Postings
 Applicants
 Applications
 Interview Schedules
SQL Code:
-- Create Employers Table
CREATE TABLE Employers (
employer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
company_name VARCHAR(100)
);
-- Create Job Postings Table
CREATE TABLE Job_Postings (
job_id INT PRIMARY KEY AUTO_INCREMENT,
employer_id INT,
job_title VARCHAR(100),
location VARCHAR(100),
salary DECIMAL(10, 2),
job_description TEXT,
FOREIGN KEY (employer_id) REFERENCES
Employers(employer_id)
);

-- Create Applicants Table


CREATE TABLE Applicants (
applicant_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15)
);

-- Create Applications Table


CREATE TABLE Applications (
application_id INT PRIMARY KEY AUTO_INCREMENT,
applicant_id INT,
job_id INT,
application_status ENUM('Applied', 'Interview
Scheduled', 'Hired', 'Rejected'),
application_date DATE,
FOREIGN KEY (applicant_id) REFERENCES
Applicants(applicant_id),
FOREIGN KEY (job_id) REFERENCES
Job_Postings(job_id)
);

-- Create Interview Schedules Table


CREATE TABLE Interview_Schedules (
interview_id INT PRIMARY KEY AUTO_INCREMENT,
application_id INT,
interview_date DATETIME,
interview_location VARCHAR(200),
FOREIGN KEY (application_id) REFERENCES
Applications(application_id)
);
Stored Procedure for Auto-updating Application
Status:
DELIMITER //

CREATE PROCEDURE update_application_status(


IN application_id INT,
IN new_status ENUM('Applied', 'Interview Scheduled',
'Hired', 'Rejected')
)
BEGIN
UPDATE Applications
SET application_status = new_status
WHERE application_id = application_id;
END //

DELIMITER ;

8. Real-Time Sales Analytics Database


Tables:
 Sales
 Products
 Customers
 Stores
SQL Code:
-- Create Products Table
CREATE TABLE Products (
product_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
category VARCHAR(50),
price DECIMAL(10, 2)
);
-- Create Customers Table
CREATE TABLE Customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15)
);

-- Create Stores Table


CREATE TABLE Stores (
store_id INT PRIMARY KEY AUTO_INCREMENT,
location VARCHAR(100),
manager_name VARCHAR(100)
);

-- Create Sales Table


CREATE TABLE Sales (
sale_id INT PRIMARY KEY AUTO_INCREMENT,
product_id INT,
customer_id INT,
store_id INT,
quantity INT,
total_price DECIMAL(10, 2),
sale_date DATETIME,
FOREIGN KEY (product_id) REFERENCES
Products(product_id),
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id),
FOREIGN KEY (store_id) REFERENCES Stores(store_id)
);
Trigger to Update Sales Dashboard:
CREATE TRIGGER update_sales_dashboard
AFTER INSERT ON Sales
FOR EACH ROW
BEGIN
-- Update dashboard or sales statistics in another
table (if required)
UPDATE Sales_Dashboard SET total_sales =
total_sales + NEW.total_price WHERE store_id =
NEW.store_id;
END;

9. Restaurant Reservation System


Tables:
 Reservations
 Customers
 Menu Items
 Orders
 Payment Transactions
SQL Code:
-- Create Reservations Table
CREATE TABLE Reservations (
reservation_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
reservation_time DATETIME,
table_number INT,
reservation_status ENUM('Confirmed', 'Cancelled',
'Completed'),
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id)
);

-- Create Customers Table


CREATE TABLE Customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
phone VARCHAR(15),
email VARCHAR(100)
);

-- Create Menu Items Table


CREATE TABLE Menu_Items (
item_id INT PRIMARY KEY AUTO_INCREMENT,
item_name VARCHAR(100),
price DECIMAL(10, 2),
category VARCHAR(50)
);

-- Create Orders Table


CREATE TABLE Orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
reservation_id INT,
item_id INT,
quantity INT,
total_price DECIMAL(10, 2),
FOREIGN KEY (reservation_id) REFERENCES
Reservations(reservation_id),
FOREIGN KEY (item_id) REFERENCES
Menu_Items(item_id)
);

-- Create Payment Transactions Table


CREATE TABLE Payments (
payment_id INT PRIMARY KEY AUTO_INCREMENT,
reservation_id INT,
payment_amount DECIMAL(10, 2),
payment_date DATE,
FOREIGN KEY (reservation_id) REFERENCES
Reservations(reservation_id)
);
Query to Calculate Revenue by Table:
SELECT table_number, SUM(oi.total_price) AS revenue
FROM Reservations r
JOIN Orders oi ON r.reservation_id = oi.reservation_id
GROUP BY table_number;

10. Healthcare System Database


Tables:
 Patients
 Doctors
 Prescriptions
 Appointments
 Medical History
SQL Code:
-- Create Patients Table
CREATE TABLE Patients (
patient_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
dob DATE,
email VARCHAR(100),
phone VARCHAR(15)
);

-- Create Doctors Table


CREATE TABLE Doctors (
doctor_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
specialty VARCHAR(100),
email VARCHAR(100)
);

-- Create Appointments Table


CREATE TABLE Appointments (
appointment_id INT PRIMARY KEY AUTO_INCREMENT,
patient_id INT,
doctor_id INT,
appointment_date DATETIME,
appointment_status ENUM('Scheduled', 'Completed',
'Cancelled'),
FOREIGN KEY (patient_id) REFERENCES
Patients(patient_id),
FOREIGN KEY (doctor_id) REFERENCES
Doctors(doctor_id)
);

-- Create Prescriptions Table


CREATE TABLE Prescriptions (
prescription_id INT PRIMARY KEY AUTO_INCREMENT,
appointment_id INT,
medicine_name VARCHAR(100),
dosage VARCHAR(50),
FOREIGN KEY (appointment_id) REFERENCES
Appointments(appointment_id)
);

-- Create Medical History Table


CREATE TABLE Medical_History (
history_id INT PRIMARY KEY AUTO_INCREMENT,
patient_id INT,
disease_name VARCHAR(100),
diagnosis_date DATE,
treatment VARCHAR(100),
FOREIGN KEY (patient_id) REFERENCES
Patients(patient_id)
);

These are the SQL database designs, including tables,


relationships, triggers, stored procedures, and
concurrency handling mechanisms, for questions 6 to
10. Let me know if you need more details or
adjustments!

Here’s the SQL code and explanations for questions 11


to 15 from scratch:
11. Database for a Library with Book Reservation
System
Tables:
 Books
 Members
 Reservations
 Borrow Transactions
 Fines
SQL Code:
-- Create Books Table
CREATE TABLE Books (
book_id INT PRIMARY KEY AUTO_INCREMENT,
title VARCHAR(200),
author VARCHAR(100),
isbn VARCHAR(50) UNIQUE,
available_copies INT
);

-- Create Members Table


CREATE TABLE Members (
member_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
phone_number VARCHAR(15),
membership_date DATE
);

-- Create Reservations Table


CREATE TABLE Reservations (
reservation_id INT PRIMARY KEY AUTO_INCREMENT,
member_id INT,
book_id INT,
reservation_date DATE,
status ENUM('Reserved', 'Canceled', 'Picked up'),
FOREIGN KEY (member_id) REFERENCES
Members(member_id),
FOREIGN KEY (book_id) REFERENCES Books(book_id)
);

-- Create Borrow Transactions Table


CREATE TABLE Borrow_Transactions (
borrow_id INT PRIMARY KEY AUTO_INCREMENT,
member_id INT,
book_id INT,
borrow_date DATE,
due_date DATE,
return_date DATE,
FOREIGN KEY (member_id) REFERENCES
Members(member_id),
FOREIGN KEY (book_id) REFERENCES Books(book_id)
);

-- Create Fines Table


CREATE TABLE Fines (
fine_id INT PRIMARY KEY AUTO_INCREMENT,
member_id INT,
fine_amount DECIMAL(10, 2),
fine_date DATE,
FOREIGN KEY (member_id) REFERENCES
Members(member_id)
);
Trigger for Automatic Fine Application:
CREATE TRIGGER apply_fine
AFTER UPDATE ON Borrow_Transactions
FOR EACH ROW
BEGIN
DECLARE overdue INT;
DECLARE fine DECIMAL(10,2);
SET overdue = DATEDIFF(CURRENT_DATE,
NEW.due_date);

IF overdue > 0 THEN


SET fine = overdue * 2; -- $2 fine for each overdue
day
INSERT INTO Fines (member_id, fine_amount,
fine_date)
VALUES (NEW.member_id, fine, CURRENT_DATE);
END IF;
END;
Query to List Overdue Books and Calculate Fines:
SELECT bt.member_id, b.title,
DATEDIFF(CURRENT_DATE, bt.due_date) AS
overdue_days,
DATEDIFF(CURRENT_DATE, bt.due_date) * 2 AS fine
FROM Borrow_Transactions bt
JOIN Books b ON bt.book_id = b.book_id
WHERE bt.return_date IS NULL AND
DATEDIFF(CURRENT_DATE, bt.due_date) > 0;
Stored Procedure for Book Reservation:
DELIMITER //

CREATE PROCEDURE process_reservation(


IN member_id INT,
IN book_id INT
)
BEGIN
DECLARE available INT;

-- Check if the book is available


SELECT available_copies INTO available FROM Books
WHERE book_id = book_id;
IF available > 0 THEN
-- Create a reservation record
INSERT INTO Reservations (member_id, book_id,
reservation_date, status)
VALUES (member_id, book_id, CURRENT_DATE,
'Reserved');

-- Decrease available copies


UPDATE Books SET available_copies =
available_copies - 1 WHERE book_id = book_id;
ELSE
SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT =
'Book not available for reservation';
END IF;
END //

DELIMITER ;
Handling Concurrent Reservations:
For concurrency, we can lock the book record for
updates to prevent multiple reservations at the same
time:
START TRANSACTION;

-- Lock the book row for update


SELECT available_copies FROM Books WHERE book_id
= book_id FOR UPDATE;
-- Proceed with reservation logic after lock

COMMIT;

12. Design a Job Portal Database


Tables:
 Employers
 Job Postings
 Applicants
 Applications
 Interview Schedules
SQL Code:
-- Create Employers Table
CREATE TABLE Employers (
employer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
company_name VARCHAR(100)
);

-- Create Job Postings Table


CREATE TABLE Job_Postings (
job_id INT PRIMARY KEY AUTO_INCREMENT,
employer_id INT,
job_title VARCHAR(100),
location VARCHAR(100),
salary DECIMAL(10, 2),
job_description TEXT,
FOREIGN KEY (employer_id) REFERENCES
Employers(employer_id)
);

-- Create Applicants Table


CREATE TABLE Applicants (
applicant_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15)
);

-- Create Applications Table


CREATE TABLE Applications (
application_id INT PRIMARY KEY AUTO_INCREMENT,
applicant_id INT,
job_id INT,
application_status ENUM('Applied', 'Interview
Scheduled', 'Hired', 'Rejected'),
application_date DATE,
FOREIGN KEY (applicant_id) REFERENCES
Applicants(applicant_id),
FOREIGN KEY (job_id) REFERENCES
Job_Postings(job_id)
);

-- Create Interview Schedules Table


CREATE TABLE Interview_Schedules (
interview_id INT PRIMARY KEY AUTO_INCREMENT,
application_id INT,
interview_date DATETIME,
interview_location VARCHAR(200),
FOREIGN KEY (application_id) REFERENCES
Applications(application_id)
);
Stored Procedure for Updating Application
Status:
DELIMITER //

CREATE PROCEDURE update_application_status(


IN application_id INT,
IN new_status ENUM('Applied', 'Interview Scheduled',
'Hired', 'Rejected')
)
BEGIN
UPDATE Applications
SET application_status = new_status
WHERE application_id = application_id;
END //

DELIMITER ;

13. Real-Time Data Analytics for Sales


Transactions
Tables:
 Sales
 Products
 Customers
 Stores
SQL Code:
-- Create Products Table
CREATE TABLE Products (
product_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
category VARCHAR(50),
price DECIMAL(10, 2)
);

-- Create Customers Table


CREATE TABLE Customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
email VARCHAR(100),
phone VARCHAR(15)
);

-- Create Stores Table


CREATE TABLE Stores (
store_id INT PRIMARY KEY AUTO_INCREMENT,
location VARCHAR(100),
manager_name VARCHAR(100)
);

-- Create Sales Table


CREATE TABLE Sales (
sale_id INT PRIMARY KEY AUTO_INCREMENT,
product_id INT,
customer_id INT,
store_id INT,
quantity INT,
total_price DECIMAL(10, 2),
sale_date DATETIME,
FOREIGN KEY (product_id) REFERENCES
Products(product_id),
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id),
FOREIGN KEY (store_id) REFERENCES Stores(store_id)
);
Trigger to Update Sales Dashboard:
CREATE TRIGGER update_sales_dashboard
AFTER INSERT ON Sales
FOR EACH ROW
BEGIN
-- Update dashboard or sales statistics in another
table (if required)
UPDATE Sales_Dashboard SET total_sales =
total_sales + NEW.total_price WHERE store_id =
NEW.store_id;
END;

14. Restaurant Reservation System


Tables:
 Reservations
 Customers
 Menu Items
 Orders
 Payments
SQL Code:
-- Create Reservations Table
CREATE TABLE Reservations (
reservation_id INT PRIMARY KEY AUTO_INCREMENT,
customer_id INT,
reservation_time DATETIME,
table_number INT,
reservation_status ENUM('Confirmed', 'Cancelled',
'Completed'),
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id)
);

-- Create Customers Table


CREATE TABLE Customers (
customer_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
phone VARCHAR(15),
email VARCHAR(100)
);

-- Create Menu Items Table


CREATE TABLE Menu_Items (
item_id INT PRIMARY KEY AUTO_INCREMENT,
item_name VARCHAR(100),
price DECIMAL(10, 2),
category VARCHAR(50)
);

-- Create Orders Table


CREATE TABLE Orders (
order_id INT PRIMARY KEY AUTO_INCREMENT,
reservation_id INT,
item_id INT,
quantity INT,
total_price DECIMAL(10, 2),
FOREIGN KEY (reservation_id) REFERENCES
Reservations(reservation_id),
FOREIGN KEY (item_id) REFERENCES
Menu_Items(item_id)
);

-- Create Payments Table


CREATE TABLE Payments (
payment_id INT PRIMARY KEY AUTO_INCREMENT,
reservation_id INT,
payment_amount DECIMAL(10, 2),
payment_date DATE,
FOREIGN KEY (reservation_id) REFERENCES
Reservations(reservation_id)
);
Query to Calculate Revenue by Table:
SELECT table_number, SUM(oi.total_price) AS revenue
FROM Reservations r
JOIN Orders oi ON r.reservation_id = oi.reservation_id
GROUP BY table_number;

15. Healthcare System Database


Tables:
 Patients
 Doctors
 Prescriptions
 Appointments
 Medical History
SQL Code:
-- Create Patients Table
CREATE TABLE Patients (
patient_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
dob DATE,
email VARCHAR(100),
phone VARCHAR(15)
);

-- Create Doctors Table


CREATE TABLE Doctors (
doctor_id INT PRIMARY KEY AUTO_INCREMENT,
name VARCHAR(100),
specialty VARCHAR(100),
email VARCHAR(100)
);

-- Create Appointments Table


CREATE TABLE Appointments (
appointment_id INT PRIMARY KEY AUTO_INCREMENT,
patient_id INT,
doctor_id INT,
appointment_date DATETIME,
appointment_status ENUM('Scheduled', 'Completed',
'Cancelled'),
FOREIGN KEY (patient_id) REFERENCES
Patients(patient_id),
FOREIGN KEY (doctor_id) REFERENCES
Doctors(doctor_id)
);

-- Create Prescriptions Table


CREATE TABLE Prescriptions (
prescription_id INT PRIMARY KEY AUTO_INCREMENT,
appointment_id INT,
medicine_name VARCHAR(100),
dosage VARCHAR(50),
FOREIGN KEY (appointment_id) REFERENCES
Appointments(appointment_id)
);

-- Create Medical History Table


CREATE TABLE Medical_History (
history_id INT PRIMARY KEY AUTO_INCREMENT,
patient_id INT,
disease_name VARCHAR(100),
diagnosis_date DATE,
treatment VARCHAR(100),
FOREIGN KEY (patient_id) REFERENCES
Patients(patient_id)
);
4. Implement a Trigger to Automatically Update a
Patient's Medical History Every Time a New
Prescription is Issued
To ensure that a patient's medical history is
automatically updated when a new prescription is
issued, we can create a trigger that inserts an entry
into the Medical_History table whenever a new record is
added to the Prescriptions table.
Here's the SQL code to implement this trigger:
SQL Code for Trigger:
CREATE TRIGGER update_medical_history
AFTER INSERT ON Prescriptions
FOR EACH ROW
BEGIN
-- Insert into Medical History for the given patient
INSERT INTO Medical_History (patient_id,
disease_name, diagnosis_date, treatment)
VALUES (NEW.patient_id, 'Prescription for ' ||
NEW.medicine_name, CURRENT_DATE, 'Medication: ' ||
NEW.medicine_name);
END;
Explanation:
1. Trigger Name: update_medical_history is created
to trigger after an insert operation on the
Prescriptions table.
2. Trigger Event: This trigger fires after a new record
is inserted into the Prescriptions table, so it
updates the medical history of the patient
associated with that prescription.
3. New Record Handling: The trigger inserts a new
entry into the Medical_History table with the
patient_id taken from the inserted prescription. The
disease_name field can be assumed to be a
placeholder text ('Prescription for
[medicine_name]'), which can be customized
based on your actual application logic. The
diagnosis_date is the current date when the
prescription is issued, and the treatment field holds
the medication prescribed.
This ensures that the patient's medical history is always
kept up to date with the latest prescriptions.

5. Security: Ensuring the Privacy and Security of


Sensitive Health Data in the Database
When dealing with sensitive health data, such as
patient information, prescriptions, and medical history,
ensuring security and privacy is paramount. Here are
several key strategies to achieve this:
1. Data Encryption
 Encryption at Rest: Store sensitive data, such as
patient records, prescriptions, and medical history,
in an encrypted format in the database. This
ensures that even if an attacker gains access to
the storage media, they cannot read the data
without the encryption key.
o Example: Use encryption algorithms like AES
(Advanced Encryption Standard) to encrypt
sensitive fields (e.g., patient_id,
disease_name, treatment).
 Encryption in Transit: Ensure that all data
transmitted between the database and the
application is encrypted using secure protocols like
TLS (Transport Layer Security). This prevents
eavesdropping and data tampering during
communication.
2. Access Control and Authentication
 Role-based Access Control (RBAC): Implement
role-based access to restrict access to sensitive
data based on the user's role. For example, doctors
and healthcare professionals might have read and
write access to patient records, while
administrators can manage system configurations
but may not need access to detailed medical data.
o Example: Use the GRANT command to assign
permissions to different roles in the system
(e.g., SELECT, INSERT, UPDATE, DELETE).
 Multi-factor Authentication (MFA): Require MFA
for logging into systems that interact with sensitive
health data. This adds an additional layer of
security beyond just usernames and passwords.
 Audit Logs: Keep detailed logs of who accessed
the data, what actions were performed (e.g.,
reading, updating, deleting data), and when these
actions occurred. This can help in detecting
unauthorized access or suspicious activity.
3. Data Masking and Pseudonymization
 Data Masking: In non-production environments
(e.g., testing or development), use data masking
techniques to obfuscate sensitive data. For
example, replacing actual patient names with
random names, or hiding portions of phone
numbers or email addresses (e.g.,
"xxxxxx@domain.com").
 Pseudonymization: Pseudonymize sensitive data
by replacing identifiable information with
pseudonyms or unique identifiers. This way, the
real identities of patients are not directly exposed.
4. Secure Database Configuration
 Database Configuration Hardening: Secure the
database by disabling unnecessary features or
services, setting up firewalls to protect from
external access, and configuring security settings
for user authentication and access control.
 Regular Updates and Patching: Ensure that the
database software and all related components are
regularly updated and patched to fix any known
security vulnerabilities.
5. Data Minimization
 Only collect and store the minimum amount of
sensitive data necessary for your system to
function. For example, instead of storing complete
medical records for every patient, store only
essential details needed for treatment and
diagnosis.
 Avoid retaining sensitive data longer than
necessary. Implement data retention policies and
delete sensitive records when they are no longer
needed.
6. Legal and Regulatory Compliance
 HIPAA Compliance (for U.S. healthcare systems):
If your system is operating in the U.S., you must
ensure that your database and data handling
practices comply with the Health Insurance
Portability and Accountability Act (HIPAA), which
sets national standards for the protection of health
information.
 GDPR Compliance (for European Union systems):
If your system is operating in the EU, ensure
compliance with the General Data Protection
Regulation (GDPR), which protects personal data
and privacy.
 Ensure that all sensitive data handling and
processing practices adhere to local regulations
and healthcare privacy laws.

By implementing these security measures, you can


ensure the privacy and integrity of sensitive health data
in your database, protecting it from unauthorized
access, breaches, and other security threats.

16. Database Design for a Ticketing System (e.g.,


Concerts, Sports Events)
Objective:
Design a database to manage event ticket sales,
seating arrangements, and customer preferences.
Exercise:
Scenario:
You need to design a database for a ticketing system
that handles events, seating arrangements, ticket
sales, and customer information.
Tasks:
1. Design Tables:
o Events Table: Holds information about events
(concerts, sports, etc.)
o Tickets Table: Contains ticket sales data,
including the event ID and seat information.
o Customers Table: Stores customer details
like name, contact, etc.
o Seating Arrangements Table: Holds seating
details like seat number, availability, and
section.
CREATE TABLE Events (
event_id INT PRIMARY KEY,
event_name VARCHAR(255),
event_date DATE,
event_location VARCHAR(255)
);

CREATE TABLE Customers (


customer_id INT PRIMARY KEY,
customer_name VARCHAR(255),
email VARCHAR(255),
phone_number VARCHAR(15)
);

CREATE TABLE Seating_Arrangements (


seat_id INT PRIMARY KEY,
event_id INT,
seat_number VARCHAR(10),
section VARCHAR(50),
availability BOOLEAN,
FOREIGN KEY (event_id) REFERENCES
Events(event_id)
);

CREATE TABLE Tickets (


ticket_id INT PRIMARY KEY,
customer_id INT,
event_id INT,
seat_id INT,
purchase_date DATE,
price DECIMAL(10, 2),
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id),
FOREIGN KEY (event_id) REFERENCES
Events(event_id),
FOREIGN KEY (seat_id) REFERENCES
Seating_Arrangements(seat_id)
);
2. Foreign Key Relationships:
o Tickets is linked to Events, Customers, and
Seating_Arrangements to ensure data
consistency and referential integrity.
3. SQL Queries:
o Total sales for a specific event:
4. SELECT event_id, SUM(price) AS total_sales
5. FROM Tickets
6. WHERE event_id = ?
7. GROUP BY event_id;
o Customer ticket purchase history:
8. SELECT customer_name, event_name,
seat_number, purchase_date
9. FROM Customers
10. JOIN Tickets ON Customers.customer_id =
Tickets.customer_id
11. JOIN Events ON Tickets.event_id =
Events.event_id
12. JOIN Seating_Arrangements ON Tickets.seat_id
= Seating_Arrangements.seat_id
13. WHERE customer_id = ?;
o Revenue per event:
14. SELECT event_name, SUM(price) AS revenue
15. FROM Tickets
16. JOIN Events ON Tickets.event_id =
Events.event_id
17. GROUP BY event_name;
18. Advanced: Stored Procedure to
Automatically Issue Tickets:
CREATE PROCEDURE issue_ticket(
IN customer_id INT,
IN event_id INT,
IN seat_id INT,
IN price DECIMAL(10, 2)
)
BEGIN
-- Reserve the seat
UPDATE Seating_Arrangements
SET availability = FALSE
WHERE seat_id = seat_id;

-- Insert the ticket


INSERT INTO Tickets (customer_id, event_id, seat_id,
purchase_date, price)
VALUES (customer_id, event_id, seat_id,
CURRENT_DATE, price);
END;
5. Concurrency: Locking Mechanism to Prevent
Double-Booking:
o Implement pessimistic locking to prevent
double-booking during high-demand periods
by locking the seat row for the event until the
transaction is complete.
START TRANSACTION;

SELECT * FROM Seating_Arrangements


WHERE seat_id = ? AND availability = TRUE
FOR UPDATE;

-- If the seat is available, reserve it and proceed with


the ticket purchase.

COMMIT;

17. Database Design for a Content Management


System (CMS)
Objective:
Design a CMS database to handle articles, categories,
authors, and comments.
Exercise:
Scenario:
Design a content management system for a website
where users can post articles, comment on them, and
categorize them.
Tasks:
1. Design Tables:
o Articles Table: Holds article data.
o Authors Table: Contains information about
authors.
o Categories Table: Lists article categories.
o Comments Table: Stores comments on
articles.
CREATE TABLE Authors (
author_id INT PRIMARY KEY,
author_name VARCHAR(255),
bio TEXT
);

CREATE TABLE Categories (


category_id INT PRIMARY KEY,
category_name VARCHAR(255)
);

CREATE TABLE Articles (


article_id INT PRIMARY KEY,
title VARCHAR(255),
content TEXT,
publish_date DATE,
author_id INT,
category_id INT,
FOREIGN KEY (author_id) REFERENCES
Authors(author_id),
FOREIGN KEY (category_id) REFERENCES
Categories(category_id)
);

CREATE TABLE Comments (


comment_id INT PRIMARY KEY,
article_id INT,
author_name VARCHAR(255),
comment_text TEXT,
comment_date DATE,
FOREIGN KEY (article_id) REFERENCES
Articles(article_id)
);
2. Foreign Key Relationships:
o Articles is linked to Authors and Categories.
o Comments is linked to Articles.
3. SQL Queries:
o Articles by a particular author:
4. SELECT title, publish_date
5. FROM Articles
6. WHERE author_id = ?;
o Most commented articles:
7. SELECT article_id, COUNT(comment_id) AS
comment_count
8. FROM Comments
9. GROUP BY article_id
10. ORDER BY comment_count DESC;
o Articles in a specific category:
11. SELECT title, publish_date
12. FROM Articles
13. WHERE category_id = ?;
14. Advanced: Stored Procedure to Publish
an Article:
CREATE PROCEDURE publish_article(
IN article_id INT,
IN category_id INT,
IN author_id INT
)
BEGIN
-- Set article status to 'Published' (could add column
for status)
UPDATE Articles
SET category_id = category_id, author_id =
author_id, publish_date = CURRENT_DATE
WHERE article_id = article_id;
-- Notify the author (simplified, actual
implementation would require an email system)
INSERT INTO Notifications (author_id, message)
VALUES (author_id, 'Your article has been
published.');
END;
5. Full-Text Search:
o Implement full-text indexing to enable
efficient searches on article titles and content.
CREATE FULLTEXT INDEX idx_article_search ON Articles
(title, content);

18. Design a Database for a Supply Chain


Management System
Objective:
Design a system to manage suppliers, products,
inventory, and shipments.
Exercise:
Scenario:
Create a database to manage the flow of products from
suppliers to customers, tracking inventory levels, order
shipments, and supplier details.
Tasks:
1. Design Tables:
o Suppliers Table: Contains supplier details.
o Products Table: Stores product information.
o Inventory Table: Tracks inventory levels.
o Orders Table: Contains order details.
o Shipments Table: Stores shipment details.
CREATE TABLE Suppliers (
supplier_id INT PRIMARY KEY,
supplier_name VARCHAR(255),
contact_info TEXT
);
CREATE TABLE Products (
product_id INT PRIMARY KEY,
product_name VARCHAR(255),
supplier_id INT,
FOREIGN KEY (supplier_id) REFERENCES
Suppliers(supplier_id)
);

CREATE TABLE Inventory (


product_id INT,
quantity INT,
last_updated DATE,
FOREIGN KEY (product_id) REFERENCES
Products(product_id)
);

CREATE TABLE Orders (


order_id INT PRIMARY KEY,
product_id INT,
quantity INT,
order_date DATE,
FOREIGN KEY (product_id) REFERENCES
Products(product_id)
);
CREATE TABLE Shipments (
shipment_id INT PRIMARY KEY,
order_id INT,
shipment_date DATE,
status VARCHAR(255),
FOREIGN KEY (order_id) REFERENCES
Orders(order_id)
);
2. SQL Queries:
o Track products by supplier:
3. SELECT product_name
4. FROM Products
5. WHERE supplier_id = ?;
o Inventory levels:
6. SELECT product_name, quantity
7. FROM Inventory
8. JOIN Products ON Inventory.product_id =
Products.product_id;
9. Triggers to Update Inventory:
CREATE TRIGGER update_inventory
AFTER INSERT ON Shipments
FOR EACH ROW
BEGIN
UPDATE Inventory
SET quantity = quantity - NEW.quantity
WHERE product_id = NEW.product_id;
END;
4. Advanced: Stored Procedure to Reorder Low-
Stock Products:
CREATE PROCEDURE reorder_low_stock()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE prod_id INT;
DECLARE qty INT;
DECLARE reorder_cursor CURSOR FOR
SELECT product_id, quantity FROM Inventory
WHERE quantity < 10;

OPEN reorder_cursor;

read_loop: LOOP
FETCH reorder_cursor INTO prod_id, qty;
IF done THEN
LEAVE read_loop;
END IF;

-- Reorder logic (e.g., create new order for


supplier)
INSERT INTO Orders (product_id, quantity,
order_date)
VALUES (prod_id, 100, CURRENT_DATE);
END LOOP;

CLOSE reorder_cursor;
END;
5. Performance:
o Use indexes on frequently queried fields (e.g.,
product_name, supplier_id) to speed up
queries, particularly for finding the fastest
delivery routes.

These solutions cover the tasks and database design


for Ticketing System, CMS, and Supply Chain
Management System, with SQL code, stored
procedures, triggers, and performance considerations.

21. Database Design for a Fleet Management


System
Objective:
Design a database to manage vehicle fleet operations,
including vehicles, drivers, maintenance schedules, and
routes.
Exercise:
Scenario:
Create a fleet management system database to track
vehicle details, maintenance schedules, and driver
assignments.
Tasks:
1. Design Tables:
o Vehicles Table: Contains details about each
vehicle in the fleet.
o Drivers Table: Stores information about
drivers.
o Maintenance_Schedules Table: Tracks
scheduled maintenance for each vehicle.
o Routes Table: Stores details about each route
a vehicle can take.
o Assignments Table: Links drivers to vehicles
for specific trips.
CREATE TABLE Vehicles (
vehicle_id INT PRIMARY KEY,
vehicle_model VARCHAR(255),
vehicle_type VARCHAR(255),
license_plate VARCHAR(20),
year INT
);

CREATE TABLE Drivers (


driver_id INT PRIMARY KEY,
driver_name VARCHAR(255),
driver_license_number VARCHAR(255),
phone_number VARCHAR(15)
);

CREATE TABLE Maintenance_Schedules (


maintenance_id INT PRIMARY KEY,
vehicle_id INT,
maintenance_type VARCHAR(255),
maintenance_date DATE,
cost DECIMAL(10, 2),
FOREIGN KEY (vehicle_id) REFERENCES
Vehicles(vehicle_id)
);

CREATE TABLE Routes (


route_id INT PRIMARY KEY,
route_name VARCHAR(255),
distance INT -- in kilometers
);

CREATE TABLE Assignments (


assignment_id INT PRIMARY KEY,
vehicle_id INT,
driver_id INT,
route_id INT,
assignment_date DATE,
FOREIGN KEY (vehicle_id) REFERENCES
Vehicles(vehicle_id),
FOREIGN KEY (driver_id) REFERENCES
Drivers(driver_id),
FOREIGN KEY (route_id) REFERENCES
Routes(route_id)
);
2. SQL Queries:
o Vehicle Maintenance History:
3. SELECT vehicle_id, maintenance_type,
maintenance_date, cost
4. FROM Maintenance_Schedules
5. WHERE vehicle_id = ?;
o Average Maintenance Cost per Vehicle:
6. SELECT vehicle_id, AVG(cost) AS
average_maintenance_cost
7. FROM Maintenance_Schedules
8. GROUP BY vehicle_id;
o Total Distance Covered by Each Vehicle:
9. SELECT vehicle_id, SUM(distance) AS total_distance
10. FROM Assignments
11. JOIN Routes ON Assignments.route_id =
Routes.route_id
12. GROUP BY vehicle_id;
13. Advanced: Stored Procedure to Assign
Drivers and Schedule Maintenance:
CREATE PROCEDURE
assign_driver_and_schedule_maintenance(
IN vehicle_id INT,
IN driver_id INT,
IN route_id INT,
IN maintenance_type VARCHAR(255),
IN maintenance_date DATE
)
BEGIN
-- Assign the driver to the vehicle for the specific
route
INSERT INTO Assignments (vehicle_id, driver_id,
route_id, assignment_date)
VALUES (vehicle_id, driver_id, route_id,
CURRENT_DATE);

-- Schedule the maintenance for the vehicle


INSERT INTO Maintenance_Schedules (vehicle_id,
maintenance_type, maintenance_date, cost)
VALUES (vehicle_id, maintenance_type,
maintenance_date, 100.00); -- Example cost
END;
4. Concurrency: Prevent Overlapping
Maintenance Tasks:
o Use pessimistic locking to ensure that no
overlapping maintenance tasks are scheduled
for the same vehicle.
START TRANSACTION;

SELECT * FROM Maintenance_Schedules


WHERE vehicle_id = ? AND maintenance_date = ?
FOR UPDATE;

-- Proceed with scheduling maintenance if available

COMMIT;
5. Optimization: Use Indexing for Routes and
Vehicle Utilization:
o Index vehicle_id in the Assignments table
and route_id in the Routes table for faster
querying.
CREATE INDEX idx_vehicle_id ON Assignments
(vehicle_id);
CREATE INDEX idx_route_id ON Routes (route_id);

22. Database Design for a Real Estate


Management System
Objective:
Design a real estate management system to track
property listings, agents, buyers, and transactions.
Exercise:
Scenario:
Design a real estate management system to track
property listings, agents, buyers, and transactions.
Tasks:
1. Design Tables:
o Properties Table: Holds details about
properties.
o Agents Table: Stores information about real
estate agents.
o Buyers Table: Tracks buyer details.
o Transactions Table: Records transactions
(property sales).
o Property_Types Table: Classifies properties
(e.g., residential, commercial).
CREATE TABLE Agents (
agent_id INT PRIMARY KEY,
agent_name VARCHAR(255),
agent_email VARCHAR(255),
agent_phone VARCHAR(15)
);

CREATE TABLE Property_Types (


property_type_id INT PRIMARY KEY,
type_name VARCHAR(255)
);

CREATE TABLE Properties (


property_id INT PRIMARY KEY,
property_name VARCHAR(255),
property_type_id INT,
price DECIMAL(15, 2),
location VARCHAR(255),
status VARCHAR(50), -- e.g., for sale, sold, etc.
FOREIGN KEY (property_type_id) REFERENCES
Property_Types(property_type_id)
);

CREATE TABLE Buyers (


buyer_id INT PRIMARY KEY,
buyer_name VARCHAR(255),
buyer_email VARCHAR(255),
buyer_phone VARCHAR(15)
);

CREATE TABLE Transactions (


transaction_id INT PRIMARY KEY,
property_id INT,
buyer_id INT,
agent_id INT,
transaction_date DATE,
sale_price DECIMAL(15, 2),
FOREIGN KEY (property_id) REFERENCES
Properties(property_id),
FOREIGN KEY (buyer_id) REFERENCES
Buyers(buyer_id),
FOREIGN KEY (agent_id) REFERENCES
Agents(agent_id)
);
2. SQL Queries:
o Most Popular Property Types:
3. SELECT property_type_id, COUNT(*) AS
property_count
4. FROM Properties
5. GROUP BY property_type_id
6. ORDER BY property_count DESC;
o Average Transaction Value per Agent:
7. SELECT agent_id, AVG(sale_price) AS
avg_transaction_value
8. FROM Transactions
9. GROUP BY agent_id;
o Properties Sold by Location:
10. SELECT location, COUNT(*) AS properties_sold
11. FROM Properties
12. WHERE status = 'sold'
13. GROUP BY location;
14. Trigger to Update Property Status upon
Transaction Completion:
CREATE TRIGGER update_property_status
AFTER INSERT ON Transactions
FOR EACH ROW
BEGIN
UPDATE Properties
SET status = 'sold'
WHERE property_id = NEW.property_id;
END;
4. Advanced: Stored Procedure for Commission
Calculation:
CREATE PROCEDURE calculate_commission(
IN agent_id INT
)
BEGIN
DECLARE commission_rate DECIMAL(5, 2) DEFAULT
0.05; -- 5% commission
DECLARE total_sales DECIMAL(15, 2);

-- Calculate total sales made by the agent


SELECT SUM(sale_price) INTO total_sales
FROM Transactions
WHERE agent_id = agent_id;

-- Calculate and display the commission


SELECT total_sales * commission_rate AS
commission;
END;
5. Performance Optimization:
o Use partitioning in the Transactions table
based on transaction_date for better query
performance during reports.
o Create indexes on commonly queried fields
such as status in the Properties table and
agent_id in the Transactions table.
CREATE INDEX idx_property_status ON Properties
(status);
CREATE INDEX idx_agent_id ON Transactions (agent_id);

23. Database Design for a Movie Rental System


Objective:
Design a system for managing movie rentals, inventory,
customers, and rental history.
Exercise:
Scenario:
Create a database to manage movie rentals, inventory,
and customer data.
Tasks:
1. Design Tables:
o Movies Table: Contains details about movies
available for rent.
o Customers Table: Stores customer details.
o Rentals Table: Tracks rental history.
o Inventory Table: Stores information about
available movie copies.
o Payments Table: Stores payment transaction
details.
CREATE TABLE Movies (
movie_id INT PRIMARY KEY,
title VARCHAR(255),
genre VARCHAR(50),
release_year INT
);

CREATE TABLE Customers (


customer_id INT PRIMARY KEY,
customer_name VARCHAR(255),
customer_email VARCHAR(255),
customer_phone VARCHAR(15)
);

CREATE TABLE Inventory (


inventory_id INT PRIMARY KEY,
movie_id INT,
copies_available INT,
FOREIGN KEY (movie_id) REFERENCES
Movies(movie_id)
);

CREATE TABLE Rentals (


rental_id INT PRIMARY KEY,
customer_id INT,
movie_id INT,
rental_date DATE,
due_date DATE,
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id),
FOREIGN KEY (movie_id) REFERENCES
Movies(movie_id)
);

CREATE TABLE Payments (


payment_id INT PRIMARY KEY,
rental_id INT,
payment_date DATE,
amount DECIMAL(10, 2),
FOREIGN KEY (rental_id) REFERENCES
Rentals(rental_id)
);
2. SQL Queries:
o Top 10 Most Rented Movies:
3. SELECT movie_id, COUNT(*) AS rental_count
4. FROM Rentals
5. GROUP BY movie_id
6. ORDER BY rental_count DESC
7. LIMIT 10;
o Rental History by Customer:
8. SELECT customer_name, title, rental_date,
due_date
9. FROM Rentals
10. JOIN Customers ON Rentals.customer_id =
Customers.customer_id
11. JOIN Movies ON Rentals.movie_id =
Movies.movie_id
12. WHERE Rentals.customer_id = ?;
13. Advanced: Stored Procedure for Rental
Fees and Due Dates:
CREATE PROCEDURE apply_rental_fees_and_due_dates(
IN movie_id INT
)
BEGIN
DECLARE rental_fee DECIMAL(10, 2);
DECLARE due_date DATE;
DECLARE category VARCHAR(50);

-- Determine rental fee based on movie category


(example logic)
SELECT genre INTO category FROM Movies WHERE
movie_id = movie_id;

IF category = 'New Release' THEN


SET rental_fee = 5.00;
ELSE
SET rental_fee = 2.50;
END IF;

-- Calculate due date


SET due_date = DATE_ADD(CURRENT_DATE,
INTERVAL 7 DAY);

-- Insert rental record (this would be triggered during


the rental process)
INSERT INTO Rentals (customer_id, movie_id,
rental_date, due_date)
VALUES (1, movie_id, CURRENT_DATE, due_date); --
Example for customer 1
END;
4. Concurrency: Locking to Prevent Double
Rentals:
o Optimistic Locking to ensure a movie cannot
be rented to multiple customers at the same
time.
START TRANSACTION;

SELECT copies_available FROM Inventory


WHERE movie_id = ?
FOR UPDATE;

-- Check if movie is available and proceed with rental

COMMIT;

These solutions cover database design, queries,


advanced stored procedures, triggers, and concurrency
strategies for Fleet Management, Real Estate
Management, and Movie Rental Systems.

26. Database Design for an Automated Ticketing


System (Transport)
Objective:
Build a system to manage ticket sales, train or bus
schedules, and customer bookings.
Exercise:
Scenario:
Create a database for a public transport system to
manage ticket bookings, schedules, and available
seats.
Tasks:
1. Design Tables:
o Customers Table: Stores customer details.
o Tickets Table: Stores ticket details and links
to customers and routes.
o Routes Table: Stores route details for buses
or trains.
o Vehicles Table: Stores vehicle information
(e.g., bus or train).
o Schedules Table: Stores scheduled
departures for each route.
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(255),
customer_email VARCHAR(255),
customer_phone VARCHAR(15)
);

CREATE TABLE Routes (


route_id INT PRIMARY KEY,
route_name VARCHAR(255),
departure_location VARCHAR(255),
arrival_location VARCHAR(255),
distance INT -- in kilometers
);

CREATE TABLE Vehicles (


vehicle_id INT PRIMARY KEY,
vehicle_type VARCHAR(255), -- e.g., bus, train
capacity INT -- number of seats
);

CREATE TABLE Schedules (


schedule_id INT PRIMARY KEY,
route_id INT,
vehicle_id INT,
departure_time DATETIME,
available_seats INT, -- Seats available for the
schedule
FOREIGN KEY (route_id) REFERENCES
Routes(route_id),
FOREIGN KEY (vehicle_id) REFERENCES
Vehicles(vehicle_id)
);

CREATE TABLE Tickets (


ticket_id INT PRIMARY KEY,
customer_id INT,
schedule_id INT,
ticket_price DECIMAL(10, 2),
seat_number INT,
booking_time DATETIME,
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id),
FOREIGN KEY (schedule_id) REFERENCES
Schedules(schedule_id)
);
2. SQL Queries:
o Track Available Seats for Specific Routes:
3. SELECT route_name, available_seats
4. FROM Schedules
5. JOIN Routes ON Schedules.route_id =
Routes.route_id
6. WHERE route_id = ? AND departure_time > NOW();
o Most Popular Travel Times or Routes:
7. SELECT route_name, COUNT(*) AS booking_count
8. FROM Tickets
9. JOIN Schedules ON Tickets.schedule_id =
Schedules.schedule_id
10. JOIN Routes ON Schedules.route_id =
Routes.route_id
11. GROUP BY route_name
12. ORDER BY booking_count DESC;
13. Advanced: Stored Procedure to
Automatically Assign Seats:
14. CREATE PROCEDURE assign_seat(
15. IN customer_id INT,
16. IN schedule_id INT
17. )
18. BEGIN
19. DECLARE available_seats INT;
20. DECLARE seat_number INT;
21.
22. -- Get available seats for the given schedule
23. SELECT available_seats INTO
available_seats
24. FROM Schedules
25. WHERE schedule_id = schedule_id;
26.
27. IF available_seats > 0 THEN
28. -- Assign a seat number and reduce
available seats
29. SET seat_number = available_seats;
30. UPDATE Schedules
31. SET available_seats = available_seats - 1
32. WHERE schedule_id = schedule_id;
33.
34. -- Insert a new ticket record
35. INSERT INTO Tickets (customer_id,
schedule_id, seat_number, booking_time,
ticket_price)
36. VALUES (customer_id, schedule_id,
seat_number, NOW(), 100.00); -- Example price
37. ELSE
38. SIGNAL SQLSTATE '45000' SET
MESSAGE_TEXT = 'No available seats';
39. END IF;
40. END;
41. Concurrency: Locking to Prevent Double-
Booking:
o Use pessimistic locking to prevent multiple
customers from booking the same seat.
START TRANSACTION;

SELECT available_seats FROM Schedules


WHERE schedule_id = ? FOR UPDATE;
-- If seats are available, proceed with booking

COMMIT;
5. Optimization: Real-Time Ticket Availability
and Price Estimates:
o Indexing for faster queries related to
schedule availability and ticket price
calculations.
CREATE INDEX idx_schedule_id ON Schedules
(schedule_id);
CREATE INDEX idx_route_id ON Routes (route_id);

27. Database Design for a Subscription Service


(e.g., Netflix, Spotify)
Objective:
Design a database to manage subscriptions, user
preferences, content libraries, and billing.
Exercise:
Scenario:
Create a database for a streaming service that tracks
user subscriptions, content watched, and payment
details.
Tasks:
1. Design Tables:
o Users Table: Stores user details.
o Subscriptions Table: Stores subscription
plans and their details.
o Content Table: Stores content (movies,
music, etc.) in the library.
o Billing Table: Stores payment details.
o Watch History Table: Tracks user watch
history.
CREATE TABLE Users (
user_id INT PRIMARY KEY,
user_name VARCHAR(255),
user_email VARCHAR(255),
user_subscription_id INT
);

CREATE TABLE Subscriptions (


subscription_id INT PRIMARY KEY,
subscription_name VARCHAR(255),
monthly_fee DECIMAL(10, 2)
);

CREATE TABLE Content (


content_id INT PRIMARY KEY,
title VARCHAR(255),
genre VARCHAR(50),
release_year INT
);
CREATE TABLE Billing (
billing_id INT PRIMARY KEY,
user_id INT,
payment_date DATE,
amount DECIMAL(10, 2),
FOREIGN KEY (user_id) REFERENCES Users(user_id)
);

CREATE TABLE Watch_History (


watch_id INT PRIMARY KEY,
user_id INT,
content_id INT,
watch_date DATE,
FOREIGN KEY (user_id) REFERENCES Users(user_id),
FOREIGN KEY (content_id) REFERENCES
Content(content_id)
);
2. SQL Queries:
o Top Content by User Rating:
3. SELECT title, AVG(rating) AS avg_rating
4. FROM Content
5. JOIN Watch_History ON Content.content_id =
Watch_History.content_id
6. GROUP BY title
7. ORDER BY avg_rating DESC;
o Subscription Revenue per Region:
8. SELECT region, SUM(monthly_fee) AS total_revenue
9. FROM Users
10. JOIN Subscriptions ON
Users.user_subscription_id =
Subscriptions.subscription_id
11. GROUP BY region;
12. Advanced: Stored Procedure to
Recommend Content Based on Watch
History:
13. CREATE PROCEDURE recommend_content(
14. IN user_id INT
15. )
16. BEGIN
17. DECLARE preferred_genre VARCHAR(50);
18.
19. -- Get preferred genre based on user watch
history
20. SELECT genre INTO preferred_genre
21. FROM Content
22. JOIN Watch_History ON Content.content_id
= Watch_History.content_id
23. WHERE Watch_History.user_id = user_id
24. GROUP BY genre
25. ORDER BY COUNT(*) DESC
26. LIMIT 1;
27.
28. -- Recommend content from the preferred
genre
29. SELECT title FROM Content WHERE genre =
preferred_genre;
30. END;
31. Performance: Indexing for Quick Queries
on Content Preferences and Renewals:
o Create indexes on frequently queried fields
such as user_subscription_id in Users and
genre in Content.
CREATE INDEX idx_user_subscription_id ON Users
(user_subscription_id);
CREATE INDEX idx_content_genre ON Content (genre);
5. Concurrency: Handle Concurrent Requests for
Streaming:
o Use optimistic concurrency control for
handling concurrent streaming access.
START TRANSACTION;

SELECT * FROM Content WHERE content_id = ?;

-- Check if content is available for streaming and


proceed

COMMIT;
28. Database Design for a Customer Relationship
Management (CRM) System
Objective:
Build a CRM system database to track customer
interactions, sales pipelines, and marketing campaigns.
Exercise:
Scenario:
Design a CRM system to manage customer interactions,
sales opportunities, and marketing efforts.
Tasks:
1. Design Tables:
o Customer Table: Stores customer details.
o Sales Opportunities Table: Tracks potential
sales for each customer.
o Activities Table: Logs interactions with
customers.
o Leads Table: Stores details of sales leads.
o Campaigns Table: Tracks marketing
campaigns.
CREATE TABLE Customers (
customer_id INT PRIMARY KEY,
customer_name VARCHAR(255),
customer_email VARCHAR(255),
customer_phone VARCHAR(15)
);
CREATE TABLE Sales_Opportunities (
opportunity_id INT PRIMARY KEY,
customer_id INT,
opportunity_description VARCHAR(255),
value DECIMAL(15, 2),
status VARCHAR(50),
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id)
);

CREATE TABLE Activities (


activity_id INT PRIMARY KEY,
customer_id INT,
activity_type VARCHAR(50),
activity_date DATE,
activity_notes TEXT,
FOREIGN KEY (customer_id) REFERENCES
Customers(customer_id)
);

CREATE TABLE Leads (


lead_id INT PRIMARY KEY,
lead_name VARCHAR(255),
lead_source VARCHAR(50)
);
CREATE TABLE Campaigns (
campaign_id INT PRIMARY KEY,
campaign_name VARCHAR(255),
start_date DATE,
end_date DATE
);
2. SQL Queries:
o Sales Pipeline Status:
3. SELECT status, COUNT(*) AS opportunity_count
4. FROM Sales_Opportunities
5. GROUP BY status;
o Lead Conversion Rates:
6. SELECT lead_source, COUNT(*) AS converted_leads
7. FROM Leads
8. JOIN Sales_Opportunities ON Leads.lead_id =
Sales_Opportunities.lead_id
9. WHERE Sales_Opportunities.status = 'Converted'
10. GROUP BY lead_source;
11. Advanced: Stored Procedure to Calculate
Lead Scoring:
12. CREATE PROCEDURE calculate_lead_score(
13. IN lead_id INT
14. )
15. BEGIN
16. DECLARE score INT DEFAULT 0;
17.
18. -- Calculate score based on customer
interactions
19. SELECT COUNT(*) INTO score
20. FROM Activities
21. WHERE customer_id = lead_id;
22.
23. -- Adjust score based on interaction history
24. IF score > 10 THEN
25. SET score = score + 5;
26. END IF;
27.
28. -- Return final lead score
29. SELECT score;
30. END;
31. Concurrency: Avoid Conflicting Updates
in the Sales Pipeline:
o Use optimistic concurrency control to
ensure updates to opportunities are not lost.
START TRANSACTION;

SELECT * FROM Sales_Opportunities


WHERE opportunity_id = ?;

-- Check for changes and proceed with updates


COMMIT;

These database designs provide solutions for an


Automated Ticketing System, a Subscription
Service, and a CRM System, with SQL queries,
advanced stored procedures, and concurrency control.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy