SQL Group By
The GROUP BY clause in SQL divides your dataset into subsets, grouping rows that share the same values in one or more specified columns. It is almost always paired with aggregate functions (COUNT(), SUM(), AVG(), MIN(), MAX()) to compute summary statistics for each distinct group.
Think of GROUP BY as the SQL equivalent of creating a Pivot Table in Excel.
The Golden Rule of GROUP BY
When using GROUP BY, every column listed in your SELECT statement must meet one of two conditions:
- It is explicitly listed inside the GROUP BY clause.
- It is wrapped inside an aggregate function.
If you violate this rule, SQL will throw an error because it doesn't know which individual row's value to display for the unaggregated column.
Syntax & Logical Order
In an SQL query, GROUP BY must come after the FROM and WHERE clauses, but before HAVING and ORDER BY.
SELECT column_1, AGGREGATE_FUNCTION(column_2)
FROM table_name
WHERE condition
GROUP BY column_1
ORDER BY column_1;
Core Examples
Standard Grouping (Single Column)
To find out how many employees work in each department, you group by the department column and count the rows.
SELECT department, COUNT(*) AS employee_count
FROM employees
GROUP BY department;
Grouping by Multiple Columns
You can break groups down into sub-groups. For example, to find the total sales broken down by Year and then by Region:
SELECT order_year, region, SUM(sales_amount) AS total_revenue
FROM sales_data
GROUP BY order_year, region
ORDER BY order_year DESC, total_revenue DESC;
Filtering Groups: WHERE vs. HAVING
A common mistake is trying to filter grouped data using a WHERE clause. They serve completely different purposes:
- WHERE: Filters individual rows before grouping happens. It cannot look at aggregate results.
- HAVING: Filters entire groups after grouping and aggregations are calculated.
SELECT department, AVG(salary) AS avg_salary
FROM employees
WHERE status = 'Active' -- 1. Filter out inactive employees first
GROUP BY department -- 2. Group the remaining active employees
HAVING AVG(salary) > 60000; -- 3. Only keep departments with a high average