Difficulty: Easy
Correct Answer: Correct
Explanation:
Introduction / Context: In Structured Query Language (SQL), both WHERE and HAVING filter results, but they operate at different stages of query processing. WHERE filters rows before grouping or aggregation, while HAVING filters groups that result from a GROUP BY or implicit grouping around aggregate functions. This question tests whether you understand that HAVING is conceptually “like WHERE for groups.”
Given Data / Assumptions:
Concept / Approach: The logical order of SQL evaluation is: FROM → WHERE → GROUP BY → HAVING → SELECT → ORDER BY. WHERE eliminates rows prior to aggregation; GROUP BY forms groups; HAVING applies predicates to aggregated groups. Thus, HAVING can reference aggregate expressions (for example, SUM(sales) > 1000), which WHERE cannot. If no GROUP BY exists but aggregates are used, the entire result is treated as a single group, and HAVING can still filter that single group by its aggregate value.
Step-by-Step Solution:
Write a query with GROUP BY (for example, SELECT region, SUM(revenue) FROM T GROUP BY region).Apply WHERE to remove irrelevant rows first (for example, WHERE year = 2025).Use HAVING to keep only those groups meeting an aggregate threshold (for example, HAVING SUM(revenue) > 100000).Confirm WHERE cannot refer to SUM(revenue) but HAVING can.Verification / Alternative check: Compare execution plans: WHERE predicates appear before grouping; HAVING predicates appear after grouping and aggregation.
Why Other Options Are Wrong:
Common Pitfalls: Using WHERE with aggregates; forgetting HAVING when filtering on GROUP BY results; adding non-aggregated columns to SELECT without grouping them.
Final Answer: Correct
Discussion & Comments