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.