Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
When calculating business metrics, you often need to differentiate between the raw volume of events and the number of unique entities involved. For example, a customer may place 10 orders in a single week. If you calculate total orders, you want to count all 10. But if you want to know how many distinct customers placed orders, you must deduplicate before counting. In SQL, this is achieved by embedding DISTINCT inside aggregate functions.
COUNT(*) vs COUNT(col) vs COUNT(DISTINCT col)Let us observe how each query evaluates against the table above:
MySQL allows executing multiple distinct aggregate calculations simultaneously:
DISTINCT with SUM() or AVG()?Yes, although it is less common:
SUM(DISTINCT salary): Sums each unique salary value only once. If three engineers earn ₹80,000, it only includes ₹80,000 once in the sum.AVG(DISTINCT salary): Calculates the average of unique salary values, ignoring frequency.COUNT(DISTINCT): Calculating COUNT(DISTINCT col) requires MySQL to maintain a temporary hash set or B-Tree in memory to track all previously seen values. Across 100 million rows with high cardinality, this can consume significant server memory.COUNT(DISTINCT col1, col2): MySQL uniquely supports counting distinct combinations of multiple columns:[10, 10, 20, 20, NULL], what does COUNT(DISTINCT column) return?COUNT(*) and COUNT(DISTINCT user_id)?COUNT(DISTINCT col1, col2))?SUM(DISTINCT val) return for the dataset [100, 100, 200, 300]?COUNT(DISTINCT) on a column with 50 million unique values be slow?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Filtering Groups with HAVING vs WHERE | Database Backups with mysqldump |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.