sqlstreak

SQL error

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

Updated · Tested on PostgreSQL 18.6 and SQLite 3.54.1 (results generated , re-checked on every release)

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

  • PostgreSQLERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list
  • SQLiteNo error, but a silent surprise: see below.

How to read this message

This is what PostgreSQL 18.6 prints for the broken query below, the way psql shows it. LINE gives the line it was reading when it gave up, and the ^ marks the exact spot.

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).

Reproduce it, then fix it

Both queries run on a real database in your browser. Switch dialects to compare.

Broken
SELECT DISTINCT category
FROM menu_items
ORDER BY price;
Fixed
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.

The fix returns, PostgreSQL: 4 rows

category
drink
side
dessert
pizza

The fix returns, SQLite: 4 rows

category
drink
side
dessert
pizza

Experiment with it: PostgreSQL playground·SQLite playground

Another fix

If you want each category-price pair, put price in the select list; DISTINCT then applies to the pair.

SELECT DISTINCT category, price
FROM menu_items
ORDER BY price, category;

Returns, PostgreSQL: first 6 of 11 rows

categoryprice
drink2.5
drink3
side5
dessert6.5
side7
side8.5

Returns, SQLite: first 6 of 11 rows

categoryprice
drink2.5
drink3
side5
dessert6.5
side7
side8.5

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.

Official documentation

Stop hitting this error

Practise the concept behind it in a five-minute lesson, or read the full guide: SQL ORDER BY, LIMIT and OFFSET.