MySQL SUM is one of the Aggregate Function, which is used to calculate the total or Sum of records (or rows) selected by the SELECT Statement. For example, If you want to find the Total Sales in your Area, or to find Total manufacturing Cost then you can simply use this Sum function.
MySQL SUM Function Syntax
The basic syntax of the SUM in MySQL is as shown below:
SELECT SUM ([Column_Name]) FROM [Source]
In this article we will show you, How to calculate the Sum in MySQL with example. For this, We are going to use the below shown data
MySQL SUM Example
The Sum function in MySQL returns the sum of all records present in the specified column. For example, The following query will calculate the Sum of total number records present in Yearly_Income column from 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 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 Sum Function in MySQL to find the total in each group. Let us see the Example
-- SUM Function in MySQL Example USE company; SELECT Education, SUM(Yearly_Income) FROM customerdetails GROUP BY Education;
Above Query will group the Customers by their education, and finds the total income in each group (education qualification)
MySQL SUM Function – Distinct Example
MySQL allows you to use the DISTINCT keyword along with the SUM function. 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 will find Unique records (by removing duplicates) in Yearly_Income, and then calculates the Sum
Thank You for Visiting Our Blog