Grouping Data with GROUP BY (Single & Multiple Columns)
Slice metrics by one or more dimensions and keep SELECT lists valid.
In plain words
GROUP BY puts rows with the same values into piles, and then you count or add up each pile.
Think of it like…
Sorting a bag of receipts into piles by month, then adding up each pile. Each pile becomes one line in your summary; you can't report "the shop name" for a pile unless every receipt in it has the same shop, or you pick one with a rule like MAX.
Where you’ve seen it
SELECT country, plan, COUNT(*) AS users FROM users GROUP BY country, plan ORDER BY users DESC; returns one row per country-and-plan combination, which is exactly the shape a pivot chart needs.
Words you’ll hear
- Grain
- What one output row represents: here, one country and plan combination.
- Grouped column
- A column listed in GROUP BY; it has one value per group.
- Aggregate
- A function that turns many rows into one value: COUNT, SUM, AVG, MIN, MAX.
- Functional dependency
- If you group by a table's primary key, PostgreSQL lets you select that table's other columns too.
Visual diagram
Theory & example queries
Grain and the SELECT rule
After GROUP BY, each output row stands for a whole group, so a non-grouped column like signup_date has many possible values per row. That's why standard SQL requires every selected column to be grouped or aggregated: pick a value with MIN, MAX or another aggregate, or add the column to GROUP BY and accept a finer grain.
PostgreSQL relaxes the rule when you group by a primary key: GROUP BY c.id lets you also select c.name, because the key determines it. Old MySQL versions returned an arbitrary value for non-grouped columns; since 5.7 the ONLY_FULL_GROUP_BY mode rejects that by default.
| id | country | city | signup_date |
|---|---|---|---|
| 1 | IN | Pune | 2026-10-01 |
| 2 | IN | Delhi | 2026-10-02 |
| 3 | NULL | Mumbai | 2026-10-03 |
SELECT country, city, COUNT(*)FROM usersGROUP BY countryPostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected database error
Note: The wording varies by database. The fix must still produce one unambiguous output row per group.
fails because city isn't grouped. Either GROUP BY country, city (one row per city) or drop city from SELECT.
Key takeaway: Decide the grain first; then every column is grouped or aggregated.
Grouping by expressions, NULLs and ordering
You can group by an expression, such as date_trunc('month', created_at) for monthly totals. PostgreSQL and MySQL also accept a SELECT alias or position (GROUP BY 1), which keeps long expressions from being repeated; SQL Server requires the expression itself.
All NULL values in a grouped column form one group, so rows with no country appear together as a NULL row in the result. GROUP BY doesn't promise any order, even if results often come out sorted, so always add ORDER BY when order matters.
| id | created_at | amount |
|---|---|---|
| 101 | 2026-10-08 | 500 |
| 102 | 2026-10-25 | 950 |
| 103 | 2026-11-03 | 1200 |
| 104 | 2026-11-19 | 1125 |
SELECT date_trunc('month', created_at) AS MONTH, SUM(amount) AS revenueFROM ordersGROUP BY 1ORDER BY 1;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Expected output2 sample rows
| month | revenue |
|---|---|
| 2026-10-01 | 1450 |
| 2026-11-01 | 2325 |
Note: Sample monthly totals are shown as two groups, ordered from October to November.
Key takeaway: Group by expressions for time buckets, and never rely on GROUP BY for sorting.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Choose the grain
Say what one output row should mean ("one row per country and plan"). That list of dimensions is your GROUP BY.
one row per country × plan
When to use it & trade-offs
What it is
GROUP BY collapses rows that share the same values in the listed columns into one row per group, so aggregates like COUNT, SUM and AVG can be computed for each group. With several columns you get one row per *combination*. Every column in SELECT must either be in GROUP BY or be inside an aggregate.
Why it matters: Almost every report is "some metric by some dimension": revenue by month, orders by country, users by plan. GROUP BY is how you get there, and the "must appear in the GROUP BY clause" error is one of the first things every SQL learner runs into.
When to reach for it
- Metrics by dimension: revenue by month, users by plan
- Finding duplicates with HAVING COUNT(*) > 1
- Building the input for charts and pivot tables
When to avoid or be careful
- Selecting columns that aren't grouped or aggregated
- Grouping by a column with a different grain than you intended (user_id instead of country)
- Relying on GROUP BY to sort the output
GROUP BY vs DISTINCT vs window functions
Strengths: One row per group, with any aggregates you need.
Watch out: Detail columns are lost unless aggregated.
Strengths: Short and clear for "which values exist?".
Watch out: Can't compute aggregates.
Strengths: Keeps every detail row.
Watch out: Doesn't reduce the row count, which a summary report usually needs.
Interview signals & numbers to know
When this topic comes up
- “… per month / per country / per category”
- "must appear in the GROUP BY clause" error
- Counting or summing by a dimension
- Duplicate detection
- Pivot chart data
Benchmarks & rules of thumb
- 1 row
- per distinct combination of grouped values
- 1 group
- for all NULLs in a grouped column
- MySQL 5.7
- ONLY_FULL_GROUP_BY enabled by default
Common mistakes & follow-ups
Common interview mistakes
- Selecting a non-grouped column and either getting an error or, in old MySQL, a random value.
- Grouping by too many columns (including an id) so every row becomes its own group.
- Expecting the output to be sorted without ORDER BY.
Likely interviewer follow-ups
- What's the difference between GROUP BY and DISTINCT?
- How would you get each department's total salary and also the highest earner's name?
- How do NULL values behave in GROUP BY?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Grouping Data with GROUP BY (Single & Multiple Columns) with hands-on SQL practice and interview Q&A.