Appearance
SUM
Return the sum of the values for a numeric expression.
SUM(expression)
The expression must be numeric.
The following example calculates the total capacity for all of the stadiums used by London teams.
premdb=# SELECT SUM(capacity) FROM team WHERE city='London';
sum
--------
296983
(1 row)
The following example returns the five cities that have the highest total stadium capacity:
premdb=# SELECT city, SUM(capacity) FROM team
GROUP BY city ORDER BY 2 desc LIMIT 5;
city | sum
------------+--------
London | 296983
Manchester | 130732
Birmingham | 99801
Liverpool | 84963
Sheffield | 72434
(5 rows)
Return Types
The return type of the SUM function depends on the input type. The result is promoted where possible to prevent overflow errors.
SUM(INT2)
returnsINT8
SUM(INT4)
returnsINT8
SUM(INT8)
returnsINT8
SUM(FLOAT4)
returnsFLOAT8
SUM(FLOAT8)
returnsFLOAT8
AVG(DECIMAL(p,s))
returnsDECIMAL(38,s)
Parent topic:Aggregate Functions