intermediateCore SQL100% Free

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

SQL
SELECT column, AGG_FUNC(value)
FROM table
WHERE condition
GROUP BY column
HAVING AGG_FUNC(value) > threshold
ORDER BY AGG_FUNC(value) DESC;

Examples

1

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 Playground
2

Average 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 Playground
3

Filter 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 Playground

Common 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?
GROUP BY collapses multiple rows with the same value into one summary row. It is used with aggregate functions (COUNT, SUM, AVG, MIN, MAX) to compute statistics per group. Example: SELECT dept, COUNT(*) FROM employees GROUP BY dept;
Can you GROUP BY multiple columns?
Yes. GROUP BY col1, col2 creates one group for each unique combination of col1 and col2 values. Example: SELECT year, quarter, SUM(revenue) FROM sales GROUP BY year, quarter;
What is the difference between GROUP BY and ORDER BY?
GROUP BY aggregates rows into groups. ORDER BY sorts the final result set. They serve different purposes but are often used together — GROUP BY first, then ORDER BY to sort the grouped results.
Can you use GROUP BY without aggregate functions?
Technically yes — it behaves like SELECT DISTINCT in that case. But standard practice is to always pair GROUP BY with at least one aggregate function.

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.