Memra

HAVING: filtering groups

◈ 2 cards

Keep only the groups that pass a test.

Filter the groups

WHERE filters rows before grouping; HAVING filters the groups after aggregation. "Genres with more than two books":

SELECT genre, COUNT(*) AS books
FROM books
GROUP BY genre
HAVING COUNT(*) > 2;

Think of it as WHERE for aggregates. You can use both in one query: WHERE narrows the rows, HAVING narrows the resulting groups.

FROM books10 rowsWHEREdrops rowsGROUP BY genre5 groupsHAVINGdrops groupsSELECTthe report
WHERE runs before there are any groups, so it can never see an aggregate. HAVING runs after, so an aggregate is the only thing it usefully sees.
genreCOUNT(*)HAVING COUNT(*) >= 2fiction3keptscience2keptpoetry2kepthistory2keptchildren1dropped
HAVING removes whole groups, not rows. The one children book is not filtered out — its entire group is.
NORMAL ~/memra/learn/postgresql/having utf-8 LF