π‘ 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 data | Only use SUM() on numeric columns |
| Forgetting GROUP BY | Always 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
| Feature | Description |
|---|---|
| Function | SUM() |
| Returns | The total of a numeric column |
| Ignores NULLs | β Yes |
| Used with | GROUP 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.