Late at night, after her shop closes, Mrs. Sri does not read every sale of the day again. She only needs a few numbers: how many sales, the total money in, the average spend per customer, and the smallest and the largest purchase. Dozens of lines become a few numbers.
In SQL, a summary like Mrs. Sri's few numbers is made with aggregate functions (aggregate means combined). A function is a name followed by parentheses, for example COUNT(*), and it gives one result. Each aggregate function summarises many rows into one value: how many rows there are, what the total is, what the average is, which is the smallest and which is the largest.
Five aggregate functions
The products table in the Lab and the exercise:
| id | name | price | category |
|---|---|---|---|
| 1 | Laptop | 1200 | electronics |
| 2 | Mouse | 15 | electronics |
| 3 | Notebook | 4 | stationery |
| 4 | Monitor | 350 | electronics |
| 5 | Pen | 1 | stationery |
These are five aggregate functions, with their results on the products table:
| Function | Meaning | Result on products |
|---|---|---|
COUNT(*) |
the number of rows | 5 |
SUM(price) |
every value added up | 1570 |
AVG(price) |
the average: the sum divided by how many | 314 |
MIN(price) |
the smallest value | 1 |
MAX(price) |
the largest value | 1200 |
Another small example: if the score column holds 80, 90 and 70, SUM(score) = 240 and AVG(score) = 240 / 3 = 80.
Many rows become one row
The products table has 5 rows. Before you look at the result of the query below, guess: how many rows come back?
SELECT
COUNT(*) AS total_products,
AVG(price) AS avg_price,
MAX(price) AS max_price
FROM products;
| total_products | avg_price | max_price |
|---|---|---|
| 5 | 314 | 1200 |
The result is one row, even though the table has 5 rows. Each aggregate function summarises all the rows into one value, so the result is just 1 row.
COUNT(*)counts rows. The*here means "any row", not "every column".AVG(price)adds up everyprice, then divides the sum by the number of prices: 1,570 / 5 = 314.MAX(price)takes the largest price.AS total_productsgives theCOUNT(*)column a new heading, called an alias. WithoutAS, its heading staysCOUNT(*). In the exercise, the checker looks for a column namedtotal_products.- Several functions may go in one
SELECT, separated by commas.
Aggregates with WHERE
Aggregate functions also work together with WHERE. The query below summarises only the electronics products:
SELECT COUNT(*) AS total_products, AVG(price) AS avg_price
FROM products
WHERE category = 'electronics';
| total_products | avg_price |
|---|---|
| 3 | 521.6666666666666 |
WHERE runs first, and only the 3 electronics rows pass: Laptop, Mouse, Monitor. Then the aggregate functions summarise only those three rows. So avg_price is (1,200 + 15 + 350) / 3.
NULL is skipped
SUM, AVG, MIN, MAX and COUNT(column) (COUNT with a column name in the parentheses) skip NULL: a NULL value is not counted. But COUNT(*) still counts a row that holds NULL. Say there is a sixth product, Stapler, whose price is NULL:
COUNT(*)= 6, because there are 6 rows.COUNT(price)= 5, because only 5 products have a price.AVG(price)stays 314, because NULL is not counted as 0.AVGalways gives a decimal number, so sqlite3 in the terminal writes it as314.0.
COUNT(DISTINCT category) counts only the different values: the result is 2 (electronics and stationery).
💡 SQLite, MySQL and PostgreSQL differ here
- Integer division.
SELECT 7 / 2;gives 3 in SQLite and PostgreSQL (the remainder is dropped), and 3.5000 in MySQL.AVGis safe in all three: its result is always a decimal number, so no remainder is dropped. - A plain column next to an aggregate.
SELECT name, MAX(price) FROM products;runs in SQLite and gives Laptop. MySQL (5.7 and later, with its default settings) and PostgreSQL refuse it, becausenameis not a summary. To get the name of the most expensive product, useORDER BY price DESC LIMIT 1.
⚠️ Wrong place, wrong name, wrong count
- An aggregate in WHERE. SQLite refuses
SELECT name FROM products WHERE price = MAX(price);withmisuse of aggregate function MAX().WHEREchecks the rows one by one, whileMAXneeds every row at the same time. - Forgetting the alias. The column's heading becomes
AVG(price). If the task asks foravg_price, writeAS avg_price. - Thinking COUNT(column) equals COUNT(*). Their results differ as soon as that column holds a NULL.
- An empty table.
COUNT(*)gives 0, butSUM,AVG,MINandMAXgive NULL. If you want 0, writeCOALESCE(SUM(price), 0):COALESCEgives the first value in its parentheses that is not NULL.
TL;DR: Aggregate functions summarise many rows into one value: COUNT(*) counts the rows, SUM adds up, AVG calculates the average, MIN takes the smallest, MAX the largest. Without GROUP BY (grouping, which the next lesson explains), the result is 1 row. Give a result column a new heading (an alias) with AS. WHERE filters the rows first, and only the rows that pass are summarised. Every function skips NULL (no value yet) except COUNT(*). Aggregate functions are not allowed in WHERE.
⚡ Five summarisers
Meaning: Aggregate functions summarise many rows into one value. Five of them: COUNT(*) counts the rows, SUM adds up the values, AVG calculates the average, MIN takes the smallest, and MAX takes the largest.
⚡ Many rows become one
Write:
SELECT
COUNT(*) AS total_products,
AVG(price) AS avg_price,
MAX(price) AS max_price
FROM products;
Guess first: the products table has 5 rows. How many rows does this query return?
One row: 5 products, an average price of 314, and a top price of 1200. Aggregate functions summarise every row, so without GROUP BY (grouping, which the next lesson explains) the result is just 1 row.
Meaning: AS gives a result column a new heading, called an alias. In the exercise, the checker looks for a column named total_products, so don't forget the alias.
⚡ WHERE first, then summarise
Write:
SELECT COUNT(*) AS total_products, AVG(price) AS avg_price
FROM products
WHERE category = 'electronics';
Meaning: WHERE runs first: of the 5 products, only the 3 electronics products pass. Then COUNT(*) and AVG(price) summarise only those three rows.
⚡ NULL is skipped
Meaning: NULL means no value yet. SUM, AVG, MIN, MAX and COUNT(column) (COUNT with a column name in the parentheses) skip NULL: a NULL value is not counted. Only COUNT(*) still counts a row that holds NULL. Aggregate functions also can't go in WHERE, because WHERE checks the rows one by one, while an aggregate function needs every row at the same time.