GROUP BY and COUNT(DISTINCT)
So far every query returned one output row per table row. Many interview questions ask for something different: "for each teacher / customer / day, how many …?" That needs a new step that turns many rows into one row per group.
What you will be able to do:
- Say where
GROUP BYruns, and what it does to the rows. - Choose between
COUNT(*),COUNT(col)andCOUNT(DISTINCT col). - Explain why
SELECTcan only show grouped columns and aggregates. - Solve LeetCode 2356 alone.
Four words you need
COUNT, SUM, MAX, MIN, AVG.COUNT(*) AS cnt.1. A new step in the run order
1. FROM → 2. WHERE → 3. GROUP BY → 4. SELECT → 5. ORDER BY
Mental model: buckets. GROUP BY user_id puts every row into a bucket labelled with its user_id. After this step, the query no longer sees single rows. It sees one bucket per user. SELECT then makes exactly one output row per bucket.
Click through the steps. The example uses a music app's play log, not the exercise table:
SELECT user_id,
COUNT(*) AS plays,
COUNT(DISTINCT song_id) AS songs
FROM Plays
GROUP BY user_id;
FROM reads all 5 plays. Notice the repeats: ana played s1 twice, and bo played s3 twice.
GROUP BY user_id sorts the rows into buckets, one per user. From here on, the query works with buckets.
Aggregates run inside each bucket. COUNT(*) counts rows (plays). COUNT(DISTINCT song_id) counts different songs, so ana's two s1 plays count once.
SELECT makes one output row per bucket: the bucket label (user_id) plus the aggregates.
2. Three kinds of COUNT
COUNT(*) counts ROWS, including rows full of NULLs
COUNT(song_id) counts rows where song_id IS NOT NULL
COUNT(DISTINCT song) counts DIFFERENT non-NULL values
- The word in the question tells you which one: "how many plays" means rows, so
COUNT(*). "How many unique / different songs" meansCOUNT(DISTINCT …). COUNT(col)skips NULLs, for the same reason you saw in Lesson 3: NULL is "unknown", so it isn't counted as a value (MySQL manual). You will need this for joins.- Interview fact: in MySQL's InnoDB engine,
COUNT(*)andCOUNT(1)are handled the same way, with no speed difference (same manual page).
3. The GROUP BY rule for SELECT
After grouping, each output row stands for a whole bucket. So every item in SELECT must have one value per bucket:
- a column you grouped by (
user_id: the same for the whole bucket), or - an aggregate (
COUNT(…): one number per bucket).
SELECT user_id, device, COUNT(*) -- ✗ which device? ana has "phone" AND "laptop"
FROM Plays GROUP BY user_id;
MySQL 8 turns on ONLY_FULL_GROUP_BY by default. It rejects this query with error 1055 (MySQL manual). If you see that error, ask yourself: "which column in my SELECT has more than one value per bucket?"
Practice from memory
Try not to scroll up.
1. Where does GROUP BY run?
2. A table has 1,000 plays by 40 users. GROUP BY user_id returns how many rows?
3. In the example, what is COUNT(DISTINCT song_id) for ana?
4. Some rows have song_id = NULL. What does COUNT(song_id) do with them?
5. SELECT user_id, device, COUNT(*) FROM Plays GROUP BY user_id; in MySQL 8 with default settings. What happens?
Fill in the blanks: a different table
Orders(customer_id, product_id, store_id). For each customer, return how many different stores they bought from, as stores.
SELECT customer_id, ( store_id) AS
FROM Orders
;
🏆 Challenge: LeetCode 2356 (Number of Unique Subjects Taught by Each Teacher)
Your task: open 2356 and choose MySQL. The table is Teacher(teacher_id, subject_id, dept_id). A teacher can teach the same subject in several departments. Return each teacher_id with the number of unique subjects they teach, as cnt. Time box: 8 minutes.
Send me in the chat:
- Your query, and the LeetCode result.
- Two full sentences, written from memory, the way you'd say them out loud (an interview gives you no notes):
- Why
COUNT(DISTINCT subject_id)and notCOUNT(*)? Use one real teacher from the LeetCode example and give both numbers. - Why can't you add
dept_idto your SELECT list?
- Why
To pass (check these yourself first):
- LeetCode says Accepted, and the output columns are
teacher_idandcnt. - Sentence 1 names a teacher from the example and gives both counts (rows vs different subjects).
- Sentence 2 says that one teacher's bucket has several
dept_idvalues, so there is no single value to show.
Read next
Main source: MySQL Handling of GROUP BY (MySQL 8.0 manual). Read only the first four paragraphs and the error 1055 example.
- MySQL Handling of GROUP BY 📄 Docs · 5 min (first part) · Why the "one value per bucket" rule exists, and the exact error you'll see.
- Aggregate Function Descriptions 📄 Docs · reference · Look up COUNT:
COUNT(expr)skips NULL, andCOUNT(*)doesn't. - SQL queries don't start with SELECT 📄 Article · 5 min · Julia Evans. Find GROUP BY in her order diagram. HAVING (a later lesson) sits right after it.
💬 Is something still unclear? Ask me in the chat. I'm your tutor for this course.