# for SELECT DISTINCT, ORDER BY expressions must appear in select list

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


**Short answer:** After `SELECT DISTINCT category`, there's one row per category but several prices behind it, so `ORDER BY price` has no single value to sort by. Decide which price you mean: group and sort by `MIN(price)`, or add the column to the select list.

## The exact messages

- PostgreSQL: `ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list`

## How PostgreSQL prints it

```
ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 3: ORDER BY price;
                 ^
```

## Why it happens

### Sorting by a column you didn't select

DISTINCT collapses rows first. A column that isn't in the result has several values per result row.

### You meant the cheapest or the most expensive

That's a GROUP BY question: `GROUP BY category ORDER BY MIN(price)`.

## The broken query

```sql
SELECT DISTINCT category
FROM menu_items
ORDER BY price;
```

## The fix

```sql
SELECT category
FROM menu_items
GROUP BY category
ORDER BY MIN(price), category;
```

Categories sorted by their cheapest item. `category` as a second key keeps ties in a fixed order.

| category |
| --- |
| drink |
| side |
| dessert |
| pizza |

## What SQLite does instead

SQLite runs it and sorts each category by the price of one of its rows, picked arbitrarily. The order can change when the data changes.
