Skip to main content
Documents
Share
LinkedIn
Facebook
Twitter
Copy
ClausesStatementsKeywordsExpressionsFunctions

MySQL SUM() Function

The `SUM()` function in MySQL is used to calculate the total sum of a numeric column. It is particularly useful for aggregating data across rows in queries like sales totals, amounts, or any numerical data.

Usage

The `SUM()` function is commonly used in `SELECT` statements combined with `GROUP BY` to aggregate values across a dataset. It calculates the sum of all values in the specified column.

sql
SELECT SUM(column_name)
FROM table_name
[WHERE condition];

In this syntax, `SUM(column_name)` sums up the values of `column_name` from the specified table or subset of rows.

Examples

1. Basic Sum

sql
SELECT SUM(price) AS total_price
FROM products;

This query calculates the total sum of the `price` column from the `products` table.

2. Sum with a Condition

sql
SELECT SUM(amount) AS total_sales
FROM sales
WHERE sale_date = '2023-10-01';

Here, the `SUM()` function calculates the total sales amount for sales made on October 1, 2023.

3. Sum with Grouping

sql
SELECT customer_id, SUM(amount) AS total_spent
FROM orders
GROUP BY customer_id;

This example uses `SUM()` along with `GROUP BY` to calculate the total amount spent by each customer.

Tips and Best Practices

  • Use Aliases. Use aliases (`AS`) for clear and understandable result column names.
  • Combine with GROUP BY. Use `SUM()` with `GROUP BY` for grouped totals to gain insights into data segments. Use `HAVING` to filter aggregated results.
  • Filter with WHERE. Combine `SUM()` with `WHERE` to focus on relevant subsets of data for precise results.
  • Mind Null Values. Be aware that `SUM()` ignores `NULL` values. Use `COALESCE()` to handle `NULL` values effectively, e.g., `SUM(COALESCE(column_name, 0))`.
  • Decimal Precision. Be cautious with decimal precision, especially in financial calculations. `SUM()` maintains the precision of the input column.
  • Performance Considerations. When using `SUM()` on large datasets, consider indexing columns involved in `WHERE` and `GROUP BY` clauses to improve query performance.
  • Error Handling. Be prepared to handle potential errors or unexpected results by validating inputs and reviewing complex queries for correctness.