← Lessons

quiz vs the machine

Gold1340

Databases

Group By and Having

GROUP BY collapses rows into groups for aggregation, and HAVING filters those groups after the aggregate is computed.

4 min read · core · beat Gold to climb

Collapsing Rows Into Groups

GROUP BY takes rows that share the same value in the grouping columns and collapses them into one row per group. Aggregate functions like COUNT, SUM, and AVG then compute a value for each group.

The Select List Rule

Every column in SELECT must either appear in GROUP BY or be wrapped in an aggregate. A bare non grouped column has no single value per group, so most engines reject it.

WHERE vs HAVING

These two filters run at different stages:

  • WHERE filters individual rows before grouping.
  • HAVING filters whole groups after the aggregate is computed.
  • Use WHERE to drop rows cheaply, and HAVING only for conditions on aggregates.

A Common Example

To find departments with more than ten employees, you group by department, count rows, and add HAVING count greater than ten. The same count condition cannot go in WHERE because the count does not exist yet at that stage.

Key idea

GROUP BY collapses rows into groups for aggregation, WHERE filters rows before grouping, and HAVING filters groups using aggregate conditions.

Check yourself

Answer to earn rating on the learn ladder.

1. What must every SELECT column be when using GROUP BY?

2. Why filter on a count with HAVING instead of WHERE?

3. When does WHERE run relative to GROUP BY?