SQL GROUP BY

The SQL GROUP BY Statement

The GROUP BY statement groups rows that have the same values into summary rows, like "find the number of customers in each country".

The GROUP BY statement is often used with aggregate functions (COUNT(), MAX(), MIN(), SUM(), AVG()) to group the result-set by one or more columns.


GROUP BY Syntax

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

Demo Database

Below is a selection from the Customers table:

Customers Table:

CustomerID CustomerName Country
1 Alfreds Futterkiste Germany
2 Ana Trujillo Emparedados Mexico
3 Antonio Moreno Taquería Mexico
4 Around the Horn UK
5 Berglunds snabbköp Sweden
6 Blauer See Delikatessen Germany

GROUP BY Example

The following SQL statement lists the number of customers in each country.

GROUP BY Example

SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country;

The result set would look like this:

COUNT(CustomerID) Country
2 Germany
2 Mexico
1 Sweden
1 UK

GROUP BY with JOIN Example

The following SQL statement lists the number of orders sent by each customer.

GROUP BY with JOIN Example

SELECT Customers.CustomerName, COUNT(Orders.OrderID) AS NumberOfOrders
FROM Orders
LEFT JOIN Customers ON Orders.CustomerID = Customers.CustomerID
GROUP BY CustomerName;