GP6 Lab
GP6 Lab
Date Received :
1 / 46
2 / 46
Task 1: Database Integrity
SearchHistoryID (FK),
User Not Null UserID (PK) LoanID (FK)
UserID (FK),
Loan Not Null LoanID (PK) ContentID (FK)
UserID (FK),
FineHistory Not Null FineID (PK) LoanID (FK)
LocationID (FK),
Not Null, Check (type, ResourceAvailabilityI
Content status) ContentID (PK) D (FK)
ResourceAvailabilityI
ResourceAvailability Not Null D (PK) ContentID (FK)
Task 2: SQL
A: Table creation
use LibraryManagement;
3 / 46
LocationID VARCHAR(10) PRIMARY KEY NOT NULL,
RackNo VARCHAR(10) NOT NULL,
ShelfNo VARCHAR(10) NOT NULL
);
4 / 46
CREATE TABLE ResourceAvailability (
ResourceAvailabilityID VARCHAR(10) PRIMARY KEY NOT NULL,
IsAvailability TINYINT(1),
AvailabilityDate DATE,
ContentID VARCHAR(10) NOT NULL,
CONSTRAINT FK_ResourceAvailability_Content FOREIGN KEY (ContentID)
REFERENCES Content(ContentID)
);
5 / 46
UserID VARCHAR(10) NOT NULL,
LoanID VARCHAR(10) NOT NULL,
CONSTRAINT FK_FineHistory_UserID FOREIGN KEY (UserID)
REFERENCES User(UserID),
CONSTRAINT FK_FineHistory_LoanID FOREIGN KEY (LoanID)
REFERENCES Loan(LoanID)
);
B: Insert data
6 / 46
('A001', 'John', 'Doe', 'john_doe', 'password123', '[email protected]', '1234567890',
'123 Main St', 'Administrative Staff', '2021-01-01'),
('S001', 'Jane', 'Smith', 'jane_smith', 'pass456', '[email protected]', '9876543210',
'456 Oak St', 'Student', '2021-02-15'),
('S002', 'Bob', 'Johnson', 'bob_j', 'secret789', '[email protected]', '5556667777', '789
Pine St', 'Student', '2020-03-20'),
('P001', 'Alice', 'Brown', 'alice_b', 'topsecret', '[email protected]', '3332221111', '321
Elm St', 'Professor', '2022-04-10'),
('A002', 'Charlie', 'Green', 'charlie_g', 'classified', '[email protected]',
'9998887777', '654 Birch St', 'Administrative Staff', '2023-05-05'),
('L001', 'Eva',' Martinez', 'eva_m', 'pass789', '[email protected]', '1112223333', '987
Oak St', 'libarian', '2013-06-01'),
('P002', 'Michael',' Lee', 'mike_l', 'keypass', '[email protected]', '4445556666', '654
Elm St', 'Professor', '2021-06-15'),
('P003', 'Sophie',' Taylor', 'sophie_t', 'secure123', '[email protected]',
'7778889999', '321 Pine St', 'Professor', '2022-07-01'),
('S003', 'David', 'Wright', 'david_w', 'mypass789', '[email protected]',
'2223334444', '768 Maple St', 'Student', '2023-07-15'),
('A003', 'Emily', 'Johnson', 'emily_j', 'mypassword', '[email protected]',
'6667778888', '932 Cherry Ln', 'Administrative Staff', '2023-08-01');
7 / 46
INSERT INTO Content (ContentID, Type, Title, Author, Subject, PublicationDate,
LocationID, Price)
VALUES
('C1', 'Book', 'The Art of SQL', 'John Doe', 'Database', '2022-01-15', 'L1', 24.99),
('C2', 'Magazine', 'Tech Today', 'Jane Smith', 'Technology', '2022-02-01', 'L2', 22.99),
('C3', 'Journal', 'Data Science Review', 'Bob Johnson', 'Data Science', '2022-03-10',
'L3', 28.99),
('C4', 'Book', 'Programming Basics', 'Alice Brown', 'Programming', '2022-04-05', 'L4',
26.99),
('C5', 'Magazine', 'Science News', 'Charlie Green', 'Science', '2022-05-20', 'L5', 25.99),
('C6', 'Book', 'Advanced Mathematics', 'Emma Wilson', 'Mathematics', '2022-06-15',
'L1', 27.50),
('C7', 'Journal', 'World History Review', 'Liam Nguyen', 'History', '2022-07-10', 'L2',
23.75),
('C8', 'Book', 'Modern Physics', 'Olivia Kim', 'Physics', '2022-08-05', 'L3', 29.95),
('C9', 'Magazine', 'Global Economics', 'Ethan Brown', 'Economics', '2022-09-20', 'L4',
21.99),
('C10', 'Journal', 'Literary Classics', 'Sophia Garcia', 'Literature', '2022-10-25', 'L5',
24.89);
8 / 46
INSERT INTO resourceAvailability (ResourceAvailabilityID, isAvailability,
availabilityDate, contentID)
VALUES
('RA1', 1, '2023-01-20', 'C1'),
('RA2', 0, '2023-02-10', 'C2'),
('RA3', 1, '2023-03-15', 'C3'),
('RA4', 1, '2023-04-25', 'C4'),
('RA5', 0, '2023-05-30', 'C5');
9 / 46
insert into searchhistory (searchHistoryID,searchQuery,searchDate,UserID)
values
('sea1','Check if this book is available','2023-01-28','A001'),
('sea2','Find the location of this book','2023-02-21','S001'),
('sea3','Query personal borrowing information','2023-03-28','S002'),
('sea4','Find the location of this book','2023-04-12','P001'),
('sea5','View past due notices','2023-06-03','A002');
Lin Mochen
1. Logical Operators Query:
Find all books that are either categorized as 'Magazine' or 'Non-Magazine' and have
been checked out after 1/5/2022.
SELECT *
FROM content
WHERE (type = 'Magazine' OR type = 'Non-Magazine')
AND PublicationDate > '2022-05-01';
10 / 46
'Lost') and adds the FineAmount from the FineHistory table to the total fine
calculation for each user.
TotlaFine is calculated according to the following conditions: for each user, if the
status is "Normal", the amount of the fine is zero; if the status is "LateReturn", the
amount of the fine is calculated according to the number of days of delayed return; if
the status is "Damage", the amount of the fine is the price of the content; and if the
status is "Lost", the amount of the fine is twice the price of the content.
Before calculating the amount of a user's fine, update data is needed to keep track of
each user's book returns. This is the comment that updates the data:
START TRANSACTION;
UPDATE Loan
SET ReturnedDate = CASE LoanID
WHEN 'L1' THEN '2023-02-20'
WHEN 'L2' THEN '2023-04-15'
WHEN 'L3' THEN '2023-03-30'
WHEN 'L4' THEN '2023-04-20'
WHEN 'L5' THEN '2023-05-15'
WHEN 'L6' THEN '2023-07-09'
WHEN 'L7' THEN '2023-10-15'
WHEN 'L8' THEN '2023-11-20'
WHEN 'L9' THEN '2023-10-15'
WHEN 'L10' THEN '2023-11-13'
END,
State = CASE LoanID
WHEN 'L1' THEN 'Normal'
WHEN 'L2' THEN 'LateReturn'
WHEN 'L3' THEN 'Normal'
WHEN 'L4' THEN 'Damage'
WHEN 'L5' THEN 'Lost'
11 / 46
WHEN 'L6' THEN 'Normal'
WHEN 'L7' THEN 'LateReturn'
WHEN 'L8' THEN 'LateReturn'
WHEN 'L9' THEN 'Normal'
WHEN 'L10' THEN 'Damage'
END
WHERE LoanID IN ('L1', 'L2', 'L3', 'L4', 'L5', 'L6', 'L7', 'L8', 'L9', 'L10');
COMMIT;
Query:
SELECT
U.UserID,
COALESCE(SUM(
CASE
WHEN L.State = 'Normal' THEN 0
WHEN L.State = 'LateReturn' THEN
CASE
WHEN DATEDIFF(L.ReturnedDate, L.DueDate) > 10 THEN 5 +
(DATEDIFF(L.ReturnedDate, L.DueDate) - 10)
ELSE 5
END
WHEN L.State = 'Damage' THEN C.Price
WHEN L.State = 'Lost' THEN 2 * C.Price
ELSE 0
END + FH.FineAmount
), 0) AS TotalFine
FROM User U
LEFT JOIN Loan L ON U.UserID = L.UserID
LEFT JOIN FineHistory FH ON L.LoanID = FH.LoanID
LEFT JOIN Content C ON L.ContentID = C.ContentID
12 / 46
GROUP BY U.UserID;
SELECT
U.UserID,
U.FirstName,
U.LastName,
C.Title AS CheckedOutBookTitle
FROM User U
INNER JOIN Loan L ON U.UserID = L.UserID
INNER JOIN Content C ON L.ContentID = C.ContentID;
13 / 46
Gao Zhihan
1. Write a query to display userID, FullName, MemberType, contentID, LoanDate,
Title from user, Loan, and Content table, whose MemberType is student or
professor. Implement an INNER JOIN to include users and their corresponding
information.
(This query uses Logical Operator IN and Join Query INNER, this is a two inner
between three tables)
SELECT user.userID,
concat(user.FirstName,' ',user.Lastname) As'FullName',
user.MemberType,Loan.contentID,Loan.LoanDate,content.Title
FROM user
Inner join loan on user.userID=loan.userID
Inner join content on loan.contentID=content.contentID
WHERE MemberType IN ('student', 'professor');
14 / 46
2. Write a query to display UserID, FullName, ContentID, LoanDate from User and
Loan table. Implement a LEFT JOIN to include all users and their corresponding
loan information, showing null where there are no loans and list in descending
order by LoanDate.
(This query use Join Query LEFT, Logical Operator ORDER BY, and I learn a new
function COALESCE as a replacement value)
SELECT user.userID,
concat(user.FirstName,' ',user.Lastname) As'FullName',
COALESCE(loan.contentID, 'No loan available') AS ContentID, loan.LoanDate
FROM user
LEFT JOIN loan ON user.userID = loan.userID
ORDER BY loan.LoanDate DESC;
15 / 46
(*This query was implemented before I created before insert trigger, but after I
created the update trigger to display the situation: No loan available.)
16 / 46
Li Minjia
1. Logical Operators -‘LIKE’:
Write a query to display the list of resource information where Title starts with T.
SELECT * FROM librarymanagement.content
where Title like 'T%';
2. Logical Operators-‘between’:
Write a query to display the ContentID, Title, Type, Author, and PublicationDate of
the resources published between 9th March 2022 and 19th May 2022. Order by
ContentID.
select ContentID, Type, Author, PublicationDate
from librarymanagement.content
17 / 46
where PublicationDate between '2022-03-09' and '2022-05-19'
order by ContentID;
3. Logical Operators-‘COUNT’:
Write a query to count how many times each content has been borrowed, ordered by
ContentID.
select content.ContentID, content.Title,
Count(content.ContentID) as 'Total Loans'
from loan inner join content ON content.ContentID = loan.ContentID
Group by ContentID;
Chen Yuanxi
1. INER JOIN and ORDER BY
18 / 46
Queries all users who have borrowed the book "The Art of SQL" and the date they
borrowed it, sorted in ascending order by the date they borrowed it.
19 / 46
3. RIGHT JOIN and BETWEEN
Lists all loan records for books borrowed In the second half of 2023 (30 th June
through 31st December), including book titles and loan dates.
20 / 46
Zhang Ruohan
1. This query uses logical operators (AND, OR) to filter users who have returned their
loans on time or without penalties:
2. This query uses the sum() aggregation function to calculate the total amount of
fines for each user:
21 / 46
GROUP BY User.UserID,fullname;
3. Retrieve details of the content, its availability status and the users who borrowed it:
SELECT
C.ContentID,
C.Title,
C.Author,
R.IsAvailability,
L.LoanDate,
L.DueDate,
L.ReturnedDate,
U.UserID,
22 / 46
concat(U.firstname,U.lastname)as 'fullname'
FROM Content C
JOIN ResourceAvailability R ON C.ContentID = R.ContentID
LEFT JOIN Loan L ON C.ContentID = L.ContentID
LEFT JOIN User U ON L.UserID = U.UserID;
Task 3: Trigger
Before update
This is when I have not created any trigger, we can see that ReturenedDate,
FineAmount, and State is null.
23 / 46
The following that I create before update trigger in the table ‘Loan’.
This trigger achieves the function is that if update the Loan table, then FineAmount
can be calculated as follows if late return then the fine is Excess days*0.5, if damage
then the fine equal to the book price, if lost then the fine equal to the book price*2.
DELIMITER //
CREATE TRIGGER before_update_CalculateFine
BEFORE UPDATE ON Loan
FOR EACH ROW
IF NEW.ReturnedDate IS NOT NULL AND NEW.ReturnedDate > OLD.DueDate
THEN
SET NEW.FineAmount = DATEDIFF(NEW.ReturnedDate, OLD.DueDate) *
0.5;
ELSEIF NEW.State = 'Damage' THEN
SET NEW.FineAmount = (SELECT price FROM content WHERE ContentID =
NEW.ContentID);
ELSEIF NEW.State = 'Lost' THEN
SET NEW.FineAmount = (SELECT price FROM content WHERE ContentID =
NEW.ContentID) * 2;
ELSE
SET NEW.FineAmount = 0.00;
END IF;
//DELIMITER ;
Show triggers
24 / 46
Then I update the Loan table
UPDATE Loan
SET ReturnedDate = '2023-02-20', State = 'Normal'
WHERE LoanID = 'L1';
UPDATE Loan
SET ReturnedDate = '2023-04-15', State = 'LateReturn'
WHERE LoanID = 'L2';
UPDATE Loan
SET ReturnedDate = '2023-03-30', State = 'Normal'
WHERE LoanID = 'L3';
UPDATE Loan
SET ReturnedDate = '2023-04-20', State = 'Damage'
WHERE LoanID = 'L4';
UPDATE Loan
SET ReturnedDate = '2023-05-15', State = 'Lost'
WHERE LoanID = 'L5';
Select * from Loan
25 / 46
This is evidence that I successfully create before update in Loan table.
Before insert
I will create a before insert trigger to ensure that if I insert LoanDate, then the table
will automatically generate DueDate (one month later)
First, I insert new values to see if we don’t have before insert trigger, and then what
the Loan table will be like.
26 / 46
We can see that we cannot get DueDate.
The following that I create before insert trigger in the table ‘Loan’.
Then I insert new values ’L8’,‘L9’,‘L10’, we can see that the DueDate can be
generated automatically.
27 / 46
This is evidence that I successfully create before update in Loan table.
To facilitate queries and show the availability of triggers, I will update the table again.
The following table shows when I insert new values, we can see that before insert
played a role.
The following table is when updating the Loan table, It can calculate FineAmount,
before update played a role.
28 / 46
After updating the loan table – about FineHistory table :
29 / 46
The Loan table after updating:
UPDATE Loan
UPDATE Loan
30 / 46
We can see that the FineHistory table has not been updated despite the new fines.
Create trigger:
Let's create a trigger to solve this problem:
Delimiter//
BEGIN
END IF;
END; //
Delimiter;
31 / 46
After creating the trigger, try updating the Loan table again.
UPDATE Loan
UPDATE Loan
32 / 46
FineHistory table after Updat:
UPDATE Loan
33 / 46
As you can see, our problem has been successfully solved, and after updating the loan
table, the record of the fine will be automatically recorded in the finehistory table,
which can help the administrator to review the damage condition of resources or
financial reconciliation.
34 / 46
INSERT INTO Loan (LoanID, LoanDate, UserID, ContentID)
VALUES
The ResourceAvailability table after inserting a set of data into the loan table:
We can see that the Resource with ContentID = 'C1' has been borrowed, but the state
of "IsAvailability" and "AvailabilityDate" have not changed. "AvailabilityDate"
represents the time when the resource can be borrowed, and should be set to the day
when the resource is estimated to be returned, that is, "DueDate".
35 / 46
Create trigger:
We solve this problem by creating a trigger:
Update ResourceAvailability
show triggers;
VALUES
36 / 46
SELECT * FROM librarymanagement.loan;
We find that the "IsAvailability" status of a resource with ContentID 'C3' has changed
from 1 to 0, indicating that the resource has been borrowed and there are no resources
to borrow. In addition, the "AvailabilityDate" of the Resource with the ContentID of
'C3' has been changed to the corresponding "DueDate" in the Loan table
37 / 46
Insert another set of data and see:
VALUES
38 / 46
Before creating a trigger:
Before creating a trigger, we updated a set of data and found that changes to the loan
table did not cause updates to the ResourceAvailability table.
UPDATE Loan
39 / 46
SET ReturnedDate = '2023-07-29', State = 'Normal'
UPDATE Loan
UPDATE Loan
40 / 46
The ResourceAvailability table after update:
We found that the state of the resource did not change accordingly, which is not good.
Create trigger:
Create a trigger to solve this problem:
Delimiter//
BEGIN
Update ResourceAvailability
END IF;
41 / 46
END; //
Delimiter;
show triggers;
42 / 46
The current ResourceAvailability table:
UPDATE Loan
UPDATE Loan
UPDATE Loan
43 / 46
SELECT * FROM librarymanagement.loan;
44 / 46
APPENDIX 1 MARKING RUBRICS
Component Lab Report (Group) Percentage 13.5%
Title (%)
Score and Descriptors
10 - 8 7-5 4-0 Weight
Criteria
Outstanding - Excellent - Good - Above Average - Below Average - Poor Mark
(%)
Very Good Average
s
TASK 1 (15 Marks)
Domain Identifies all of the main Can identify Was able to 5
Integrity parts of the concepts and the key parts identify key Cannot identify important
Entity has a high level of of concepts components elements of the integrity 5
Integrity understanding of the and of the concept and has difficulty
Referential concepts' relationships. An demonstrate concepts. recognizing the
Integrity example was given to awareness of An example relationship between
elaborate more on the the links given is concepts and applications. 5
integrity concepts. between the acceptable.
concepts.
TASK 2A, & 2B (30 Marks)
All of the tables Most of the tables specified Some of the tables
specified in the project in the project requirements specified in the project
requirements were were created. requirements were
Database created. Choose the majority of the partially constructed.
Design Tables that are fully primary and foreign keys The name of the table
(Create & populated with the correctly while adhering to did not correspond to
Insert Data) relevant data pieces and the naming convention. its data items. 15
mirror the E-ERD
design.
Tables have been Tables have been filled Most of the primary
appropriately named with the majority of the and foreign keys were
concerning their data data elements described in chosen incorrectly,
elements. the E-ERD design. Data although the naming
Select all primary and items were entered into convention was
foreign keys correctly tables with minimal followed.
while adhering to the keypunch errors. Tables are populated
naming standard. with minimum data
Data items were inserted elements defined in
into tables correctly, the E-ERD design 15
with no keypunch project. When
errors. inserting data items
into tables, there are
45 / 46
several keypunch
errors.
TASK 3C (35 Marks)
Query is adequate and
Query fits the data well
does not twist the data.
and makes it easy to
interpret.
Used multiple database
Logical table to filter data with.
Used multiple database Query seriously twist
operators,
table to filter data with.
The written query is very
comparison, satisfactory. the data interpreting
The query was written almost impossible.
arithmetic,
professionally.
Adequate way of writing 35
case queries and satisfactory. No output table.
Used multiple syntax to
expression &
show the creativity of the
Output tables retrieved with
Join queries. a simple/ average
queries.
complexity representation
Output tables retrieved.
of SQL.
TASK 3 (10 Marks)
Demonstrates a limited
understanding of the
triggering concepts
Show fully understand Understands the concepts with an example but
the SQL Trigger in the and triggers applications. without an output.
SQL Trigger database design with Showed a good example with Demonstrates a limited 10
proper examples with output. understanding of the
output. triggering concepts but
without any proper
examples and output.
TOTAL 90
46 / 46