Sobes.tech
Junior

В чем отличие между предложениями WHERE и HAVING в SQL?

sobes.tech AI

Answer from AI

WHERE filters rows before grouping. HAVING filters groups created with GROUP BY, after grouping.

WHERE:

  • Applied to individual rows.
  • Cannot use aggregate functions (COUNT, SUM, AVG, MIN, MAX).
  • Executed before GROUP BY, HAVING, and SELECT.

HAVING:

  • Applied to groups of rows.
  • Can use aggregate functions.
  • Executed after WHERE and GROUP BY, but before SELECT.

Example:

Find clients from the city 'Moscow' (where WHERE) whose total order amount exceeds 1000 (where HAVING).

SELECT customer_id, SUM(order_amount)  -- Select customer ID and sum of their orders
FROM orders  -- From the orders table
WHERE city = 'Moscow'  -- Filter rows before grouping, keep only orders from Moscow
GROUP BY customer_id  -- Group rows by customer ID
HAVING SUM(order_amount) > 1000;  -- Filter groups, keep only groups where total orders > 1000