SQL GROUP BY explained
GROUP BY collapses rows with the same value into one row per group, so you can calculate a total, count or average for each group. Every column in SELECT must either be in GROUP BY or inside an aggregate.
How does a basic GROUP BY look?
SELECT country, COUNT(*) AS orders, SUM(amount) AS revenueFROM ordersGROUP BY countryORDER BY revenue DESC;
How do you group by two columns?
SELECT country, strftime('%Y-%m', order_date) AS month, SUM(amount)FROM ordersGROUP BY country, month;
You get one row per country and month. The date function differs between databases, for example DATE_TRUNC in PostgreSQL and FORMAT in SQL Server.
Why do I get "must appear in the GROUP BY clause"?
You selected a column that isn't grouped or aggregated, such as SELECT country, city, SUM(amount) … GROUP BY country. The database can't know which city to show. Add it to GROUP BY or aggregate it. SQLite and older MySQL settings sometimes return an arbitrary value instead of an error, which is worse.
How do you filter groups?
With HAVING, after GROUP BY: HAVING SUM(amount) > 1000. Row filters go in WHERE, before grouping.
Practise GROUP BY Practise GROUP BY and HAVING
Updated November 2026.