📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials PostgreSQL Essentials GROUP BY and HAVING

GROUP BY and HAVING

6 min read Quiz at the end
GROUP BY groups rows with the same values so aggregates apply per group. HAVING filters groups after aggregation. Example: find departments with more than 5 employees using GROUP BY and HAVING COUNT(*) > 5.

Grouping Results

-- Sales per city
SELECT city, COUNT(*) AS orders
FROM orders
GROUP BY city;

-- Only cities with 10+ orders
SELECT city, COUNT(*) AS orders
FROM orders
GROUP BY city
HAVING COUNT(*) >= 10
ORDER BY orders DESC;

WHERE filters rows before grouping. HAVING filters after.

Topic Quiz · 5 questions

Test your understanding before moving on

1. Which clause filters after grouping?
💡 HAVING filters groups — like WHERE but applied after GROUP BY.
2. Which clause filters before grouping?
💡 WHERE filters individual rows before they are grouped.
3. What does GROUP BY do?
💡 GROUP BY combines rows with the same column value for aggregation.
4. Can you GROUP BY multiple columns?
💡 You can GROUP BY any number of columns.
5. Which is the correct order?
💡 Correct SQL order: WHERE (filter rows) → GROUP BY (group) → HAVING (filter groups).