SUM()
Adds up all the values in a numeric column across a group of rows.
Description
SUM is an aggregate function that adds together all the values in a
numeric column across the rows in a result set. It's one of the most common
functions for reporting totals, like total revenue, total quantity sold, or
total salary paid.
Syntax
SUM(column_name)Parameters
| Name | Description | Optional |
|---|---|---|
| expression | The numeric column or expression whose values should be added together. NULL values are ignored. | No |
Return Type
SUM typically returns a DOUBLE (or a larger integer type when summing
integers), matching or widening the type of the input column so the total
doesn't overflow.
Examples
Loading database engine...
Loading database engine...
NULLs don't break your total
SUM ignores NULL values rather than turning the whole result into NULL.
If every value in the group is NULL, SUM returns NULL, but a mix of
numbers and NULLs still sums correctly.
Common Mistakes
- Summing a column that isn't actually numeric, like an ID column, which produces a meaningless total.
- Forgetting
GROUP BY.SELECT customer_id, SUM(quantity) FROM orderswithoutGROUP BY customer_idwill error in most databases becausecustomer_idisn't aggregated. - Confusing
SUMwithCOUNT.SUM(quantity)adds up the quantities themselves, whileCOUNT(quantity)just counts how many rows have a quantity value, regardless of its size.
Related Functions
See also: COUNT, AVG, MAX.