Re: Reproducing incorrect order with order by in a subquery

From: Ruslan Zakirov <ruslan(dot)zakirov(at)gmail(dot)com>
To: Karsten Hilbert <Karsten(dot)Hilbert(at)gmx(dot)net>
Cc: pgsql-general(at)lists(dot)postgresql(dot)org
Subject: Re: Reproducing incorrect order with order by in a subquery
Date: 2023-06-14 21:58:55
Message-ID: CAMOxC8sx85u5=oA+U6VSDd0MR1o8sxMsv6gfHgyoraZkV+9BMA@mail.gmail.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

On Wed, Jun 14, 2023 at 3:50 PM Karsten Hilbert <Karsten(dot)Hilbert(at)gmx(dot)net>
wrote:

> IOW neither is help to be expected on this list nor can any
> testing (on PG) help with anything to be expected on MySQL ?
>

Don't expect any help on mysql part.

As to the question: since the outer query does not have an
> ORDER BY it can return results in any order INCLUDING the one
> produced by the subquery. Which renders impossible any

*proving* that it can return rows in orders different from
>

Well, in *theory* it can return rows in a different order that doesn't
match the order produced
by the subquery. As far as I know no RDBMS state in its documentation that
ordering between
subquery and its outer query is preserved. Some explicitly state the
opposite:

https://mariadb.com/kb/en/why-is-order-by-in-a-from-subquery-ignored/

MS SQL server:

"The ORDER BY clause is not valid in views, inline functions, derived
tables, and subqueries, unless either the TOP or OFFSET and FETCH clauses
are also specified. When ORDER BY is used in these objects, the clause is
used only to determine the rows returned by the TOP clause or OFFSET and
FETCH clauses. The ORDER BY clause does not guarantee ordered results when
these constructs are queried, unless ORDER BY is also specified in the
query itself."

My goal was to find a small dataset that demonstrates this ordering
mismatch.

Failed to reach my goal. Ended up with a code change with a lot of
explanations,
comments and links to documentation. No prove in tests that the old code
was wrong
and a new one fixes it.

> the subquery *unless* one forces a different order on the
> outer query. Which in turn would defeat the purpose as then
> the outer query *does* have an explicit ordering...
>

--
Best regards, Ruslan.

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Ruslan Zakirov 2023-06-14 23:00:12 Re: Helping planner to chose sequential scan when it improves performance
Previous Message Laurenz Albe 2023-06-14 20:44:36 Re: date format