Joins · Problem 56 of 118

Offered Before but Not Later

HardJoinsSchool data

Return the code of every course that has a section in the term '2025-Spring' but no section in '2026-Spring'. Sort by code.

Hint 1

EXCEPT returns the rows of the first query that are not in the second.

Reference solution

SELECT c.code
FROM sections AS s JOIN courses AS c ON c.course_id = s.course_id
WHERE s.term = '2025-Spring'
EXCEPT
SELECT c.code
FROM sections AS s JOIN courses AS c ON c.course_id = s.course_id
WHERE s.term = '2026-Spring'
ORDER BY code;

Set operators work on whole result tables: UNION (either), INTERSECT (both), EXCEPT (first but not second). Each also removes duplicates. The tempting WHERE term = 'A' AND term <> 'B' does not compare the courses across terms at all: a single row can never have two terms, so the second condition is always true and the filter does nothing. "In A but not in B" is a statement about sets of rows, so use EXCEPT or an anti-join.

Another way. The same idea as an anti-join with NOT EXISTS.

SELECT DISTINCT c.code
FROM courses AS c
JOIN sections AS s ON s.course_id = c.course_id AND s.term = '2025-Spring'
WHERE NOT EXISTS (
  SELECT 1 FROM sections AS s2 WHERE s2.course_id = c.course_id AND s2.term = '2026-Spring'
)
ORDER BY c.code;