3259
MariaDBERRORNotableQuery SyntaxHIGH confidence
ORDER BY with aggregate in UNION context is not supported
Production Risk
Low — query is rejected; restructure the SQL.
How to reproduce
trigger — this will error
trigger — this will error
SELECT a, COUNT(*) FROM t1 GROUP BY a ORDER BY COUNT(*) UNION SELECT b, COUNT(*) FROM t2 GROUP BY b;
expected output
ERROR 3259 (HY000): Aggregate functions with ORDER BY clause is not supported in UNION context.
Fix
Wrap in a derived table
Wrap in a derived table
SELECT * FROM (SELECT a, COUNT(*) AS cnt FROM t1 GROUP BY a UNION SELECT b, COUNT(*) FROM t2 GROUP BY b) sub ORDER BY cnt;
Why this works
Wrapping the UNION in a subquery allows ordering on the aggregate at the outer level.
What not to do
✕
Sources
Official documentation ↗
MySQL 8.0 — 3259 ER_AGGREGATE_ORDER_FOR_UNION
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev