Aggregate functions

Topic 1 of 4 in Summarising data10 min readBeginnerFree course

Overview

Until now every query has returned one result row per table row. Business questions are usually about totals: how many customers, how much revenue, the average order, the latest signup. Aggregate functions answer those by collapsing many rows into a single value.

Aggregate functions turn many rows into one. The twelve values of products.price — 14.50, 12.00, 11.25, 18.00, 9.50, 12.75, 8.00, 24.00, 89.00, 59.90, 32.00 and 25.00 — become single values: count() is 12, min(price) is 8.00, max(price) is 89.00, sum(price) is 315.90, avg(price) is 26.3250000…, and round(avg(price), 2) is 26.33. An aggregate turns a whole column — or each group, in the next lesson — into a single value. Aggregates ignore NULLs, except count(), which counts rows; count(phone) counts only rows that have a phone. Filter before aggregating with WHERE, or inside the aggregate with count(*) FILTER (WHERE stock = 0).

The five essentials

SQL
SELECT count(*)              AS products,
       min(price)            AS cheapest,
       max(price)            AS dearest,
       sum(price)            AS total,
       round(avg(price), 2)  AS average
FROM products;
Text
 products | cheapest | dearest | total  | average 
----------+----------+---------+--------+---------
       12 |     8.00 |   89.00 | 315.90 |   26.33
(1 row)

Twelve rows went in; one row came out. Each function looked at the whole price column and produced a single answer.

  • count(*) — how many rows.
  • sum(x) — the total of a numeric column.
  • avg(x) — the mean. It returns a long numeric, so it’s usually wrapped in round.
  • min(x) and max(x) — the smallest and largest values. They work on text (alphabetically first and last) and dates (earliest and latest), not just numbers.
SQL
SELECT min(signup_date)  AS first_signup,
       max(signup_date)  AS latest_signup,
       min(last_name)    AS first_alphabetically,
       max(last_name)    AS last_alphabetically
FROM customers;
Text
 first_signup | latest_signup | first_alphabetically | last_alphabetically 
--------------+---------------+----------------------+---------------------
 2025-11-03   | 2026-09-15    | Ali                  | Wilson
(1 row)

Aggregates and WHERE

WHERE filters rows before they’re aggregated, so it controls what gets counted:

SQL
SELECT count(*)          AS teas,
       sum(stock)        AS units,
       sum(price * stock) AS stock_value
FROM products
WHERE category_id = 2;
Text
 teas | units | stock_value 
------+-------+-------------
    4 |   147 |     1688.50
(1 row)

Notice that sum(price * stock) aggregates an expression: the database calculates price * stock for each tea and then adds those results up.

Counting: three kinds of count

count comes in three flavours, and the difference matters:

SQL
SELECT count(*)                 AS customers,
       count(phone)             AS with_phone,
       count(DISTINCT country)  AS countries,
       count(DISTINCT city)     AS cities
FROM customers;
Text
 customers | with_phone | countries | cities 
-----------+------------+-----------+--------
        10 |          6 |         7 |      9
(1 row)
  • count(*) counts rows, whatever they contain.
  • count(phone) counts rows where phone is not NULL — 6 of the 10 customers have a phone number.
  • count(DISTINCT country) counts different values — 7 countries, because India and the USA each have more than one customer. DISTINCT works inside sum and avg too, though that’s rarely what you want.

NULLs are skipped

Apart from count(*), aggregate functions ignore NULLs. Usually that’s right — an unknown value shouldn’t drag an average down — but it’s worth seeing:

SQL
SELECT count(*)            AS rows,
       count(category_id)  AS with_category,
       avg(category_id)    AS avg_of_known
FROM products;
Text
 rows | with_category |    avg_of_known    
------+---------------+--------------------
   12 |            11 | 2.0909090909090909
(1 row)

Twelve rows, but avg divided by 11, because the gift card’s NULL category was left out. (An average of category ids means nothing in itself — it’s only here to show what gets counted.) If missing values should count as zero, say so: avg(COALESCE(x, 0)).

Aggregating nothing

What happens when WHERE leaves no rows at all?

SQL
SELECT count(*)    AS how_many,
       sum(price)  AS total,
       max(price)  AS dearest
FROM products
WHERE category_id = 4;
Text
 how_many | total | dearest 
