MySQL MariaDB

How to use SUM function with GROUP BY in MySQL

Different functions are used in MySQL to obtain particular results; one of them is the SUM() function which is used to perform addition on the given data. This function is applied to the selected data to obtain the sum or we can make groups of values using the “GROUP BY” clause to perform addition on them.

The users who don’t know much about MySQL; MySQL is an RDMS that uses the SQL language to manage the data of a website. In MySQL to perform addition on the particular groups, we use the SUM() function with the GROUP BY clause. This post helps us to understand the usage of the GROUP BY clause with the SUM() function.

What is a SUM() function

The SUM() function is used to calculate the sum of integer data in the table, for better understanding, let us consider an example:

Customer_name Customer_books Total_price($) Price_of_stationary
John Geography 7 3
Paul International law 23 1
John Science 6 12
Paul English 20 4

A table has been created in MySQL with the name of Customer_data using the data above, which can be represented by using the command:

SELECT * FROM Customer_data;

If we want to perform addition on the Total_price column, we can do so simply using the SUM() function:

SELECT SUM(Total_price) From (Customer_data);

The total sum of the column, Total_price, has been displayed.

How to use SUM() with GROUP BY in MySQL

To perform addition on groups, we use the GROUP BY clause with the SUM(), for example, in the above table, there are only two customers; John and Paul who purchased the books, to have the Total_price of both customers we use the SUM() function with the GROUP BY clause:

SELECT customer_name ,SUM(total_price) FROM Customer_data GROUP BY customer_name;

In the above output, we can see that the sum of the price of the books purchased by both customers is displayed separately. We can also sum the multiple columns by using the SUM() function with GROUP BY clause:

SELECT Customer_name,  SUM (Total_price + Price_of_stationary) FROM Customer_data  GROUP BY Customer_name;

Conclusion

MySQL is a popular RDBMS to manage data of the relational database, it supports a lot of SQL functions that take one or more inputs and give a single output after performing that specific task. The SUM() is one of the aggregate functions that is used to perform addition on provided data. In this post, we have discussed the usage of the SUM() function and also used it with the GROUP BY clause

About the author

Hammad Zahid

I'm an Engineering graduate and my passion for IT has brought me to Linux. Now here I'm learning and sharing my knowledge with the world.