Functions & Grouping Lesson 12 of 21
SQL GROUP BY and HAVING
Summarize data per group with GROUP BY — products per category, orders per customer, average per subject — and filter groups with HAVING.
Aggregate functions give one answer for the whole table. But often you want one answer per group: the number of products in each category, the average score in each subject. That's what GROUP BY does.
Counting per group
SELECT category, COUNT(*) AS products
FROM products
GROUP BY category;
The database puts the rows into piles, one pile per category, and runs COUNT(*) on each pile.
Other aggregates per group
SELECT subject,
COUNT(*) AS students,
ROUND(AVG(score), 1) AS average,
MAX(score) AS highest
FROM grades
GROUP BY subject;
SELECT category, SUM(price * stock) AS stock_value
FROM products
GROUP BY category
ORDER BY stock_value DESC;
The golden rule of GROUP BY
Every column in SELECT must be either:
- in the
GROUP BYlist, or - inside an aggregate function like
COUNT,SUMorAVG.
Grouping by several columns
SELECT grade, section, COUNT(*) AS students
FROM students
GROUP BY grade, section
ORDER BY grade, section;
Orders per customer
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
ORDER BY orders DESC;
Customer 1 (Maria Santos) is the most loyal. In the JOIN lessons, you'll show names instead of ids.
HAVING: filtering groups
WHERE filters rows before grouping. HAVING filters groups after grouping, so it can use aggregate functions:
SELECT category, COUNT(*) AS products
FROM products
GROUP BY category
HAVING COUNT(*) > 1;
SELECT customer_id, COUNT(*) AS orders
FROM orders
GROUP BY customer_id
HAVING COUNT(*) >= 2;
WHERE and HAVING together
SELECT subject, ROUND(AVG(score), 1) AS avg_of_80_plus
FROM grades
WHERE score >= 80
GROUP BY subject
HAVING AVG(score) > 88;
Step by step: WHERE removes scores below 80, GROUP BY makes one pile per subject, HAVING keeps only subjects whose average is above 88.
The full order of clauses
SELECT columns, aggregates
FROM table
WHERE row conditions
GROUP BY columns
HAVING group conditions
ORDER BY columns
LIMIT number;
A popular memory trick: Some Friendly Workers Go Home On Lunch.
Best-selling products
SELECT product_id, SUM(qty) AS sold
FROM order_items
GROUP BY product_id
ORDER BY sold DESC
LIMIT 5;
Quick Quiz
Check what you learned. Walang grade ito, practice lang. 🙂
By Sir Reyel · Last updated 2026-12-04