TutorialsSQLGROUP BY
🟢 Free Demo
SQL TutorialTopic 8 of 20

GROUP BY

Aggregate data by category

✅ What You Will Learn

How GROUP BY groups rows with the same value into a single summary row
How to use GROUP BY with COUNT, SUM, AVG, MIN, MAX
How to group by multiple columns
The difference between WHERE (filters rows) and HAVING (filters groups)
How to sort grouped results with ORDER BY

GROUP BY divides rows into groups based on one or more columns, then applies an aggregate function to each group separately. This is how you answer "total sales per product", "number of orders per customer", "average salary per department".

It is one of the most used clauses in real analytics work. Almost every summary report — daily revenue by region, monthly orders by product category, top customers by spend — uses GROUP BY.

📋 The orders table used in examples

order_idcustomer_nameproductamountcity
1001Rahul SharmaLaptop45000Delhi
1002Priya VermaMobile Phone18000Noida
1003Amit KumarHeadphones3500Gurgaon
1004Sneha KapoorLaptop52000Delhi
1005Vikram SinghTablet28000Noida
1006Neha JoshiLaptop48000Delhi

Syntax

SQL SYNTAX
SELECT column, AGGREGATE_FUNCTION(column)
FROM table_name
GROUP BY column;

Examples

Example 1Total revenue per product
SELECT product,
       COUNT(*) AS number_of_orders,
       SUM(amount) AS total_revenue
FROM orders
GROUP BY product;
OUTPUT
product      | number_of_orders | total_revenue
-------------|------------------|-------------
Laptop       | 2                | 97000
Mobile Phone | 1                | 18000
Headphones   | 1                | 3500
💡

GROUP BY product splits the table into three groups — one per product — and SUM calculates the total for each group separately.

Example 2Orders per date
SELECT order_date,
       COUNT(*) AS orders_that_day,
       SUM(amount) AS daily_revenue
FROM orders
GROUP BY order_date
ORDER BY order_date ASC;
OUTPUT
order_date  | orders_that_day | daily_revenue
------------|-----------------|-------------
2026-01-15  | 1               | 45000
2026-01-16  | 2               | 21500
2026-01-17  | 1               | 52000
Example 3GROUP BY multiple columns
SELECT order_date, product, SUM(amount) AS revenue
FROM orders
GROUP BY order_date, product
ORDER BY order_date;
💡

Groups by the combination of date AND product — each unique date+product pair becomes one group.

Example 4Important rule: SELECT and GROUP BY must match
-- CORRECT: every non-aggregate column in SELECT is in GROUP BY
SELECT product, SUM(amount)
FROM orders
GROUP BY product;

-- WRONG: customer_name is in SELECT but not in GROUP BY
SELECT product, customer_name, SUM(amount)
FROM orders
GROUP BY product;  -- This will error in most databases
💡

Any column in SELECT that is not inside an aggregate function (SUM, COUNT, etc.) must appear in GROUP BY.

📌 Key Points to Remember

  • GROUP BY splits rows into groups before aggregation
  • Every non-aggregated column in SELECT must be in GROUP BY
  • ORDER BY can sort the grouped result
  • GROUP BY runs after WHERE — WHERE filters rows, then GROUP BY groups them
  • You can GROUP BY multiple columns to get more granular breakdowns

🏢 Real-World Application

GROUP BY is what transforms raw transactional data into business intelligence. "Total sales by region" — GROUP BY region, SUM(sales). "Number of orders per customer" — GROUP BY customer_id, COUNT(*). "Average order value by product category" — GROUP BY category, AVG(order_value). Every pivot table in Excel is essentially a GROUP BY query. Power BI and Tableau dashboards that show data broken down by dimension (city, product, month, salesperson) are all running GROUP BY queries behind the scenes. A data analyst who cannot write GROUP BY queries cannot build reports — it is that fundamental.

⚠️ Common Mistakes to Avoid

WRONGSelecting a non-aggregated column that is not in GROUP BY
FIXEvery column in SELECT must either be in GROUP BY or wrapped in an aggregate function. SELECT product, customer_name, SUM(amount) FROM orders GROUP BY product will error because customer_name is not grouped or aggregated.
WRONGUsing WHERE to filter aggregated results
FIXWHERE runs before GROUP BY and cannot use aggregate functions. To filter after grouping (e.g., only groups where SUM > 10000), use HAVING instead of WHERE.
WRONGGrouping by the wrong column when using aliases
FIXYou cannot use SELECT aliases in GROUP BY in most databases. If you alias a column, GROUP BY must reference the original expression, not the alias.
✏️Test Yourself

What does the GROUP BY clause do?

❓ Frequently Asked Questions

What does GROUP BY do in SQL?

GROUP BY collapses multiple rows that share the same value in a column into a single summary row. It is always used with aggregate functions like COUNT, SUM, AVG, MIN, MAX to calculate totals per group.

Can I GROUP BY multiple columns in SQL?

Yes. GROUP BY col1, col2 creates groups for each unique combination of col1 and col2. For example, GROUP BY product, city groups by product within each city, giving revenue per product per city.

What is the difference between WHERE and HAVING?

WHERE filters individual rows before grouping. HAVING filters groups after GROUP BY. You must use HAVING (not WHERE) with aggregate functions: HAVING SUM(amount) > 50000.

Can I use ORDER BY with GROUP BY?

Yes. Add ORDER BY at the end to sort grouped results. A common pattern is GROUP BY product ORDER BY SUM(amount) DESC to show products ranked by total revenue.

What happens to NULL values in GROUP BY?

NULL values are grouped together into their own group. All rows where the GROUP BY column is NULL will be combined into one group, and the aggregate functions will be applied to that NULL group.

✏️ Practice Exercise

Write a query to find the number of orders and total revenue for each product, only for orders above ₹5,000, sorted by total revenue highest first.

← PreviousAggregate FunctionsNext →HAVING Clause
🎓 Level Up Faster

Learn SQL with Live Trainer Guidance

These tutorials give you the theory. Our live SQL course at EVIKA Academy, Noida teaches you to apply SQL on real company datasets — with a trainer who uses it daily at MakeMyTrip.