
204 views
MySQL sum()
The SUM()
function in MySQL is an aggregate function used to calculate the sum of values in a numeric column. It is often used to generate summary statistics about a dataset. The basic syntax of the SUM()
function is as follows:
SUM(expression)
expression
: This should be a numeric column or a numeric expression that you want to sum.
Here are some common ways to use the SUM()
function:
- Calculate the Sum of Values in a Column:
To calculate the sum of all values in a numeric column, useSUM(column_name)
.
SELECT SUM(salary) FROM employees;
- Calculate the Sum of Values Based on a Condition:
You can calculate the sum of values that meet specific conditions by using theSUM()
function with aWHERE
clause.
SELECT SUM(sales_amount) FROM sales WHERE year = 2023;
- Calculate the Sum of Distinct Values in a Column:
If you want to calculate the sum of distinct (unique) values in a numeric column, you can use theSUM(DISTINCT column_name)
syntax.
SELECT SUM(DISTINCT price) FROM products;
- Calculate the Sum of Values Grouped by a Column:
When you want to calculate the sum of values for each group within a dataset, you can use theGROUP BY
clause with theSUM()
function.
SELECT department, SUM(salary) FROM employees GROUP BY department;
The SUM()
function always returns a numeric result. It is a useful tool for calculating totals, subtotals, and aggregating data for reporting and analysis in your database.