SQL GROUP BY Clause
Definition
The SQL GROUP BY clause groups rows with the same values in specified columns into summary rows, typically used with aggregate functions like COUNT, SUM, AVG, MIN, and MAX.
Introduction to SQL GROUP BY Clause
GROUP BY is essential for business analytics — it collapses multiple rows into a single summary row per group. Every column in the SELECT list must either appear in the GROUP BY clause or be wrapped in an aggregate function. Combine with HAVING to filter groups after aggregation.
Syntax
SELECT column, AGG_FUNC(value) FROM table WHERE condition GROUP BY column HAVING AGG_FUNC(value) > threshold ORDER BY AGG_FUNC(value) DESC;
Examples
Count Employees Per Department
SELECT department, COUNT(*) AS employee_count FROM employees GROUP BY department ORDER BY employee_count DESC;
Groups all employees by department, counts each group, and sorts from largest to smallest.
Try in PlaygroundAverage Salary Per Department
SELECT department, AVG(salary) AS avg_salary, MAX(salary) AS top_salary FROM employees GROUP BY department;
Calculates both average and maximum salary for each department in a single query.
Try in PlaygroundFilter Groups with HAVING
SELECT department, SUM(salary) AS total_payroll FROM employees GROUP BY department HAVING SUM(salary) > 500000 ORDER BY total_payroll DESC;
HAVING filters departments after grouping — only shows departments where total payroll exceeds $500k.
Try in PlaygroundCommon Mistakes
Selecting non-aggregated columns not in GROUP BY (causes an error in strict SQL modes)
Confusing WHERE and HAVING — WHERE filters before grouping, HAVING after
Using column aliases in HAVING (not supported in most databases — repeat the expression)
Expecting GROUP BY to sort results — it doesn't guarantee order, always add ORDER BY
Frequently Asked Questions
What is GROUP BY in SQL?
Can you GROUP BY multiple columns?
What is the difference between GROUP BY and ORDER BY?
Can you use GROUP BY without aggregate functions?
Related SQL Topics
Practice This in the SQL Playground
Write real queries, see live results, and master SQL GROUP BY Clause hands-on. 100% free.