I\'ve two table:
1) profiles
+----+---------+
| id | name |
+----+---------+
| 1 | WILLIAM |
| 2 | JOHN |
| 3 | ROBERT |
| 4 | MI
(Explaining the loss of ORDER BY
)
The SQL standard essentially says that a subquery is an unordered set of rows. This implies that the Optimizer is free to ignore the ORDER BY
in the 'derived' table: FROM ( SELECT ... ORDER BY )
. In "recent" versions of MySQL and MariaDB, such ORDER BYs
are being dropped. There are other cases where ORDER BY
is ignored.
In some situations (not sure about this one), adding a LIMIT 99999999
(big number) after the ORDER BY
tricks the Optimizer into doing the ORDER BY
. However, it is still free to ignore the "order" later.
A general rule for MySQL: Avoid subqueries. (There are cases where subqueries are faster, but not yours.)
A strong rule: You must have an ORDER BY
on the outermost if you want the results to be sorted.
If you had added LIMIT 3
to the derived table in your first query, you would get only CHARLES, DAVID, JAMES, but not necessarily in that order. That is, you would need two ORDER BYs
- one in the derived table, one at the very end.