SQL GROUP BY
GROUP BY splits rows into groups that share a value, then an aggregate function (COUNT, SUM, AVG...) summarises each group into one row. It answers "per" questions: revenue per category, customers per country.
Every column in the SELECT list must either be in GROUP BY or be inside an aggregate function. This is the rule behind the most common GROUP BY error.
Syntax
SELECT column, AGG(other_column) FROM table_name GROUP BY column;
Try it yourself
Run the example below on a real PostgreSQL database, then change it and run it again. Nothing to install, no sign-up.
Examples
1. Count per group
SELECT country, COUNT(*) AS customers FROM customers GROUP BY country;
One row per country.
2. Sum per group
SELECT product_id, SUM(quantity) AS units FROM order_items GROUP BY product_id;
Units sold per product.
3. Group by two columns
SELECT EXTRACT(YEAR FROM order_date) AS year, status, COUNT(*) FROM orders GROUP BY 1, 2;
GROUP BY 1, 2 refers to the first two SELECT columns.
Common mistakes
- Selecting a column that is neither grouped nor aggregated ("must appear in the GROUP BY clause").
- Filtering groups with WHERE instead of HAVING.
Practice: test yourself
This challenge is from our interactive course. Write the query and press Check answer.
Return each country and the number of customers from it.
FAQ
Can I GROUP BY a calculated value?
Yes, for example GROUP BY EXTRACT(YEAR FROM order_date), or refer to it by its position in the SELECT list.
Does GROUP BY sort the result?
No. Add ORDER BY if you need a specific order.
Learn SQL step by step
65 hands-on exercises, streaks, a leaderboard and a certificate.