When you use the ORDER BY inside a subquery used with UNION mysql optimizes the ORDER BY .
This is because, by default, UNION returns an unordered list, so ORDER BY will not do anything.
Optimization is mentioned in the documentation and says:
To apply ORDER BY or LIMIT to a single SELECT, put the statement in parentheses that enclose SELECT:
(SELECT a FROM t1 WHERE a=10 AND B=1 ORDER BY a LIMIT 10) UNION (SELECT a FROM t2 WHERE a=11 AND B=2 ORDER BY a LIMIT 10);
However, using ORDER BY for individual SELECT statements implies nothing in the order in which the rows appear in the final result, since UNION creates an unordered set of rows by default. Consequently, 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 this does not necessarily affect the order of these rows in the final UNION result. If ORDER BY appears without a LIMIT in a SELECT, it is optimized because it will still have no effect.
The last sentence is a bit misleading, because it should have an effect. This optimization causes a problem when you are in a situation where you need to place an order inside a subquery.
To prevent MySQL from performing this optimization, you can add a LIMIT clause as follows:
(SELECT 1 AS rank, id, add_date FROM my_table WHERE distance < 5 ORDER BY add_date LIMIT 9999999999) UNION ALL (SELECT 2 AS rank, id, add_date FROM my_table WHERE distance BETWEEN 5 AND 15 ORDER BY rank LIMIT 9999999999) UNION ALL (SELECT 3 AS rank, id, add_date from my_table WHERE distance BETWEEN 5 and 15 ORDER BY id LIMIT 9999999999)
A high LIMIT means that you can add OFFSET to the general query if you want to do something, such as pagination.
It also gives you the added benefit of ORDER BY able to have different columns for each join.