Aggregate Functions
COUNT, SUM, AVG, MIN, MAX — turning rows into insights
📖 Concept Recap
Aggregate functions collapse multiple rows into a single value:
- COUNT(*) — count all rows; COUNT(column) — count non-null values
- SUM(column) — total of all values
- AVG(column) — arithmetic mean
- MIN(column) — smallest value
- MAX(column) — largest value
Use AS to give your aggregated columns meaningful names. Use ROUND(value, 2) to round decimals. Without GROUP BY, aggregates apply to the whole table and return one row.
Add GROUP BY category to get one row per category (we dig deep into GROUP BY in Lab 5).
👀 Worked Example
Exercise 1 — Revenue Summary
Fill in the blanks to get total orders, total revenue, and average order value from the orders table.
Exercise 2 — Inventory Overview
Write a query showing:
- Total number of products (COUNT)
- Total inventory value:
SUM(price * stock) - Most expensive product price (MAX)
- Cheapest product price (MIN)
- Average product price (AVG, rounded to 2 decimal places)
SUM(price * stock) AS total_inventory_valueExercise 3 — Monthly Order Stats
Write a query showing order statistics by month. Use substr(order_date, 1, 7) to extract the year-month (e.g., “2024-01”). Show: month, order count, total revenue, average order value. Order by month.
SELECT substr(order_date, 1, 7) AS month, COUNT(*) AS orders, ... FROM orders GROUP BY substr(order_date, 1, 7) ORDER BY month;Mini Project — Quarterly Business Review
You’re a business analyst presenting a quarterly review. Write 4 aggregate queries:
- Overall metrics — total orders, total revenue, total customers (from customers table), average order value
- Product performance by category — category, product count, avg price, total stock
- Customer engagement — total customers, total orders, average orders per customer (use subquery or just divide the counts)
- High-value orders summary — count, total, and average of orders where total > 500
✅ Lab 4 Complete!
Aggregate functions are how analysts answer “how many?”, “how much?”, and “what’s the average?” questions. Next, learn to slice those aggregates into groups.
Continue to Lab 5: GROUP BY & HAVING →