Wrong Query results with max() window function and order by in window clause

From: Hans Buschmann <buschmann(at)nidsa(dot)net>
To: "pgsql-hackers(at)postgresql(dot)org" <pgsql-hackers(at)postgresql(dot)org>
Subject: Wrong Query results with max() window function and order by in window clause
Date: 2025-06-23 11:53:32
Message-ID: a5006cfdea6343949afa7dc7ee4e7582@nidsa.net
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-hackers

Hello hackers,

While exploring some data cleanup and transformation in old data I stumbeld over $topic:

In a set of data (selected by season=23) I want to determine the min and max value of an order number (of_fac_order_n) for all occuring factories (am_fac_code).

I defined an external window clause for use in min and max functions in the query:

window wfac as (partition by of_season,am_fac_code)

For the purpose of additionally using the row_number function with the same window clause I changed the window clause to

window wfac as (partition by of_season,am_fac_code order by of_fac_order_n,id_of)

When executing the same query with only this change the values of max(of_fac_order_n) are wrong and not identical for all rows of the selected partition.

It seems max(of_fac_order_n) is only evaluated til the current row and not for the whole partition.

The problem occurred under PG18 beta1, but the error is the same in PG17.5 (others not tested).

For a quick response I didn't construct a full reproducable demo case, but in the attached I include the whole queries and the corresponding results.

All olumns in this example are simple integers/small integers from normal btree tables, nothing special.

The clue is the addition of an order by clause in the query wide windows definition which gives the wrong results.

There certainly may be other combinations (min function with descending order, other window functions) which may be sensible to the same problem, but this was not tested here.

Please find the queries and the results in the attached error report (not directly callable).

Thank you for looking

Hans Buschmann

Attachment Content-Type Size
postgres_max_window_function_error.sql application/octet-stream 8.5 KB

Responses

Browse pgsql-hackers by date

  From Date Subject
Next Message Christoph Berg 2025-06-23 12:10:08 LTS (Re: minimum Meson version)
Previous Message John Naylor 2025-06-23 11:07:47 Re: Improve CRC32C performance on SSE4.2