T
Tech Town
Log InSign Up Free
← Back to Blog

June 17, 2025 · admin

SUM Function

πŸ’‘ SQL SUM() Function – Calculate Total Values in SQL

The SQL SUM() function is a powerful aggregate function that calculates the total of a numeric column. Whether you’re totaling sales, revenue, expenses, or scores, SUM() helps you generate actionable insights from raw data.

In this tutorial, you’ll learn:

  • βœ… What the SUM() function does
  • πŸ”§ Syntax and usage
  • πŸ“Š Real-world examples
  • ⚠️ Best practices and common pitfalls

βœ… What is SQL SUM()?

The SUM() function calculates the total value of a numeric column across multiple rows. It’s ideal for summarizing data such as sales amounts, order totals, hours worked, and more.


πŸ”§ Syntax

SELECT SUM(column_name)
FROM table_name
WHERE condition;
  • column_name: The numeric column you want to sum.
  • table_name: The source table.
  • WHERE (optional): Filters to limit which rows are included.

πŸ“Š SQL SUM() Examples

πŸ§ͺ Example 1: Calculate Total Sales

SELECT SUM(sale_amount) AS total_sales
FROM orders;

πŸ’° Returns the total revenue from the orders table.


πŸ§ͺ Example 2: Total Hours Worked by Employees

SELECT SUM(hours_worked) AS total_hours
FROM timesheet;

πŸ•’ Helps HR or management calculate total hours worked across all employees.


πŸ§ͺ Example 3: Total Score Per Student

SELECT student_id, SUM(score) AS total_score
FROM test_results
GROUP BY student_id;

πŸ“š Summarizes the total marks scored by each student.


πŸ§ͺ Example 4: Monthly Revenue

SELECT MONTH(order_date) AS month, SUM(sale_amount) AS monthly_revenue
FROM orders
GROUP BY MONTH(order_date);

πŸ“† Analyze sales trends across different months.


🧠 Pro Tip: Use SUM() with GROUP BY

GROUP BY lets you compute totals for each group of data.

SELECT department_id, SUM(salary) AS total_salary
FROM employees
GROUP BY department_id;

🏒 Useful for budgeting across different departments.


⚠️ Common Mistakes to Avoid

❌ Mistakeβœ… Solution
Using SUM() on non-numeric dataOnly use SUM() on numeric columns
Forgetting GROUP BYAlways use GROUP BY when selecting additional columns
Expecting SUM() to ignore NULL by defaultβœ… It does! SUM() automatically ignores NULLs

πŸ” Use Cases of SQL SUM()

  • πŸ’Ό Business: Total revenue, total expenses
  • πŸ“Š Analytics: Total engagement, usage time
  • πŸŽ“ Education: Total marks or credits per student
  • πŸ“¦ Inventory: Total stock levels or reorder volumes

πŸ”‘ SEO Keywords to Target

  • SQL SUM function
  • SQL total value calculation
  • SQL add column values
  • SQL revenue total query
  • Aggregate functions in SQL

🏁 Summary Table

FeatureDescription
FunctionSUM()
ReturnsThe total of a numeric column
Ignores NULLsβœ… Yes
Used withGROUP BY, WHERE, JOIN, etc.

🧠 Bonus: Use SUM() in Subqueries

SELECT department_id
FROM employees
WHERE salary > (
    SELECT SUM(salary) / COUNT(*) FROM employees
);

πŸ“ˆ Returns departments where salaries are higher than the average total salary.