Classes With At Least 5 Students
Find classes with five or more students enrolled.
Start practiceProblem statement
Prompt
Given the courses table below (one row per student enrollment), write a query that returns the class of every class with at least five students.
- Output a single column:
class. - The order of the result does not matter.
- Each row is one enrollment; count rows per class.
Example
| student | class |
|---|---|
| A | Math |
| B | Math |
| C | Math |
| D | Math |
| E | Math |
| F | English |
Expected result:
| class |
|---|
| Math |
Constraints
- There is no primary key; a student may have duplicate rows for the same class.
Tips
GROUP BY classthenHAVING COUNT(*) >= 5.
Schema
CREATE TABLE courses (
student TEXT NOT NULL,
class TEXT NOT NULL
);
Sample data
INSERT INTO courses (student, class) VALUES
('A', 'Math'),
('B', 'Math'),
('C', 'Math'),
('D', 'Math'),
('E', 'Math'),
('F', 'Math'),
('A', 'English'),
('B', 'English'),
('C', 'English'),
('D', 'English');
Additional hidden fixtures are applied during validation to test edge cases.
Solution
One correct approach — try solving it yourself in the practice editor first, then compare. There is usually more than one valid solution.
-- Reference: classes with at least five enrollments.
SELECT class
FROM courses
GROUP BY class
HAVING COUNT(*) >= 5
ORDER BY class;
Key concepts
- GROUP BY
- HAVING
- COUNT
Related questions
- mediumCustomers Who Bought All ProductsFind customers who have purchased every product in the catalogue.
- mediumDepartments by Average SalaryFind departments whose average salary is above the company average.
- easyDuplicate EmailsList the email addresses that appear more than once in the person table.
- easyActive Users Per DayReport the number of distinct active users for each date of activity.
- mediumMonthly Sales RankingRank salespeople by their monthly sales, including ties, and handle months with no sales.