Function Reference

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;
total
92533

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;
family_memberspent
112504
274644
33659
4650
51076

Empty set of rows

PostgreSQL 17.5
SELECT SUM(unit_price) AS total
FROM Payments
WHERE unit_price < 0;
total
<NULL>

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 ...).

See also

Where to learn