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
| country | customers |
|---|---|
| Australia | 12 |
| Nepal | 4 |
| United Kingdom | 3 |
| New Zealand | 1 |
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.