SQL Learning Hub
SQL SUM Function
SQL SUM Function
Learn how to calculate totals and aggregate numeric data effectively using SQL's SUM function.
Understanding the SQL SUM Function
The SUM
function is a fundamental SQL aggregate function used for calculating the total sum of values in a specified numeric column. It's essential for financial reporting, performance analysis, inventory tracking, and any scenario where you need to aggregate quantitative data.
Basic Syntax
SUM
operates only on columns with numeric data types (like INTEGER, REAL, DECIMAL, FLOAT, etc.).
Common SQL SUM Interview Questions
- Explain how the
SUM
function handles NULL values. - What happens if you try to use
SUM
on a non-numeric column? - How can you calculate sums for different categories within a single query?
- Show how to calculate a running total or cumulative sum using
SUM
(often involves window functions). - When would you use
SUM
in aHAVING
clause versus aWHERE
clause?
SUM Function Basics
Simple Total Calculation
At its core, SUM
adds all non-NULL values in the specified column for the rows selected by the query.
Result: A single row with a single column (total_platform_views
) containing the sum of all values in the views
column.
SUM with Conditions (WHERE Clause)
Use the WHERE
clause to filter rows before applying the SUM
function, allowing you to calculate totals for specific subsets of your data.
Only the views
from rows where user_id
is 5 are included in the sum.
SUM and NULL Value Handling
Crucially, the SUM
function ignores NULL values. It sums only the non-NULL numeric values it encounters. If all values in the column for the selected rows are NULL, SUM
typically returns NULL (or sometimes 0, depending on the database system and context, though NULL is standard SQL behavior).
To treat NULLs as 0 in a sum, you often need to use a function like COALESCE
or IFNULL
. For example: SUM(COALESCE(bonus_points, 0))
.
Data Types and SUM
SUM
is designed for numeric data types (INTEGER
, FLOAT
, DECIMAL
, etc.). Applying it to non-numeric types like strings or dates will usually result in an error. The data type of the result of SUM
is typically large enough to hold the potential sum (e.g., summing INTEGER
might return a BIGINT
or DECIMAL
).
Using SUM with GROUP BY
The real analytical power of SUM
emerges when combined with the GROUP BY
clause. This allows you to calculate subtotals for different categories or groups within your data.
Calculating Subtotals by Group
Aggregate numeric values for each distinct group defined in the GROUP BY
clause.
This query calculates the sum of views
separately for each unique user_id
, showing the total view count achieved by each content creator.
Combining with Joins for Richer Grouping
Join tables to group by descriptive names rather than just IDs.
Joining with Users
allows us to display the username
. Using LEFT JOIN
and COALESCE
ensures users with no videos appear with a total view count of 0.
Filtering Groups Based on SUM (HAVING Clause)
Use the HAVING
clause to filter the results based on the calculated sum for each group. The HAVING
clause acts after the grouping and summation, allowing us to select only the high-performing user groups based on their total views.
Advanced SUM Techniques
Multiple Aggregations (SUM, COUNT, AVG)
Combine SUM
with other aggregate functions like COUNT
and AVG
for more comprehensive summaries.
This provides a multi-faceted view of each user's content performance.
SUM with Expressions
You can apply SUM
to expressions involving columns, not just single columns.
This calculates an estimated revenue per user based on their total views and a hypothetical ad rate.
Summary
The SUM
function is a cornerstone of numeric data aggregation in SQL:
- It calculates the total sum of non-NULL values in a numeric column.
- It ignores NULL values during calculation. Use
COALESCE
or similar functions if you need to treat NULLs as zero. - Use with a
WHERE
clause to calculate sums for specific subsets of data. - Combine with
GROUP BY
to calculate subtotals for different categories. - Use with
HAVING
to filter groups based on their calculated sum. - Can be applied to expressions involving numeric columns.
Understanding how and when to use SUM
is crucial for performing meaningful quantitative analysis and generating insightful reports from your database.
Test Your Knowledge
Take a quick quiz to reinforce what you've learned about SQL SUM Function
Ready for hands-on SQL practice?
We have 200+ questions on real companies and real products.