Explain the difference between WHERE and HAVING clauses

SQL
Medium
102.6K views

This is a classic SQL question about filtering timing relative to aggregation. It tests logical flow understanding.

Why Interviewers Ask This

Interviewers want to see if you understand the order of operations in SQL execution. Confusing these leads to syntax errors and incorrect results. It proves you grasp when to filter raw data versus aggregated groups.

How to Answer This Question

Clarify that WHERE filters rows before grouping happens. State that HAVING filters groups after aggregation. Mention that WHERE cannot use aggregate functions, but HAVING can. Use a simple example to illustrate the difference.

Key Points to Cover

  • WHERE filters before grouping
  • HAVING filters after grouping
  • WHERE excludes aggregates
  • HAVING requires aggregates

Sample Answer

WHERE filters individual rows before any grouping or aggregation occurs, so it cannot use aggregate functions like SUM. It is best for narrowing down raw data early, such as filtering by date range. HAVING, however, filters the resulting groups after GROUP BY, specifically designed for conditions on aggregates like finding groups with totals above a threshold.

Common Mistakes to Avoid

  • Using aggregates in WHERE clause
  • Confusing the execution order
  • Thinking HAVING replaces WHERE entirely

Practice This Question with AI

Answer this question orally or via text and get instant AI-powered feedback on your response quality, structure, and delivery.

Start Practicing

Related Interview Questions

Browse all 49 SQL questions