11. Aggregate Functions: SUM COUNT AVG MIN MAX
11.3 COUNT(*) vs COUNT(DISTINCT column)
Why. Counting orders vs counting unique customers are different questions.
What. COUNT(*) = rows. COUNT(DISTINCT col) = unique values in that column.
How. SELECT COUNT(*) , COUNT(DISTINCT customer_id) FROM orders;
Steps
- Count orders.
- Count distinct customers who ordered.
- Explain the gap.
Examples
Example 1 · dataset: raja_coffee
SELECT COUNT(*) AS orders,
COUNT(DISTINCT customer_id) AS unique_customers,
COUNT(DISTINCT city) AS unique_cities
FROM orders;Output
| orders | unique_customers | unique_cities |
|---|---|---|
| 24 | 8 | 6 |
Meaning. Orders vs people vs cities.
Ravindra Bagale's Tip
COUNT(DISTINCT …) is slower on huge tables — fine on practice sizes.
Ravindra Bagale's Tip – मराठी
मोठ्या टेबलवर COUNT(DISTINCT) मंद — सराव आकारावर ठीक.
Ravindra Bagale's Tip – हिंदी
बड़ी टेबल पर COUNT(DISTINCT) धीमा — अभ्यास आकार पर ठीक।