MySQL COUNT() AVG() and SUM() Functions

MySQL COUNT() , AVG() and SUM() Functions
In MySQL, aggregate functions like COUNT(), AVG(), and SUM() are used to analyze data by performing calculations on multiple rows and returning one result per group.
- These are must-know functions for reports, analytics, exams, and interviews.
What are Aggregate Functions?
Aggregate functions:
Work on multiple rows
Return a single value
Commonly used with
GROUP BYandHAVING
The most important ones:
COUNT()→ total rowsAVG()→ average valueSUM()→ total value
COUNT() Function
Purpose
Returns the number of rows.
Syntax
Examples
Count all rows
Count non-NULL values
Difference:
COUNT(*)→ counts all rowsCOUNT(column)→ counts non-NULL values only
AVG() Function
Purpose
Returns the average (mean) value of a numeric column.
Syntax
Example
- NULL values are ignored automatically.
SUM() Function
Purpose
Returns the total sum of a numeric column.
Syntax
Example
Using COUNT, AVG, SUM with GROUP BY
Department-wise Employee Count
Department wise Average Salary
Department-wise Total Salary
Using Aggregate Functions with WHERE
WHEREfilters rows before aggregation.
Using Aggregate Functions with HAVING
HAVINGfilters groups after aggregation.
Aggregate Functions & NULL Values
| Function | NULL Handling |
|---|---|
COUNT(*) | Counts NULL |
COUNT(column) | Ignores NULL |
AVG() | Ignores NULL |
SUM() | Ignores NULL |
Common Mistakes
- Using aggregate functions in
WHERE ForgettingGROUP BYExpecting AVG/SUM to count NULL- Confusing
COUNT(*)withCOUNT(column)
Interview Questions & MCQs (Very Important)
Q1. What does COUNT(*) do?
A) Counts non-NULL values
B) Counts NULL values only
C) Counts all rows
D) Counts columns
Answer: C
Q2. What does COUNT(column_name) do?
A) Counts all rows
B) Counts non-NULL values
C) Counts NULL values
D) Counts duplicate values
Answer: B
Q3. Which function returns average value?
A) SUM()
B) COUNT()
C) AVG()
D) MEAN()
Answer: C
Q4. Which function returns total value?
A) TOTAL()
B) SUM()
C) ADD()
D) COUNT()
Answer: B
Q5. Do AVG() and SUM() include NULL values?
A) Yes
B) No
Answer: B
Q6. Which clause filters aggregated results?
A) WHERE
B) GROUP BY
C) HAVING
D) ORDER BY
Answer: C
Q7. Which is correct?
A) Correct
B) Incorrect
Answer: A
Real-Life Use Cases
- Total sales calculation
- Average marks / salary
- Counting users / orders
- Department-wise reports
- Business analytics dashboards
Summary
COUNT()→ counts rowsAVG()→ calculates averageSUM()→ calculates totalWork with
GROUP BY&HAVINGIgnore NULL values (except
COUNT(*))Extremely important for SQL exams & interviews
