Interview Puzzles · Problem 101 of 118

Courses and Teachers Never Used

MediumInterview PuzzlesSchool data

Return kind ('course' or 'teacher') and name (the course code or the teacher's name) for every course that has no section and every teacher who teaches no section. Sort by kind, then name.

Hint 1

Write two anti-joins (NOT EXISTS) and stack them with UNION ALL, adding a constant label column to each.

Reference solution

SELECT 'course' AS kind, c.code AS name
FROM courses AS c
WHERE NOT EXISTS (SELECT 1 FROM sections AS s WHERE s.course_id = c.course_id)
UNION ALL
SELECT 'teacher' AS kind, t.name AS name
FROM teachers AS t
WHERE NOT EXISTS (SELECT 1 FROM sections AS s WHERE s.teacher_id = t.teacher_id)
ORDER BY kind, name;

A constant in the select list ('course' AS kind) labels where each row came from, so two different kinds of rows can live in one result table. The two halves of a UNION ALL need the same number of columns of compatible types. Combining several data-quality checks into one labelled report is a common real-world use.