Is there any reason why or why not you should do an 'order by' in a subquery?
相关问题
- SQL join to get the cartesian product of 2 columns
- sql execution latency when assign to a variable
- Difference between Types.INTEGER and Types.NULL in
- php PDO::FETCH_ASSOC doesnt detect select after ba
- Bulk update SQL Server C#
You should use it if the subquery uses some kind of
LIMIT
/TOP
.SQL Server
will not allow it unless the subquery containsTOP
orFOR XML
clause as well:Unless you use top it is not useful since you will be ordering in the outer query anyway
Smarter people say that is not proper/valid way to do it. In my case SELECT TOP 100 PERCENT in sub-query solved the problem.
Cheers
It's totally legit. I.e.
SELECT id FROM entries WHERE author_id IN (SELECT id FROM authors ORDER BY name DESC)
but you'll really get the same results usually.You can do it, but I wouldn't usually unless you have a need.
The optimiser will ignore it (or throw an error?)
See "Intermediate materialisation" for some usages.
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...