AskDB
·6 min read

SQL GROUP BY Explained with Examples

GROUP BY is one of the most powerful SQL clauses. It groups rows with the same values and lets you perform aggregate calculations on each group.

Basic Syntax

SELECT column, AGGREGATE_FUNCTION(column)
FROM table
GROUP BY column;

COUNT — Count Rows per Group

SELECT department, COUNT(*) as employee_count
FROM employees
GROUP BY department;

Result: One row per department with the count of employees.

SUM — Total per Group

SELECT category, SUM(amount) as total_sales
FROM orders
GROUP BY category;

AVG — Average per Group

SELECT department, AVG(salary) as avg_salary
FROM employees
GROUP BY department;

Multiple Aggregates

SELECT department,
  COUNT(*) as count,
  AVG(salary) as avg_salary,
  MIN(salary) as min_salary,
  MAX(salary) as max_salary
FROM employees
GROUP BY department;

GROUP BY Multiple Columns

SELECT department, title, COUNT(*) as count
FROM employees
GROUP BY department, title;

Groups by the combination of department AND title.

HAVING — Filter Groups

WHERE filters rows before grouping. HAVING filters groups after grouping.

SELECT department, COUNT(*) as count
FROM employees
GROUP BY department
HAVING COUNT(*) > 10;

Only shows departments with more than 10 employees.

ORDER BY with GROUP BY

SELECT category, SUM(amount) as total
FROM orders
GROUP BY category
ORDER BY total DESC;

GROUP BY with JOINs

SELECT u.name, COUNT(o.id) as order_count, SUM(o.total) as total_spent
FROM users u
LEFT JOIN orders o ON u.id = o.user_id
GROUP BY u.id, u.name
ORDER BY total_spent DESC;

Common Mistakes

  • Selecting columns not in GROUP BY or an aggregate (causes errors in strict mode)
  • Using WHERE instead of HAVING to filter aggregates
  • Forgetting to GROUP BY all non-aggregated columns in SELECT

Practice

Format your GROUP BY queries with the SQL Formatter to keep complex aggregations readable.