LESSON 01 / 24·2 min readFoundation

WHERE vs HAVING: what is the difference?

01 Understand02 Recall03 Prepare

Understand the concept

WHERE filters individual rows before groups are built, while HAVING filters the groups produced by aggregation. They exist at different logical stages of a query. Use WHERE for conditions on source rows and HAVING for conditions such as “the group's total is greater than 1000.”

Important ideas

  • WHERE filters rows before grouping.

  • HAVING filters groups after aggregation.

  • Example: filter paid orders with WHERE, then customers spending over 1000 with HAVING.

  • A condition on an aggregate such as SUM(amount) generally belongs in HAVING, not WHERE.

Work through the example

SQL
SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'paid'
GROUP BY customer_id
HAVING SUM(amount) > 1000;
  • Only paid orders enter the groups; only customer groups over 1000 remain.
PAUSE & RECALL

Can you explain it without the notes?

WHERE vs HAVING: what is the difference?

Use your own words. Explain an example and one limitation before checking the explanation.

Check your explanation

WHERE filters individual rows before groups are built, while HAVING filters the groups produced by aggregation. They exist at different logical stages of a query. Use WHERE for conditions on source rows and HAVING for conditions such as “the group's total is greater than 1000.”

CONNECT IT TO YOUR INTERVIEW

Turn this concept into a clear answer.

  • Explain the rows that enter the group separately from the groups that survive the final filter.
Practice this concept
YOUR NEXT STEP

Keep connecting the ideas.

Next lesson: What is the difference between the join types?

Adapted from 05_SQL_POSTGRESQL.md · “WHERE vs HAVING: what is the difference?”. Examples are study fragments; framework behavior can depend on your version.