Back

Aggregate functions (COUNT, SUM, AVG)

Aggregate functions take many rows and return one value: COUNT, SUM, AVG, MIN, MAX. Pair them with GROUP BY to get one result per group, and use HAVING to filter those groups.

SELECT COUNT(*) FROM users;
SELECT AVG(price) FROM products;
SELECT MAX(price), MIN(price) FROM products;

-- Total sales per customer
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id;

-- Only customers who spent over 500
SELECT customer_id, SUM(total) AS spent
FROM orders
GROUP BY customer_id
HAVING SUM(total) > 500;

Roadmap