PostgreSQL 18 reference · Aggregate Functions

PostgreSQL SUM() Function

Add up the non-NULL values in a group. Returns NULL, not 0, when there are no rows; wrap it in coalesce() if needed.

PostgreSQL 18

Create a free account to save this page, take notes and track your progress. Sign in

Syntax

sum(expression)

Parameters

ParameterDescription
expression A column or expression.

Return value

bigint for integers, numeric for numeric, or NULL for no rows.

Examples

Totals per order
SELECT order_id, sum(quantity * unit_price) AS total
FROM order_items
GROUP BY order_id
ORDER BY total DESC
LIMIT 3;

Output

 order_id | total
----------+--------
        9 | 658.00
        4 | 408.90
        7 | 114.99
(3 rows)

Run this on your computer — see “Get Started” for setup.

No rows gives NULL
SELECT sum(price) AS raw, coalesce(sum(price), 0) AS safe
FROM products
WHERE price > 1000;

Output

 raw  | safe
------+------
 NULL |    0
(1 row)

Run this on your computer — see “Get Started” for setup.

In other languages

Was this page helpful?