How to use GROUP BY and aggregate functions
· Category: SQL & Databases
Short answer
GROUP BY collapses rows that share the same values in specified columns into summary rows. Aggregate functions like COUNT, SUM, AVG, MIN, and MAX compute values per group.
Steps
- Count per group:
SELECT department, COUNT(*) FROM employees GROUP BY department; - Sum values:
SELECT department, SUM(salary) FROM employees GROUP BY department; - Average:
SELECT department, AVG(salary) FROM employees GROUP BY department; - Filter groups with
HAVING:SELECT department, AVG(salary) FROM employees GROUP BY department HAVING AVG(salary) > 50000; - Use multiple grouping columns:
GROUP BY year, month
Tips
- Columns in
SELECTthat are not aggregated must appear inGROUP BY. HAVINGfilters groups after aggregation;WHEREfilters rows before aggregation.
Common issues
- Including non-aggregated, non-grouped columns in
SELECTcauses an error in strict SQL modes. NULLvalues form their own group and affectCOUNT(*)versusCOUNT(column).r