SQLPathLab
Aggregation · Intermediate

GROUP BY

Groups rows by one or more columns for aggregation.

Overview

GROUP BY collects rows that share the same grouping keys, then applies aggregates such as SUM, COUNT, or AVG to each group. Regular selected columns should normally appear in GROUP BY. Use WHERE before grouping and HAVING to filter aggregate results afterward.

Basic syntax

SELECT department, SUM(amount) FROM orders GROUP BY department;

Examples

GROUP BY example

Group orders by department and sum amount so each department returns one aggregate row.

Sample table

Table:orders
orders
departmentamount
Sales 1200
IT 900
Sales 1500
HR 700

Run result

result
departmentSUM(amount)
HR 700
IT 900
Sales 2700

Common issues

Which columns should follow GROUP BY?

Use the columns you want to group by. Non-aggregate selected columns should usually appear in GROUP BY.

How is GROUP BY different from DISTINCT?

DISTINCT removes duplicates, while GROUP BY is mainly used with aggregates such as COUNT, SUM, and AVG.

Can GROUP BY use multiple columns?

Yes. For example, group by customer_id and status together.

Tags

AggregationCommon

Was this explanation clear?