MySQL 2356.sql
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM Teacher
GROUP BY teacher_id
Difficulty
and has an acceptance rate of about 89% (600k+ submissions).
Typical patterns to solve this problem:
- Database
AI Disclaimer
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.
See this dedicated page for more details.
Code Walkthrough
Overview
The provided SQL statement extracts, for each teacher, the number of unique subjects they are associated with. It aggregates rows from the Teacher table, groups them by teacher_id, and counts distinct subject_id values within each group. The result set contains two columns: the identifier of the teacher and the count of different subjects taught.
SELECT teacher_id, COUNT(DISTINCT subject_id) AS cnt
FROM Teacher
GROUP BY teacher_id
Key Steps
Selecting Columns
The query begins by selecting teacher_id, which serves as the grouping key, and an aggregate expression COUNT(DISTINCT subject_id). The alias cnt gives a readable name to the computed count.
Aggregation
COUNT(DISTINCT subject_id) tallies only unique subject_id values for each teacher. If a teacher appears multiple times with the same subject, those repetitions are ignored, ensuring the count reflects distinct subjects rather than total rows.
Grouping
GROUP BY teacher_id partitions the rows of the Teacher table into subsets, each containing all rows that share the same teacher_id. The aggregate function is then applied to each subset independently, producing one output row per teacher.
Edge Cases Handled
When a teacher has no associated rows in the Teacher table, the query naturally excludes that teacher from the result because there is no row to group. If a teacher appears but all subject_id values are NULL, the COUNT(DISTINCT ...) treats NULL as non-existent, yielding a count of zero for that teacher. Duplicate subject entries for a teacher are collapsed by the DISTINCT qualifier, preventing over-counting. The query also gracefully handles the situation where the Teacher table contains a single row per teacher, returning a count of one for each non-null subject.
Performance Optimizations Observed
The execution plan for this pattern typically benefits from indexes on the grouping and distinct columns. An index on (teacher_id, subject_id) provides a covering path: the database can read the index entries directly, satisfying both the grouping key and the distinct subject values without touching the base table. This reduces I/O and speeds up the hash or sort aggregation used to compute the distinct counts.
If the underlying engine supports index-only aggregation, the COUNT(DISTINCT ...) can be performed directly on the index, avoiding a separate distinct-value sort step. The presence of a composite index also enables the optimizer to use a “group by” shortcut where the rows are already ordered by teacher_id, allowing a streaming aggregation that processes rows sequentially without additional sorting.
When the table is large, the database may choose a hash aggregation strategy, building an in-memory hash table keyed by teacher_id and maintaining a set of distinct subject_id values per key. The hash table size is limited by available memory, and the engine may spill to disk if necessary, but the composite index helps keep the hash table small by providing pre-filtered, ordered input.
Overall, the query leverages standard SQL aggregation mechanisms and can achieve efficient execution when appropriate indexes are present, especially a composite index covering both grouping and distinct columns.
ELI5 - Simplified Explanation
Imagine a big classroom filled with teachers and all the different subjects they teach. This code acts like a helper who looks at a list of names and activities. The helper goes through the whole list and gathers every teacher who shares a name. Since one teacher might teach the same subject to different classes, the helper carefully counts only the unique subjects for each person. Once the counting is done, the helper makes a neat little chart that shows exactly how many different subjects each teacher is in charge of. It is just like organizing a pile of colorful blocks and counting how many different colors you have.
Code Quality
Complexity Analysis
Other Solutions
Obviously, I did that after I solved the problem myself.
In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.
And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.
(click on a column header to sort the table)
| author | ||||||
|---|---|---|---|---|---|---|
| author | solutions | |||||
| www | AlgoMonster | C++ | Java | Python | TS | |
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| Progiez | C++ | Java | Python | |||
| github | muhammadfarhankt | SQL | ||||
| AlgoMonster | C++, Python, Java, TypeScript | |||||
| WalkCCC | SQL | |||||
| leetcode.ca | SQL | |||||
| Progiez | C++, Java, Python | |||||
| muhammadfarhankt | SQL |
Videos
Solved On The Same Day
- problem 415: Add Strings
- problem 463: Island Perimeter
- problem 541: Reverse String II
- problem 1211: Queries Quality and Percentage
- problem 1251: Average Selling Price
- problem 1280: Students and Examinations
- problem 1327: List the Products Ordered in a Period
- problem 1378: Replace Employee ID With The Unique Identifier
- problem 1407: Top Travellers
- problem 1484: Group Sold Products By The Date
- problem 1517: Find Users With Valid E-Mails
- problem 1527: Patients With a Condition
- problem 1581: Customer Who Visited but Did Not Make Any Transactions
- problem 1587: Bank Account Summary II
- problem 1633: Percentage of Users Attended a Contest
- problem 1661: Average Time of Process per Machine
- problem 1667: Fix Names in a Table
- problem 1683: Invalid Tweets
- problem 1693: Daily Leads and Partners
- problem 1729: Find Followers Count
- problem 1731: The Number of Employees Which Report to Each Employee
- problem 1741: Find Total Time Spent by Each Employee
- problem 1757: Recyclable and Low Fat Products
- problem 1789: Primary Department for Each Employee
- problem 1795: Rearrange Products Table
- problem 1873: Calculate Special Bonus
- problem 1890: The Latest Login in 2020
- problem 1965: Employees With Missing Information
- problem 1978: Employees Whose Manager Left the Company
- problem 166: Fraction to Recurring Decimal
- problem 223: Rectangle Area
- problem 240: Search a 2D Matrix II
- problem 318: Maximum Product of Word Lengths
- problem 357: Count Numbers with Unique Digits
- problem 394: Decode String
- problem 1158: Market Analysis I
- problem 1341: Movie Rating
- problem 1492: The kth Factor of n
- problem 1498: Number of Subsequences That Satisfy the Given Sum Condition
- problem 1907: Count Salary Categories
- problem 1934: Confirmation Rate
- problem 2405: Optimal Partition of String
Extra
- Tech Stack - my development environment and tools
- AI - how AI helped me create this website (NOT solving the problems)
- Progress - progression over time
- Quality - code quality