# column "x" must appear in the GROUP BY clause or be used in an aggregate function

Source: https://sqlstreak.com/sql/errors/must-appear-in-group-by · Tested on PostgreSQL 18.6 and SQLite 3.54.1; results generated 2026-11-22.


**Short answer:** Every column in `SELECT` must either be listed in `GROUP BY` or wrapped in an aggregate like `MAX()` or `COUNT()`. PostgreSQL can't guess which row's value to show for a column that has several values per group.

## The exact messages

- PostgreSQL: `ERROR: must appear in the GROUP BY clause or be used in an aggregate function`

## How PostgreSQL prints it

```
ERROR:  column "menu_items.name" must appear in the GROUP BY clause or be used in an aggregate function
LINE 1: SELECT category, name, MAX(price)
                         ^
```

## Why it happens

### You selected a column that has many values per group

Grouping by `category` produces one row per category, but each category has several item names. PostgreSQL won't pick one for you.

### You really wanted the row with the max or min

“The most expensive item in each category” isn't a GROUP BY question at all. It's a top-N-per-group question, solved with a window function (see the fix).

### You forgot to add a column to GROUP BY

If you want one row per combination, list every non-aggregated column: `GROUP BY category, name`.

## The broken query

```sql
SELECT category, name, MAX(price)
FROM menu_items
GROUP BY category;
```

## The fix

```sql
SELECT category, name, price
FROM (SELECT *, ROW_NUMBER() OVER (
  PARTITION BY category ORDER BY price DESC) AS rn
  FROM menu_items) t
WHERE rn = 1;
```

Number the rows inside each category by price, then keep row 1. If you only need the top price itself (not the item's name), drop `name` and keep the GROUP BY: `SELECT category, MAX(price) FROM menu_items GROUP BY category;`

| category | name | price |
| --- | --- | --- |
| dessert | Tiramisu | 6.5 |
| drink | Lemon Soda | 3 |
| pizza | BBQ Meteor | 15.5 |
| side | Wings | 8.5 |

## What SQLite does instead

SQLite runs this query without complaint. With a single MAX or MIN it takes the other columns from that row, but with any other aggregate the value comes from an arbitrary row, which is exactly why PostgreSQL refuses.
