Window Functions · Problem 77 of 118

Second-Highest Grade per Section

HardWindow FunctionsSchool data

For sections 5 to 9, return section_id and second_highest: the second-highest distinct grade among the enrollments with a grade. (If two students share the top grade, the second-highest is the next lower grade, not the same grade again.) Sort by section_id.

Hint 1

DENSE_RANK() gives tied values the same rank and does not skip numbers, so the second-highest distinct value has rank 2.

Hint 2

Use DISTINCT (or MAX) in the final query, because several students can have the same grade.

Reference solution

WITH ranked AS (
  SELECT section_id, grade,
         DENSE_RANK() OVER (PARTITION BY section_id ORDER BY grade DESC) AS r
  FROM enrollments
  WHERE section_id BETWEEN 5 AND 9 AND grade IS NOT NULL
)
SELECT section_id, MAX(grade) AS second_highest
FROM ranked
WHERE r = 2
GROUP BY section_id
ORDER BY section_id;

Values 100, 100, 90 get RANK 1, 1, 3 (the number 2 is skipped) but DENSE_RANK 1, 1, 2. "Second highest value" therefore needs DENSE_RANK. This is the famous "second highest salary" interview question, and it has traps: ties at the top, a group with only one distinct value (no second value, so no row), and NULLs. Test with data that has ties.