0
0
SQLquery~10 mins

Aggregate with NULL handling in SQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Aggregate with NULL handling
Start with dataset
Apply aggregate function
Check for NULL values
Ignore NULLs
Calculate result
Return aggregate output
The aggregate function processes data rows, skips NULLs, then calculates and returns the result.
Execution Sample
SQL
SELECT AVG(score) FROM tests;
-- scores: 10, NULL, 20, 30
-- AVG ignores NULL and averages 10,20,30
Calculates average score ignoring NULL values in the 'score' column.
Execution Table
StepRow ValueIs NULL?ActionRunning SumCountIntermediate AVG
110NoInclude in sum and count10110.0
2NULLYesIgnore NULL10110.0
320NoInclude in sum and count30215.0
430NoInclude in sum and count60320.0
End--Calculate AVG = sum/count60320.0
💡 All rows processed; NULL values ignored in aggregate calculation.
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
Running Sum01010306060
Count011233
Intermediate AVGNULL10.010.015.020.020.0
Key Moments - 2 Insights
Why does the NULL value not affect the average calculation?
Because the aggregate function AVG ignores NULLs, as shown in step 2 of the execution_table where NULL is skipped without changing sum or count.
What happens if all values are NULL?
The aggregate function returns NULL since count remains zero and no values are included, similar to how step 2 skips NULLs but if all were NULL, no sum or count would accumulate.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the Running Sum after processing the third row?
A20
B10
C30
D60
💡 Hint
Check the 'Running Sum' column at step 3 in the execution_table.
At which step does the aggregate function ignore a value due to NULL?
AStep 2
BStep 1
CStep 3
DStep 4
💡 Hint
Look for 'Is NULL?' = Yes in the execution_table.
If the second row was 15 instead of NULL, what would the final AVG be?
A15
B18.75
C20
D25
💡 Hint
Add 10 + 15 + 20 + 30 = 75, divide by 4 rows; check variable_tracker logic.
Concept Snapshot
Aggregate functions like AVG ignore NULL values.
They sum only non-NULLs and count those rows.
Final result = sum of values / count of non-NULLs.
If all values are NULL, result is NULL.
NULLs do not affect sum or count.
Full Transcript
This visual execution shows how SQL aggregate functions handle NULL values. Starting with a list of values including NULL, each row is checked. If the value is NULL, it is ignored and does not add to the sum or count. Non-NULL values add to the running sum and increase the count. The average is calculated by dividing the sum by the count of non-NULL values. This process ensures NULLs do not skew the aggregate result. If all values were NULL, the aggregate would return NULL. This step-by-step trace helps beginners understand how NULLs are handled in aggregates.