SUM
Returns the sum of the expression values in a group of rows.
PostgreSQL 17.5
SUM([DISTINCT] expression)Parameters
- DISTINCTkeywordoptional
- Sum only unique values
- expressionnumeric
- Numeric expression whose values are summed
Return value
A number: bigint for smallint and integer, numeric for bigint and numeric, the same type for real and double precision; NULLs are ignored, NULL for an empty set, not 0
Examples
Total of all payments
PostgreSQL 17.5
SELECT SUM(amount * unit_price) AS total
FROM Payments;Spending of each family member
PostgreSQL 17.5
SELECT family_member,
SUM(amount * unit_price) AS spent
FROM Payments
GROUP BY family_member
ORDER BY family_member;Empty set of rows
PostgreSQL 17.5
SELECT SUM(unit_price) AS total
FROM Payments
WHERE unit_price < 0;Details
To get 0 for an empty set, wrap the result in COALESCE: COALESCE(SUM(amount), 0). To sum only some rows of a group, use FILTER (WHERE ...).