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
1 row

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
1 row

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
1 row

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)
10810
1 row

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)
104
1 row

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:

FunctionGives
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)
89057.515.0150.0
1 row

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
1 row

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;
totalitems
490.08
1 row

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_orderlast_order
2026-09-022026-11-25
1 row
SELECT min(name), max(name) FROM customer;
min(name)max(name)
Anan WongsaWichai Saelim
1 row

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.666666666666746.67
1 row

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)
0NULL0.0NULLNULL
1 row

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
1 row

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
1 row

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
1 row

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;
citycount(*)
Bangkok10
1 row

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;
namemax(price)
Cashew Nuts150.0
1 row

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);
Error: misuse of aggregate: avg()

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.

  1. How many products are out of stock (stock = 0)?
  2. How many items has the shop sold altogether (the sum of qty), and how many different products has it ever sold (product_id counted once each), from order_item?
  3. In the snacks (category_id = 3), what are the lowest and highest prices, and the average rounded to 2 places?
  4. The customers' cities in one text, each city once (use DISTINCT inside group_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
1 row
sum(qty)count(DISTINCT product_id)
9611
1 row
min(price)max(price)round(avg(price), 2)
25.0150.088.33
1 row
group_concat(DISTINCT city)
Bangkok,Chiang Mai,Phuket,Khon Kaen
1 row

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