SQL interview question

Data ScienceSQLbasic

In a query that uses GROUP BY, how does the WHERE clause differ from the HAVING clause?

  1. AWHERE filters groups after the aggregates are computed, while HAVING filters individual rows before grouping.
  2. BWHERE filters individual rows before grouping, while HAVING filters groups after the aggregates are computed.
  3. CWHERE and HAVING are synonyms; HAVING is simply the older keyword that is kept for backward compatibility.
  4. DWHERE can compare aggregates such as SUM(amount), while HAVING can only compare plain, non-aggregated columns.
Show the answer and explanation

Correct answer: B, WHERE filters individual rows before grouping, while HAVING filters groups after the aggregates are computed.

Explanation SQL

WHERE filters individual rows before GROUP BY forms groups, so it cannot contain aggregate functions. HAVING filters whole groups after the aggregates are computed, so conditions such as SUM(amount) > 1000 belong there.

SELECT customer_id, SUM(amount) AS total
FROM orders
WHERE status = 'paid'          -- row filter
GROUP BY customer_id
HAVING SUM(amount) > 1000;     -- group filter

Why the other statements are wrong:

  • Saying WHERE works on groups and HAVING on rows reverses the real order: rows are filtered first, groups afterwards.
  • Aggregates are not allowed in WHERE (WHERE SUM(amount) > 1000 is an error), while HAVING may use aggregates and grouped columns.
  • They are not synonyms: WHERE works on rows and HAVING on groups, so moving a condition between them can change the result or cause an error.

Interview tip: add that row-level conditions belong in WHERE, because filtering early means fewer rows have to be grouped.

Practice it as a quiz

Answer this and the other free questions with instant grading, streaks and weak-topic tracking, or unlock all 4,000 questions.

More Data Science questions

  1. In Python, what is the main difference between a list and a tuple?
  2. An inventory agent asks an LLM for a JSON reorder decision and passes the fields to a typed helper. This time the model returned units as a string. What…
  3. The chart plots weekly active users of a new GenAI app on a log scale (the y-axis shows log10 of users). How should the change after week 10 be interpreted?
  4. A test ran at 10% treatment on Friday and was ramped to 50% for the weekend. Treatment converts better within each period but worse when the data are pooled…
  5. In PostgreSQL, converted is an INTEGER column holding 0 or 1. This daily conversion-rate query shows 0 for almost every day, and 1 only on days where every…