SQL Practice Logo

SQLPractice Online

HAVING Clause: Interview

Module: Aggregate Functions & Grouping

What is the difference between WHERE and HAVING?

WHERE filters rows before grouping and cannot use aggregates. HAVING filters groups after aggregation and can use aggregate functions. Use WHERE for row conditions, HAVING for group conditions.

Explain the query execution order with WHERE, GROUP BY, and HAVING.

Order: FROM → WHERE (filter rows) → GROUP BY (create groups) → Aggregates (calculate) → HAVING (filter groups) → SELECT → ORDER BY. This explains why WHERE cannot use aggregates but HAVING can.

Find products with total sales greater than $50,000

SELECT product_id, SUM(order_total) AS total_sales FROM orders GROUP BY product_id HAVING SUM(order_total) > 50000;

HAVING filters groups based on aggregate SUM. WHERE cannot be used because SUM is calculated after grouping.