Cover Image for MySQL sum()
73 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:

  1. Calculate the Sum of Values in a Column:
    To calculate the sum of all values in a numeric column, use SUM(column_name).
   SELECT SUM(salary) FROM employees;
  1. Calculate the Sum of Values Based on a Condition:
    You can calculate the sum of values that meet specific conditions by using the SUM() function with a WHERE clause.
   SELECT SUM(sales_amount) FROM sales WHERE year = 2023;
  1. 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 the SUM(DISTINCT column_name) syntax.
   SELECT SUM(DISTINCT price) FROM products;
  1. 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 the GROUP BY clause with the SUM() 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.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS