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
gradeswheregrade IS NOT NULL. Students who have not yet been assigned aprimary_teacher_id(NULL) are still eligible and must be included if they have completed grades. - Exclude ungraded students: Omit any student with zero non-
NULLgrades from both the output and the headcountN. - Top-half cutoff (
CEIL(N / 2)): LetNbe the number of students who have at least one non-NULLgrade. Keep only the topCEIL(N / 2)students ordered by exact unrounded average score descending, breaking ties bystudent_idascending. - Display rounding and rank: Output
student_id,name,avg_score(the student's mean score rounded to1decimal place), andrnk, defined asDENSE_RANK()across the selected students ordered by exact average score descending,student_idascending. - Dynamic sizing: Do not hard-code
Nor 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 ingrades.- Non-
NULLgradevalues lie between0.0and100.0. students.primary_teacher_idandgrades.grademay beNULL.- If no non-
NULLgrades exist (N = 0), return zero rows. - Output rows may appear in any order.
Step-by-step walkthrough
Restate the leaderboard rules
Using
students(id, name, primary_teacher_id)andgrades(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), rnkLet's line up all five rules before writing a single clause:
- Compute each student's mean score across their completed (
grade IS NOT NULL) assignments. - Exclude students with zero completed assignments — both from the output and from the student count
N. - Let
Nbe the number of students with at least one completed grade. Keep only the topCEIL(N / 2)students ordered by exact average descending, breaking ties bystudent_id ASC. - Compute
rnkasDENSE_RANK()over the selected students ordered by exact average descending,student_id ASC, and roundavg_scoreto 1 decimal place. (Becausestudent_idis unique and included in theDENSE_RANKorder key, every row gets a distinct rank1, 2, ..., k; see the explanation for the one-line variant if equal averages should share a rank.) - Never hard-code
Nor a fixedLIMIT— the query must adapt automatically as students and grades are added.
Notice also what not to join:
teachersandassignmentshold no columns needed by the output, and anINNER JOINtoteachersonprimary_teacher_idwould silently drop student14(Noahin Example 1), whoseprimary_teacher_idisNULL!- Compute each student's mean score across their completed (
Compute each student's exact average over completed grades
We start from
grades, joinstudentsto look upname, filter out missing grades withWHERE g.grade IS NOT NULL, and group by student in a Common Table Expression (CTE — a named temporary subquery written withWITH):- Starting from
gradeswithWHERE g.grade IS NOT NULLguarantees that enrolled students with zero rows ingrades(like Zoe,id = 18, in Example 1) — or onlyNULLgrades — never enterstudent_avg, so they cannot inflateN. - We keep
avg_gradeunrounded 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 ),- Starting from
Number graded students and count `N` in one pass
Next, we attach two window functions to every row of
student_avgwithout collapsing the rows:ROW_NUMBER() OVER (ORDER BY avg_grade DESC, student_id ASC) AS rnassigns positions1, 2, ..., Nfrom highest average to lowest. Includingstudent_id ASCbreaks ties deterministically (as between Ariaid = 21and Calebid = 24in Example 2); usingRANK()onavg_gradealone could let two tied students at the boundary both pass the cutoff and return more thanCEIL(N / 2)rows.COUNT(*) OVER () AS ncounts the total rows instudent_avg(the emptyOVER ()window spans the entire table) and placesNright alongsidernon 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 ),Keep the top `CEIL(N / 2)` across SQL dialects
SQL evaluates
WHEREbefore window functions, so we filterrnin the next CTEtop_half. Writing theCEIL(n / 2)cutoff requires care because/behaves differently across databases:- In SQLite and PostgreSQL, dividing two integers truncates the fraction before
CEILsees it, soCEIL(5 / 2)becomesCEIL(2) = 2instead of3! - Using
(n + 1) / 2works cleanly for every positive integernwhether/is integer division (SQLite, PostgreSQL) or decimal division (MySQL 8.0), becausernitself 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 )- In SQLite and PostgreSQL, dividing two integers truncates the fraction before
Round for display, assign `DENSE_RANK`, and trace Example 1
In the outer
SELECT, we roundavg_gradeto 1 decimal place asavg_scoreand computeDENSE_RANK() OVER (ORDER BY avg_grade DESC, student_id ASC) AS rnkover thetop_halfrows.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 2Complete 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):
- In
student_avg, we aggregategrades(WHERE grade IS NOT NULL) joined only tostudents. On Example 1, Liam (92.5), Noah (87.0), Maya (82.0), and Elena (58.0) produce 4 rows while ungraded Zoe is excluded. - In
ordered,ROW_NUMBER(a window function that assigns sequential integers1, 2, 3, ...with no duplicates) numbers them1through4by(avg_grade DESC, student_id ASC), whileCOUNT(*) OVER ()tags every row withn = 4. - In
top_halfand the outerSELECT,WHERE rn <= (n + 1) / 2keeps rows1and2, roundsavg_gradeto 1 decimal place, and appliesDENSE_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 outNULLs, looking upstudents.nameby primary key, and grouping into per-student averages takesO(G)expected time with hash aggregation (orO(G log G)with sort-based grouping). Sorting theSstudent averages forROW_NUMBERtakesO(S log S)time, and ranking the finalCEIL(S / 2)rows takesO(S log S)time — givingO(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
NULLgrades: Excluded by joining fromgradeswithWHERE g.grade IS NOT NULL, so they neither appear in the output nor inflateN(such as Zoe in Example 1). - Mix of
NULLand non-NULLgrades for one student:NULLgrades are ignored rather than treated as0, so Owen's(91.0, NULL)in Example 2 averages91.0, not45.5. - Odd number of graded students (
Nis odd):(n + 1) / 2rounds up cleanly (N = 3keeps2students in Example 2;N = 5keeps3;N = 1keeps1). - Exact average tie at the
CEIL(N / 2)boundary:ORDER BY avg_grade DESC, student_id ASCinsideROW_NUMBER()awards the final slot deterministically to the smallerstudent_id(Ariaid = 21ahead of Calebid = 24in Example 2). - Student with
primary_teacher_id IS NULL: Kept and counted inN(like Noah in Example 1) because we never jointeachers. - Empty
gradestable:student_avgis empty (N = 0), and the query cleanly returns zero rows.
Common mistakes
- Counting
Nfromstudentsinstead of graded students: In Example 1, 5 students exist instudentswhile only 4 have grades, soCEIL(5 / 2) = 3would wrongly return 3 students instead ofCEIL(4 / 2) = 2. - Writing
CEIL(n / 2)in integer-division dialects: In SQLite and PostgreSQL,5 / 2evaluates to integer2beforeCEILruns, keeping 2 rows instead of 3. Writing(n + 1) / 2(orCEIL(n / 2.0)) avoids this trap. - Hard-coding
LIMIT 2: Fails as soon as more students are added, and dynamic expressions insideLIMITfail with a syntax error in MySQL 8.0. - Filtering on
RANK()without a unique tie-breaker: Two students tied at rank 2 whenCEIL(N / 2) = 2would both satisfyrnk <= 2and return 3 rows instead of 2. - Putting a window function directly inside
WHERE: SQL evaluatesWHEREbefore window functions, soWHERE ROW_NUMBER() OVER (...) <= ...is invalid syntax; filter in a subsequent CTE or outer query. - Inner-joining
teachersorassignments: Unnecessary joins drop students withprimary_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)insideorderedso the top-half headcount cutoffCEIL(N / 2)remains exact and deterministic, and omitstudent_id ASCfrom the outerDENSE_RANK()window. Because the problem specification includesstudent_id ASCinside theDENSE_RANKorder key, every selected row receives a unique rank1, 2, ...; asking the interviewer whetherstudent_id ASCshould break ties only for selection/display order or also insideDENSE_RANKdemonstrates 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 averaging85.04ahead of one averaging84.96even though both display85.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 byROUND(avg_grade, 1) DESC, student_id ASCinstead — 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()andmutate()so each step sees the cleaned columns from prior steps: drop missing account IDs first, replaceNAbilling amounts with0viacoalesce(), reclassifyNAchurn flags to0Lwheneverbilling > 0, clamp negativelast_seen - joined_onday spans to0withpmax(), and guard subsetting with!is.na(churned) & churned == 1Lso remainingNAflags never contaminatemean().
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
- What if students tied on average score within the selected top half should receive the same dense rank?
- Should you order the ranking window by each student's exact average or by the one-decimal rounded score?
- How would you implement a companion data-cleaning pipeline in R (tidyverse) to impute missing billing fields and compute customer activity and churn averages?
Similar questions
- Consecutive Activity Streaks with Window Functions
- Designing a Leak-Free Churn ML Pipeline and Rollout Plan
- Job Posting Engagement Metrics Excluding Non-Viewing Applicants
- Compute 7-Day DAU, D1 Retention, and Revenue Cohorts
- Class-Level 2024 Exam Summary with Zero-Filled Averages
- Summarizing Imaging Claims Spend and Fiscal Months