Add up and count

INPUT · Slides

Working out an average

01 / 04

A total does not let you compare

A total tells you "how much altogether". But when the other side has a different number of records, comparing totals is unfair.

So instead you ask how much per record. That is the average, and AVG gives it to you.

02 / 04

AVG for an average

AVG(column) gives the average of that column. It is the total divided by how many there were.

The prices in sales come to 9000 across eight records. So the average is 1125.

SELECT AVG(price) FROM sales;

Result

1125

03 / 04

Empty rows are not counted either

This is the important bit about AVG. A row with no value is left out of the dividing as well.

Two of the eight rows have no rating. The total is 24, but it gets divided by the six that had a value, not by eight. So the answer is 4.

SELECT SUM(rating), AVG(rating)  FROM sales;

Result

24 | 4

04 / 04

Narrow first, then average

Narrow the rows with WHERE and you get the average within them. You could compare how dear each stall's range is, for instance.

A total and an average can sit in the same query. You can line up as many aggregate functions as you like. Let us write some.

SELECT AVG(price) FROM sales  WHERE stall = 'Komorebi Studio';

Result

700