Back to AGGREGATIONS & GROUP BY, ORDER BY

HAVING CLAUSE AND WHERE

Understand filtering with GROUP BY and difference between HAVING and WHERE

4 minutesVideo LessonPDF notes
🎯 Free Guest Mode: You are learning for free. Sign in to save your completion progress and quiz answers.

Ready to continue?

Mark this lesson as complete when you're ready to proceed.

Key moments

  1. WHERE Aggregate ErrorAttempting to filter by an aggregate function in the WHERE clause results in an error because the aggregation has not yet occurred.
  2. HAVING Clause PurposeThe HAVING clause was created specifically to filter results based on aggregate functions after the GROUP BY clause executes.
  3. Basic HAVING ExampleA successful query filters groups where the average age is greater than 40 using HAVING.
  4. WHERE Row FilteringThe WHERE clause is used first to filter individual rows, such as selecting only occupations that are managers.
  5. Combined Filtering LogicBoth WHERE and HAVING are used in one query to filter rows first, then filter the resulting aggregated groups.
  6. Summary and DistinctionWHERE filters row data before grouping, while HAVING filters aggregated results after grouping.
PDF notes

Frequently asked questions

Why does using an aggregate function in WHERE cause an error?

The aggregate function result has not been calculated yet because the grouping (GROUP BY) has not occurred when WHERE executes.

Can I use both WHERE and HAVING in the same query?

Yes, WHERE filters the initial rows, and HAVING filters the resulting groups after aggregation.

Does HAVING replace WHERE?

No, they serve different purposes; WHERE filters rows, and HAVING filters groups based on aggregate results.