Junior — Middle
How does the sequence of execution of GROUP BY, HAVING, and WHERE operators affect the query result in SQL?
sobes.tech AI
Answer from AI
In SQL, the order of operator execution affects the result as follows:
- WHERE — filters rows from the original table before grouping.
- GROUP BY — groups the filtered rows by specified columns.
- HAVING — filters the already grouped data based on aggregate conditions.
Thus, first, only the necessary rows are selected, then they are grouped, and after that, groups can be filtered based on aggregate criteria.
For example:
SELECT department, COUNT(*)
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING COUNT(*) > 5;
First, employees with a salary above 50,000 are selected, then they are grouped by department, and finally, only departments with more than 5 employees remain.