Skip to content
Exercises · Q9

Q.Explain the concept of GROUP BY with help on an example.

Telangana TsbieTextbookSubjective· 3mImportance★★★★★
55% · 29/53 Questions
🔒 Locked · start free trial →

You're viewing a preview — the full solution, concept, methods & PYQ mapping are locked.

Start your 14-day free trial to unlock the full solution →

GROUP BY collapses rows that share the same value(s) in specified column(s) into a single row per group, enabling aggregate calculations (count, sum, average, etc.) on each group separately.

Why GROUP BY exists

Imagine you have a table of sales transactions, each row recording one sale. You want to answer "What is the total revenue per product?" or "How many orders did each customer place?" These questions require you to partition your data into subsets—one subset per product, or one per customer—and then compute a summary statistic for each subset.

GROUP BY is the SQL clause that performs this partitioning. It takes all rows that share the same value in the grouping column(s) and treats them as a single logical unit. Any aggregate function (COUNT(), SUM(), AVG(), MAX(), MIN()) then operates within each group, producing one result per group rather than one result for the entire table.

Without GROUP BY, an aggregate function collapses the entire table into a single row. With GROUP BY, you get one row per distinct value (or combination of values) in the grouping column(s).


A concrete example

Suppose you manage a bookstore and have a Sales table:

OrderIDBookTitleCategoryQuantityPrice
1Python Crash CourseProgramming2500
2Clean CodeProgramming1600
3SapiensHistory3400
4EducatedBiography1350
5The Pragmatic...Programming2550
6Guns, Germs...History1450

Question: What is the total quantity sold in each category?

You want one row per category, showing the category name and the sum of Quantity for all books in that category.

SELECT Category, SUM(Quantity) AS TotalQuantity
FROM Sales
GROUP BY Category;

How it works:

  1. GROUP BY Category partitions the six rows into three groups:

    • Programming: rows 1, 2, 5
    • History: rows 3, 6
    • Biography: row 4
  2. SUM(Quantity) is evaluated separately for each group:

    • Programming: 2+1+2=52 + 1 + 2 = 5
    • History: 3+1=43 + 1 = 4
    • Biography: 11
  3. The result is one row per group:

CategoryTotalQuantity
Programming5
History4
Biography1

Key rules

Every column in the SELECT list must be either:

  • in the GROUP BY clause, or
  • wrapped in an aggregate function.

This is because once you group, each result row represents multiple input rows. If you tried to SELECT BookTitle without grouping by it, SQL wouldn't know which of the three Programming book titles to show in the single Programming row—hence it's forbidden.

Valid:

SELECT Category, COUNT(*) AS NumOrders
FROM Sales
GROUP BY Category;

Invalid (will raise an error):

SELECT Category, BookTitle, COUNT(*)
FROM Sales
GROUP BY Category;
-- BookTitle is neither grouped nor aggregated
Watch out

A common mistake is forgetting to include a non-aggregated column in GROUP BY. If you SELECT Category, BookTitle but only GROUP BY Category, the query will fail (or in MySQL's lenient mode, return an arbitrary BookTitle from each group, which is almost never what you want).


Grouping by multiple columns

You can group by more than one column. Each unique combination of values becomes a separate group.

Question: Total quantity sold per category and price point?

SELECT Category, Price, SUM(Quantity) AS TotalQuantity
FROM Sales
GROUP BY Category, Price;

Now rows are grouped by (Category, Price) pairs. For instance, if two Programming books have different prices, they form two separate groups.


Using HAVING to filter groups

WHERE filters rows before grouping. HAVING filters groups after aggregation.

Question: Which categories sold more than 3 items in total?

Unlock everything free for 14 days

  • Full step-by-step solutions
  • Concept-first explanations
  • Methods, shortcuts & mistakes
  • PYQ mapping + timed mock tests

Full access for 14 days. No credit card required.