Careeroza
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
| Country | Customers |
|---|---|
| UK | 2 |
| India | 2 |
| USA | 1 |
| Singapore | 1 |
| Norway | 1 |
| Canada | 1 |
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
| CustomerID | EmployeeID | Orders | Total |
|---|---|---|---|
| 1 | 2 | 1 | 245.5 |
| 1 | 3 | 1 | 56.25 |
| 2 | 2 | 1 | 412 |
| 3 | 2 | 1 | 320.75 |
| 4 | 3 | 2 | 116.9 |
| 5 | NULL | 1 | 150 |
| 7 | 2 | 1 | 198.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
| Category | Revenue |
|---|---|
| Grocery | 489.71 |
| Beverages | 425.25 |
| Snacks | 95.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.