Junior — Middle
Mis vahe on HAVING ja WHERE tingimustel SQL-päringute töötamisel?
sobes.tech AI
Vastus AI-lt
The main difference between WHERE and HAVING in SQL:
- WHERE filters rows before grouping (GROUP BY). It applies to individual records in the table.
- HAVING filters groups after grouping. It is used for conditions on aggregate functions (e.g., COUNT, SUM).
Example:
SELECT department, COUNT(*) as employee_count
FROM employees
WHERE salary > 50000 -- filter employees with salary above 50000
GROUP BY department
HAVING COUNT(*) > 10 -- select departments with more than 10 employees
Here, WHERE selects rows for grouping, and HAVING filters the already grouped data.