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
Syntax
sum(expression)
Parameters
| Parameter | Description |
|---|---|
expression |
A column or expression. |
Return value
bigint for integers, numeric for numeric, or NULL for no rows.
Examples
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.
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
Related
AVG()· Return the average of the non-NULL values in a group. Integer input gives a numeric result with full precision.COUNT()· Count rows: count(*) counts every row, count(x) skips NULLs, and count(DISTINCT x) counts unique values. Returns bigint.COALESCE()· Return the first argument that isn't NULL. The standard way to replace NULL with a default.- SQL Aggregate Functions · tutorial
- SQL GROUP BY · tutorial