SQL

Grouping Data

GROUP BY

GROUP BY is what makes aggregate functions truly powerful. It groups rows with the same value and lets you calculate aggregates per group.

Without GROUP BY

SELECT COUNT(*) FROM products;
-- Returns: 5 (total count of ALL products)

With GROUP BY

SELECT category, COUNT(*) FROM products
GROUP BY category;
-- Returns: count PER category
-- Electronics  2
-- Office        2
-- Books         1

How It Works

  • SQL looks at the GROUP BY column
  • Groups all rows with the same value together
  • Applies the aggregate function to each group separately

💡 Real-World Examples

  • "How many orders per customer?" → GROUP BY customer_id
  • "Total sales per month?" → GROUP BY month
  • "Average salary per department?" → GROUP BY department

⚠️ Important Rule

Every column in SELECT must either be:

  • In the GROUP BY clause, OR
  • Inside an aggregate function (COUNT, SUM, AVG, etc.)

Your Task

Count how many products are in each category.

query.sql
Loading SQL engine...
Downloading SQL engine… (one-time)

Downloading SQL engine… (one-time)

This runs entirely in your browser and is cached for next time.