Junior — Middle
What is the difference between the WHERE and HAVING conditional operators in SQL, and what are their purposes?
sobes.tech AI
Answer from AI
The SQL WHERE operator is used to filter rows before grouping, meaning it selects individual records from a table based on conditions. HAVING is used to filter already grouped data, that is, after executing GROUP BY.
Example:
SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000 -- filter employees with salary greater than 50000
GROUP BY department
HAVING COUNT(*) > 10 -- select departments with more than 10 such employees
Thus, WHERE filters the raw data, and HAVING filters the results of aggregate functions and groupings.