Junior — Middle
Is it possible to combine WHERE conditions, GROUP BY grouping, and HAVING filter in a single SQL query?
sobes.tech AI
Answer from AI
Yes, in a single SQL query, you can use WHERE conditions, GROUP BY grouping, and HAVING filtering simultaneously.
- WHERE is used to filter rows before grouping.
- GROUP BY groups rows based on specified columns.
- HAVING filters the already grouped data based on aggregate conditions.
Example:
SELECT department, COUNT(*) AS employee_count
FROM employees
WHERE salary > 50000
GROUP BY department
HAVING COUNT(*) > 5;
In this query, employees with a salary above 50000 are selected first (WHERE), then they are grouped by departments (GROUP BY), and only those groups where the number of employees is greater than 5 are selected (HAVING).