Functions & Grouping Lesson 11 of 21
SQL Aggregate Functions — COUNT, SUM, AVG, MIN, MAX
Summarize data with COUNT, SUM, AVG, MIN and MAX — how many products, total stock, average grade, cheapest and most expensive item — plus ROUND.
So far, each query returned rows from the table. Aggregate functions do something different: they look at many rows and return one summary value, such as a count, a total or an average.
The five aggregate functions
| Function | Returns |
|---|---|
COUNT() | How many rows |
SUM() | Total of the values |
AVG() | Average of the values |
MIN() | Smallest value |
MAX() | Largest value |
COUNT
SELECT COUNT(*) AS product_count FROM products;
SELECT COUNT(*) AS utang_orders
FROM orders
WHERE status = 'utang';
WHERE filters first, then COUNT counts what's left.
SUM
SELECT SUM(stock) AS total_items,
SUM(price * stock) AS total_value
FROM products;
AVG
SELECT AVG(score) AS math_average
FROM grades
WHERE subject = 'Math';
Rounding with ROUND
SELECT ROUND(AVG(score), 2) AS math_average
FROM grades
WHERE subject = 'Math';
MIN and MAX
SELECT MIN(price) AS cheapest, MAX(price) AS most_expensive
FROM products;
SELECT MIN(order_date) AS first_order, MAX(order_date) AS latest_order
FROM orders;
MIN and MAX work on dates and text too (alphabetically first and last).
Which product is the cheapest?
A common mistake is to mix an aggregate with a normal column:
SELECT name, MIN(price) FROM products; -- don't rely on this!
Some databases give an error; others return a random name. The reliable way is to sort and limit, or use a subquery:
SELECT name, price FROM products ORDER BY price LIMIT 1;
SELECT name, price FROM products
WHERE price = (SELECT MIN(price) FROM products);
The second version also shows ties, if two products share the lowest price.
Products above average price
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;
Several summaries at once
SELECT COUNT(*) AS products,
SUM(stock) AS items,
ROUND(AVG(price), 2) AS avg_price,
MIN(price) AS min_price,
MAX(price) AS max_price
FROM products;
Total sales
How much has the store sold in total? We need prices from products and quantities from order_items. That requires a JOIN, coming soon, but here's a preview:
SELECT SUM(p.price * oi.qty) AS total_sales
FROM order_items oi
JOIN products p ON p.id = oi.product_id;
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04