SpinTheMic
Pro

SQL · Beginner

What is the difference between WHERE and HAVING in SQL?

By Anurag Pandey, Lead Data Engineer ·

The short answer

WHERE filters rows before they are grouped, so it can't use aggregates. HAVING filters groups after GROUP BY, so it can, for example HAVING COUNT(*) > 5.

Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Say it like this

About 50 seconds out loud. Use it as a model, then put it in your own words.

Both filter, but at different points. WHERE runs before grouping and filters individual rows, so it can't use aggregate functions. HAVING runs after GROUP BY and filters whole groups, so it can use aggregates like COUNT or SUM. For example, to find customers with more than five orders in 2025, I'd write WHERE order_date is in 2025 to keep only those rows, then GROUP BY customer_id, then HAVING COUNT(*) greater than five. A good habit is to put every condition that doesn't need an aggregate in WHERE, because that removes rows before the grouping work. Most databases would let me put a plain column condition in HAVING too, but it reads worse and can make the database do extra work.

What interviewers look for

  • You explain the order: WHERE before grouping, HAVING after.
  • You give one query that uses both correctly.
  • You know non-aggregate filters belong in WHERE.

Common mistakes

  • Trying to use COUNT or SUM in a WHERE clause.
  • Saying HAVING can only be used with GROUP BY in every database without checking.
  • Not giving an example, which makes the answer sound memorised.

Follow-up questions to expect

  1. 1Can you use a column alias from SELECT in HAVING?
  2. 2What is the logical order in which a SELECT is processed?
  3. 3How would you filter on the result of a window function?
Practice this out loud

Opens this question on SpinTheMic. Start without signing up; sign in free for an AI report card.

Checked against

All interview question guides