Lesson 4 · Milestone: Join + group

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:

Four words you need

groupA bucket of rows that share the same value in the GROUP BY column.
aggregateA function that turns many values into one: COUNT, SUM, MAX, MIN, AVG.
DISTINCT"Count each different value once." Repeats don't add to the count.
aliasA name for an output column: 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;
1 · FROM Plays user  song  device ana   s1    phone ana   s1    laptop ana   s2    phone bo    s3    phone bo    s3    phone 5 rows, one per play 2 · GROUP BY user_id bucket: ana s1    phone s1    laptop s2    phone bucket: bo s3    phone s3    phone 2 buckets, not 5 rows 3 · count per bucket COUNT(*)  = 3 s1 s1 s2 DISTINCT  = 2 COUNT(*)  = 2 DISTINCT  = 1 repeats of s1 / s3 count once 4 · SELECT user plays songs ana  3     2 bo   2     1 one row per bucket

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

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:

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:

To pass (check these yourself first):

Read next

Main source: MySQL Handling of GROUP BY (MySQL 8.0 manual). Read only the first four paragraphs and the error 1055 example.

💬 Is something still unclear? Ask me in the chat. I'm your tutor for this course.