Explanation:
It is important to understand how this works in order to avoid "gotchas" in such use cases. Note that union syntax is somewhat "special":
subsatement union all subsatement union all subsatement [ order by -clause] [ limit -clause]
where "reinforcement" may be further surrounded ( ) . Some working examples:
However , if you surround the first “reinforcement” with braces, you must surround all the other “substations” with braces:
(Please note that the above point is not mentioned in official documents .)
Failure to do so is a syntax error:
Then each "slice" may contain where , group by , having , join , limit , but not order by .
If you want to use order by , the subtitle containing order by must be surrounded by curly braces. (This means that they are no longer optional.)
Now, if we look at the syntax again:
subsatement union all subsatement union all subsatement [ order by -clause] [ limit -clause]
we see that the whole union statement ends with an optional order by / limit . These two keywords apply to the entire union expression, and not just to the last “smudge”:
We mentioned earlier that the limit keyword can also be applied to individual s sub-panels:
If you want to apply limit to the last "subtopic" (as opposed to the entire union operator), you must surround the last "subtitle" with braces:
To apply limit to the last subtopic, as well as to the entire union operator, use:
Same thing with order by :
But note that applying order by to "subatement" s is pointless because the docs explicitly state that order by guaranteed ( cf. ) to work throughout the union statement:
& puncsp; - & sect; - & ensp; .. use order by for individual SELECT does not say anything about the order in which rows appear in the final result.
The only way order by make sense in a "drip" is to combine it with limit :
& puncsp; - & sect; - & ensp; .. using ORDER BY in this context is usually associated with limit , so it is used to define a subset of the selected rows to retrieve for SELECT , even if it does not necessarily affect the order of these lines in the final union result.
Also, if you want to combine select into with union , there will be more “gotchas” to keep track of, see question 32858 regarding this.