3260
MySQLERRORNotableQuery SyntaxHIGH confidence

ORDER BY with aggregate in non-aggregate query context

Production Risk

Low — query is rejected.

How to reproduce
trigger — this will error
trigger — this will error
SELECT name FROM t1 ORDER BY COUNT(*);

expected output

ERROR 3260 (HY000): Expression #1 of ORDER BY contains aggregate function and applies to the result of a non-aggregated query.

Fix

Add GROUP BY

Add GROUP BY
SELECT name, COUNT(*) AS cnt FROM t1 GROUP BY name ORDER BY cnt;

Why this works

GROUP BY makes the query an aggregate query, allowing the aggregate in ORDER BY.

What not to do

Sources
Official documentation ↗

MySQL 8.0 — 3260 ER_AGGREGATE_ORDER_NON_AGG_QUERY

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MySQL errors