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 dependant 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 REAL

  • 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,
   "Team" text,
   "Number" tinyint,
   "Position" text,
   "Age" tinyint,
   "Height" text,
   "Weight" real,
   "College" text,
   "Salary" float
 );

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

nba.csv

Avery Bradley

Boston Celtics

0

PG

25

2-Jun

180

Texas

7730337

Jae Crowder

Boston Celtics

99

SF

25

6-Jun

235

Marquette

6796117

John Holland

Boston Celtics

30

SG

27

5-Jun

205

Boston University

R.J. Hunter

Boston Celtics

28

SG

22

5-Jun

185

Georgia State

1148640

Jonas Jerebko

Boston Celtics

8

PF

29

10-Jun

231

5000000

Amir Johnson

Boston Celtics

90

PF

29

9-Jun

240

12000000

Jordan Mickey

Boston Celtics

55

PF

21

8-Jun

235

LSU

1170960

Kelly Olynyk

Boston Celtics

41

C

25

Jul-00

238

Gonzaga

2165160

Terry Rozier

Boston Celtics

12

PG

22

2-Jun

190

Louisville

1824360

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