# Group By & Having

The GROUP BY statement groups rows with the same values into summary rows.

Its often used with aggregate functions (Count, Min, Max, Sum, Avg)

**Simple Syntax:**

```
Select column(s)
From tablename
Group By column(s)
```

**Example:**

```sql
select * from Chinook.Customer order by country;
```

How to find out the number of countries in the table

```sql
SELECT  country,count(*) FROM  Chinook.Customer group by country;
```

Does this result make sense?

```sql
Select count(*) from Chinook.Invoice group by CustomerId;
```

What do you think about it now?

```sql
Select CustomerId,count(*) from Chinook.Invoice group by CustomerId;
```

```sql
Select CustomerId ,count(*),min(total),max(total), sum(total), avg(total) from Chinook.Invoice group by CustomerId;
```

### Group By Having <a href="#group-by-having" id="group-by-having"></a>

Having clause is used in SQL to filter Grouped data.

Wait.. if Where does filtering.. why need Having?

Let's learn more

```sql
SELECT
    COUNT(country)
    ,Country
FROM
    Customer
GROUPBY
    Country
HAVING
    COUNT(country) >5;
```

Where clause filters on the entire dataset.

The Having clause filters on the grouped dataset.

**Note:** When Having is used without Group By, it acts like a Where clause. (this feature is available in current MySQL)
