We're sorry but this app doesn't work properly without JavaScript enabled. Please enable it to continue.

This lesson's interactive features are locked, please to keep using them

HAVING vs. WHERE in SQL

It's common for developers to get confused about the difference between the HAVING and WHERE clauses – they're pretty similar after all.

The difference, though, is straightforward enough:

  • A WHERE condition is applied to all the data in a query before it's grouped by a GROUP BY clause.
  • A HAVING condition is applied only to the grouped rows that are returned after a GROUP BY is applied.

This means that if you want to filter based on the result of an aggregation, you need to use HAVING. If you want to filter on a value that's present in the raw data, you should use a simple WHERE clause.

Example for Questions

SELECT class_id, COUNT(id) AS class_size
FROM students
WHERE ...
GROUP BY class_id
HAVING ...