Subjects Taught By Each Teacher
Count the distinct subjects each teacher teaches.
Start practiceProblem statement
Prompt
Given the teacher table below, write a query that returns, for each teacher, the number of distinct subjects they teach.
- Output columns:
teacher_idandcnt, ordered byteacher_id. - The table may contain duplicate (teacher, subject) rows — those count once.
Example
| teacher_id | subject_id | dept_id |
|---|---|---|
| 1 | 2 | 3 |
| 1 | 2 | 4 |
| 1 | 3 | 3 |
| 2 | 1 | 1 |
Expected result:
| teacher_id | cnt |
|---|---|
| 1 | 2 |
| 2 | 1 |
Constraints
- There is no primary key; the same (teacher_id, subject_id) can repeat.
Tips
COUNT(DISTINCT subject_id)grouped byteacher_idhandles the duplicates for you.
Schema
CREATE TABLE teacher (
teacher_id INTEGER NOT NULL,
subject_id INTEGER NOT NULL,
dept_id INTEGER NOT NULL
);
Sample data
INSERT INTO teacher (teacher_id, subject_id, dept_id) VALUES
(1, 2, 3),
(1, 2, 4),
(1, 3, 3),
(2, 1, 1),
(2, 2, 1),
(2, 3, 1);
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: distinct subjects per teacher.
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM teacher
GROUP BY teacher_id
ORDER BY teacher_id;
Key concepts
- COUNT(DISTINCT)
- GROUP BY
Related questions
- easyActive Users Per DayReport the number of distinct active users for each date of activity.
- mediumUsers With the Most FriendsFind the user(s) with the largest number of friends.
- easyAverage Process Time Per MachineCompute each machine's average time to complete a process.
- easyClasses With At Least 5 StudentsFind classes with five or more students enrolled.
- mediumConsecutive Login DaysFind users who logged in on three or more consecutive calendar days.