It is well known that using ORDER BY in a subquery in PostgreSQL is not meaningful, and the DBMS will only respect the outer most ORDER BY.
However, if we include LIMIT (alongside ORDER BY) in the sub query, is this still the case?
It is well known that using ORDER BY in a subquery in PostgreSQL is not meaningful, and the DBMS will only respect the outer most ORDER BY.
However, if we include LIMIT (alongside ORDER BY) in the sub query, is this still the case?
2
Answers
Using
LIMIT
in a subquery will affect the intermediate result set generated by that subquery. Consider the following two queries:In this query, the inner
ORDER BY
will (or maybe will not) execute, but since there is noLIMIT
, the ordering of that intermediate result has no bearing on the ordering of the final result. The order of the final result will only depend on the outerORDER BY
clause.However, in this query:
The subquery aliased as
t
would only return 10 records. Again, the final ordering would only depend on the outerORDER BY
clause, but there would only be 10 records in the result set, i.e. that result set might be different than the first query.From the docs:
https://www.postgresql.org/docs/current/sql-select.html#SQL-LIMIT
So yes using
LIMIT
andORDER BY
together is defined.