📊 GROUP BY – Grouping Data and Performing Aggregate Functions

(because sometimes you want to calculate things on grouped data, not individual rows)

🔧 Quick Syntax

SELECT column, aggregate_function(column)
FROM table
GROUP BY column;

This tells SQL:
“Group the rows by a column, and apply aggregate functions (like SUM, AVG, COUNT) on the grouped data.”

👀 Imagine You Have This Table:

🧑 sales table:

sale_idproductquantitysale_date
1Laptop32024-01-01
2Phone52024-01-01
3Laptop22024-01-02
4Phone32024-01-02
5Laptop42024-01-03
6Phone72024-01-03

Scenario: You want to calculate the total quantity sold for each product.

Step 1: GROUP BY Product

Here, we’ll group by the product to calculate the total quantity sold for each one.

SELECT product, SUM(quantity) AS total_quantity
FROM sales
GROUP BY product;

✅ Result:

producttotal_quantity
Laptop9
Phone15

🧃 Recap

  • GROUP BY groups the data by a column (in this case, product).
  • We use aggregate functions like SUM, AVG, COUNT on the grouped data.
  • The result shows total quantities sold for each product.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top