GROUP BY and HAVING

Lesson 9 of 20

Bucket rows by city, count each bucket, then let HAVING throw away the groups that are too small to matter.

The big picture

Buckets, counts, and the group filter

GROUP BY deals the rows into buckets; aggregates summarise each bucket; HAVING then throws away buckets you do not want.

GROUP BY buckets

Rows sharing a value — same city, same dept — land in the same bucket before counting.

One row per bucket

Each bucket collapses into a single summary row in the result.

WHERE vs HAVING

WHERE filters rows BEFORE grouping; HAVING filters the finished groups AFTER.

HAVING needs aggregates

Conditions like COUNT(*) >= 2 make sense only per group — that is the job of HAVING.