SUM() Function in MySQL (original) (raw)

Last Updated : 27 Mar, 2026

The SUM() function in MySQL is an aggregate function used to calculate the total sum of values in a numeric column. It helps generate overall totals for better data analysis.

**Syntax:

SUM(expression)

**expression: A specified expression which can either be a field or a given formula.

Working with the SUM() Function

This section demonstrates how the MySQL SUM() function works in different scenarios. First, we will create a demo table on which the SUM() function will be applied:

Screenshot-2026-03-27-163636

sales Table

Example 1: Finding Total Quantity Sold

This example calculates the total quantity of all products present in the table. It shows the basic usage of the SUM() function.

**Query:

SELECT SUM(quantity) AS total_quantity FROM sales;

**Output:

Screenshot-2026-03-27-164440

Example 2: SUM() with WHERE Clause

This example calculates the total quantity for a specific product using a condition. It filters rows before applying SUM().

**Query:

SELECT SUM(quantity) AS total_laptop_quantity FROM sales WHERE product_name = 'Laptop';

**Output:

Screenshot-2026-03-27-165327

Example 3: SUM() with GROUP BY Clause

This example calculates the total quantity for each product separately. It groups rows and applies SUM() on each group.

**Query:

SELECT product_name, SUM(quantity) AS total_quantity FROM sales GROUP BY product_name;

**Output:

Screenshot-2026-03-27-165423

Example 4: SUM() with HAVING Clause

This example filters grouped results based on total quantity. It is used after GROUP BY to apply conditions on aggregated values.

**Query:

SELECT product_name, SUM(quantity) AS total_quantity FROM sales GROUP BY product_name HAVING SUM(quantity) > 10;

**Output:

Screenshot-2026-03-27-165518

Example 5: SUM() with DISTINCT Clause

This example calculates the sum of only unique values in the column. Duplicate values are ignored before summing.

**Query:

SELECT SUM(DISTINCT quantity) AS total_distinct_quantity FROM sales;

**Output:

Screenshot-2026-03-27-170005