MyMisPal
← SQL lessons
Lesson 5 of 12

Aggregate functions

Aggregate functions compute one value from many rows. They are the base of every report or dashboard a manager asks for.

number of rowsCOUNT(*)
totalSUM(column)
averageAVG(column)
smallest / largestMIN(column) MAX(column)
SQL
SELECT COUNT(*)    AS employees,
       MIN(salary) AS lowest,
       MAX(salary) AS highest,
       ROUND(AVG(salary), 2) AS average
FROM employees;

You can aggregate with a condition. For example the total value of order 1:

SQL
SELECT SUM(quantity * unit_price) AS order_total
FROM order_items
WHERE order_id = 1;
Watch outCOUNT(*) counts all rows, while COUNT(column) skips rows where that column is NULL. Try COUNT(manager_id).

Exercises

Exercise 1

How many customers are from Saudi Arabia?

Exercise 2

Total stock of all products in the Hardware category.

Spotted a mistake on this page, or have an idea to improve the site?