{question}
Does it matter if I use an ORDER BY in the outer query or the subquery query?
{question}
{answer}
In queries that SELECT from a subquery, it is essential to note that any ORDER BY statement within the subquery will not be enforced in the outer SELECT query. The ordering of rows in the outer SELECT is not deterministic; this follows the MySQL wire protocol and is expected behavior.
For example:
CREATE TABLE `t` (
`id` bigint(11) NOT NULL AUTO_INCREMENT,
PRIMARY KEY (`id`));
INSERT INTO t VALUES (),(),(),(),(),(),(),(),(),();
SELECT * FROM (SELECT * FROM t ORDER BY id);
+----+
| id |
+----+
| 5 |
| 7 |
| 8 |
| 2 |
| 4 |
| 10 |
| 1 |
| 3 |
| 6 |
| 9 |
+----+
To order the results set, have an ORDER BY in the outer SELECT:
SELECT * FROM (SELECT * FROM t) ORDER BY id;
+----+
| id |
+----+
| 1 |
| 2 |
| 3 |
| 4 |
| 5 |
| 6 |
| 7 |
| 8 |
| 9 |
| 10 |
+----+
You can find more information here.
{answer}