Lab 4
Lab 4
Task_1:
SELECT * FROM Students
WHERE dob > '2009-06-16';
Task_2:
SELECT * FROM Student
WHERE first_name LIKE 'A%' OR first_name LIKE 'J%';
Task_3:
SELECT * FROM Student
WHERE first_name != 'Alice'
AND email LIKE '%@example.com';
Assignment 2:
Task_1:
CREATE TABLE Person (
PersonID INT PRIMARY KEY,
FirstName VARCHAR(255),
LastName VARCHAR(255),
Age INT
);
Task_2:
CREATE TABLE Employee (
emp_id INT PRIMARY KEY,
first_name VARCHAR(255),
last_name VARCHAR(255),
age INT
);
Task_3:
INSERT INTO Person (PersonID, FirstName, LastName, Age)
VALUES
(1, 'John', 'Doe', 28),
(2, 'Jane', 'Smith', 34),
(3, 'Emily', 'Johnson', 22);
Task_4:
INSERT INTO Employee (emp_id, first_name, last_name, age)
VALUES
(101, 'Alice', 'Brown', 25),
(102, 'Bob', 'Davis', 30),
(103, 'Charlie', 'Wilson', 40);
Task 5:
SELECT FirstName, LastName, Age
FROM Person
UNION
SELECT first_name AS FirstName, last_name AS LastName, age
FROM Employee;
--LAB_1--
SELECT
s.student_id,
s.first_name,
s.last_name,
e.enrollment_id,
e.course_id
FROM Student s
JOIN Enrollment e ON s.student_id = e.student_id;
----ChatGPT Exercise----
Sure! To retrieve courses where the average grade is below a 'C', we can use SQL to calculate the
average grade for each course and then filter the courses where this average grade is below 'C'. Since
'C' is considered a passing grade, we need to interpret that as a numerical value for comparison.
Typically, the grades could be stored as letters, but for averaging, we would map those letters to
numerical equivalents. Let's assume the following mappings for simplicity:
• A=4
• B=3
• C=2
• D=1
• F=0
The approach would be:
1. Join the Course and Grade tables based on CourseID.
2. Compute the average grade for each course.
3. Filter courses where the average grade is below a 2 (representing a grade below 'C').
Here is the SQL query:
SELECT
c.CourseId,
c.CourseName,
AVG(
CASE
WHEN g.Grade = 'A' THEN 4
WHEN g.Grade = 'B' THEN 3
WHEN g.Grade = 'C' THEN 2
WHEN g.Grade = 'D' THEN 1
WHEN g.Grade = 'F' THEN 0
ELSE NULL
END
) AS AverageGrade
FROM
Course c
JOIN
Grade g ON c.CourseId = g.CourseID
GROUP BY
c.CourseId, c.CourseName
HAVING
AVG(
CASE
WHEN g.Grade = 'A' THEN 4
WHEN g.Grade = 'B' THEN 3
WHEN g.Grade = 'C' THEN 2
WHEN g.Grade = 'D' THEN 1
WHEN g.Grade = 'F' THEN 0
ELSE NULL
END
) < 2;
Explanation:
• SELECT: We are selecting the CourseId, CourseName, and the calculated average grade for
each course.
• AVG(CASE WHEN ... THEN ...): We are using a CASE statement inside the AVG function to
convert letter grades ('A', 'B', 'C', etc.) into numeric equivalents (4, 3, 2, 1, 0).
• FROM Course c JOIN Grade g: We join the Course table with the Grade table based on the
CourseId to get the relevant grades for each course.
• GROUP BY c.CourseId, c.CourseName: We group by CourseId and CourseName to calculate the
average grade for each course.
• HAVING: The HAVING clause is used to filter out the courses where the average grade is below
2, which corresponds to a grade below 'C'.