GROUP BY

The SQL GROUP BY Statement

GROUP BY groups rows that have the same values into summary rows, such as "number of customers in each country". It is used with aggregate functions.

SELECT column_name(s), aggregate_function(column)
FROM table_name
WHERE condition
GROUP BY column_name(s)
ORDER BY column_name(s);

Count per Group

Example

Number of customers in each country:

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

Result: 6 rows

CountryCustomers
UK2
India2
USA1
Singapore1
Norway1
Canada1

Group by Several Columns

Example

Orders per customer per employee:

SELECT CustomerID, EmployeeID, COUNT(*) AS Orders, SUM(Amount) AS Total
FROM Orders
GROUP BY CustomerID, EmployeeID
ORDER BY CustomerID;

Result: 7 rows

CustomerIDEmployeeIDOrdersTotal
121245.5
13156.25
221412
321320.75
432116.9
5NULL1150
721198.4

GROUP BY with a JOIN

Example

Revenue per product category:

SELECT p.Category, SUM(od.Quantity * p.Price) AS Revenue
FROM OrderDetails od
JOIN Products p ON p.ProductID = od.ProductID
GROUP BY p.Category
ORDER BY Revenue DESC;

Result: 3 rows

CategoryRevenue
Grocery489.71
Beverages425.25
Snacks95.82

The Golden Rule

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

-- Error in PostgreSQL / SQL Server / Oracle:
-- FirstName is neither grouped nor aggregated
SELECT Department, FirstName, COUNT(*)
FROM Employees
GROUP BY Department;

Note: MySQL (without ONLY_FULL_GROUP_BY) and SQLite accept this and return an arbitrary FirstName from each group. Do not rely on it.