Solve “Departments with more than three people”

Free. Runs in your browser, no install.

SQL · Aggregations & Grouping

What is GROUP BY?

Mediumgroup byaggregation

Interview question

What is GROUP BY?

How to answer

The short answer

GROUP BY combines rows into groups so aggregate functions can operate on each group.

SQL
SELECT department, COUNT(*)
FROM employees
GROUP BY department;

Output might be:

Output
IT       20
HR       10
Finance  15

If you select a normal column that isn't in GROUP BY and isn't aggregated:

SQL
SELECT department, name, COUNT(*)
FROM employees
GROUP BY department;

SQL doesn't know which employee name to return for each department.

So most SQL dialects reject it.

Lock it in with a real drill

You remember an answer longer once you have used it. Try a hands-on problem on this concept.

Open related drill