MySQL SUM Aggregate Function is useful to calculate the total number 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 the Total Manufacturing Cost. The basic syntax of the SUM function is as shown below:
SELECT SUM ([Column_Name]) FROM [Source]
For this 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 total number of records present in the 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 Sum Function to calculate the total product price belonging to a particular group, 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 Function Example
It allows you to use the DISTINCT keyword along with it. The below SUM query calculates the gross of the 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.