Alex Rivera | Logout

Why or why not do an ORDER BY in a subquery?

Asked 2010-01-20T14:15:06.543
10

Why should you or should you not do an order by in a subquery?

Edit
Report

2 Answers

14

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.

If you use TOP or LIMIT in the subquery, you will need to use ORDER. But that's not standard SQL anyway.

answered 2010-01-20T14:17:33.870
1

Depending on the size of the sub-query, it will impact performance to a varrying degree.

Order shouldn't matter on a sub-query though. You should be able to move the Order By portion to the Outer Query (which should be the one returning the final results).

answered 2010-01-20T14:17:29.673

Your Answer