0
0
MySQLquery~10 mins

AVG function in MySQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - AVG function
Start with a column of numbers
Sum all values in the column
Count how many values are in the column
Divide sum by count
Return the average value
The AVG function calculates the average by adding all values in a column and dividing by the number of values.
Execution Sample
MySQL
SELECT AVG(score) FROM tests;
This query calculates the average score from the 'tests' table.
Execution Table
StepActionValues InvolvedResult
1Identify column 'score' values[80, 90, 70, 100, 60]Values collected
2Sum all values80 + 90 + 70 + 100 + 60400
3Count number of values55
4Divide sum by count400 / 580
5Return average8080
💡 All values processed; average calculated as 80
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 4Final
sum0400400400400
count00555
averageundefinedundefinedundefined8080
Key Moments - 2 Insights
Why does AVG ignore NULL values in the column?
AVG only sums and counts non-NULL values, so NULLs do not affect the sum or count, as shown in the execution_table where only actual numbers are processed.
What happens if the column has zero rows?
If there are no rows, the count is zero, so AVG returns NULL because dividing by zero is undefined. This is not shown in the current table but is important to remember.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the sum of the 'score' values at Step 2?
A5
B80
C400
D4000
💡 Hint
Check the 'Result' column at Step 2 in the execution_table.
At which step does the AVG function calculate the final average value?
AStep 2
BStep 4
CStep 3
DStep 1
💡 Hint
Look for the division operation in the execution_table.
If one score was NULL, how would the count change in the variable_tracker?
ACount would decrease by 1
BCount would stay the same
CSum would increase
DAverage would be NULL
💡 Hint
Recall that AVG ignores NULLs, so count only includes non-NULL values.
Concept Snapshot
AVG(column_name)
Calculates the average of non-NULL values in a column.
Steps: sum values, count values, divide sum by count.
Returns NULL if no non-NULL values.
Useful for finding mean values in data.
Full Transcript
The AVG function in SQL calculates the average value of a numeric column. It works by first collecting all the non-NULL values in the column, then summing these values, counting how many there are, and finally dividing the sum by the count. For example, if the scores are 80, 90, 70, 100, and 60, the sum is 400 and the count is 5, so the average is 80. AVG ignores NULL values and returns NULL if there are no non-NULL values to average. This process helps find the mean value in a dataset easily.