MySQL SUM Aggregate Function is useful to calculate the total or Sum of records (or rows) selected by the SELECT Statement. For example, you can use this function to find the Total Sales in your Area or to find Total manufacturing Cost. The basic syntax of the MySQL SUM function is as shown below:
SELECT SUM ([Column_Name]) FROM [Source]
For this MySQL SUM function example, We are going to use the below shown data.
MySQL SUM Function Example
This function returns the sum of all records present in the specified column. For example, the following query calculates the gross of total number records present in Yearly_Income column from the customer details table.
SELECT SUM(Yearly_Income) AS `Total Income` FROM customerdetails;
SUM Group By Example
In general, we use this MySQL Sum Function to calculate the total product price belonging to a particular color or category, etc.
In this situation, we can use Group By Clause to group the products by color or category. Next, we use the Aggregate Function to find the total in each group. Let us see the MySQL example SELECT Statement.
USE company; SELECT Education, SUM(Yearly_Income) FROM customerdetails GROUP BY Education;
Above query group the Customers by their education, and finds the total income in each group (education qualification)
MySQL SUM Distinct Example
It allows you to use the DISTINCT keyword along with it. It calculate the gross of unique number of records present in the table.
TIP: The DISTINCT Keyword is used to remove the Duplicates from the specified column Name.
USE company; SELECT Education, SUM(DISTINCT Yearly_Income) FROM customerdetails GROUP BY Education;
Above Query finds Unique records (by removing duplicates) in Yearly_Income, and then calculates the grand total.