sql / intermediate
Snippet
Filtering Aggregated Data with HAVING
The HAVING clause filters groups created by the GROUP BY clause. Unlike WHERE, which filters individual rows, HAVING filters based on aggregate function results.
snippet.sql
1
2
3
4
SELECT department_id, AVG(salary) AS avg_salFROM employeesGROUP BY department_idHAVING AVG(salary) > 5000;
Breakdown
1
GROUP BY department_id
Groups the raw data into segments based on the department ID.
2
HAVING AVG(salary) > 5000;
Filters out entire departments where the average salary does not meet the criteria.