Sobes.tech
Junior

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

sobes.tech AI

Answer from AI

WHERE is applied before grouping and filters the result rows of FROM. HAVING is applied after grouping and filters the groups formed with GROUP BY.

Example:

Suppose we have a table orders with columns customer_id, order_date, and amount.

Find all customers whose total orders exceed 1000:

SELECT customer_id, SUM(amount)
FROM orders
GROUP BY customer_id
HAVING SUM(amount) > 1000;

Find all orders with an amount greater than 1000:

SELECT customer_id, order_date, amount
FROM orders
WHERE amount > 1000;

Comparison table:

Feature WHERE HAVING
Application To individual rows before grouping To groups of rows after grouping
Uses Columns from FROM Aggregate functions and columns from GROUP BY
Executed Before GROUP BY After GROUP BY
Aggregate functions Cannot be used directly Can be used