# SQL GROUP BY Statement

### The SQL GROUP BY Statement

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

```sql
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 in the Northwind sample database:<br>

![](https://826093633-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS8lPNzCGPR5-DLbGXv%2F-LSc3itxVbEk4mY52T_z%2F-LSc4-USj4iuix88FXAL%2Fimage.png?alt=media\&token=c5df8747-68d8-4c08-9755-baf238f83808)

### SQL GROUP BY Examples

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

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

The following SQL statement lists the number of customers in each country, sorted high to low:

```sql
SELECT COUNT(CustomerID), Country
FROM Customers
GROUP BY Country
ORDER BY COUNT(CustomerID) DESC;
```

Demo Database

Below is a selection from the "Orders" table in the Northwind sample database

![](https://826093633-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS8lPNzCGPR5-DLbGXv%2F-LSc3itxVbEk4mY52T_z%2F-LSc4ii9oyG5ECvKQSE6%2Fimage.png?alt=media\&token=c91f4f36-8d39-4b74-af09-7405dc352701)

\
And a selection from the "Shippers" table:<br>

![](https://826093633-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LS8lPNzCGPR5-DLbGXv%2F-LSc3itxVbEk4mY52T_z%2F-LSc4sGWogEZ1uCutAho%2Fimage.png?alt=media\&token=f60f7281-edbf-473a-9f45-3fc044a5f15c)

### GROUP BY With JOIN Example

The following SQL statement lists the number of orders sent by each shipper:

```sql
SELECT Shippers.ShipperName, COUNT(Orders.OrderID) AS 
NumberOfOrders FROM Orders
LEFT JOIN Shippers ON Orders.ShipperID = Shippers.Shippe
GROUP BY ShipperName;
```

<br>
