SQL FOUNDATIONS:GROUP BY & HAVING
Group rows and filter grouped results with HAVING.
SQL GROUP BY & HAVING Explained with Examples + Practice Questions
When to Use GROUP BY & HAVING
- Use GROUP BY to group rows based on a column
- Use HAVING to filter grouped results
These are essential for:
- Data analysis
- Reporting
- SQL interviews (very high frequency)
Example Dataset
Table: employees
GROUP BY
GROUP BY groups rows that have the same values in a column.
Example: Count employees per department
sqlSELECT department, COUNT(*) AS total_employeesFROM employeesGROUP BY department;
Example: Average salary per department
sqlSELECT department, AVG(salary) AS avg_salaryFROM employeesGROUP BY department;
Important Rule
Every column in SELECT must be:
- Either in GROUP BY
- Or used with an aggregate function
HAVING
HAVING is used to filter grouped results.
Example: Departments with more than 2 employees
sqlSELECT department, COUNT(*) AS totalFROM employeesGROUP BY departmentHAVING COUNT(*) > 2;
WHERE vs HAVING
Example Combining WHERE and HAVING
sqlSELECT department, AVG(salary) AS avg_salaryFROM employeesWHERE salary > 40000GROUP BY departmentHAVING AVG(salary) > 50000;
GROUP BY + ORDER BY
sqlSELECT department, SUM(salary) AS total_salaryFROM employeesGROUP BY departmentORDER BY total_salary DESC;
Key Concepts
- GROUP BY groups data
- HAVING filters grouped data
- WHERE filters before grouping
- Always use aggregate functions with GROUP BY
- Common interview pattern
GROUP BY vs HAVING Summary
Common Questions (FAQ)
What is GROUP BY in SQL
GROUP BY groups rows with the same values and applies aggregate functions.
What is HAVING in SQL
HAVING filters grouped results after aggregation.
Difference between WHERE and HAVING
WHERE filters rows before grouping, HAVING filters after grouping.
Can we use HAVING without GROUP BY
Yes, but it is uncommon and usually not needed.
Internal Learning Links
- Learn Aggregations
- Learn WHERE filtering
- Learn ORDER BY
Practice CTA
Practice GROUP BY and HAVING problems on Schoolabe to master interview-level SQL queries.
GROUP BY & HAVING Missions
Solve exercises in sequence to unlock the next mission.
Average per department
Find average salary for each department.
Total per department
Find total salary for each department.
Departments with >1
Find departments with more than 1 employee.
Avg salary > 55000
Find departments where average salary is greater than 55000.
Count salary > 50000
Count employees with salary greater than 50000 in each department.
Total salary > 100000
Find total salary of departments where total salary is greater than 100000.
Min salary > 45000
Find departments with minimum salary greater than 45000.
Sort by avg salary
Sort departments by average salary in descending order.
Highest total salary
Find department with highest total salary.