The Number of Unique Subjects Taught by Each Teacher SQL problem asks you to count how many distinct subjects each teacher teaches. Each row in the Teacher table has (teacher_id, subject_id, dept_id), and a teacher may teach the same subject in multiple departments. Count DISTINCT subjects per teacher. This is a straightforward GROUP BY with COUNT DISTINCT.
Microsoft, Capgemini, Amazon, Google, and Bloomberg ask this easy SQL problem to verify that candidates know to use COUNT(DISTINCT column) rather than COUNT(*) when rows can be duplicated. The database interview pattern is demonstrated at its simplest with a key DISTINCT nuance.
GROUP BY + COUNT DISTINCT.
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM Teacher
GROUP BY teacher_id
Teacher table: (1, Math, A), (1, Math, B), (1, Physics, A), (2, Biology, A).
COUNT(DISTINCT column) vs COUNT(*) is one of the most common SQL mistakes. Always ask: "can the same value appear multiple times in this column?" If yes, use DISTINCT. This pattern appears in: "count distinct customers," "count unique products ordered," "count unique skills per employee." Memorize the template: SELECT key, COUNT(DISTINCT value) AS cnt FROM table GROUP BY key. It solves a large fraction of easy-to-medium SQL interview questions.
| Title | Difficulty | Topics | LeetCode |
|---|---|---|---|
| Patients With a Condition | Easy | Solve | |
| Fix Names in a Table | Easy | Solve | |
| Not Boring Movies | Easy | Solve | |
| Primary Department for Each Employee | Easy | Solve | |
| Queries Quality and Percentage | Easy | Solve |