SQL GROUP BY

One result row per group.

✍️ 3 exercises + code challenge in this lesson

GROUP BY groups rows with the same values, so aggregate functions can be calculated per group.

"How many customers per country?" → SELECT Country, COUNT(*) FROM Customers GROUP BY Country;

Every column in the SELECT list must be either in GROUP BY or inside an aggregate function.

Key Takeaways: SQL GROUP BY

Mastering SQL GROUP BY helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.

SQL GROUP BY Code Example

SQL
SELECT Country, COUNT(*) AS Customers
FROM Customers
GROUP BY Country
ORDER BY Customers DESC;

SELECT Category, COUNT(*) AS Products, ROUND(AVG(Price)) AS AvgPrice
FROM Products
GROUP BY Category;
Free sign-in required · Google login available

SQL GROUP BY Practice Exercises

Check what you learned in “SQL GROUP BY”.

/ 3 solved
Fill in the blank

Count customers per country.

SELECT Country, COUNT(*) FROM Customers  Country;
✓ Correct! Not quite. Try again.
Multiple choice

Every selected column must be in GROUP BY or…

✓ Correct! Not quite. Try again.
Code challenge

Select each Category and the number of products in it (as Products), sorted by Category.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

Stuck on something?

Ask the community in the CodesInTech forum.

Need a developer?

Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.

Explore Our Services