Rank the Top Half of Graded Students

Medium · Data Manipulation (SQL/Python) · Data Scientist · Technical Screen

Problem Statement

A school gradebook tracks teachers, students, assignments, and assignment grades. Write a single SQL query that builds an honor-roll leaderboard for the top half of graded students according to these rules:

  • Average over completed work: For each student, compute their exact arithmetic mean across all rows in grades where grade IS NOT NULL. Students who have not yet been assigned a primary_teacher_id (NULL) are still eligible and must be included if they have completed grades.
  • Exclude ungraded students: Omit any student with zero non-NULL grades from both the output and the headcount N.
  • Top-half cutoff (CEIL(N / 2)): Let N be the number of students who have at least one non-NULL grade. Keep only the top CEIL(N / 2) students ordered by exact unrounded average score descending, breaking ties by student_id ascending.
  • Display rounding and rank: Output student_id, name, avg_score (the student's mean score rounded to 1 decimal place), and rnk, defined as DENSE_RANK() across the selected students ordered by exact average score descending, student_id ascending.
  • Dynamic sizing: Do not hard-code N or a fixed row limit; the query must adapt automatically as students and grade records are added.

Return the selected rows in any order.

Input Schema

teachers

Column Type Description
id INTEGER Unique teacher identifier
name VARCHAR Teacher full name
classroom INTEGER Assigned room number

students

Column Type Description
id INTEGER Unique student identifier
name VARCHAR Student name
primary_teacher_id INTEGER Homeroom teacher ID in teachers, or NULL if unassigned

assignments

Column Type Description
id INTEGER Unique assignment identifier
teacher_id INTEGER Teacher who authored the assignment

grades

Column Type Description
student_id INTEGER Student who received the grade
assignment_id INTEGER Assignment being graded
grade DECIMAL(4,1) Earned score, or NULL if incomplete/ungraded

Examples

Example 1

Input:

teachers

id name classroom
10 Ms. Patel 104
20 Dr. Brooks 215

students

id name primary_teacher_id
11 Maya 10
12 Liam 20
14 Noah NULL
15 Elena 10
18 Zoe 20

assignments

id teacher_id
101 10
102 20

grades

student_id assignment_id grade
11 101 88.0
11 102 76.0
12 101 95.0
12 102 90.0
14 101 85.0
14 102 89.0
15 101 62.0
15 102 54.0

Output:

student_id name avg_score rnk
12 Liam 92.5 1
14 Noah 87.0 2

Explanation:

Zoe (id = 18) has no completed grades, so only N = 4 students are graded: Liam (92.5), Noah (87.0, included despite primary_teacher_id = NULL), Maya (82.0), and Elena (58.0). Keeping the top CEIL(4 / 2) = 2 returns Liam (rnk = 1) and Noah (rnk = 2).

Example 2

Input:

teachers

id name classroom
10 Ms. Patel 104

students

id name primary_teacher_id
21 Aria 10
24 Caleb 10
29 Owen 10

assignments

id teacher_id
101 10
102 10

grades

student_id assignment_id grade
29 101 91.0
29 102 NULL
21 101 78.0
21 102 82.0
24 101 80.0

Output:

student_id name avg_score rnk
29 Owen 91.0 1
21 Aria 80.0 2

Explanation:

Owen's NULL entry on assignment 102 is ignored, leaving his average at 91.0. With N = 3 graded students, the cutoff is CEIL(3 / 2) = 2. Aria (id = 21) and Caleb (id = 24) tie at 80.0, and student_id ASC awards the second spot to Aria.

Constraints

  • (student_id, assignment_id) is unique in grades.
  • Non-NULL grade values lie between 0.0 and 100.0.
  • students.primary_teacher_id and grades.grade may be NULL.
  • If no non-NULL grades exist (N = 0), return zero rows.
  • Output rows may appear in any order.

Step-by-step walkthrough

  1. Restate the leaderboard rules

    Using students(id, name, primary_teacher_id) and grades(student_id, assignment_id, grade), we must return one row per selected student (in any row order) with four columns:

    student_id, name, avg_score (rounded to 1 decimal), rnk
    

    Let's line up all five rules before writing a single clause:

    1. Compute each student's mean score across their completed (grade IS NOT NULL) assignments.
    2. Exclude students with zero completed assignments — both from the output and from the student count N.
    3. Let N be the number of students with at least one completed grade. Keep only the top CEIL(N / 2) students ordered by exact average descending, breaking ties by student_id ASC.
    4. Compute rnk as DENSE_RANK() over the selected students ordered by exact average descending, student_id ASC, and round avg_score to 1 decimal place. (Because student_id is unique and included in the DENSE_RANK order key, every row gets a distinct rank 1, 2, ..., k; see the explanation for the one-line variant if equal averages should share a rank.)
    5. Never hard-code N or a fixed LIMIT — the query must adapt automatically as students and grades are added.

    Notice also what not to join: teachers and assignments hold no columns needed by the output, and an INNER JOIN to teachers on primary_teacher_id would silently drop student 14 (Noah in Example 1), whose primary_teacher_id is NULL!

  2. Compute each student's exact average over completed grades

    We start from grades, join students to look up name, filter out missing grades with WHERE g.grade IS NOT NULL, and group by student in a Common Table Expression (CTE — a named temporary subquery written with WITH):

    • Starting from grades with WHERE g.grade IS NOT NULL guarantees that enrolled students with zero rows in grades (like Zoe, id = 18, in Example 1) — or only NULL grades — never enter student_avg, so they cannot inflate N.
    • We keep avg_grade unrounded here so we rank students by their true average rather than creating artificial ties from early rounding.
    -- Step 1: Compute exact average grade per student with at least one non-NULL grade.
    -- Avoid joining teachers/assignments so students with NULL primary_teacher_id stay included.
    WITH student_avg AS (
        SELECT
            s.id AS student_id,
            s.name,
            AVG(g.grade) AS avg_grade
        FROM grades AS g
        JOIN students AS s
            ON s.id = g.student_id
        WHERE g.grade IS NOT NULL
        GROUP BY s.id, s.name
    ),
    
  3. Number graded students and count `N` in one pass

    Next, we attach two window functions to every row of student_avg without collapsing the rows:

    • ROW_NUMBER() OVER (ORDER BY avg_grade DESC, student_id ASC) AS rn assigns positions 1, 2, ..., N from highest average to lowest. Including student_id ASC breaks ties deterministically (as between Aria id = 21 and Caleb id = 24 in Example 2); using RANK() on avg_grade alone could let two tied students at the boundary both pass the cutoff and return more than CEIL(N / 2) rows.
    • COUNT(*) OVER () AS n counts the total rows in student_avg (the empty OVER () window spans the entire table) and places N right alongside rn on every row.
    student_avg + window columns on Example 1 (Zoe id=18 excluded before this stage):
    student_id  name   avg_grade  rn  n
    12          Liam    92.5      1   4
    14          Noah    87.0      2   4   <-- primary_teacher_id is NULL, still counted and ranked #2!
    11          Maya    82.0      3   4
    15          Elena   58.0      4   4
    
    -- Step 2: Rank graded students best-first (breaking ties by student_id) and count N in one pass.
    ordered AS (
        SELECT
            student_id,
            name,
            avg_grade,
            ROW_NUMBER() OVER (ORDER BY avg_grade DESC, student_id ASC) AS rn,
            COUNT(*) OVER () AS n
        FROM student_avg
    ),
    
  4. Keep the top `CEIL(N / 2)` across SQL dialects

    SQL evaluates WHERE before window functions, so we filter rn in the next CTE top_half. Writing the CEIL(n / 2) cutoff requires care because / behaves differently across databases:

    • In SQLite and PostgreSQL, dividing two integers truncates the fraction before CEIL sees it, so CEIL(5 / 2) becomes CEIL(2) = 2 instead of 3!
    • Using (n + 1) / 2 works cleanly for every positive integer n whether / is integer division (SQLite, PostgreSQL) or decimal division (MySQL 8.0), because rn itself is always a whole number:
    Graded count n   Target CEIL(n/2)   SQLite int (n+1)/2   MySQL decimal (n+1)/2   Whole rn <= (n+1)/2
    n = 3 (odd)      2                  4 / 2 = 2            4 / 2 = 2.0             rn in {1, 2}  (2 rows)
    n = 4 (even)     2                  5 / 2 = 2            5 / 2 = 2.5             rn in {1, 2}  (2 rows)
    n = 5 (odd)      3                  6 / 2 = 3            6 / 2 = 3.0             rn in {1,2,3} (3 rows)
    
    -- Step 3: Keep the top CEIL(n / 2) students; (n + 1) / 2 equals CEIL(n / 2) for positive integers.
    top_half AS (
        SELECT
            student_id,
            name,
            avg_grade
        FROM ordered
        WHERE rn <= (n + 1) / 2
    )
    
  5. Round for display, assign `DENSE_RANK`, and trace Example 1

    In the outer SELECT, we round avg_grade to 1 decimal place as avg_score and compute DENSE_RANK() OVER (ORDER BY avg_grade DESC, student_id ASC) AS rnk over the top_half rows.

    Tracing Example 1 from start to finish:

    1. student_avg (Zoe id=18 has no grades and is excluded):
       Liam  (id=12): (95 + 90) / 2 = 92.5
       Noah  (id=14): (85 + 89) / 2 = 87.0
       Maya  (id=11): (88 + 76) / 2 = 82.0
       Elena (id=15): (62 + 54) / 2 = 58.0
    
    2. ordered: N = 4 graded students -> cutoff (4 + 1) / 2 = 2 -> keep rn <= 2.
    
    3. Final output:
       student_id  name  avg_score  rnk
       12          Liam  92.5       1
       14          Noah  87.0       2
    
  6. Complete query

    Putting all four stages together gives the complete single-statement query:

    -- Step 1: Compute exact average grade per student with at least one non-NULL grade.
    -- Avoid joining teachers/assignments so students with NULL primary_teacher_id stay included.
    WITH student_avg AS (
        SELECT
            s.id AS student_id,
            s.name,
            AVG(g.grade) AS avg_grade
        FROM grades AS g
        JOIN students AS s
            ON s.id = g.student_id
        WHERE g.grade IS NOT NULL
        GROUP BY s.id, s.name
    ),
    -- Step 2: Rank graded students best-first (breaking ties by student_id) and count N in one pass.
    ordered AS (
        SELECT
            student_id,
            name,
            avg_grade,
            ROW_NUMBER() OVER (ORDER BY avg_grade DESC, student_id ASC) AS rn,
            COUNT(*) OVER () AS n
        FROM student_avg
    ),
    -- Step 3: Keep the top CEIL(n / 2) students; (n + 1) / 2 equals CEIL(n / 2) for positive integers.
    top_half AS (
        SELECT
            student_id,
            name,
            avg_grade
        FROM ordered
        WHERE rn <= (n + 1) / 2
    )
    -- Step 4: Round average to 1 decimal for display and assign dense rank over the kept students.
    SELECT
        student_id,
        name,
        ROUND(avg_grade, 1) AS avg_score,
        DENSE_RANK() OVER (ORDER BY avg_grade DESC, student_id ASC) AS rnk
    FROM top_half
    

    ✅ Submit now — all tests should pass.

Intuition & how it works

Imagine lining up only the students who have turned in at least one graded assignment, sorted from highest GPA to lowest (using student ID badge numbers so ties have a fixed order). Once everyone is in line, you count how many students are standing there (N), divide N in half rounding up (CEIL(N / 2)), and invite that front half of the line onto the honor roll.

A naive query tries to use a fixed LIMIT 2 or counts N from the students table. Hard-coding LIMIT 2 fails as soon as new students are graded (and MySQL 8.0 does not allow calculated expressions inside LIMIT), while counting N from students includes enrolled students who have zero grades (like Zoe in Example 1) and inflates the cutoff. Worse, inner-joining teachers on primary_teacher_id silently drops valid students like Noah (primary_teacher_id = NULL), shrinking N and changing who makes the cut.

Instead, we chain three Common Table Expressions (CTEs) — named temporary query steps written with WITH — and window functions (calculations across rows that attach rankings or totals to each row without collapsing them):

  1. In student_avg, we aggregate grades (WHERE grade IS NOT NULL) joined only to students. On Example 1, Liam (92.5), Noah (87.0), Maya (82.0), and Elena (58.0) produce 4 rows while ungraded Zoe is excluded.
  2. In ordered, ROW_NUMBER (a window function that assigns sequential integers 1, 2, 3, ... with no duplicates) numbers them 1 through 4 by (avg_grade DESC, student_id ASC), while COUNT(*) OVER () tags every row with n = 4.
  3. In top_half and the outer SELECT, WHERE rn <= (n + 1) / 2 keeps rows 1 and 2, rounds avg_grade to 1 decimal place, and applies DENSE_RANK (a ranking function that assigns consecutive rank numbers without gaps) to output (12, 'Liam', 92.5, 1) and (14, 'Noah', 87.0, 2).

Complexity

Let G be the total number of rows in grades and S be the number of students who have at least one non-NULL grade (S <= G).

  • Time: Scanning grades, filtering out NULLs, looking up students.name by primary key, and grouping into per-student averages takes O(G) expected time with hash aggregation (or O(G log G) with sort-based grouping). Sorting the S student averages for ROW_NUMBER takes O(S log S) time, and ranking the final CEIL(S / 2) rows takes O(S log S) time — giving O(G + S log S) overall.
  • Space: O(S) memory to hold one summary row per graded student during the window sort.

Database indexes: In MySQL 8.0 (InnoDB), a table's primary key is a clustered index (the table rows themselves are stored on disk sorted by the primary key), so PK(student_id, assignment_id) on grades already stores all of a student's grades contiguously and lets the engine stream per-student averages without an extra sort or hash table. In PostgreSQL, adding a covering index on grades(student_id, grade) achieves the same index-only streaming scan.

Edge cases

  • Students with zero grades or only NULL grades: Excluded by joining from grades with WHERE g.grade IS NOT NULL, so they neither appear in the output nor inflate N (such as Zoe in Example 1).
  • Mix of NULL and non-NULL grades for one student: NULL grades are ignored rather than treated as 0, so Owen's (91.0, NULL) in Example 2 averages 91.0, not 45.5.
  • Odd number of graded students (N is odd): (n + 1) / 2 rounds up cleanly (N = 3 keeps 2 students in Example 2; N = 5 keeps 3; N = 1 keeps 1).
  • Exact average tie at the CEIL(N / 2) boundary: ORDER BY avg_grade DESC, student_id ASC inside ROW_NUMBER() awards the final slot deterministically to the smaller student_id (Aria id = 21 ahead of Caleb id = 24 in Example 2).
  • Student with primary_teacher_id IS NULL: Kept and counted in N (like Noah in Example 1) because we never join teachers.
  • Empty grades table: student_avg is empty (N = 0), and the query cleanly returns zero rows.

Common mistakes

  • Counting N from students instead of graded students: In Example 1, 5 students exist in students while only 4 have grades, so CEIL(5 / 2) = 3 would wrongly return 3 students instead of CEIL(4 / 2) = 2.
  • Writing CEIL(n / 2) in integer-division dialects: In SQLite and PostgreSQL, 5 / 2 evaluates to integer 2 before CEIL runs, keeping 2 rows instead of 3. Writing (n + 1) / 2 (or CEIL(n / 2.0)) avoids this trap.
  • Hard-coding LIMIT 2: Fails as soon as more students are added, and dynamic expressions inside LIMIT fail with a syntax error in MySQL 8.0.
  • Filtering on RANK() without a unique tie-breaker: Two students tied at rank 2 when CEIL(N / 2) = 2 would both satisfy rnk <= 2 and return 3 rows instead of 2.
  • Putting a window function directly inside WHERE: SQL evaluates WHERE before window functions, so WHERE ROW_NUMBER() OVER (...) <= ... is invalid syntax; filter in a subsequent CTE or outer query.
  • Inner-joining teachers or assignments: Unnecessary joins drop students with primary_teacher_id IS NULL (such as Noah).

Follow-up questions

  • What if students tied on average score within the selected top half should receive the same dense rank? Keep ROW_NUMBER() OVER (ORDER BY avg_grade DESC, student_id ASC) inside ordered so the top-half headcount cutoff CEIL(N / 2) remains exact and deterministic, and omit student_id ASC from the outer DENSE_RANK() window. Because the problem specification includes student_id ASC inside the DENSE_RANK order key, every selected row receives a unique rank 1, 2, ...; asking the interviewer whether student_id ASC should break ties only for selection/display order or also inside DENSE_RANK demonstrates careful spec reading.
SELECT
    student_id,
    name,
    ROUND(avg_grade, 1) AS avg_score,
    DENSE_RANK() OVER (ORDER BY avg_grade DESC) AS rnk
FROM top_half;
  • Should you order the ranking window by each student's exact average or by the one-decimal rounded score? Ordering by exact avg_grade (and rounding only in the final projection) places a student averaging 85.04 ahead of one averaging 84.96 even though both display 85.0, which matches standard academic GPA practice. If stakeholders prefer displayed scores and ranks never to appear out of order on ties caused by display rounding, order the window by ROUND(avg_grade, 1) DESC, student_id ASC instead — and state that choice explicitly.

  • How would you implement a companion data-cleaning pipeline in R (tidyverse) to impute missing billing fields and compute customer activity and churn averages? Chain transformations in order inside filter() and mutate() so each step sees the cleaned columns from prior steps: drop missing account IDs first, replace NA billing amounts with 0 via coalesce(), reclassify NA churn flags to 0L whenever billing > 0, clamp negative last_seen - joined_on day spans to 0 with pmax(), and guard subsetting with !is.na(churned) & churned == 1L so remaining NA flags never contaminate mean().

library(dplyr)
library(readr)

accounts_clean <- read_csv("accounts.csv", na = c("", "NA", "NULL")) %>%
  filter(!is.na(account_id)) %>%
  mutate(
    billing = coalesce(billing, 0),
    churned = if_else(is.na(churned) & billing > 0, 0L, churned),
    tenure_days = pmax(as.numeric(last_seen - joined_on), 0),
    churn_on = if_else(churned == 1L, last_seen, as.Date(NA))
  )

accounts_clean %>%
  summarise(
    mean_tenure_days = round(mean(tenure_days), 2),
    mean_churned_billing = round(mean(billing[!is.na(churned) & churned == 1L]), 2)
  )

Follow-up questions

Similar questions

More Flatiron Health interview questions

All 3 Flatiron Health questions →