Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 23/ 160
02. Aggregations, Functions & Data Manipulation

Grouping Data with GROUP BY (Single & Multiple Columns)

Slice metrics by one or more dimensions and keep SELECT lists valid.

BeginnerGROUP BY · Grain · Aggs3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

The classic error and the fixQuery example
1Input dataStart from the source rows or state that the statement sees.
users
3 rows
users sample rows
idcountrycitysignup_date
1INPune2026-10-01
2INDelhi2026-10-02
3NULLMumbai2026-10-03
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  country,3  city,4  COUNT(*)5FROM6  users7GROUP BY8  country
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/8
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected database error
ERROR: column "users.city" must appear in the GROUP BY clause or be used in an aggregate function

Note: The wording varies by database. The fix must still produce one unambiguous output row per group.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Monthly revenueQuery example
1Input dataStart from the source rows or state that the statement sees.
orders
4 rows
orders sample rows
idcreated_atamount
1012026-10-08500
1022026-10-25950
1032026-11-031200
1042026-11-191125
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  date_trunc('month', created_at) AS MONTH,3  SUM(amount) AS revenue4FROM5  orders6GROUP BY7  18ORDER BY9  1;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/9
3OutputInspect the representative rows, affected-row count, plan, or command status.
Expected output2 sample rows
Expected output
monthrevenue
2026-10-011450
2026-11-012325

Note: Sample monthly totals are shown as two groups, ordered from October to November.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: Group by expressions for time buckets, and never rely on GROUP BY for sorting.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Design

Choose the grain

Say what one output row should mean ("one row per country and plan"). That list of dimensions is your GROUP BY.

Focus at this step

one row per country × plan

What to watch at this step
Grain
= GROUP BY columns
Tip: use ← → to move between steps

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

GROUP BY
Best for: Metrics per group: counts, sums, averages

Strengths: One row per group, with any aggregates you need.

Watch out: Detail columns are lost unless aggregated.

SELECT DISTINCT
Best for: Listing unique values or combinations, no metrics

Strengths: Short and clear for "which values exist?".

Watch out: Can't compute aggregates.

Window functions (OVER)
Best for: Showing each row next to its group's aggregate

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?
Interview tip: State the grain before writing the query ("one row per month and country"). It makes the GROUP BY obvious and catches grain mistakes early.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
COUNT(*) vs COUNT(column) vs COUNT(DISTINCT column)
Next topic
Filtering Groups with HAVING (WHERE vs HAVING)