The Highest Grade For Each Student coding problem is a database task. You are given an Enrollments table with columns student_id, course_id, and grade. For each student, you need to find their highest grade and the corresponding course. If a student has the same highest grade in multiple courses, you must select the one with the smallest course_id. The final output should be sorted by student_id in ascending order.
Coursera and other data-driven companies use this question to test a candidate's proficiency with Database interview patterns, specifically grouping and ranking. It evaluates whether you can handle tie-breaking scenarios correctly using SQL window functions or subqueries. It also tests your ability to return multiple specific columns from a grouped result, which is a common stumbling block for beginners.
This problem is best solved using a Window Function like ROW_NUMBER() or RANK().
student_id.grade in descending order, and then by course_id in ascending order (to handle ties).Table Enrollments:
| student_id | course_id | grade |
|---|---|---|
| 1 | 2 | 95 |
| 1 | 3 | 95 |
| 2 | 1 | 80 |
course_id for grade 95 is 2.course_id is 1.
Result: [[1, 2, 95], [2, 1, 80]].GROUP BY student_id and MAX(grade) will not necessarily return the correct course_id associated with that grade in all SQL dialects (like MySQL's older versions or standard SQL).course_id when grades are equal.student_id.Practice using RANK(), DENSE_RANK(), and ROW_NUMBER(). Understanding the subtle differences between these functions is essential for solving "Top N" problems in SQL. For this specific problem, ROW_NUMBER() is ideal because it guarantees exactly one row per student.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Active Businesses | Medium | Solve | |
| Active Users | Medium | Solve | |
| Activity Participants | Medium | Solve | |
| All People Report to the Given Manager | Medium | Solve | |
| All the Pairs With the Maximum Number of Common Followers | Medium | Solve |