SQL: Students Above Average and Passing Every Subject
ByteDanceBackend Engineer · Technical ScreenLast updated
This problem tests advanced SQL skills, including the use of window functions, conditional aggregation, and multi-level filtering to identify subsets of data that satisfy both global and per-category criteria.
Problem Statement
You are working with a database containing student performance records. Your goal is to identify students who meet two specific criteria: they must have passed every subject they are enrolled in, and their overall average grade across all subjects must be strictly higher than the global average grade of all students.
Database Schema
Table: grades
| Column Name | Type | Description |
|---|---|---|
| student_id | int | Unique ID of the student |
| subject | varchar | Name of the subject |
| score | int | Numeric grade (0-100) |
Assume a passing grade is defined as score >= 60.
Task
Write a SQL query to return the student_id of students who:
- Scored at least 60 in every subject they have taken.
- Have an overall GPA (average of all their scores) strictly greater than the global average GPA of all students in the database.
Example
Input:
| student_id | subject | score |
|---|---|---|
| 1 | Math | 80 |
| 1 | Science | 90 |
| 2 | Math | 50 |
| 2 | Science | 90 |
| 3 | Math | 70 |
| 3 | Science | 70 |
Output:
| student_id |
|---|
| 1 |
Explanation:
- Student 1: Average is 85. Passed all. Global avg is 75. 85 > 75. Included.
- Student 2: Failed Math. Excluded.
- Student 3: Average is 70. Passed all, but 70 is not greater than the global average of 75. Excluded.
Constraints
student_idis the primary key for the table rows.- Return the result set ordered by
student_idascending.
Hints
Hint 1
Use a subquery or a Common Table Expression (CTE) to calculate the global average grade across all records first.
Hint 2
Use 'GROUP BY student_id' and 'HAVING' to filter out students who have any score less than 60.
Hint 3
Calculate the individual student's average within the same grouping and compare it against the global average calculated in the first hint.
Follow-up questions
- How would you modify this query if the passing grade requirement varied by subject (e.g., Math requires 60, but Science requires 70)?
- If the 'grades' table contains millions of rows, what indexes would you add to optimize the execution speed of this query?
- How would you handle cases where a student has no grades recorded yet? Should they be included or excluded?
Solution walkthrough is for members
Get the full walkthrough with reference code and complexity analysis, plus Kitty Coach at 300 messages a day. Hints, the code runner and community answers stay free.