Question presented to candidate: "Both WHERE and HAVING filter rows, so why does SQL need two of them? Using an orders table, show me a query that needs both, and tell me what goes wrong if you put a condition in the wrong one."
What a strong answer should cover:
- WHERE filters individual rows before grouping; HAVING filters groups after GROUP BY and the aggregates are computed
- WHERE cannot use aggregate functions; HAVING is where conditions like
SUM(amount) > 200orCOUNT(*) >= 2go - Moving a row condition from WHERE to HAVING changes the answer when it is not on a grouped column, and putting a filter in WHERE can remove whole groups (conditional aggregation keeps them)
- HAVING without GROUP BY treats the whole table as one group; a HAVING condition on a grouped column is legal but belongs in WHERE (PostgreSQL pushes it down)
- Engine notes: SQLite allows HAVING without GROUP BY only since 3.39.0; MySQL and SQLite accept SELECT aliases in HAVING, PostgreSQL does not
Code / implementation expected: Yes β one GROUP BY query with a WHERE row filter and a HAVING group filter.
Schema used by the examples: