# Every column in a GROUP BY query must be grouped or aggregated

> With GROUP BY, the database doesn't know which value to show for each group, so every column in SELECT has to be in the GROUP BY clause or inside an aggregate such as COUNT or SUM.

- Question: Why does SQL say my column must appear in the GROUP BY clause or be used in an aggregate function?
- Topic: SQL
- Author: Jamal Hansen
- Full post: https://jamalhansen.com/blog/group-by-aggregating-your-data/
- This page: https://jamalhansen.com/explain/sql/group-by-golden-rule/


## In one sentence

**Every column in `SELECT` must be either:**
1. In the `GROUP BY` clause, OR
2. Inside an aggregate function

## If you know Python

Like Python's `collections.Counter` or pandas `groupby()`, SQL's `GROUP BY` lets you summarize data by category. It allows you to count, sum, and average across groups.

```python
from collections import Counter
city_counts = Counter(c['city'] for c in customers)

# or with pandas
df.groupby('city').size()
```

The issue with these is that if you simply want to know how many customers are in each city, you are sending all the records to Python and letting it manage them. SQL can do this in the database and simply return the city and the number of customers in that city.

```sql
SELECT city, COUNT(*) AS customer_count
FROM customers
GROUP BY city
```

Same result, but the work happens on the database server.

## The usual mistake

```sql
-- ✅ Correct: city is in GROUP BY, COUNT is aggregate
SELECT city, COUNT(*)
FROM customers
GROUP BY city

-- ❌ Wrong: name is not grouped or aggregated
SELECT city, name, COUNT(*)
FROM customers
GROUP BY city
-- Error! Which "name" should it show for each city?
```

This trips up everyone. The database doesn't know which `name` to pick when there are 50 customers in San Antonio, so it either throws an error or gives bad results. If you are receiving errors or unexpected results when using aggregate functions and `GROUP BY`, this is the first thing that you should check, twice.

## Example

You can use multiple aggregate functions for the same `GROUP BY`

```sql
SELECT city,
       COUNT(*) AS total,
       MIN(signup_date) AS first_signup,
       MAX(signup_date) AS last_signup
FROM customers
GROUP BY city
```

..or `GROUP BY` multiple columns

```sql
SELECT city, is_premium, COUNT(*) AS count
FROM customers
GROUP BY city, is_premium
```

Notice that in both these examples any column in the `SELECT` clause that is not an aggregate function is in the `GROUP BY` clause.

## Go deeper

[GROUP BY: Aggregating Your Data](https://jamalhansen.com/blog/group-by-aggregating-your-data/), post 10 of [SQL for Python Developers](https://jamalhansen.com/series/sql-for-python-developers/): the aggregate functions, how `WHERE` and `ORDER BY` combine with `GROUP BY`, and the order the database runs them in.

