# GROUP BY Method

### 🔶 What is `GROUP BY` in SQL?

The `GROUP BY` clause is used **to group rows that have the same values** in specified columns into summary rows. It is often used with **aggregate functions** like:

* `COUNT()` – counts items
    
* `SUM()` – adds values
    
* `AVG()` – averages values
    
* `MAX()` – finds the largest value
    
* `MIN()` – finds the smallest value
    

---

### 🔶 Why use `GROUP BY`?

To **summarize or analyze** data based on one or more columns. For example:

* Total sales per product
    
* Number of customers per country
    
* Average marks per student
    

---

### 🔶 Basic Syntax:

```sql
SELECT column_name, AGGREGATE_FUNCTION(column_name)
FROM table_name
GROUP BY column_name;
```

---

### 🔶 Example Table: `Sales`

| SaleID | Product | Quantity | Price |
| --- | --- | --- | --- |
| 1 | Pen | 10 | 5 |
| 2 | Pencil | 20 | 2 |
| 3 | Eraser | 15 | 3 |
| 4 | Pen | 8 | 5 |
| 5 | Pencil | 25 | 2 |

---

### 🔶 Example 1: Total quantity sold per product

```sql
SELECT Product, SUM(Quantity) AS TotalQuantity
FROM Sales
GROUP BY Product;
```

#### 🔸 Output:

| Product | TotalQuantity |
| --- | --- |
| Pen | 18 |
| Pencil | 45 |
| Eraser | 15 |

✅ This groups the data by each product and shows how many of each were sold.

---

### 🔶 Example 2: Count number of sales per product

```sql
SELECT Product, COUNT(*) AS SaleCount
FROM Sales
GROUP BY Product;
```

#### 🔸 Output:

| Product | SaleCount |
| --- | --- |
| Pen | 2 |
| Pencil | 2 |
| Eraser | 1 |

✅ This shows how many times each product appears in the sales records.
