← Learning Hub
Beginner

COUNT, SUM, AVG, MIN and MAX

Aggregate functions turn many rows into one number.

Aggregate functions turn many rows into one answer: how many orders, total revenue, average price, the cheapest product. They're the building blocks of every summary and report.

Example
SELECT COUNT(*)   AS products,
       SUM(stock) AS total_stock,
       AVG(price) AS average_price,
       MIN(price) AS cheapest,
       MAX(price) AS dearest
FROM products;

-- Result:
-- products | total_stock | average_price      | cheapest | dearest
-- ---------+-------------+--------------------+----------+--------
-- 9        | 795         | 1126.7777777777778 | 199      | 3999
▶ Try it yourself
  • COUNT(*) counts rows; COUNT(city) counts only rows where city is not NULL
  • SUM and AVG work on numbers
  • MIN and MAX also work on text and dates
Example
SELECT COUNT(*) AS customers, COUNT(city) AS with_city FROM customers;

-- Result:
-- customers | with_city
-- ----------+----------
-- 6         | 5
▶ Try it yourself

With a WHERE

Example
SELECT SUM(qty * price) AS revenue
FROM order_items
WHERE order_id IN (101, 102, 105);

-- Result:
-- revenue
-- -------
-- 5191
▶ Try it yourself
ROUND(AVG(price), 2) rounds to 2 decimal places.
Key points
  • COUNT, SUM, AVG, MIN, MAX summarise many rows.
  • COUNT(*) counts rows; COUNT(col) skips NULLs.
  • Aggregates ignore NULL values.

📝 Test yourself

1. What does COUNT(city) skip?
2. Which function gives the largest value?
3. Fill in the function that adds numbers:
SELECT (stock) FROM products;