Junior
В чем отличие между конструкциями WHERE и HAVING в SQL?
sobes.tech AI
Answer from AI
WHERE filters rows before grouping (GROUP BY), affecting which rows participate in aggregate functions. HAVING filters groups after grouping, based on the results of aggregate functions.
| Feature | WHERE | HAVING |
|---|---|---|
| Application | To individual rows | To groups of rows |
| Processing time | Before GROUP BY | After GROUP BY |
| Usage | With table fields but without aggregate functions | With results of aggregate functions or fields from GROUP BY |
Example of using WHERE:
SELECT product_name, price
FROM products
WHERE category_id = 1; -- Filters rows before grouping (if it were to occur)
Example of using HAVING:
SELECT category_id, COUNT(*) AS total_products
FROM products
GROUP BY category_id
HAVING COUNT(*) > 5; -- Filters groups after counting total products
Example of combined usage:
SELECT category_id, AVG(price) AS average_price
FROM products
WHERE stock > 0 -- Filters only in-stock products BEFORE grouping
GROUP BY category_id
HAVING AVG(price) < 100; -- Filters groups with average price less than 100 AFTER grouping and averaging