SQL GroupBy Visualizer
Interactively build and visualize how SQL aggregates data by grouping rows based on specific columns.
Source Table
SALES_DATALive Query
SELECT ... FROM SalesData;
Interactively build and visualize how SQL aggregates data by grouping rows based on specific columns.
SELECT ... FROM SalesData;
Transform raw data into powerful summaries. This guide, paired with the interactive tool, will make you a `GROUP BY` expert.
The `GROUP BY` clause in SQL is used with aggregate functions (`COUNT`, `SUM`, `AVG`, etc.) to group rows that have the same values in specified columns into summary rows. It's one of the most powerful tools for data analysis.
Imagine you have a table of sales data. You don't want to see every single sale; you want to know the total sales for each department. `GROUP BY` is how you do this. It performs two main steps:
The final result is a new, smaller table showing each group and its calculated aggregate value.
Use the interactive tool above to see this process in action. The animation directly mirrors how a database engine thinks.
When you use `GROUP BY`, your `SELECT` statement has a strict rule:
Any column in the `SELECT` list must either be part of the `GROUP BY` clause or be contained within an aggregate function.
-- This is ILLEGAL!
SELECT Department, Region, SUM(Sales) -- 'Region' is not in GROUP BY or an aggregate
FROM SalesData
GROUP BY Department;
-- This is LEGAL
SELECT Department, Region, SUM(Sales)
FROM SalesData
GROUP BY Department, Region; -- Group by all non-aggregated columns
This makes sense: if you've collapsed all 'Sales' department rows into one, which 'Region' should the database show? North? South? East? It's ambiguous. By grouping by both, you get a clear, unambiguous result for each Department-Region pair.
The `GROUP BY` clause in SQL is used with aggregate functions (`COUNT`, `SUM`, `AVG`, etc.) to group rows that have the same values in specified columns into summary rows. It's one of the most powerful tools for data analysis.