SQL – GROUP BY
Group rows sharing a common value and apply aggregate functions to each group using GROUP BY.
Table of Contents
GROUP BY is the mechanism that transforms row-level data into summaries. It collapses all rows sharing the same value in a specified column into a single group, and then aggregate functions (SUM, COUNT, AVG, etc.) compute a result for that group. Without GROUP BY, aggregate functions return a single value for the entire table.
Think of it like sorting physical files into folders — GROUP BY is the filing, and the aggregate functions then count or add up what is in each folder.
How GROUP BY works
Before GROUP BY: After GROUP BY city:
Aria – Mumbai 94 Mumbai rows → avg 89.05
Hiro – Mumbai 83 Delhi rows → avg 78.2
Ben – Delhi 78 ...
Try It Yourself — Interactive SQL Editor
Edit the query below and click Run Query ▶ to see live results powered by SQLite running directly in your browser.
Key Points
- Every column in SELECT must either be in GROUP BY or be aggregated
- GROUP BY is applied after WHERE and before HAVING
- GROUP BY allows grouping on multiple columns (multi-level)
- NULL values form their own group in GROUP BY
Pro Tip from CodesCompiler: The best way to learn SQL is to break things intentionally — modify the query above, change the WHERE conditions, try different columns. Every error teaches you something the docs cannot.
In the next lesson, we continue exploring SQL’s powerful feature set to build your database mastery.