# 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>

![](/files/-LSc4-USj4iuix88FXAL)

### 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

![](/files/-LSc4ii9oyG5ECvKQSE6)

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

![](/files/-LSc4sGWogEZ1uCutAho)

### 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>


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://gyansetu-sql.gitbook.io/sql-programming/sql-select/untitled-2.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
