sajad torkamani

SUM() is an aggregate function that lets you calculate the sum of values in a set.


SUM(DISTINCT expression)

Example & execution plan

select sum(salary) from salaries;

The above query will be handled by MySQL as follows:

  1. Read through the salaries table and extract the value from the salary column for each row.
  2. For each value in the salary column, add it to a running total.
  3. Return the running total as the value of the SUM() function.

By default SUM() will calculate the sum of all values in the set, including duplicate values. You can prefix your expression with DISTINCT to tell MySQL only to sum the values that are distinct.

Tagged: MySQL