← SQL and databases

Filtering groups with HAVING

Keep only groups that pass a test.

Start this lesson

WHERE filters rows before they are grouped. HAVING filters groups after they are made, so it can use aggregates: HAVING COUNT(*) > 2 keeps genres with more than two books. You cannot write WHERE COUNT(*) > 2, because when WHERE runs the groups do not exist yet.

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

Makes one group per genre, counts each, then keeps only the groups with more than 2 books.

You can use both: WHERE throws away rows you never want (cancelled orders), then GROUP BY, then HAVING keeps the groups you want.