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 MySQL Sum function to find the Total Sales in your Area or to find Total manufacturing Cost. The basic syntax of the SUM in MySQL 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 Example
The Sum function returns the sum of all records present in the specified column. For example, the following Sum function query calculates the Sum of total number records present in Yearly_Income column from the customer details table.
-- SUM in MySQL Example SELECT SUM(Yearly_Income) AS `Total Income` FROM customerdetails;
MySQL SUM Function Group By Example
In general, we use this Sum function to calculate the total product price belongs 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 Sum Aggregate Function to find the total in each group. Let us see the MySQL example SELECT Statement.
-- SUM Function in MySQL Example USE company; SELECT Education, SUM(Yearly_Income) FROM customerdetails GROUP BY Education;
Above Sum 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 the SUM function. The SUM (DISTINCT Column_Name) calculate the Sum of Unique number of records present in the table.
TIP: In MySQL, DISTINCT Keyword is used to remove the Duplicates from the specified column Name.
-- SUM Function in MySQL Example 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 Sum