----------+-------+---------
        0 |       |        
(1 row)

There are no accessories yet. count honestly answers 0, but sum, avg, min and max return NULL — there’s nothing to add up. You still get exactly one row. In reports, wrap sums in COALESCE(sum(x), 0) so an empty category shows 0 instead of a blank.

FILTER: conditional aggregates

Often you want several totals from the same rows: all orders, delivered orders, cancelled orders. The FILTER clause restricts one aggregate to the rows that match its condition:

SQL
SELECT count(*)                                          AS all_orders,
       count(*) FILTER (WHERE status = 'delivered')      AS delivered,
       count(*) FILTER (WHERE status = 'cancelled')      AS cancelled,
       count(*) FILTER (WHERE status IN ('pending', 'paid', 'shipped')) AS open,
       sum(shipping_fee) FILTER (WHERE status <> 'cancelled') AS shipping_charged
FROM orders;
Text
 all_orders | delivered | cancelled | open | shipping_charged 
------------+-----------+-----------+------+------------------
         24 |        16 |         2 |    6 |           124.95
(1 row)

One pass over the table, five answers. FILTER is standard SQL, supported by PostgreSQL and SQLite. In databases without it (MySQL, SQL Server), use the CASE pattern from the previous lesson: sum(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) — it gives the same result.

Joining text with string_agg

string_agg(expression, separator) is an aggregate for text: it joins the values from many rows into one string. You can add ORDER BY inside the brackets to control the order:

SQL
SELECT string_agg(first_name, ', ' ORDER BY first_name) AS indian_customers
FROM customers
WHERE country = 'India';
Text
  indian_customers  
--------------------
 Asha, Farhan, Isha
(1 row)

Its cousin array_agg collects values into a PostgreSQL array instead: array_agg(id ORDER BY id) gives {1,3,9,17,23}. Other useful aggregates include bool_and / bool_or (are all / any of these true?) and statistical ones such as stddev and percentile_cont.

SQL
SELECT bool_and(price > 5)   AS all_over_5,
       bool_or(stock = 0)    AS any_out_of_stock,
       percentile_cont(0.5) WITHIN GROUP (ORDER BY price) AS median_price
FROM products;
Text
 all_over_5 | any_out_of_stock | median_price 
------------+------------------+--------------
 t          | t                |        16.25
(1 row)

The median (16.25) is far below the mean (26.33) because two expensive machines pull the average up — a good reminder that the average isn’t always the “typical” value.

The one rule: no loose columns

Try to show a product name next to the maximum price:

SQL
SELECT name, max(price) FROM products;
Text
ERROR:  column "products.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT name, max(price) FROM products;
               ^

PostgreSQL refuses, and for a good reason. max(price) produces one row, but there are twelve names — which one should it show? An aggregate query returns one row per group, so every column must either be aggregated or be part of the grouping. Without GROUP BY, the whole table is one group and plain columns aren’t allowed.

How to find which product is the most expensive? Sort and limit (ORDER BY price DESC LIMIT 1), or use a subquery — both coming up. And to get one result row per category, per customer or per month, you need GROUP BY, which is the next lesson.

Other databases: MySQL, in some configurations, allows SELECT name, max(price) and returns an arbitrary name next to the maximum — a classic source of wrong reports. PostgreSQL’s strictness saves you from that.

Exercise

The order book at a glance

The owners want a one-line summary of all orders. Write a single query over orders that returns: total_orders (every order), delivered (only orders with status 'delivered', using FILTER), customers (how many different customers have ordered), first_order and last_order (the earliest and latest ordered_at), and avg_shipping (the average shipping fee rounded to 2 decimal places).

SQL
SELECT count(*) AS total_orders
FROM orders;

Summary

  • Aggregate functions — count, sum, avg, min, max — combine many rows into a single value.
  • count(*) counts rows; count(column) counts non-NULL values; count(DISTINCT column) counts different values.
  • sum, avg, min and max ignore NULLs; over zero rows, count returns 0 and the others return NULL.
  • aggregate(...) FILTER (WHERE condition) aggregates only the rows that match, so one query can produce several conditional totals.
  • string_agg(text, separator) joins values into one string; without GROUP BY, you can't mix aggregates with plain columns.