πŸ”’ SQL Aggregate Functions
Estimated reading: 2 minutes 34 views

βž• 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() with GROUP BY
  • Filter aggregated results using HAVING
  • Handle NULL values in SUM()

βœ… 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 clarityUsing raw column names in output
Combine SUM() with GROUP BY when neededUsing SUM() without aggregation context
Use COALESCE to handle NULLsAssuming 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

βž• SQL SUM

Or Copy Link

CONTENTS
Scroll to Top