Lab Problems-3
3.1 Write the following queries in SQL, using the university schema. (We
suggest you actually run these queries on a database, using the sample
data that we provide on the web site of the book, db-book.com.
Instructions for setting up a database, and loading sample data, are
provided on the above web site.)
a. Find the titles of courses in the Comp. Sci. department that have 3
credits.
Ans :
SELECT title FROM course
WHERE dept_name = 'Comp. Sci.' AND
credits =3;
title
International Finance
Computability Theory
Japanese
b. Find the IDs of all students who were taught by an instructor named Ein-
stein; make sure there are no duplicates in the result.
Ans :
SELECT DISTINCT takes.ID
FROM takes, instructor, teaches
WHERE takes.course_id = teaches.course_id
AND teaches.id = instructor.id
AND instructor.name = 'Einstein';
c. Find the highest salary of any instructor.
Ans :
SELECT max(salary) FROM instructor;
124651.41
d. Find all instructors earning the highest salary (there may be more than
one with the same salary).
Ans:
SELECT * FROM instructor
WHERE salary = (SELECT MAX(salary) FROM instructor);
19368 Wieland Pol. Sci. 124651.41
e. Find the enrollment of each section that was offered in Fall 2007.
Ans :
SELECT course_id,sec_id,
(SELECT COUNT(ID) FROM takes
WHERE takes.year = section.year
AND takes.semester = section.semester
AND takes.course_id = section.course_id
AND takes.sec_id = section.sec_id)
AS enrollment
FROM section WHERE
semester = "Fall"
AND year = 2007;
course_id sec_id enrollment
893 1 284
489 1 292
612 1 285
258 1 294
468 2 315
949 1 303
f. Find the maximum enrollment, across all sections, in Fall 2007.
Ans :
SELECT MAX(enrollment) FROM
(SELECT COUNT(ID) as enrollment
FROM section,takes
WHERE takes.year = section.year
AND takes.sec_id = section.sec_id
AND takes.course_id = section.course_id
AND takes.semester = section.semester
AND takes.semester = 'Fall'
AND takes.year = 2007
GROUP BY takes.sec_id,takes.course_id) AS subquery;
315
2. Suppose you are given a relation grade points(grade, points) that provides a con-
version from letter grades in the takes relation to numeric scores; for example,
an “A” grade could be specified to correspond to 4 points, an “A−” to 3.7 points,
a “B+” to 3.3 points, a “B” to 3 points, and so on. The grade points earned by a
student for a course offering (section) is defined as the number of credits for the
course multiplied by the numeric points for the grade that the student received.
Given the preceding relation, and our university schema, write each of the
following queries in SQL. You may assume for simplicity that no takes tuple has
the null value for grade.
a. Find the total grade points earned by the student with ID '12345', across
all courses taken by the student.
SELECT SUM(c.credits * g.points) AS total_grade_points
FROM takes t
JOIN grade_points g ON t.grade = g.grade
JOIN section s ON t.course_id = s.course_id
JOIN course c ON s.course_id = c.course_id
WHERE t.ID = '12345';