Skip to content
BENIBIX Learn

GROUP BY Clause

Development🗃️ DatabasesDatabase Basics

Also known as GROUP BY, SQL GROUP BY, Grouping in SQL

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

Think of it like

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

Example

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

Why it matters

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

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 code

sql
SELECT city, SUM(amount) AS total
FROM orders
GROUP BY city;
One row per city, with the total of its orders.
GROUP BY city puts the rows in two piles. SUM turns each pile into one row.

Common mistake

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

Key takeaways

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