Tuesday, January 8, 2013

ORDER BY clause does not work in sub query

the ORDER BY clause in the SQL (any database) does not work if we use it inside a sub query, because it sorts the result set after completing all filtering conditions and calculations.

ORDER BY clause has the last priority among all clauses (i.e. SELECT, WHERE, GROUP BY, HAVING..etc) in SQL because its nothing to do with the calculations, its just for the presentation of the resulted data set. the following query doesn't work.


SELECT * FROM dual WHERE dummy IN (SELECT * FROM dual ORDER BY dummy);

instead following query will work.


SELECT * FROM dual WHERE dummy IN (SELECT * FROM dual)  ORDER BY dummy;