Re: BUG #19732: first_value/last_value/nth_value return NULL with EXCLUDE TIES when the current row is outside its f

From: Henson Choi <assam258(at)gmail(dot)com>
To: Andrey Rachitskiy <pl0h0yp1(at)gmail(dot)com>
Cc: QQ Mail <781408517(at)qq(dot)com>, pgsql-bugs(at)lists(dot)postgresql(dot)org
Subject: Re: BUG #19732: first_value/last_value/nth_value return NULL with EXCLUDE TIES when the current row is outside its f
Date: 2026-10-28 05:48:23
Message-ID: CAAAe_zBWYeNuAYiY2C86ed9KKL+QmjkdEK=eNepHbkQYGQ741g@mail.gmail.com
Views: Whole Thread | Raw Message | Download mbox | Resend email
Thread:
Lists: pgsql-bugs

Hi Andrey,

> Added in v4.

I looked at v4.

This is how I read the old code. It assumes the current row is in
the frame. Then EXCLUDE TIES leaves only the current row of the
part of its peer group that overlaps the frame, so the arithmetic
keeps room for it: on the head side the first overlapping position
is remapped to currentpos, and the positions after it are shifted
by (grouptailpos - overlapstart - 1). The tail side is the mirror
image, with overlapend - 1 and (overlapend - 1 - groupheadpos).

The "- 1" is there because the current row is taken to be inside
this overlap.

But what if the current row is before the frame head (or, seeking
from the tail, at or after the frame tail)? Then the current row is
not part of the overlap, so there is no reason to subtract 1. The
old code uses the same arithmetic anyway: the remap points outside
the frame, and the shift falls one row short.

So in that case, without the remap and the "- 1", what is left is
exactly the EXCLUDE GROUP formula, on both the head and the tail
side. Working it out from the "- 1", I end up where your first
mail did: when the current row is not in the frame, EXCLUDE TIES
removes the same rows as EXCLUDE GROUP, so it should skip the
overlap the same way.

On backpatching: v4 applies cleanly to REL_14_STABLE through
REL_19_STABLE, and "make check" passes on all of them.

The fix looks correct to me. I'll mark it Ready for Committer.

Regards,
Henson

In response to

Browse pgsql-bugs by date

  From Date Subject
Next Message Tomas Barton 2026-10-28 07:30:30 Re: BUG #19792: BUG: Deadlock between WaitIO and read-stream look-ahead under io_method=io_uring (18.6)
Previous Message Ayush Tiwari 2026-10-28 05:40:51 Re: BUG #19783: Sorted GROUPING SETS return a grouping column's value in a set that leaves it out