Is there any reason why or why not you should do an 'order by' in a subquery?
A "table" (and subquery in the FROM clause too) is - according to the SQL standard - an unordered set of rows. Rows in a table (or in a subquery in the FROM clause) do not come in any specific order. That's why the optimizer can ignore the ORDER BY clause that you have specified.
Subqueries cannot manipulate their results internally, that is, a subquery cannot include the order by clause, the compute clause, or the into keyword. Correlated (repeating) subqueries are not allowed in the select clause of an updatable cursor defined by declare cursor.
A subquery can contain many of the keywords or clauses that an ordinary SELECT can contain: DISTINCT , GROUP BY , ORDER BY , LIMIT , joins, index hints, UNION constructs, comments, functions, and so on. Beginning with MySQL 8.0. 19, TABLE and VALUES statements can be used in subqueries.
In subqueries, the ORDER BY clause is meaningless unless it is accompanied by one or both of the result offset and fetch first clauses or in conjunction with the ROW_NUMBER function, since there is no guarantee that the order is retained in the outer result set.
Yes: It should not be done, because it does not make sense conceptually.
The subquery will be used in some outer query (otherwise it would be pointless), and that outer query will have to do ordering anyway, so there's no point ordering the subquery.
This is because query results in SQL will come in no particular order, unless you use an explicit ORDER. So even if you used ORDER in the subquery, you have no guarantee that this will affect the order of the results from the outer query; so it's pointless.
It may of course make a difference in some specific RDBMS because of its implementation, but that will be implementation-specific, and not something you should rely on.
Edit: Of course, if you use TOP or LIMIT in the subquery, you will need to use ORDER. But that's not standard SQL anyway...
No ORDER BY is valid in a subquery when you are interested in a subset of the overall data, hence you always need a TOP
(SQL Server). There's no point having an ORDER BY without TOP in a subquery because the overall ordering of the results is handled by the outer query.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With