Databases & SQL · reviewed in July 2026
GROUP BY
GROUP BY is a SQL clause (and an equivalent method in pandas) that groups rows sharing the same value in one or more columns, so an aggregate function like COUNT, SUM, or AVG can be applied to each group separately. It's the backbone of almost any summary report.
SELECT customer_id, SUM(total) AS total_spent FROM orders GROUP BY customer_id;
Frequently asked questions
Can you use GROUP BY without an aggregate function?
Technically yes, but it loses its purpose: without an aggregation, GROUP BY just removes duplicate rows on the grouped columns — something DISTINCT already does.
What's the difference between WHERE and HAVING with GROUP BY?
WHERE filters rows before grouping; HAVING filters the groups that have already formed, typically over an aggregation's result, like HAVING COUNT(*) > 10.
How do you do a GROUP BY in pandas?
With df.groupby('column').agg(...), or with direct methods like df.groupby('column')['other_column'].sum(), which mirror the same group-and-aggregate pattern.