SUM

Returns the sum of numeric values, or only the distinct values.

Syntax

-- As an aggregate
SUM( [ DISTINCT ] expr )

-- As a window function
SUM ( expr ) OVER (
         [ PARTITION BY value_expression [, ...] ]
         [ ORDER BY value_expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ]
         [ frame_clause ]
      )

Arguments

Parameter

Description

expr

Numeric expression

DISTINCT

Specifies that the operation should operate only on unique values

Returns

Return type is dependent on the argument.

  • For TINYINT, SMALLINT and INT, the return type is INT

  • For BIGINT, the return type is BIGINT

  • For REAL, the return type is DOUBLE

  • For DOUBLE, rhe return type is DOUBLE

Notes

  • NULL values are ignored

  • Because SUM returns the same data type, it can very quickly overflow on large data sets. If the SUM is over 231 for example, up-cast to a larger type like BIGINT: SUM(expr :: BIGINT)

Examples

For these examples, assume a table named nba, with the following structure:

CREATE TABLE nba
(
   "Name" text(40),
   "Team" text(40),
   "Number" tinyint,
   "Position" text(2),
   "Age" tinyint,
   "Height" text(4),
   "Weight" real,
   "College" text(40),
   "Salary" float
 );

Here’s a peek at the table contents (Download nba.csv):

nba.csv

Name

Team

Number

Position

Age

Height

Weight

College

Salary

Avery Bradley

Boston Celtics

0.0

PG

25.0

6-2

180.0

Texas

7730337.0

Jae Crowder

Boston Celtics

99.0

SF

25.0

6-6

235.0

Marquette

6796117.0

John Holland

Boston Celtics

30.0

SG

27.0

6-5

205.0

Boston University

R.J. Hunter

Boston Celtics

28.0

SG

22.0

6-5

185.0

Georgia State

1148640.0

Jonas Jerebko

Boston Celtics

8.0

PF

29.0

6-10

231.0

5000000.0

Amir Johnson

Boston Celtics

90.0

PF

29.0

6-9

240.0

12000000.0

Jordan Mickey

Boston Celtics

55.0

PF

21.0

6-8

235.0

LSU

1170960.0

Kelly Olynyk

Boston Celtics

41.0

C

25.0

7-0

238.0

Gonzaga

2165160.0

Terry Rozier

Boston Celtics

12.0

PG

22.0

6-2

190.0

Louisville

1824360.0

Simple sum

t=> SELECT SUM("Age") FROM nba;
sum
-----
12311

Sum only distinct values

t=> SELECT SUM(DISTINCT "Age") FROM nba;
sum
---
649

Combine sum with GROUP BY

t=> SELECT "Age", SUM("Salary") FROM nba GROUP BY 1;
Age | sum
----+----------
 19 |   3860880
 20 |  51790026
 21 |  39280213
 22 |  61307050
 23 |  79355103
 24 | 170338514
 25 | 172958166
 26 | 247196385
 27 | 267069647
 28 | 153305658
 29 | 168052779
 30 | 211855757
 31 | 187250724
 32 | 100320456
 33 |  55030346
 34 |  76060300
 35 |  27693918
 36 |  22381196
 37 |  38333334
 38 |   7360164
 39 |   5035745
 40 |  14000750