sqlstreak

SQL error

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

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

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

  • PostgreSQLERROR: must appear in the GROUP BY clause or be used in an aggregate function
  • 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:  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.

Reproduce it, then fix it

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

Broken
SELECT category, name, MAX(price)
FROM menu_items
GROUP BY category;
Fixed
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;

The fix returns, PostgreSQL: 4 rows

categorynameprice
dessertTiramisu6.5
drinkLemon Soda3
pizzaBBQ Meteor15.5
sideWings8.5

The fix returns, SQLite: 4 rows

categorynameprice
dessertTiramisu6.5
drinkLemon Soda3
pizzaBBQ Meteor15.5
sideWings8.5

Experiment with it: PostgreSQL playground·SQLite playground

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.

Official documentation

Stop hitting this error

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