β 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
NULL
values 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 BY
for segmented results - Use
HAVING
to 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 :