PostgreSQL COUNT, SUM & AVG
Three more aggregate functions answer the most common business questions: how many? (count), how much in total? (sum) and how much on average? (avg).
COUNT
count(*) counts rows. count(column) counts only the rows where that column is not NULL, which is a subtle but important difference:
SELECT count(*) AS customers,
count(email) AS with_email,
count(*) - count(email) AS without_email,
count(DISTINCT city) AS cities
FROM customers; customers | with_email | without_email | cities
-----------+------------+---------------+--------
15 | 12 | 3 | 14
(1 row)
Combine it with WHERE to count matching rows:
SELECT count(*) AS out_of_stock FROM books WHERE stock = 0; out_of_stock
--------------
2
(1 row)
SUM
sum(expression) adds up the values. How many books are in the warehouse, and what are they worth?
SELECT sum(stock) AS copies_in_stock,
sum(price * stock) AS stock_value
FROM books; copies_in_stock | stock_value
-----------------+-------------
188 | 3240.44
(1 row)
The total revenue of all delivered orders, computed from the order lines:
SELECT sum(oi.quantity * oi.unit_price) AS delivered_revenue
FROM order_items oi
JOIN orders o ON o.id = oi.order_id
WHERE o.status = 'delivered'; delivered_revenue
-------------------
650.85
(1 row)
(The JOIN combines order lines with their orders; joins have their own lessons soon.)
AVG
avg(expression) returns the arithmetic mean. The result of avg on integers or numeric is a numeric with many decimal places, so you will usually round it:
SELECT avg(price) AS raw_average,
round(avg(price), 2) AS average_price,
round(avg(stock), 1) AS average_stock
FROM books; raw_average | average_price | average_stock
---------------------+---------------+---------------
20.8900000000000000 | 20.89 | 9.4
(1 row)
NULLs are skipped, not counted as zero
All three functions ignore NULLs (only count(*) counts every row). That changes averages:
CREATE TABLE ratings (book_id integer, stars integer);
INSERT INTO ratings VALUES (1, 5), (1, 3), (1, NULL), (2, NULL);
SELECT count(*) AS rows, count(stars) AS rated,
sum(stars) AS total_stars,
avg(stars) AS avg_of_rated,
round(avg(coalesce(stars, 0)), 2) AS avg_null_as_zero
FROM ratings;
SELECT sum(stars) AS sum_of_nothing, count(stars) AS count_of_nothing
FROM ratings WHERE book_id = 2;CREATE TABLE
INSERT 0 4
rows | rated | total_stars | avg_of_rated | avg_null_as_zero
------+-------+-------------+--------------------+------------------
4 | 2 | 8 | 4.0000000000000000 | 2.00
(1 row)
sum_of_nothing | count_of_nothing
----------------+------------------
| 0
(1 row)
Notice that the sum of no values is NULL, while count of no values is 0. Wrap a sum in coalesce(sum(x), 0) when you want a zero.
Aggregates with FILTER
PostgreSQL lets you attach a FILTER (WHERE …) to any aggregate. This computes several conditional counts in one pass over the table:
SELECT count(*) AS all_orders,
count(*) FILTER (WHERE status = 'delivered') AS delivered,
count(*) FILTER (WHERE status = 'cancelled') AS cancelled,
count(*) FILTER (WHERE order_date < '2024-07-01') AS first_half
FROM orders; all_orders | delivered | cancelled | first_half
------------+-----------+-----------+------------
20 | 14 | 2 | 11
(1 row)
Summary
| Function | Returns | NULL inputs | No rows |
|---|---|---|---|
count(*) |
number of rows | counted | 0 |
count(x) |
number of non-NULL x |
skipped | 0 |
sum(x) |
total | skipped | NULL |
avg(x) |
mean | skipped | NULL |
Note:
countreturns abigint.sumof anintegercolumn returns abiginttoo, so it doesn't overflow easily.
Test yourself
The table has 15 customers, 3 with NULL email. What is count(email)?
- 15
- 12
- 3
- NULL
What does sum(x) return if every x is NULL?
- 0
- NULL
- An error
- The row count
Values 4, 2 and NULL. What is avg(value)?
- 2
- 3
- 6
- NULL