MySQL aggregate functions refer to a set of functions that perform calculations on a set of values and return a single value. Aggregate functions include the maximum and minimum value, average, standard deviation, count, sum, etc.
In this tutorial, we shall learn about one of the popular choices of the aggregate functions: SUM.
What is Sum? How Does it Work?
The SUM MySQL function does precisely as the name indicates: it returns the sum of a set of values. The SUM function ignores NULL values when encountered in a set.
If used in the SELECT clause where no row is returned, the resulting value from the SUM function is a NULL and not a zero.
The general syntax of the MySQL SUM function is as shown below:
The expression can be a single column or multiple columns separated by commas.
Example Use Case
Let us illustrate how the function works by using a real-world database. For this example, we shall use messy real-world data and import it into MySQL.
The data provided is in the form of CSV values.
You can download the data from the resource below:
Once you have downloaded the data, you can import it to MySQL and start using it.
To verify that you have the correct data, compare your data from the output shown from the query below:
Below is sample output from the above query:
We can use one of the columns from the database to illustrate the SUM functions.
Consider the query below that gets the sum of all the values in the koi_impact column:
This will add all the values in the table and return their sum as shown in the below output:
Sum Distinct Values
If you wish to get the sum of all the unique values in a set, you can use the DISTINCT keyword as shown in the query below:
The output result is:
This returns a different value than when the DISTINCT keywords are not used and only unique values are added.
Sum Function with Expression
We can also apply an expression using the WHERE clause to get only specific values. For example, consider the query below, which only adds value greater than 1 from the koi_impact table:
The result is as shown:
Sum with Filter
We can also add filters to the SUM operations instead of adding all values, which may take a lot of time. For example, we can add the sum of all the values where the product of koi_impact and koi_impact_err1 is greater than 10.
The above query will give an output as shown:
In this tutorial, we discussed the SUM function in MySQL, how to use it to get the sum of all the values in a set, and filter information using the SUM function.
Feel free to experiment and use the SUM function to make MySQL tasks easier and faster.