0
0
MySQLquery~10 mins

SUM function in MySQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - SUM function
Start Query
Scan Table Rows
Extract Numeric Column Values
Add Values Together
Return Total Sum
End Query
The SUM function scans all rows, extracts the numeric values from a column, adds them up, and returns the total.
Execution Sample
MySQL
SELECT SUM(sales) FROM orders;
This query calculates the total sales by adding all values in the sales column of the orders table.
Execution Table
StepActionCurrent Row salesRunning TotalNotes
1Start query execution-0Initialize sum to zero
2Read first row100100Add 100 to total
3Read second row200300Add 200 to total
4Read third row150450Add 150 to total
5Read fourth row50500Add 50 to total
6No more rows-500Return final sum
💡 All rows processed, sum of sales is 500
Variable Tracker
VariableStartAfter 1After 2After 3After 4Final
running_total0100300450500500
Key Moments - 2 Insights
Why does the SUM function start with zero instead of the first row's value?
The SUM function initializes the total to zero to ensure it correctly adds all values, including when there are no rows. This is shown in execution_table row 1 where running_total starts at 0.
What happens if the column contains NULL values?
SUM ignores NULL values and does not add them. This means the running total only increases with actual numbers, similar to the values shown in execution_table rows 2-5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the running total after reading the third row?
A150
B300
C450
D500
💡 Hint
Check the 'Running Total' column at step 4 in the execution_table.
At which step does the SUM function return the final total?
AStep 6
BStep 4
CStep 5
DStep 2
💡 Hint
Look for the step where 'No more rows' is noted in the 'Action' column.
If the first row's sales value was NULL, what would be the running total after step 2?
A100
B0
CNULL
DCannot determine
💡 Hint
Recall that SUM ignores NULL values and starts from zero as shown in variable_tracker.
Concept Snapshot
SUM(column_name) adds all numeric values in the column.
Ignores NULLs.
Returns a single total value.
Used in SELECT queries.
Example: SELECT SUM(sales) FROM orders;
Full Transcript
The SUM function in SQL adds up all the numbers in a specified column from all rows in a table. It starts with zero and adds each row's value one by one. If a row has NULL, it skips it. After processing all rows, it returns the total sum. For example, SELECT SUM(sales) FROM orders; adds all sales values in the orders table and returns the total.