Counting distinct values
Stage 3: Aggregation · Lesson 13 of 17 · 4 min read · free, interactive
COUNT(DISTINCT column) counts how many different values there are, ignoring repeats (and NULLs):
SELECT COUNT(*) AS purchases, COUNT(DISTINCT player_id) AS buyers FROM purchases;
It works per group too — how many different items did each player buy?
SELECT player_id, COUNT(*) AS purchases, COUNT(DISTINCT item_id) AS different_items FROM purchases GROUP BY player_id;
Don't confuse COUNT(qty) (how many rows have a quantity) with SUM(qty) (how many units in total):
SELECT item_id, COUNT(qty) AS purchases, SUM(qty) AS units FROM purchases GROUP BY item_id;
Practice
Each answer runs in your browser and is checked on hidden data.
- Write the query: How many different players have made a purchase? Return a single column called
buyers. - Fill in the blanks: For each player who bought something, return
player_idanditems— how many different items they bought. Row order does not matter. - Find the bug: Return each
item_idthat was bought, with the total quantity sold astotal_qty. Row order does not matter.
Previous: Filtering groups with HAVING · Next: Combining tables with JOIN · All lessons