COUNT(DISTINCT …)
Counts unique values instead of rows. Use it to count people or orders when a row can repeat.
FormulaCOUNT(*) counts rows · COUNT(DISTINCT x) counts different x
Try it · 30 seconds · from Atterna’s practice
SELECT COUNT(buyer_id) FROM orders WHERE status = 'paid';
Marketing asked for the number of customers. What does this query actually count?
Preparing the practice…
How we work it through
- 1
Ask whether the question is about rows or about people.
- 2
Count the key of the thing you mean: buyer_id for buyers.
- 3
Never SUM(DISTINCT …) money — two orders can cost the same.
On the practice dataset
The query we run on Meridian, Atterna’s practice marketplace, and what it returns.
SELECT COUNT(*) AS paid_orders,
COUNT(DISTINCT buyer_id) AS buyers
FROM meridian.orders
WHERE status = 'paid';Result9,071 paid orders from 3,652 buyers
The common trap
Using SUM(DISTINCT …) for money — two different orders can have the same amount.
ExampleMeridian: 9,071 paid orders come from 3,652 distinct buyers.
When an AI answers
“9,071 customers placed an order.”
- What it didn’t know
- It counted rows of orders and was not told a customer can order many times.
- Ask back
- “Is that orders or distinct buyers?”
Read next
Examples use Meridian, Atterna’s fictional practice marketplace.