SyntaxStudy
Sign Up
MySQL Aggregate Functions
MySQL Intermediate 9 min read

Aggregate Functions

Aggregate Functions in MySQL

COUNT, SUM, AVG, MIN, MAX

SELECT COUNT(*) FROM users;
SELECT COUNT(DISTINCT email) FROM users;

SELECT SUM(amount) FROM orders;
SELECT AVG(price) FROM products;
SELECT MIN(price), MAX(price) FROM products;

GROUP BY

SELECT category, COUNT(*) AS total
FROM products
GROUP BY category;

SELECT user_id, SUM(amount) AS total_spent
FROM orders
GROUP BY user_id
ORDER BY total_spent DESC;

HAVING

-- Filter after grouping (like WHERE for GROUP BY)
SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
HAVING avg_price > 50;
Pro Tip

Use HAVING to filter group results; use WHERE to filter individual rows before grouping.