0
0
SQLquery~10 mins

SUM function in SQL - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - SUM function
Start with empty total = 0
Read next row's value
Add value to total
More rows?
YesRepeat read and add
No
Return total sum
The SUM function adds up values from each row one by one until all rows are processed, then returns the total.
Execution Sample
SQL
SELECT SUM(sales) FROM orders;
This query calculates the total sales by adding the sales values from all rows in the orders table.
Execution Table
StepRow sales valueRunning totalAction
11000 + 100 = 100Add 100 to total
2200100 + 200 = 300Add 200 to total
350300 + 50 = 350Add 50 to total
4NULL350 + 0 = 350NULL treated as 0, no change
5150350 + 150 = 500Add 150 to total
6-500No more rows, return total
💡 All rows processed, final sum is 500
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
total0100300350350500500
Key Moments - 2 Insights
Why does the total not change when the sales value is NULL?
In the execution_table row 4, NULL is ignored by SUM, so it does not add to the total.
What happens if there are no rows in the table?
SUM returns NULL or zero depending on the database, but logically it means no values to add, so total stays at start value.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the running total after step 3?
A250
B300
C350
D100
💡 Hint
Check the 'Running total' column at step 3 in the execution_table
At which step does the SUM function encounter a NULL value?
AStep 4
BStep 2
CStep 5
DStep 6
💡 Hint
Look for 'NULL' in the 'Row sales value' column in the execution_table
If the sales value at step 5 was 100 instead of 150, what would be the final total?
A500
B450
C400
D350
💡 Hint
Subtract 50 from the final total in variable_tracker to adjust for the change at step 5
Concept Snapshot
SUM(column_name) adds all values in that column from all rows.
NULL values are ignored (treated as zero).
Returns one total number.
Used to find totals like total sales or total quantity.
Syntax: SELECT SUM(column) FROM table;
Full Transcript
The SUM function in SQL adds up all the values in a specified column from multiple rows. It starts with a total of zero, then reads each row's value and adds it to the total. If a value is NULL, it is ignored and does not change the total. After processing all rows, SUM returns the final total. For example, if sales values are 100, 200, 50, NULL, and 150, the total sum is 500. This function helps find totals like total sales or total quantity easily with a simple query.