Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is order by clause allowed in a subquery

Is there any reason why or why not you should do an 'order by' in a subquery?

like image 558
Prady Avatar asked Jan 20 '10 14:01

Prady


People also ask

Why can't you use 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.

Which clause is not allowed in a subquery?

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.

Can we use ORDER BY in subquery MySQL?

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.

Can we use ORDER BY clause in subquery in Oracle?

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.


2 Answers

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...

like image 148
sleske Avatar answered Oct 06 '22 03:10

sleske


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.

like image 38
AdaTheDev Avatar answered Oct 06 '22 03:10

AdaTheDev