Explanation:
It's important to understand how this works to avoid "gotchas" in similar use cases. Note thatunion
's syntax is somewhat "special":
substatement union all
substatement union all
substatement [order by
-clause] [limit
-clause]
where "substatement" can optionally be surrounded by (
and )
. Some working examples:
However, if you surround the first "substatement" with braces, you must surround all the other "substatement"s with braces:
(Note that the above point is not mentioned in the official docs.)
Failing to do that is a syntax error:
Next, each "substatement" can contain where
, group by
, having
, join
, limit
, but not order by
.
If you'd like to use order by
, the "substatement" that contains order by
must be surrounded by braces. (Which means they are no longer optional.)
Now, if we'd look at the syntax again:
substatement union all
substatement union all
substatement [order by
-clause] [limit
-clause]
we can see that the entire union
statement ends with an optional order by
/ limit
. These two keywords apply to the entire union
statement, not just the last "substatement":
We've mentioned previously that the limit
keyword can also be applied to individual "substatement"s:
If you want to apply limit
to the last "substatement" (as opposed to the entire union
statement), you must surround the last "substatement" with braces:
To apply limit
to the the last "substatement" and also to the entire union
statement, use:
It's the same with order by
:
But note that applying order by
to "substatement"s is meaningless because the docs have explicitly stated that order by
is only guaranteed (cf.) to work when applied to the entire union
statement:
 –§– ..use of ORDER BY
for individual SELECT
statements implies nothing about the order in which the rows appear in the final result..
The only way order by
would make sense in a "substatement" is if you combine it with limit
:
 –§– ..the use of ORDER BY in this context is typically in conjunction with LIMIT
, so that it is used to determine the subset of the selected rows to retrieve for the SELECT
, even though it does not necessarily affect the order of those rows in the final UNION
result.
Also, if you want to combine select into
with union
, there'll be more "gotchas" to watch out for. See issue 32858 regarding this.