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.

Previous: Filtering groups with HAVING · Next: Combining tables with JOIN · All lessons