SQL SUM

SQL SUM

What is SQL SUM()?

The SUM() function in SQL calculates the total sum of a numeric column. It is one of the aggregate functions in SQL and is often used to derive totals, subtotals, or other cumulative values from data.


Syntax

SELECT SUM(column_name) FROM table_name [WHERE condition];
  • column_name: The numeric column whose values you want to sum.
  • WHERE condition: Optional filter to specify a subset of rows to include in the calculation.

Key Features of SQL SUM()

  1. Operates on Numeric Columns: SUM() works only with numeric data types (e.g., integers, decimals).
  2. Excludes NULL Values: Automatically ignores NULL values in the column.
  3. Used with Filters: Combine with WHERE to calculate totals for specific subsets of data.
  4. Works with GROUP BY: Calculate subtotals for groups in the dataset.

Examples of SQL SUM()

1. Basic Usage

Calculate the total revenue from all orders.

SELECT SUM(revenue) AS total_revenue FROM orders;

2. Using SUM() with a WHERE Clause

Calculate the total revenue from orders in January 2025.

SELECT SUM(revenue) AS total_revenue FROM orders WHERE order_date BETWEEN '2025-01-01' AND '2025-01-31';

3. Using SUM() with GROUP BY

Calculate the total revenue for each product category.

SELECT category, SUM(revenue) AS total_revenue FROM products GROUP BY category;

4. Using SUM() with HAVING

Find product categories with total revenue exceeding $10,000.

SELECT category, SUM(revenue) AS total_revenue FROM products GROUP BY category HAVING SUM(revenue) > 10000;

5. Using SUM() with DISTINCT

Calculate the total of unique sales amounts.

SELECT SUM(DISTINCT sale_amount) AS total_unique_sales FROM sales;

6. Using SUM() in a Subquery

Find customers whose total purchases exceed the average total revenue.

SELECT customer_id, SUM(purchase_amount) AS total_purchases FROM orders GROUP BY customer_id HAVING SUM(purchase_amount) > ( SELECT AVG(total_revenue) FROM (SELECT SUM(revenue) AS total_revenue FROM orders GROUP BY customer_id) subquery );

Common Use Cases for SQL SUM()

  1. Financial Calculations: Calculate total sales, expenses, profits, or revenues.
    SELECT SUM(profit) AS total_profit FROM financials;
  2. Inventory Management: Calculate the total stock or value of products in inventory.
    SELECT SUM(stock_quantity) AS total_stock FROM inventory;
  3. Employee Compensation: Calculate total salaries paid.
    SELECT SUM(salary) AS total_salary FROM employees;

Handling NULL Values

The SUM() function ignores NULL values by default. However, if you want to count how many rows were included in the sum, combine SUM() with COUNT().

Example

Calculate the total salary and count of employees considered.

SELECT SUM(salary) AS total_salary, COUNT(salary) AS employees_count FROM employees;

Using SUM() with Joins

Combine SUM() with joins to calculate totals from related tables.

Example

Calculate the total revenue generated by each salesperson.

SELECT salespeople.name, SUM(orders.revenue) AS total_revenue FROM salespeople JOIN orders ON salespeople.id = orders.salesperson_id GROUP BY salespeople.name;

Performance Tips

  1. Index Columns: Ensure numeric columns used in SUM() are indexed for better performance.
  2. Filter Rows with WHERE: Reduce dataset size with WHERE before applying SUM().
  3. Optimize Queries: Use GROUP BY selectively to avoid unnecessarily large result sets.

Limitations of SQL SUM()

  1. Works Only on Numeric Data: Cannot be used on text or non-numeric columns.
  2. Excludes NULL Values: While this is generally helpful, it may require additional handling in some cases.

Conclusion

The SQL SUM() function is a powerful tool for deriving cumulative data, making it essential for reporting and analytics. Calculating total revenues, expenses, or product stock, SUM() simplifies complex queries and provides meaningful insights.

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close