Junior
248
В чем разница между оператором WHERE и оператором HAVING в SQL?
Answer from AI
sobes.tech AI
The WHERE operator is used for filtering rows before they are grouped. The HAVING operator is used for filtering groups after they have been created by the GROUP BY operator.
Main differences:
| Attribute | WHERE | HAVING |
|---|---|---|
| Purpose | Filters rows before grouping | Filters groups after grouping |
| Application | Applied to individual rows | Applied to aggregated group data |
| Execution | Executed before GROUP BY |
Executed after GROUP BY |
| Columns | Uses table columns | Uses table columns and aggregate functions |
Example with WHERE:
-- Select user names where age is greater than 18
SELECT name
FROM users
WHERE age > 18;
Example with HAVING:
-- Select departments where the average salary exceeds 50,000
SELECT department, AVG(salary)
FROM employees
GROUP BY department
HAVING AVG(salary) > 50000;
Example with both operators:
-- Select departments where the average salary of employees over 30 exceeds 60,000
SELECT department, AVG(salary)
FROM employees
WHERE age > 30
GROUP BY department
HAVING AVG(salary) > 60000;