SUM

sum([distinct] expr)

Function Description

The SUM function is used to calculate and return the total sum of a set of numeric data. If the DISTINCT keyword is specified, the sum of the distinct set of values will be calculated.

Parameter Description

  • expr: The numeric type field to be summed, which can be of type tinyint, smallint, int, bigint, float, double, or decimal.

Return Type

  • For decimal type data, a decimal type result is returned. In other cases, a double type result is returned.
  • When the distinct keyword is specified, the sum of the distinct set of values will be returned.
  • If the expression contains null values, the null values will not participate in the calculation.

Usage Example

  1. Calculate the total sum of all values:
SELECT sum(col) FROM VALUES (5), (10), (10), (15), (null) AS tab(col);
+------------+
| `sum`(col) |
+------------+
| 40         |
+------------+
  1. Calculate the sum of the deduplicated set of values:
SELECT sum(DISTINCT col) FROM VALUES (5), (10), (10), (15), (null) AS tab(col);
+---------------------+
| `sum`(DISTINCT col) |
+---------------------+
| 30                  |
+---------------------+

By the above example, you can better understand the usage and application scenarios of the SUM function. Please adjust the parameters and expressions according to your actual needs.