Last updated

SQL GROUP BY

Definition: GROUP BY groups rows that share the same value, so you can run an aggregate function (COUNT, SUM, AVG) on each group instead of the whole table.

Example 1 — customers per country

SELECT Country, COUNT(*) AS Total
FROM Customers
GROUP BY Country;

One row per country, with a count of customers in each.

Example 2 — average price per category

SELECT Category, AVG(Price) AS AvgPrice
FROM Products
GROUP BY Category;

Example 3 — filter groups with HAVING

HAVING is like WHERE, but it filters groups after they are formed:

SELECT Country, COUNT(*) AS Total
FROM Customers
GROUP BY Country
HAVING COUNT(*) > 1;

💡 Key difference: WHERE filters individual rows before grouping; HAVING filters the groups after. Together they are the heart of reporting in SQL.

Try it Yourself
Output

          
Ad · responsive