SQL SUM() Function β Calculate Totals in Your Data
Introduction β What is SQL SUM()?
The SUM() function in SQL is used to add together all values in a numeric column and return the total. Itβs one of the core aggregate functions used in reports, analytics, and financial calculations.
In this guide, you’ll learn how to:
- Use
SUM()in basic queries - Apply
SUM()withGROUP BY - Filter aggregated results using
HAVING - Handle
NULLvalues inSUM()
1. Basic SUM() Syntax
SELECT SUM(column_name) FROM table_name;
Adds all non-NULL numeric values from the specified column.
2. Example β Total Salaries
SELECT SUM(salary) AS total_salary
FROM employees;
Calculates the total sum of the salary column.
3. SUM() with GROUP BY
SELECT department, SUM(salary) AS dept_total
FROM employees
GROUP BY department;
Computes salary totals per department.
4. Filtering Aggregates with HAVING
SELECT department, SUM(sales) AS total_sales
FROM employees
GROUP BY department
HAVING SUM(sales) > 100000;
Filters groups where total sales exceed 100,000.
5. NULL Handling in SUM()
SUM()ignores NULLs- Use
COALESCE()to treat NULLs as 0:
SELECT SUM(COALESCE(sales, 0)) FROM revenue;
Ensures NULL values do not affect the result.
Best Practices
| Do This | Avoid This |
|---|---|
| Use aliases for clarity | Using raw column names in output |
| Combine SUM() with GROUP BY when needed | Using SUM() without aggregation context |
| Use COALESCE to handle NULLs | Assuming NULLs behave as zero |
Summary β Recap & Next Steps
The SQL SUM() function is a powerful tool for aggregating numeric data. From calculating revenue to summarizing totals per group, it provides fast and reliable summaries.
Key Takeaways:
- Use
SUM(column)to calculate totals - Combine with
GROUP BYfor segmented results - Use
HAVINGto filter summarized totals - Handle NULLs using
COALESCE()
Real-World Relevance:
Common in financial reports, inventory tracking, KPI dashboards, and analytics queries.
FAQ β SQL SUM Function
What does SQL SUM() do?
It returns the total of all numeric (non-NULL) values in a column.
Does SUM() ignore NULL values?
Yes. Use COALESCE() to treat NULLs as zeros if needed.
Can I use SUM() with GROUP BY?
Absolutely! Itβs one of the most common use cases.
How can I alias a SUM() result?
Use AS: SELECT SUM(sales) AS total_sales FROM orders;
Can I use SUM() in a subquery?
Yes. SUM() works inside subqueries, CTEs, and views.
Share Now :
