SQL: every selected column must be grouped or aggregated

A column that is neither is ambiguous - the group has many values for it and only one row to print. Most engines reject it; MySQL historically picked one at random.

Code
-- error: name is neither grouped nor aggregated
SELECT customer_id, name, COUNT(*)
  FROM orders GROUP BY customer_id;

-- either group by it too...
SELECT customer_id, name, COUNT(*)
  FROM orders GROUP BY customer_id, name;

-- ...or aggregate it
SELECT customer_id, MAX(name), COUNT(*)
  FROM orders GROUP BY customer_id;
Output
ERROR: column "orders.name" must appear in the GROUP BY clause
       or be used in an aggregate function

-- MySQL before 5.7 returned a row with an arbitrary name. ONLY_FULL_GROUP_BY
-- is on by default now, which is why old queries break on upgrade.
Advertisement

Run this yourself in the Online Java Compiler, spin up a live REST API in the API Sandbox, or practise with Java interview questions.

Published 2026-08-25