Home / SQL / Reference / Aggregating

SQL GROUP BY

Split rows into groups and aggregate each group.

Syntax

SELECT col, AGG(…)
FROM table
GROUP BY col;

Every column in SELECT must be in GROUP BY or inside an aggregate.

Example

Query (on the shop database used in the SQL course)

SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC;

Result

countrycustomers
Australia12
Nepal4
United Kingdom3
New Zealand1

4 rows

Good to know. SQLite and MySQL allow ungrouped columns and pick an arbitrary value; PostgreSQL rejects them.

Related

Learn it step by step in the free lesson Summarising Data, with exercises that check your queries.