AnalystPracticeGuides
DashboardSign up

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.

Watch it solved. Task 1: totals per group, filtered with HAVING, from 0:31, in our video “Data Analyst Interview Questions and Answers: 10 SQL + Excel Tasks, Solved”. Pressing play loads the video from YouTube (privacy). Open on YouTube

How does a basic GROUP BY look?

SELECT country, COUNT(*) AS orders, SUM(amount) AS revenue
FROM orders
GROUP BY country
ORDER BY revenue DESC;

How do you group by two columns?

SELECT country, strftime('%Y-%m', order_date) AS month, SUM(amount)
FROM orders
GROUP 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.

Try it yourself. Practise this in a real database in your browser, with instant feedback.
Practise GROUP BY Practise GROUP BY and HAVING

Updated November 2026.

← All free guides