SQL GROUP filtering: Evaluate the claim about HAVING vs. WHERE.\n“The HAVING clause acts like a WHERE clause, but it identifies groups that meet a criterion rather than individual rows.”\nChoose the most accurate assessment.

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:

  • Standard SQL-92/SQL:2011 behavior is assumed.
  • Queries may include GROUP BY and aggregate functions such as COUNT(), SUM(), AVG(), MIN(), and MAX().
  • No vendor-specific extensions are required to answer.


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:

  • “Incorrect” conflicts with the established semantics.
  • “Valid only in non-ANSI databases” is false; this is ANSI-standard behavior.
  • “Applies only with DISTINCT” is irrelevant; DISTINCT and HAVING are independent features.
  • “Depends on the primary key” is unrelated to filtering semantics.


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

More Questions from Introduction to SQL

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion