COUNT, SUM, AVG, MIN and MAX

Turn thousands of rows into one answer with aggregate functions.

Module 3: Summarising data · Lesson 9 of 26 · 14 min read · Free

Managers rarely want 3,000 rows. They want one number: how many, how much, what's the average. Aggregate functions collapse many rows into one value:

FunctionGives youExample
COUNT(*)number of rowshow many orders
COUNT(column)number of rows where that column isn't NULLhow many customers gave an email
COUNT(DISTINCT column)number of different valueshow many customers have ordered
SUM(column)totalrevenue
AVG(column)averageaverage price
MIN() / MAX()smallest / largestcheapest product, latest order date
SELECT COUNT(*) AS delivered_orders
FROM orders
WHERE status = 'Delivered';

2,708 delivered orders. The WHERE filters first, then COUNT counts what's left.

SELECT MIN(unit_price) AS cheapest,
       MAX(unit_price) AS dearest,
       ROUND(AVG(unit_price)) AS average_price
FROM products;

₦250, ₦18,500 and ₦3,163. Several aggregates can share one query.

Revenue

There's no revenue column. Each line in order_items has a quantity and a unit_price, so revenue is the sum of their product:

SELECT SUM(quantity * unit_price) AS revenue
FROM order_items;

₦53,175,300 — but that includes cancelled and pending orders. To count only delivered sales you need the status from orders, which means joining two tables: Module 4.

COUNT and NULLs

SELECT COUNT(*), COUNT(email), COUNT(DISTINCT state)
FROM customers;

gives 400, 349, 5. The 51 customers without an email are left out of COUNT(email). SUM, AVG, MIN and MAX also skip NULLs.

Check yourself

Answer in your head first, then open each question to see the answer and why.

  1. What does COUNT(email) count?

    • A All rows
    • B Rows where email is not NULL
    • C Different emails
    • D Emails containing @
    Show the answer

    B) Rows where email is not NULL — COUNT(column) skips NULLs.

  2. Revenue in PsalmEdu Mart is…

    • A SUM(unit_price) from products
    • B SUM(quantity * unit_price) from order_items
    • C COUNT(*) from orders
    • D MAX(amount)
    Show the answer

    B) SUM(quantity * unit_price) from order_items — Each order line's quantity times the price charged, added up.

  3. How many customers have placed an order? Which function counts different values?

    • A COUNT(*)
    • B COUNT(DISTINCT customer_id)
    • C SUM(customer_id)
    • D DISTINCT COUNT
    Show the answer

    B) COUNT(DISTINCT customer_id) — COUNT(DISTINCT …) counts unique values.

More free lessons: What SQL is, and why employers want it · Install DB Browser and open the practice database · WHERE: only the rows you need · INNER JOIN: combine two tables · CASE: if-then logic inside a query · INSERT, UPDATE and DELETE — safely · From a business question to an answer