SQL Tutorial · Aggregation and Functions · Lesson 14 of 36
SQL GROUP BY
Group rows and aggregate each group.
GROUP BY
GROUP BY splits rows into groups and computes aggregates per group:
SELECT country, COUNT(*) AS customers
FROM customers
GROUP BY country
ORDER BY customers DESC, country;
Output
country | customers USA | 5 UK | 2 Japan | 1 Netherlands | 1 Switzerland | 1
Every column in the SELECT list must either be in GROUP BY or inside an aggregate function. (SQLite and old MySQL versions are lenient about this; PostgreSQL is strict — write it correctly anyway.)
Grouping by several columns
SELECT department, title, COUNT(*) AS people, AVG(salary) AS avg_salary
FROM employees
GROUP BY department, title
ORDER BY department, avg_salary DESC;
Output
department | title | people | avg_salary Engineering | CTO | 1 | 210000 Engineering | Engineering Manager | 1 | 165000 Engineering | Senior Engineer | 1 | 140000 Engineering | Engineer | 2 | 113500 Management | CEO | 1 | 250000 Sales | Head of Sales | 1 | 150000 Sales | Account Executive | 2 | 89000 Support | Support Specialist | 1 | 65000
Test yourself
Which clause computes aggregates per country?
ORDER BY countryGROUP BY countryPARTITION countryWHERE country
Show answer
Answer: GROUP BY country