SUM
Returns the sum of the expression values in a group of rows.
MySQL 8.1
SUM([DISTINCT] expr)Parameters
- DISTINCTkeywordoptional
- Sum only unique values
- exprDECIMAL
- Numeric expression whose values are summed
Return value
A number: DECIMAL for integer and DECIMAL values, DOUBLE for floating-point numbers; NULLs are ignored, NULL for an empty set, not 0
Examples
Total of all payments
MySQL 8.1
SELECT SUM(amount * unit_price) AS total
FROM Payments;Spending of each family member
MySQL 8.1
SELECT family_member,
SUM(amount * unit_price) AS spent
FROM Payments
GROUP BY family_member;Empty set of rows
MySQL 8.1
SELECT SUM(unit_price) AS total
FROM Payments
WHERE unit_price < 0;Details
If there are no matching rows or all values are NULL, the result is NULL, not 0. To get 0, wrap the sum: IFNULL(SUM(x), 0) or COALESCE(SUM(x), 0).