chaturIQ
Thinking habit: Know what you're counting

COUNT vs COUNT(DISTINCT) in SQL: customers, not orders

The question: How many different customers placed at least one order in March 2026?

orders

order_idcustomer_idorder_date
1102026-03-02
2112026-03-05
3102026-03-09
4122026-03-15
5102026-03-20
6132026-04-01

This query looks right. Run it, decide if it is, and fix it.

SELECT COUNT(customer_id) AS customers
FROM orders
WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';
Show the answer and why the first query is wrong

Why the usual answer is wrong

SELECT COUNT(customer_id) AS customers
FROM orders
WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';

Customer 10 ordered three times in March, so they're counted three times. That's 5 orders, not 5 customers.

The answer

SELECT COUNT(DISTINCT customer_id) AS customers
FROM orders
WHERE order_date >= '2026-03-01' AND order_date < '2026-04-01';

COUNT(DISTINCT column) counts each different value once, so each customer counts once however often they ordered.

Before you count, say what one unit is: an order, a customer, a day. Then count that.

Practise more like this, on real business data

324 interview-style questions on 35 tables with the duplicates, NULLs and missing weeks interviewers test. Free.

Open the lesson

More SQL interview questions