call(back)

Most Enrolled Course

Tables courses(course_id, course_name), students(student_id, name) and enrollments(student_id, course_id) model a many-to-many enrollment. Return the single course with the most enrolled students as course_id, course_name, enrollment_count. If several courses tie, return the one with the smallest course_id.

The interview framed this as a Spring MVC application with Course and Student entities: be ready to say where the query lives (repository, service, controller), what the endpoint looks like, and which index makes it fast.

Hints

Hint 1

COUNT(*) ... GROUP BY course on the enrollments table, ORDER BY count DESC, course_id ASC, LIMIT 1 (or FETCH FIRST 1 ROW ONLY).

Hint 2

Join courses for the name; a course with no enrollments can only win if every course has none, so an inner join is fine unless the interviewer wants zeros shown.

Solution

Show the approach

Approach

SELECT c.course_id, c.course_name, COUNT(e.student_id) AS enrollment_count
FROM courses c
JOIN enrollments e ON e.course_id = c.course_id
GROUP BY c.course_id, c.course_name
ORDER BY enrollment_count DESC, c.course_id ASC
LIMIT 1;

The aggregation is one pass over enrollments grouped by course; an index on enrollments(course_id) lets the engine count each group from the index alone, and the ORDER BY ... LIMIT 1 is a top-1 selection rather than a full sort in most planners.

In a Spring MVC service

  • Entities Course and Student with a @ManyToMany through enrollments.
  • A repository method with the query above as @Query (JPQL or native), returning a small projection rather than entities.
  • A service that calls it and maps the empty case to a 404 or an empty body; a controller exposing GET /courses/most-enrolled.
  • Tests at the repository level with a seeded in-memory database, including the tie case.

Worth saying out loud

  • Doing the counting in Java (load all enrollments, group in a map) works for a demo and falls over at scale; the database should aggregate.
  • LEFT JOIN plus COUNT(e.student_id) shows courses with zero enrollments if the interviewer asks to see them; COUNT(*) would count the unmatched row as one.
  • Top three per course: swap LIMIT 1 for LIMIT 3, or use DENSE_RANK if ties should all appear.

Assistant

Sign in to use the assistant — ask what the problem means, get a hint when you're stuck, or have your current work reviewed. Conversations save to your account.

Asked at