What does the SQL standard and its mainstream DB implementations (SQL Server, Oracle, DB2, PostgreSQL, Firebird, MySQL, etc.) say about the final order in the following general case:
SELECT * FROM (SELECT * FROM Table t ORDER BY t.Field)
Can I trust that the inner order is respected by the outer projection as well or do I need to state the ORDER BY
in the outer statement explicitly, to be sure?
I understand the recommendation to "explicitly list it". However, explicit listing can cause problems in certain cases. PostgreSQL, for one, requires that all fields listed in ORDER BY
be listed in SELECT DISTINCT
as well. That's no good in some cases, because it changes the expected result set, which could no longer be distinct in light of the single column I'm interested in.
Best Answer
No, you cannot.
Yes, you do need to state the
ORDER BY
you need in the outer statement explicitly, if you want to be sure that the order that the rows are returned is what you want.While you may - more often in old versions of some DBMS - sometimes find that the order of the rows returned is the one specified in the internal
ORDER BY
, there is no guarantee about it. If you want a specific order, you need to be explicit.Related / similar questions:
Quotes from the SQL standard: