SQL GROUP BY, explained

Aggregate functions like COUNT, SUM, AVG, MIN and MAX squash many rows into one number. GROUP BY splits the rows into groups first, so you get one number per group.

Every column in SELECT should either be in GROUP BY or be inside an aggregate. To filter on an aggregate, use HAVING, which runs after grouping.

Examples

1. Count per category

SELECT category, COUNT(*) AS product_count
FROM products
GROUP BY category;

One row per category, with how many products are in it.

2. Filter groups with HAVING

SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department
HAVING COUNT(*) > 2;

Only departments with more than two people.

Practice GROUP BY

5 questions, easiest first. Your progress is saved on this device.

  • โ—‹Count the rowseasy
  • ๐Ÿ”’Count per groupeasy
  • ๐Ÿ”’Spend per customermedium
  • ๐Ÿ”’Average salarymedium
  • ๐Ÿ”’Filter groupsmedium
Practice GROUP BY