Classes With at Least 5 Students - Problem

You are given a table Courses that contains information about student enrollments in various classes.

Table: Courses

Column NameType
studentvarchar
classvarchar

The combination of (student, class) is the primary key for this table. Each row indicates the name of a student and the class in which they are enrolled.

Task: Write a SQL solution to find all the classes that have at least five students. Return the result table in any order.

Table Schema

Courses
Column Name Type Description
student PK varchar Name of the student
class PK varchar Name of the class the student is enrolled in
Primary Key: (student, class)
Note: Each row represents a unique student-class enrollment pair

Input & Output

Example 1 — Basic Class Count
Input Table:
student class
A Math
B English
C Math
D Biology
E Math
F Computer
G Math
H Math
I Math
Output:
class
Math
💡 Note:

Math has 6 students (A, C, E, G, H, I) which is ≥ 5, so it's included. English has 1 student, Biology has 1 student, and Computer has 1 student, all less than 5.

Example 2 — Multiple Qualifying Classes
Input Table:
student class
Alice Math
Bob Math
Charlie Math
David Math
Eve Math
Frank English
Grace English
Henry English
Iris English
Jack English
Output:
class
English
Math
💡 Note:

Both Math and English have exactly 5 students each, so both classes are returned in the result.

Example 3 — No Qualifying Classes
Input Table:
student class
Student1 Physics
Student2 Chemistry
Student3 Physics
Student4 Biology
Output:
class
💡 Note:

Physics has 2 students, Chemistry has 1 student, and Biology has 1 student. No class has at least 5 students, so the result is empty.

Constraints

  • 1 ≤ number of students ≤ 1000
  • 1 ≤ number of classes ≤ 1000
  • student and class are non-empty strings

Visualization

Tap to expand
Classes With At Least 5 StudentsInput: Courses TablestudentclassAMathBMathCMathDMathEMathFMathGEnglishHBiologyGROUP BY classMath: COUNT(*) = 6English: COUNT(*) = 1Biology: COUNT(*) = 1HAVINGCOUNT(*) >= 5OutputclassMath
Understanding the Visualization
1
Input
Student-class enrollment pairs
2
GROUP BY
Group by class and count students
3
HAVING
Filter classes with count >= 5
Key Takeaway
🎯 Key Insight: Use GROUP BY to aggregate data and HAVING to filter aggregated results
Asked in
Amazon 23 Microsoft 18 Google 15
23.5K Views
High Frequency
~8 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen