Assign5 Ans
Assign5 Ans
Subqueries
1. Show all the sections whose enrollment is greater than 5. Display course and section
number. Do two versions one using a join and the other with a correlated subquery. (10
rows)
SELECT s.course_no,
FROM section s
WHERE 5 < (SELECT
FROM
WHERE
s.section_no
COUNT(*)
enrollment e
e.section_id = s.section_id)
5. List all sections (course_no, description, section_no) taught by instructors that do not live in
Connecticut. Sort the result by course_no, section_no. (78 rows) Write two versions, and use a
correlated subquery in one.
SELECT s.course_no, s.section_no, c.description
FROM section s, course c, instructor i
6. List all classes (course_no, section_no) taught by Fernand Hanks (Use a correlated subquery)
(9 rows).
SELECT s.course_no, s.section_no
FROM section s
WHERE EXISTS (SELECT null
FROM instructor i
WHERE s.instructor_id = i.instructor_id
AND i.last_name = 'Hanks')
8. List all students (use the format: <last name>, <first initial> in a single column) in sections with
fewer than 5 students enrolled. Do not show any duplicate student names (87 rows).
SELECT last_name||', '||first_name
FROM student
WHERE student_id IN (SELECT student_id
FROM enrollment
WHERE section_id IN (SELECT
FROM
GROUP
HAVING
section_id
enrollment
BY section_id
COUNT(*) < 5))
9. List all zip codes that are not assigned to students. Write two versions: using a NOT EXISTS
and using an OUTER JOIN. (82 rows)
SELECT zip
FROM zipcode z
WHERE NOT EXISTS (SELECT null
FROM student s
WHERE s.zip=z.zip)
SELECT
FROM
WHERE
AND
z.zip
zipcode z, student s
z.zip = s.zip (+)
s.zip IS NULL
SELECT
FROM
ON
WHERE
z.zip
zipcode z LEFT OUTER JOIN student s
z.zip = s.zip
s.zip IS NULL
10. Display the first & last names of students (use the format: <first_name last_name> in a
single column), and the number of classes they are enrolled in, for students who are enrolled
in more than 2 classes. (7 rows)
SELECT
FROM
WHERE
GROUP
HAVING