# GROUP BY Clause

> The SQL part that puts rows with the same value into groups.

**Field:** Software Development  
**Category:** Databases  
**Also known as:** GROUP BY, SQL GROUP BY, Grouping in SQL

## Think of it like

It is like putting socks in piles by colour. Then you count each pile.

## Definition

A GROUP BY clause puts rows that share a value into one group. Then an aggregate function, like COUNT or SUM, works out one answer per group. So GROUP BY city with SUM(amount) gives one row per city with its total. Every column in the SELECT must either be in the GROUP BY or sit inside an aggregate.

## Example

Lucy wants sales per city. She groups her orders by city and sums the amounts, and gets one line for each city.

## Example code

```sql
SELECT city, SUM(amount) AS total
FROM orders
GROUP BY city;
```

One row per city, with the total of its orders.

## Why it matters

Most reports need totals per something: per day, per shop, per product. GROUP BY is how SQL makes them.

## Common mistake

Filtering groups with WHERE. WHERE runs before grouping. To filter on a total, use HAVING after the GROUP BY.

## Three principles

- **Same value, one group.** Rows that match are put together.
- **One answer per group.** An aggregate sums or counts each one.
- **HAVING filters groups.** WHERE filters rows, before grouping.

## Related terms

- [Aggregate Function](https://learn.benibix.com/term/development/aggregate-function)
- [SELECT Statement](https://learn.benibix.com/term/development/select-statement)
- [WHERE Clause](https://learn.benibix.com/term/development/where-clause)
- [Structured Query Language (SQL)](https://learn.benibix.com/term/development/sql)
- [Database Query](https://learn.benibix.com/term/development/query)

![A table of six orders, each with a city and an amount. An arrow marked WHERE amount > 10 keeps four of the rows and drops two. An arrow marked GROUP BY city puts the four rows into two piles, London and Paris. An arrow marked SUM(amount) turns each pile into one row: London 45 and Paris 30. The last box is the result the SELECT gives back.](https://learn.benibix.com/diagrams/dev-sql-query.svg)

---

Source: https://learn.benibix.com/term/development/group-by
Author: Behnia Zarei (a developer in Vienna, Austria, who builds and teaches data, AI and business intelligence at BENIBIX)
Publisher: BENIBIX Learn (https://learn.benibix.com/)
Last updated: 2026-11-16
Licence: CC BY 4.0 (https://creativecommons.org/licenses/by/4.0/). Quote freely with attribution.
