Intermediate · Lesson 4 of 20

Grouping with GROUP BY

GROUP BY groups rows together for aggregate calculations.

Count employees per department:

SELECT department_id, COUNT(*)
FROM employees
GROUP BY department_id;

Average salary per department:

SELECT department_id, AVG(salary)
FROM employees
GROUP BY department_id;

Rule: Every column in SELECT must be either:

  • In GROUP BY, or
  • Inside an aggregate function (COUNT, SUM, etc.)
Check your understanding

Count how many employees are in each department.

Examples run on the employees sample database. Open any of them in the playground to experiment.

Practice it on a real question

All Aggregation questions

Practice on your iPhone

Query Dojo for iPhone has 85 interview questions, timed mock interviews and a tile builder, so you can write queries without a keyboard.

Get the app