Lesson 5 of 13 · 16 min

HAVING: filtering groups

By the end of this lesson you can filter grouped results with HAVING, combine it with WHERE in one query, and explain the order in which PostgreSQL evaluates the clauses.

WHERE filters rows. It looks at one row at a time and decides whether that row goes into the groups. It cannot use COUNT(*) or SUM(amount), because while WHERE runs, no groups exist yet.

HAVING filters groups. It runs after GROUP BY has built the groups and their aggregates, and keeps only the groups whose condition is true. A group that fails HAVING disappears from the result as a whole.

Included with a Formula Quest membership

This lesson, its 5 graded exercises and every other Members lesson in SQL Quest come with a Formula Quest membership that includes SQL (Single Quest with SQL selected, Quest Trio including SQL, or Quest Unlimited), or with SQL access from your organization.

Free to everyone: all of SQL Foundations and Retrieving and Filtering Data, the first lesson of every track, the playground, the dataset library and the SQL reference. See free lessons