9. Aggregates: counting, adding up, averaging
Questions with one number for an answer: how many customers, how much was sold, what the dearest product costs.
Counting rows with count(*)
So far every result came a row at a time. Many questions want a single answer, though: "how many customers does the shop have?" An aggregate function does that: it reads many rows and sums them up into one value.
The one used most is count(*), which counts rows:
SELECT count(*) FROM customer;| count(*) |
|---|
| 10 |
The shop has 10 customers. The result has one row, however many rows the table has.
WHERE works as usual: the database filters the rows first, then counts only those that pass:
SELECT count(*) FROM orders WHERE status = 'paid';| count(*) |
|---|
| 8 |
8 orders have been paid.
Name the result's column with AS, as with any expression; it reads better than count(*):
SELECT count(*) AS products_out_of_stock FROM product WHERE stock = 0;| products_out_of_stock |
|---|
| 2 |
count(column) skips NULL
With a column's name instead of *, count counts only the rows where that column is not NULL:
SELECT count(*), count(phone), count(city) FROM customer;| count(*) | count(phone) | count(city) |
|---|---|---|
| 10 | 8 | 10 |
There are 10 customers, but only 8 phone numbers: the other 2 are NULL. Every one of the 10 has a city.
To know how many different values there are, put DISTINCT inside the brackets:
SELECT count(city), count(DISTINCT city) FROM customer;| count(city) | count(DISTINCT city) |
|---|---|
| 10 | 4 |
The 10 customers live in just 4 cities. count(DISTINCT ...) drops the repeats first, then counts (and it skips NULL too).
An easy way to remember: count(*) counts rows, count(column) counts values that are there. How many customers? count(*). How many gave a phone number? count(phone).
sum, avg, min, max
Four more, used every day:
| Function | Gives |
|---|---|
sum(x) | the total |
avg(x) | the average |
min(x) | the smallest value |
max(x) | the largest value |
SELECT sum(stock), avg(price), min(price), max(price) FROM product;| sum(stock) | avg(price) | min(price) | max(price) |
|---|---|---|---|
| 890 | 57.5 | 15.0 | 150.0 |
890 items in stock altogether; the average price is 57.5 baht, the cheapest 15 baht, the dearest 150 baht.
The brackets take any expression, not just a column. The shop's sales are quantity × price of every line, added up:
SELECT sum(qty * price) AS sales FROM order_item;| sales |
|---|
| 3440.0 |
Every line together comes to 3,440 baht (cancelled orders included, since nothing is filtered out yet).
And WHERE narrows it down, here to order number 9 alone:
SELECT sum(qty * price) AS total, sum(qty) AS items FROM order_item WHERE order_id = 9;| total | items |
|---|---|
| 490.0 | 8 |
Order 9 has 8 items and comes to 490 baht.
min and max work on text and dates too: text compares in alphabetical order, and dates written YYYY-MM-DD compare as they are:
SELECT min(ordered) AS first_order, max(ordered) AS last_order FROM orders;| first_order | last_order |
|---|---|
| 2026-09-02 | 2026-11-25 |
SELECT min(name), max(name) FROM customer;| min(name) | max(name) |
|---|---|
| Anan Wongsa | Wichai Saelim |
The first order came on 2 September 2026, the latest on 25 November 2026. The customer first in alphabetical order is Anan Wongsa, the last Wichai Saelim.
Rounding an average
An average often has a long tail of decimals. round(value, digits) makes it readable:
SELECT avg(price), round(avg(price), 2) FROM product WHERE category_id = 1;| avg(price) | round(avg(price), 2) |
|---|---|
| 46.6666666666667 | 46.67 |
The average price of the drinks (category_id = 1) is 46.666..., rounded to 46.67.
avg always gives a decimal, even for a column of whole numbers, but sum of whole numbers gives a whole number. If you divide a sum yourself, remember chapter 2's 10 / 4 giving 2: multiply by 1.0 first, or just use avg.
When there are no rows: sum and total
When WHERE leaves no rows at all, an aggregate still answers with one row, but the values may not be what you expect:
SELECT count(*), sum(price), total(price), avg(price), max(price) FROM product WHERE price > 1000;| count(*) | sum(price) | total(price) | avg(price) | max(price) |
|---|---|---|---|---|
| 0 | NULL | 0.0 | NULL | NULL |
count(*)gives0: right, no rows.sum,avgandmaxgiveNULL: "nothing to work out".total(price)is SQLite's own: it works likesum, but with no rows it gives0.0instead ofNULL, and its result is always a decimal.
To get 0 instead of NULL with the standard sum, write coalesce(sum(price), 0) (chapter 15 tells you about coalesce).
total() is only in SQLite and Phai SQL; other databases haven't got it. For SQL that may move to another database one day, coalesce(sum(...), 0) is the safer choice.
Joining text with group_concat and string_agg
An aggregate doesn't have to give a number. group_concat(x, separator) joins the values of every row into one text:
SELECT group_concat(name, ', ') AS drinks FROM product WHERE category_id = 1;| drinks |
|---|
| Coffee, Green Tea, Orange Juice |
string_agg(x, separator) does the same; it is the name other databases use (PostgreSQL, SQL Server):
SELECT string_agg(name, ' / ') AS drinks FROM product WHERE category_id = 1;| drinks |
|---|
| Coffee / Green Tea / Orange Juice |
DISTINCT works in group_concat as in count, but then the brackets may hold only the one value (no separator of your own: you always get commas).
ORDER BY inside the brackets (SQLite since version 3.44, and Phai SQL) sets the order of the values in the text. From cheapest to dearest:
SELECT string_agg(name, ', ' ORDER BY price) FROM product WHERE category_id = 1;| string_agg(name, ', ' ORDER BY price) |
|---|
| Orange Juice, Green Tea, Coffee |
Without ORDER BY, the values come in the order the database reads the rows, which nothing promises. When the order matters, always put ORDER BY inside the brackets; it works in group_concat and json_group_array too.
Why plain columns don't mix with aggregates
An aggregate folds many rows into one. Ask for a plain column beside it, such as city, and which row's city should the database put there, when the 10 rows have several cities?
SELECT city, count(*) FROM customer;| city | count(*) |
|---|---|
| Bangkok | 10 |
Most databases refuse this statement. SQLite and Phai SQL run it, but the city is that of some row or other and means nothing: it reads as if all 10 customers lived in Bangkok.
SQLite's one useful exception: with a single min() or max(), a plain column comes from the row that has that value:
SELECT name, max(price) FROM product;| name | max(price) |
|---|---|
| Cashew Nuts | 150.0 |
The dearest product is Cashew Nuts at 150 baht. This only works in SQLite and Phai SQL, though.
Another place an aggregate can't go is WHERE: WHERE decides one row at a time, before any total exists. Ask "how many products cost more than the average?" head on:
SELECT count(*) FROM product WHERE price > avg(price);For "a number for each city", don't just put the column beside the aggregate as above: tell the database how to split the rows into groups, with GROUP BY, chapter 10's subject. "Products dearer than the average" needs a subquery, in chapter 13.
- How many products are out of stock (
stock = 0)? - How many items has the shop sold altogether (the sum of
qty), and how many different products has it ever sold (product_idcounted once each), fromorder_item? - In the snacks (
category_id = 3), what are the lowest and highest prices, and the average rounded to 2 places? - The customers' cities in one text, each city once (use
DISTINCTinsidegroup_concat).
Show the answer
SELECT count(*) FROM product WHERE stock = 0;
SELECT sum(qty), count(DISTINCT product_id) FROM order_item;
SELECT min(price), max(price), round(avg(price), 2) FROM product WHERE category_id = 3;
SELECT group_concat(DISTINCT city) FROM customer;| count(*) |
|---|
| 2 |
| sum(qty) | count(DISTINCT product_id) |
|---|---|
| 96 | 11 |
| min(price) | max(price) | round(avg(price), 2) |
|---|---|---|
| 25.0 | 150.0 | 88.33 |
| group_concat(DISTINCT city) |
|---|
| Bangkok,Chiang Mai,Phuket,Khon Kaen |
Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made